diff --git a/cli/azd/cmd/actions/action_descriptor.go b/cli/azd/cmd/actions/action_descriptor.go index 9b8807a0d70..c26a332d131 100644 --- a/cli/azd/cmd/actions/action_descriptor.go +++ b/cli/azd/cmd/actions/action_descriptor.go @@ -165,6 +165,9 @@ const ( // process can exit as fast as possible. Set automatically by CobraBuilder when // ActionDescriptorOptions.Lightspeed is true. AnnotationLightspeed = "azd.lightspeed" + + // AnnotationRequireInteractive identifies commands that cannot run with prompts disabled. + AnnotationRequireInteractive = "azd.requireInteractive" ) // GetGroupCommandAnnotation check if there is a grouping annotation for the command. Returns the annotation value as an @@ -201,6 +204,11 @@ type ActionDescriptorOptions struct { GroupingOptions CommandGroupOptions // Whether or not the command requires a principal login RequireLogin bool + // Whether the command requires interactive input. When set, the command fails before + // login or action resolution if prompts are disabled (for example, with --no-prompt). + // Use this when the command's prompts make decisions that azd can't safely infer, so + // automatically accepting their defaults could produce the wrong result. + RequireInteractive bool // Whether the command should execute as fast as possible, skipping // non-essential background work like update checks. // Use for programmatic/hidden commands (e.g., auth token) where diff --git a/cli/azd/cmd/auto_install.go b/cli/azd/cmd/auto_install.go index f18e5c48483..8ef6f2d7999 100644 --- a/cli/azd/cmd/auto_install.go +++ b/cli/azd/cmd/auto_install.go @@ -568,7 +568,7 @@ type ExecuteResult struct { // for lightspeed commands so the process can exit quickly. IsLightspeed bool // LatestVersion receives the result of the background update check. - // Nil when the update check was not started (lightspeed commands). + // Nil when the update check was not started (such as for lightspeed commands). // When the check is skipped via AZD_SKIP_UPDATE_CHECK, the returned channel // is closed without a value. LatestVersion <-chan *update.VersionInfo @@ -676,6 +676,14 @@ func executeWithAutoInstallCommand( // Detect lightspeed commands from the cobra annotation set by CobraBuilder. result.IsLightspeed = foundCmd.Annotations[actions.AnnotationLightspeed] == "true" + // Update checks and extension auto-install run before action middleware. + // Bypass that work when interactiveGuard would reject the command, but still + // go through Cobra so help and flag errors take precedence. + if globalOpts.NoPrompt && foundCmd.Annotations[actions.AnnotationRequireInteractive] == "true" { + result.Err = rootCmd.ExecuteContext(ctx) + return result + } + // Start the background update check AFTER command identification. // Lightspeed commands (e.g., auth token) skip the update check entirely // so the process can exit as fast as possible — this prevents the diff --git a/cli/azd/cmd/auto_install_integration_test.go b/cli/azd/cmd/auto_install_integration_test.go index 6125295575c..54c4b372dd6 100644 --- a/cli/azd/cmd/auto_install_integration_test.go +++ b/cli/azd/cmd/auto_install_integration_test.go @@ -6,6 +6,7 @@ package cmd import ( "bytes" "encoding/json" + "errors" "io" "os" "path/filepath" @@ -13,6 +14,7 @@ import ( "github.com/azure/azure-dev/cli/azd/internal" "github.com/azure/azure-dev/cli/azd/internal/runcontext/agentdetect" + "github.com/azure/azure-dev/cli/azd/internal/tracing/fields" "github.com/azure/azure-dev/cli/azd/pkg/ioc" "github.com/azure/azure-dev/cli/azd/pkg/output" "github.com/azure/azure-dev/cli/azd/pkg/project" @@ -173,7 +175,10 @@ func TestExecuteWithAutoInstall_InvalidProjectYamlReturnsParseError(t *testing.T projectDir := t.TempDir() t.Chdir(projectDir) - t.Setenv("AZD_CONFIG_DIR", t.TempDir()) + configDir := t.TempDir() + t.Setenv("AZD_CONFIG_DIR", configDir) + require.NoError(t, os.WriteFile(filepath.Join(configDir, "config.json"), + []byte(`{"extension":{"sources":{}}}`), 0o600)) t.Setenv("AZD_SKIP_UPDATE_CHECK", "true") t.Setenv("AZURE_DEV_COLLECT_TELEMETRY", "no") t.Setenv("NO_COLOR", "1") @@ -196,6 +201,127 @@ func TestExecuteWithAutoInstall_InvalidProjectYamlReturnsParseError(t *testing.T require.ErrorContains(t, result.Err, "unable to parse azure.yaml file") } +func TestExecuteWithAutoInstall_RejectsNoPromptBeforePreparingPipeline(t *testing.T) { + configDir := t.TempDir() + t.Setenv("AZD_CONFIG_DIR", configDir) + require.NoError(t, os.WriteFile(filepath.Join(configDir, "config.json"), + []byte(`{"extension":{"sources":{}}}`), 0o600)) + + // Keep the test offline even if a regression reaches the update check. + t.Setenv("AZD_SKIP_UPDATE_CHECK", "true") + t.Setenv("AZURE_DEV_COLLECT_TELEMETRY", "no") + t.Chdir(t.TempDir()) + + originalArgs := os.Args + t.Cleanup(func() { os.Args = originalArgs }) + os.Args = []string{"azd", "pipeline", "config", "--no-prompt"} + container := ioc.NewNestedContainer(nil) + ioc.RegisterInstance(container, t.Context()) + _, recorder := recordCommandSpans(t) + + // Use the CLI entry point to cover global flag parsing and root construction as well as execution. + result := ExecuteWithAutoInstall(t.Context(), container) + + require.ErrorIs(t, result.Err, internal.ErrInteractiveRequired) + // Even a skipped update check returns a closed channel if the check was reached. + require.Nil(t, result.LatestVersion, "the update check must not be started") + + // The rejection happens inside the telemetry middleware, so it's recorded on the command span. Errors with + // suggestions report the "error.suggestion" result code, with the underlying classification in error.type. + var errorTypes []string + for _, span := range recorder.Ended() { + if span.Name() != "cmd.pipeline.config" { + continue + } + + require.Equal(t, "error.suggestion", span.Status().Description) + for _, attr := range span.Attributes() { + if attr.Key == fields.ErrType.Key { + errorTypes = append(errorTypes, attr.Value.AsString()) + } + } + } + require.Equal(t, []string{"internal.interactive_required"}, errorTypes) +} + +func TestExecuteWithAutoInstall_InteractiveRequirementBeforeExtensions(t *testing.T) { + tests := []struct { + name string + args []string + help bool + flagError string + }{ + {name: "missing project extension"}, + {name: "help", args: []string{"--help"}, help: true}, + { + name: "invalid flag", + args: []string{"--unknown-flag"}, + flagError: "unknown flag: --unknown-flag", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + configDir := t.TempDir() + t.Setenv("AZD_CONFIG_DIR", configDir) + require.NoError(t, os.WriteFile(filepath.Join(configDir, "config.json"), + []byte(`{"extension":{"sources":{}}}`), 0o600)) + t.Setenv("AZD_SKIP_UPDATE_CHECK", "true") + t.Setenv("AZURE_DEV_COLLECT_TELEMETRY", "no") + t.Setenv("NO_COLOR", "1") + t.Chdir(t.TempDir()) + + // A missing required extension would fail first if auto-install ran before the guard. + require.NoError(t, project.Save(t.Context(), &project.ProjectConfig{ + Name: "interactive-guard", + RequiredVersions: &project.RequiredVersions{ + Extensions: map[string]*string{"test.missing": nil}, + }, + }, "azure.yaml")) + + originalArgs := os.Args + t.Cleanup(func() { os.Args = originalArgs }) + os.Args = append([]string{"azd", "pipeline", "config", "--no-prompt"}, tt.args...) + opts := &internal.GlobalCommandOptions{} + require.NoError(t, ParseGlobalFlags(os.Args[1:], opts)) + container := ioc.NewNestedContainer(nil) + ioc.RegisterInstance(container, t.Context()) + ioc.RegisterInstance(container, opts) + + // Build the root here to capture Cobra's stdout and stderr separately. + root := NewRootCmd(false, nil, container) + var stdout, stderr bytes.Buffer + root.SetOut(&stdout) + root.SetErr(&stderr) + root.SetArgs(os.Args[1:]) + result := executeWithAutoInstallCommand(t.Context(), container, root, opts, &ExecuteResult{}) + + // Help and flag errors take precedence over the interactive-mode error. + switch { + case tt.help: + require.NoError(t, result.Err) + require.Contains(t, stdout.String(), "requires interactive input") + case tt.flagError != "": + require.ErrorContains(t, result.Err, tt.flagError) + require.Contains(t, stderr.String(), tt.flagError) + default: + require.ErrorIs(t, result.Err, internal.ErrInteractiveRequired) + suggestionErr, ok := errors.AsType[*internal.ErrorWithSuggestion](result.Err) + require.True(t, ok) + require.Equal(t, "Run 'azd pipeline config --no-prompt=false' in an interactive terminal.", + suggestionErr.Suggestion) + + // The UX middleware renders the error through the console, like any other command error. + require.Empty(t, stderr.String()) + require.Equal(t, "\nERROR: interactive mode required: azd pipeline config can't run with prompts disabled. "+ + "Prompts are disabled by --no-prompt, and automatically in CI/CD and AI-agent environments.\n\n"+ + "Suggestion: Run 'azd pipeline config --no-prompt=false' in an interactive terminal.\n\n", + stdout.String()) + } + }) + } +} + // TestExecuteWithAutoInstallIntegration tests the integration between // extractFlagsWithValues and findFirstNonFlagArg in the context of // the auto-install feature. diff --git a/cli/azd/cmd/cobra_builder.go b/cli/azd/cmd/cobra_builder.go index 604cf4ea796..f5ad6e49879 100644 --- a/cli/azd/cmd/cobra_builder.go +++ b/cli/azd/cmd/cobra_builder.go @@ -310,6 +310,13 @@ func (cb *CobraBuilder) bindCommand(cmd *cobra.Command, descriptor *actions.Acti cmd.Annotations[actions.AnnotationLightspeed] = "true" } + if descriptor.Options.RequireInteractive { + if cmd.Annotations == nil { + cmd.Annotations = make(map[string]string) + } + cmd.Annotations[actions.AnnotationRequireInteractive] = "true" + } + // `generateCmdHelp` sets a default help section when `descriptor.Options.HelpOptions` is nil. // This call ensures all commands gets the same help formatting. cmd.SetHelpTemplate(generateCmdHelp(cmd, generateCmdHelpOptions{ diff --git a/cli/azd/cmd/middleware/interactive_guard.go b/cli/azd/cmd/middleware/interactive_guard.go new file mode 100644 index 00000000000..73d5a65132e --- /dev/null +++ b/cli/azd/cmd/middleware/interactive_guard.go @@ -0,0 +1,43 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package middleware + +import ( + "context" + "fmt" + + "github.com/azure/azure-dev/cli/azd/cmd/actions" + "github.com/azure/azure-dev/cli/azd/internal" + "github.com/azure/azure-dev/cli/azd/pkg/input" +) + +// InteractiveGuardMiddleware rejects commands that require interactive input when prompts are disabled. +type InteractiveGuardMiddleware struct { + console input.Console + options *Options +} + +// NewInteractiveGuardMiddleware creates a new instance of the InteractiveGuardMiddleware. +func NewInteractiveGuardMiddleware(console input.Console, options *Options) Middleware { + return &InteractiveGuardMiddleware{ + console: console, + options: options, + } +} + +// Run returns an error in no-prompt mode, otherwise it runs the next middleware or action. +func (m *InteractiveGuardMiddleware) Run(ctx context.Context, next NextFn) (*actions.ActionResult, error) { + if m.console.IsNoPromptMode() { + return nil, &internal.ErrorWithSuggestion{ + Err: fmt.Errorf( + "%w: %s can't run with prompts disabled. %s", + internal.ErrInteractiveRequired, m.options.CommandPath, + "Prompts are disabled by --no-prompt, and automatically in CI/CD and AI-agent environments.", + ), + Suggestion: fmt.Sprintf("Run '%s --no-prompt=false' in an interactive terminal.", m.options.CommandPath), + } + } + + return next(ctx) +} diff --git a/cli/azd/cmd/middleware/interactive_guard_test.go b/cli/azd/cmd/middleware/interactive_guard_test.go new file mode 100644 index 00000000000..96960bfb7bd --- /dev/null +++ b/cli/azd/cmd/middleware/interactive_guard_test.go @@ -0,0 +1,52 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package middleware + +import ( + "context" + "errors" + "testing" + + "github.com/stretchr/testify/require" + + "github.com/azure/azure-dev/cli/azd/cmd/actions" + "github.com/azure/azure-dev/cli/azd/internal" + "github.com/azure/azure-dev/cli/azd/test/mocks/mockinput" +) + +func TestInteractiveGuard_RejectsNoPrompt(t *testing.T) { + t.Parallel() + + console := mockinput.NewMockConsole() + console.SetNoPromptMode(true) + guard := NewInteractiveGuardMiddleware(console, &Options{CommandPath: "azd pipeline config"}) + + nextCalled := false + result, err := guard.Run(t.Context(), func(context.Context) (*actions.ActionResult, error) { + nextCalled = true + return nil, nil + }) + + require.Nil(t, result) + require.False(t, nextCalled, "later middleware and the action must not run in no-prompt mode") + require.ErrorIs(t, err, internal.ErrInteractiveRequired) + suggestionErr, ok := errors.AsType[*internal.ErrorWithSuggestion](err) + require.True(t, ok) + require.Equal(t, "Run 'azd pipeline config --no-prompt=false' in an interactive terminal.", suggestionErr.Suggestion) +} + +func TestInteractiveGuard_AllowsInteractive(t *testing.T) { + t.Parallel() + + console := mockinput.NewMockConsole() + guard := NewInteractiveGuardMiddleware(console, &Options{CommandPath: "azd pipeline config"}) + + expected := &actions.ActionResult{} + result, err := guard.Run(t.Context(), func(context.Context) (*actions.ActionResult, error) { + return expected, nil + }) + + require.NoError(t, err) + require.Same(t, expected, result) +} diff --git a/cli/azd/cmd/pipeline.go b/cli/azd/cmd/pipeline.go index e208f477696..96f072607c6 100644 --- a/cli/azd/cmd/pipeline.go +++ b/cli/azd/cmd/pipeline.go @@ -103,6 +103,13 @@ func pipelineActions(root *actions.ActionDescriptor) *actions.ActionDescriptor { Description: getCmdPipelineConfigHelpDescription, Footer: getCmdPipelineConfigHelpFooter, }, + // In no-prompt mode, prompts silently return their default values. That's only safe when the default + // came from something the user already provided (ex: azd's subscription prompt defaults + // to AZURE_SUBSCRIPTION_ID). + // + // This command has flags values that can't be inferred, like whether we push the repo, etc... so + // we require an interactive setup. + RequireInteractive: true, }) return group @@ -377,6 +384,10 @@ func getCmdPipelineConfigHelpDescription(*cobra.Command) string { output.WithHighLightFormat("pipeline config") + " will set deployment pipeline variables and secrets using the current environment. " + "To configure for a new or an existing environment, provide a value for the '-e' flag."), + formatHelpNote( + output.WithHighLightFormat("pipeline config") + + " requires interactive input and cannot be run with --no-prompt, including when azd " + + "enables no-prompt mode automatically in CI/CD or AI-agent environments."), }) } diff --git a/cli/azd/cmd/pipeline_test.go b/cli/azd/cmd/pipeline_test.go index 0a70e17e93f..19b86989089 100644 --- a/cli/azd/cmd/pipeline_test.go +++ b/cli/azd/cmd/pipeline_test.go @@ -6,12 +6,14 @@ package cmd import ( "context" "errors" + "slices" "testing" "github.com/spf13/cobra" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/azure/azure-dev/cli/azd/cmd/actions" "github.com/azure/azure-dev/cli/azd/cmd/middleware" "github.com/azure/azure-dev/cli/azd/internal" "github.com/azure/azure-dev/cli/azd/pkg/environment" @@ -45,6 +47,19 @@ func Test_NewPipelineConfigFlags(t *testing.T) { require.NotNil(t, flags) } +func Test_PipelineConfig_RequiresInteractive(t *testing.T) { + t.Parallel() + + group := pipelineActions(actions.NewActionDescriptor("azd", nil)) + + configIdx := slices.IndexFunc(group.Children(), func(d *actions.ActionDescriptor) bool { + return d.Name == "config" + }) + require.GreaterOrEqual(t, configIdx, 0) + require.True(t, group.Children()[configIdx].Options.RequireInteractive) + require.False(t, group.Options.RequireInteractive, "only 'pipeline config' should require interactive input") +} + type pipelineConfigTestActivator struct { providerNames []string environmentName string diff --git a/cli/azd/cmd/root.go b/cli/azd/cmd/root.go index 23713f18817..86ca50301f5 100644 --- a/cli/azd/cmd/root.go +++ b/cli/azd/cmd/root.go @@ -570,6 +570,15 @@ func registerGlobalMiddleware(root *actions.ActionDescriptor) { return !descriptor.Options.DisableTroubleshooting }). UseMiddleware("cancellation", middleware.NewCancellationMiddleware). + // Runs before loginGuard so commands that require interactive input fail before + // attempting login or resolving actions with side effects. + UseMiddlewareWhen( + "interactiveGuard", + middleware.NewInteractiveGuardMiddleware, + func(descriptor *actions.ActionDescriptor) bool { + return descriptor.Options.RequireInteractive + }, + ). UseMiddlewareWhen("loginGuard", middleware.NewLoginGuardMiddleware, func(descriptor *actions.ActionDescriptor) bool { // Check if the command or any of its parents require login current := descriptor diff --git a/cli/azd/cmd/root_test.go b/cli/azd/cmd/root_test.go index 2479e0d312e..02260762c0e 100644 --- a/cli/azd/cmd/root_test.go +++ b/cli/azd/cmd/root_test.go @@ -25,7 +25,9 @@ func TestRegisterGlobalMiddleware(t *testing.T) { names[i] = registration.Name } - require.Equal(t, []string{"debug", "ux", "telemetry", "error", "cancellation", "loginGuard"}, names) + require.Equal(t, []string{ + "debug", "ux", "telemetry", "error", "cancellation", "interactiveGuard", "loginGuard", + }, names) require.NotContains(t, names, "toolFirstRun") require.NotContains(t, names, "toolUpdateCheck") } diff --git a/cli/azd/cmd/testdata/TestUsage-azd-pipeline-config.snap b/cli/azd/cmd/testdata/TestUsage-azd-pipeline-config.snap index a65a22d1f2a..09d3ec67a8a 100644 --- a/cli/azd/cmd/testdata/TestUsage-azd-pipeline-config.snap +++ b/cli/azd/cmd/testdata/TestUsage-azd-pipeline-config.snap @@ -4,6 +4,7 @@ Configure your deployment pipeline to connect securely to Azure • Supports GitHub Actions and Azure Pipelines. To configure using a specific pipeline provider, provide a value for the '--provider' flag. • pipeline config creates or uses a service principal on the Azure subscription to create a secure connection between your deployment pipeline and Azure. • By default, pipeline config will set deployment pipeline variables and secrets using the current environment. To configure for a new or an existing environment, provide a value for the '-e' flag. + • pipeline config requires interactive input and cannot be run with --no-prompt, including when azd enables no-prompt mode automatically in CI/CD or AI-agent environments. Usage azd pipeline config [flags] diff --git a/cli/azd/docs/manual-pipeline-config.md b/cli/azd/docs/manual-pipeline-config.md index 3944cec3750..b9e308cbb78 100644 --- a/cli/azd/docs/manual-pipeline-config.md +++ b/cli/azd/docs/manual-pipeline-config.md @@ -17,6 +17,11 @@ installation before running azd project commands. This command **must** be executed by someone who has a `Contributor` role, in order to create the service principal with the given role. The next steps can be used to manually configure a pipeline without a `Contributor` role, for example, by using an existing service principal. +`azd pipeline config` requires interactive input, so it fails in no-prompt mode (`--no-prompt`, `--non-interactive`, +`AZD_NON_INTERACTIVE=true`, or automatic CI/CD or AI-agent detection). Run `azd pipeline config --no-prompt=false` manually in an interactive terminal to review and answer its prompts. + +If you can't run the command interactively, configure the pipeline with the manual steps below. + ## Setting up the local repository There a few ways to get the initial project, even before thinking about the pipeline and how to set it up. For example: diff --git a/cli/azd/internal/cmd/errors_test.go b/cli/azd/internal/cmd/errors_test.go index 19d72920ee8..9270592d345 100644 --- a/cli/azd/internal/cmd/errors_test.go +++ b/cli/azd/internal/cmd/errors_test.go @@ -2242,10 +2242,9 @@ func isErrorConstructorCall(call *ast.CallExpr) bool { (ident.Name == "fmt" && sel.Sel.Name == "Errorf") } -// Test_RunMethodsNoBareErrors walks all action Run() methods and flags inline bare errors -// (errors.New or fmt.Errorf without %w) that would produce opaque errors_errorString in telemetry. -// These errors reach MapError via the telemetry middleware and must use typed sentinels or wrap -// an existing error with %w for proper classification. +// Test_RunMethodsNoBareErrors checks inline error returns from action and middleware Run methods. +// It reads source instead of executing commands so it can catch errors on paths that tests don't +// exercise. It does not resolve variables or verify the wrapped error's telemetry classification. func Test_RunMethodsNoBareErrors(t *testing.T) { t.Parallel() azdRoot, err := filepath.Abs(filepath.Join("..", "..")) @@ -2340,9 +2339,18 @@ func Test_RunMethodsNoBareErrors(t *testing.T) { if len(violations) > 0 { t.Errorf( "Found %d NEW bare error(s) in action Run() methods that would produce opaque telemetry.\n"+ - "Use typed sentinel errors (internal.ErrXxx) with %%w wrapping, or wrap with an existing\n"+ - "typed error from a dependency. Bare errors.New()/fmt.Errorf() without %%w produce\n"+ - "'internal.errors_errorString' in telemetry.\n\n"+ + "For inline fmt.Errorf calls, this source check expects %%w in a single string literal.\n"+ + "It does not evaluate concatenation or named format strings.\n"+ + "Expected: fmt.Errorf(\"loading project: %%w\", err)\n"+ + "For a longer message, pass the extra text as an argument instead of concatenating the format:\n\n"+ + " return nil, &internal.ErrorWithSuggestion{\n"+ + " Err: fmt.Errorf(\n"+ + " \"%%w: %%s\",\n"+ + " internal.ErrInteractiveRequired,\n"+ + " \"This command can't run with prompts disabled.\",\n"+ + " ),\n"+ + " Suggestion: \"Run the command in an interactive terminal.\",\n"+ + " }\n\n"+ "Violations:\n%s", len(violations), strings.Join(violations, "\n"), @@ -2444,11 +2452,12 @@ func isBareErrorCall(call *ast.CallExpr) bool { return false } -// fmtErrorfHasWrap checks if a fmt.Errorf call contains %w in the format string. +// fmtErrorfHasWrap reports whether a fmt.Errorf call has %w in a single literal format string. func fmtErrorfHasWrap(call *ast.CallExpr) bool { if len(call.Args) == 0 { return false } + lit, ok := call.Args[0].(*ast.BasicLit) if !ok { return false