From a59cfb6c19fbb972e92e32df4f0adba5abda9a9e Mon Sep 17 00:00:00 2001 From: ripark Date: Tue, 17 Nov 2026 17:41:06 -0800 Subject: [PATCH 1/6] Adding new middleware to error out if you go into a no-prompt mode with a command that requires interactive answer (pipeline config doesn't want to guess!). --- cli/azd/cmd/actions/action_descriptor.go | 5 ++ cli/azd/cmd/middleware/interactive_guard.go | 46 +++++++++++++++ .../cmd/middleware/interactive_guard_test.go | 57 +++++++++++++++++++ cli/azd/cmd/pipeline.go | 11 ++++ cli/azd/cmd/pipeline_test.go | 15 +++++ cli/azd/cmd/root.go | 9 +++ cli/azd/cmd/root_test.go | 4 +- .../TestUsage-azd-pipeline-config.snap | 1 + cli/azd/docs/manual-pipeline-config.md | 7 +++ 9 files changed, 154 insertions(+), 1 deletion(-) create mode 100644 cli/azd/cmd/middleware/interactive_guard.go create mode 100644 cli/azd/cmd/middleware/interactive_guard_test.go diff --git a/cli/azd/cmd/actions/action_descriptor.go b/cli/azd/cmd/actions/action_descriptor.go index 9b8807a0d70..483a1018fae 100644 --- a/cli/azd/cmd/actions/action_descriptor.go +++ b/cli/azd/cmd/actions/action_descriptor.go @@ -201,6 +201,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/middleware/interactive_guard.go b/cli/azd/cmd/middleware/interactive_guard.go new file mode 100644 index 00000000000..81d266cd916 --- /dev/null +++ b/cli/azd/cmd/middleware/interactive_guard.go @@ -0,0 +1,46 @@ +// 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( + "%s requires interactive input and cannot be run with --no-prompt: %w", + m.options.CommandPath, + internal.ErrInteractiveRequired, + ), + Message: fmt.Sprintf( + "%s requires interactive input and cannot be run with --no-prompt. No changes were made.", + 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..804c61dcea9 --- /dev/null +++ b/cli/azd/cmd/middleware/interactive_guard_test.go @@ -0,0 +1,57 @@ +// 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) + require.EqualError(t, err, + "azd pipeline config requires interactive input and cannot be run with --no-prompt: "+ + "interactive mode required") + + suggestionErr, ok := errors.AsType[*internal.ErrorWithSuggestion](err) + require.True(t, ok) + require.Contains(t, suggestionErr.Message, "No changes were made") + require.Empty(t, 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..f5ed9a2cc17 100644 --- a/cli/azd/docs/manual-pipeline-config.md +++ b/cli/azd/docs/manual-pipeline-config.md @@ -17,6 +17,13 @@ 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). Its prompts default to azd's suggestions, such as +creating a new repository or identity, or pushing your code. Without someone to review them, those suggestions could +create or change resources you didn't intend. + +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: From 19da38ae2f03dfc48a7894bc929ddc8cd991796c Mon Sep 17 00:00:00 2001 From: ripark Date: Wed, 18 Nov 2026 16:39:11 -0800 Subject: [PATCH 2/6] A much simpler implementation that covers auto-install for commands _and_ our normal "invoke command" path as well. --- cli/azd/cmd/actions/action_descriptor.go | 5 +- cli/azd/cmd/auto_install.go | 8 +- cli/azd/cmd/auto_install_integration_test.go | 112 +++++++++++++++++- cli/azd/cmd/cobra_builder.go | 7 ++ cli/azd/cmd/middleware/interactive_guard.go | 46 ------- .../cmd/middleware/interactive_guard_test.go | 57 --------- cli/azd/cmd/root.go | 20 ++-- cli/azd/cmd/root_test.go | 2 +- cli/azd/docs/manual-pipeline-config.md | 4 +- 9 files changed, 142 insertions(+), 119 deletions(-) delete mode 100644 cli/azd/cmd/middleware/interactive_guard.go delete mode 100644 cli/azd/cmd/middleware/interactive_guard_test.go diff --git a/cli/azd/cmd/actions/action_descriptor.go b/cli/azd/cmd/actions/action_descriptor.go index 483a1018fae..1e939193383 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 @@ -202,7 +205,7 @@ type ActionDescriptorOptions struct { // 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). + // command preparation and execution 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 diff --git a/cli/azd/cmd/auto_install.go b/cli/azd/cmd/auto_install.go index f18e5c48483..f264bb7690e 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,12 @@ func executeWithAutoInstallCommand( // Detect lightspeed commands from the cobra annotation set by CobraBuilder. result.IsLightspeed = foundCmd.Annotations[actions.AnnotationLightspeed] == "true" + // Let Cobra handle help and flag errors without starting update or extension work. + if blockedByNoPrompt(foundCmd, globalOpts) { + 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..b7d44a3337e 100644 --- a/cli/azd/cmd/auto_install_integration_test.go +++ b/cli/azd/cmd/auto_install_integration_test.go @@ -173,7 +173,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 +199,113 @@ 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()) + + // Point --cwd at a missing directory to verify that rejection leaves it uncreated. + cwd := filepath.Join(t.TempDir(), "not-created") + originalArgs := os.Args + t.Cleanup(func() { os.Args = originalArgs }) + os.Args = []string{"azd", "pipeline", "config", "--no-prompt", "--cwd", cwd} + container := ioc.NewNestedContainer(nil) + ioc.RegisterInstance(container, t.Context()) + + // 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) + require.NoDirExists(t, cwd) + // 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") +} + +func TestExecuteWithAutoInstall_InteractiveRequirementBeforeExtensions(t *testing.T) { + tests := []struct { + name string + args []string + help bool + missingCwd bool + flagError string + }{ + {name: "missing project extension"}, + {name: "missing cwd", missingCwd: true}, + {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...) + cwd := filepath.Join(t.TempDir(), "not-created") + if tt.missingCwd { + os.Args = append(os.Args, "--cwd", cwd) + } + 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{}) + if tt.missingCwd { + require.NoDirExists(t, cwd) + } + + // 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) + require.Empty(t, stdout.String()) + require.Equal(t, "Error: interactive mode required: azd pipeline config was invoked with prompts disabled. "+ + "Run 'azd pipeline config --no-prompt=false' in an interactive terminal.\n", stderr.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 deleted file mode 100644 index 81d266cd916..00000000000 --- a/cli/azd/cmd/middleware/interactive_guard.go +++ /dev/null @@ -1,46 +0,0 @@ -// 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( - "%s requires interactive input and cannot be run with --no-prompt: %w", - m.options.CommandPath, - internal.ErrInteractiveRequired, - ), - Message: fmt.Sprintf( - "%s requires interactive input and cannot be run with --no-prompt. No changes were made.", - 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 deleted file mode 100644 index 804c61dcea9..00000000000 --- a/cli/azd/cmd/middleware/interactive_guard_test.go +++ /dev/null @@ -1,57 +0,0 @@ -// 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) - require.EqualError(t, err, - "azd pipeline config requires interactive input and cannot be run with --no-prompt: "+ - "interactive mode required") - - suggestionErr, ok := errors.AsType[*internal.ErrorWithSuggestion](err) - require.True(t, ok) - require.Contains(t, suggestionErr.Message, "No changes were made") - require.Empty(t, 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/root.go b/cli/azd/cmd/root.go index 86ca50301f5..548487b70d7 100644 --- a/cli/azd/cmd/root.go +++ b/cli/azd/cmd/root.go @@ -88,6 +88,13 @@ func newRootCmd( Use: "azd", Short: fmt.Sprintf("%s is an open-source tool that helps onboard and manage your project on Azure", productName), PersistentPreRunE: func(cmd *cobra.Command, args []string) error { + if blockedByNoPrompt(cmd, opts) { + return fmt.Errorf( + "%w: %s was invoked with prompts disabled. Run '%s --no-prompt=false' in an interactive terminal.", + internal.ErrInteractiveRequired, cmd.CommandPath(), cmd.CommandPath(), + ) + } + // If there was a platform configuration error report it to the user until it is resolved // Using fmt.Printf directly here since we can't leverage our IoC container to resolve a console instance if errors.Is(platform.Error, platform.ErrPlatformNotSupported) { @@ -559,6 +566,10 @@ func newRootCmd( return cmd } +func blockedByNoPrompt(cmd *cobra.Command, opts *internal.GlobalCommandOptions) bool { + return opts.NoPrompt && cmd.Annotations[actions.AnnotationRequireInteractive] == "true" +} + func registerGlobalMiddleware(root *actions.ActionDescriptor) { root. UseMiddleware("debug", middleware.NewDebugMiddleware). @@ -570,15 +581,6 @@ 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 02260762c0e..5eaf1f783ca 100644 --- a/cli/azd/cmd/root_test.go +++ b/cli/azd/cmd/root_test.go @@ -26,7 +26,7 @@ func TestRegisterGlobalMiddleware(t *testing.T) { } require.Equal(t, []string{ - "debug", "ux", "telemetry", "error", "cancellation", "interactiveGuard", "loginGuard", + "debug", "ux", "telemetry", "error", "cancellation", "loginGuard", }, names) require.NotContains(t, names, "toolFirstRun") require.NotContains(t, names, "toolUpdateCheck") diff --git a/cli/azd/docs/manual-pipeline-config.md b/cli/azd/docs/manual-pipeline-config.md index f5ed9a2cc17..b9e308cbb78 100644 --- a/cli/azd/docs/manual-pipeline-config.md +++ b/cli/azd/docs/manual-pipeline-config.md @@ -18,9 +18,7 @@ This command **must** be executed by someone who has a `Contributor` role, in or 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). Its prompts default to azd's suggestions, such as -creating a new repository or identity, or pushing your code. Without someone to review them, those suggestions could -create or change resources you didn't intend. +`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. From 54d3d1943293b913f2236648ae1ef8f2699fd4d1 Mon Sep 17 00:00:00 2001 From: ripark Date: Thu, 19 Nov 2026 13:55:48 -0800 Subject: [PATCH 3/6] Adding in a small workaround so we can print the suggestion in the same format as others, even though we're a bit early in setup. --- cli/azd/cmd/auto_install_integration_test.go | 12 ++++++++-- cli/azd/cmd/root.go | 23 ++++++++++++++++---- 2 files changed, 29 insertions(+), 6 deletions(-) diff --git a/cli/azd/cmd/auto_install_integration_test.go b/cli/azd/cmd/auto_install_integration_test.go index b7d44a3337e..95da8fb85e2 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" @@ -298,9 +299,16 @@ func TestExecuteWithAutoInstall_InteractiveRequirementBeforeExtensions(t *testin 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) + require.Empty(t, stdout.String()) - require.Equal(t, "Error: interactive mode required: azd pipeline config was invoked with prompts disabled. "+ - "Run 'azd pipeline config --no-prompt=false' in an interactive terminal.\n", stderr.String()) + require.Equal(t, "ERROR: 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", + stderr.String()) } }) } diff --git a/cli/azd/cmd/root.go b/cli/azd/cmd/root.go index 548487b70d7..8d8292642f7 100644 --- a/cli/azd/cmd/root.go +++ b/cli/azd/cmd/root.go @@ -29,6 +29,7 @@ import ( "github.com/azure/azure-dev/cli/azd/internal/cmd/show" "github.com/azure/azure-dev/cli/azd/internal/telemetry" "github.com/azure/azure-dev/cli/azd/pkg/output" + outputux "github.com/azure/azure-dev/cli/azd/pkg/output/ux" "github.com/azure/azure-dev/cli/azd/pkg/ux" "github.com/spf13/cobra" ) @@ -89,10 +90,24 @@ func newRootCmd( Short: fmt.Sprintf("%s is an open-source tool that helps onboard and manage your project on Azure", productName), PersistentPreRunE: func(cmd *cobra.Command, args []string) error { if blockedByNoPrompt(cmd, opts) { - return fmt.Errorf( - "%w: %s was invoked with prompts disabled. Run '%s --no-prompt=false' in an interactive terminal.", - internal.ErrInteractiveRequired, cmd.CommandPath(), cmd.CommandPath(), - ) + err := &internal.ErrorWithSuggestion{ + Err: fmt.Errorf( + "%w: %s can't run with prompts disabled. Prompts are disabled by --no-prompt, "+ + "and automatically in CI/CD and AI-agent environments.", + internal.ErrInteractiveRequired, cmd.CommandPath(), + ), + Suggestion: fmt.Sprintf("Run '%s --no-prompt=false' in an interactive terminal.", cmd.CommandPath()), + } + + // This runs before the UX middleware, which normally renders suggestions, so render it here + // and keep Cobra from printing the bare message a second time. + cmd.SilenceErrors = true + fmt.Fprint(cmd.ErrOrStderr(), (&outputux.ErrorWithSuggestion{ + Err: err.Err, + Suggestion: err.Suggestion, + }).ToString("")) + + return err } // If there was a platform configuration error report it to the user until it is resolved From 1b58d7be6a5ca4e010713b4998e75d6093bd1c20 Mon Sep 17 00:00:00 2001 From: ripark Date: Thu, 19 Nov 2026 15:11:13 -0800 Subject: [PATCH 4/6] Interactive guard middleware, so we can just inject it into the stack and it'll do our little "interactive command" check. --- cli/azd/cmd/middleware/interactive_guard.go | 46 +++++++++++++++ .../cmd/middleware/interactive_guard_test.go | 57 +++++++++++++++++++ 2 files changed, 103 insertions(+) create mode 100644 cli/azd/cmd/middleware/interactive_guard.go create mode 100644 cli/azd/cmd/middleware/interactive_guard_test.go diff --git a/cli/azd/cmd/middleware/interactive_guard.go b/cli/azd/cmd/middleware/interactive_guard.go new file mode 100644 index 00000000000..81d266cd916 --- /dev/null +++ b/cli/azd/cmd/middleware/interactive_guard.go @@ -0,0 +1,46 @@ +// 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( + "%s requires interactive input and cannot be run with --no-prompt: %w", + m.options.CommandPath, + internal.ErrInteractiveRequired, + ), + Message: fmt.Sprintf( + "%s requires interactive input and cannot be run with --no-prompt. No changes were made.", + 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..804c61dcea9 --- /dev/null +++ b/cli/azd/cmd/middleware/interactive_guard_test.go @@ -0,0 +1,57 @@ +// 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) + require.EqualError(t, err, + "azd pipeline config requires interactive input and cannot be run with --no-prompt: "+ + "interactive mode required") + + suggestionErr, ok := errors.AsType[*internal.ErrorWithSuggestion](err) + require.True(t, ok) + require.Contains(t, suggestionErr.Message, "No changes were made") + require.Empty(t, 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) +} From fed1dc1384d112d83dc741fc096b6eadb55c26ba Mon Sep 17 00:00:00 2001 From: ripark Date: Fri, 20 Nov 2026 13:26:11 -0800 Subject: [PATCH 5/6] Rework and go back to the middleware approach. Without it we end up having to replicate so much silliness just to report errors the same (with suggestions!). While it seeemed bad at first, just doing a manual check in auto-install is a smaller change and is the least bad of all options. --- cli/azd/cmd/actions/action_descriptor.go | 2 +- cli/azd/cmd/auto_install.go | 6 ++- cli/azd/cmd/auto_install_integration_test.go | 50 +++++++++++-------- cli/azd/cmd/middleware/interactive_guard.go | 11 ++-- .../cmd/middleware/interactive_guard_test.go | 7 +-- cli/azd/cmd/root.go | 35 ++++--------- cli/azd/cmd/root_test.go | 2 +- 7 files changed, 49 insertions(+), 64 deletions(-) diff --git a/cli/azd/cmd/actions/action_descriptor.go b/cli/azd/cmd/actions/action_descriptor.go index 1e939193383..c26a332d131 100644 --- a/cli/azd/cmd/actions/action_descriptor.go +++ b/cli/azd/cmd/actions/action_descriptor.go @@ -205,7 +205,7 @@ type ActionDescriptorOptions struct { // Whether or not the command requires a principal login RequireLogin bool // Whether the command requires interactive input. When set, the command fails before - // command preparation and execution if prompts are disabled (for example, with --no-prompt). + // 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 diff --git a/cli/azd/cmd/auto_install.go b/cli/azd/cmd/auto_install.go index f264bb7690e..8ef6f2d7999 100644 --- a/cli/azd/cmd/auto_install.go +++ b/cli/azd/cmd/auto_install.go @@ -676,8 +676,10 @@ func executeWithAutoInstallCommand( // Detect lightspeed commands from the cobra annotation set by CobraBuilder. result.IsLightspeed = foundCmd.Annotations[actions.AnnotationLightspeed] == "true" - // Let Cobra handle help and flag errors without starting update or extension work. - if blockedByNoPrompt(foundCmd, globalOpts) { + // 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 } diff --git a/cli/azd/cmd/auto_install_integration_test.go b/cli/azd/cmd/auto_install_integration_test.go index 95da8fb85e2..54c4b372dd6 100644 --- a/cli/azd/cmd/auto_install_integration_test.go +++ b/cli/azd/cmd/auto_install_integration_test.go @@ -14,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" @@ -211,33 +212,46 @@ func TestExecuteWithAutoInstall_RejectsNoPromptBeforePreparingPipeline(t *testin t.Setenv("AZURE_DEV_COLLECT_TELEMETRY", "no") t.Chdir(t.TempDir()) - // Point --cwd at a missing directory to verify that rejection leaves it uncreated. - cwd := filepath.Join(t.TempDir(), "not-created") originalArgs := os.Args t.Cleanup(func() { os.Args = originalArgs }) - os.Args = []string{"azd", "pipeline", "config", "--no-prompt", "--cwd", cwd} + 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) - require.NoDirExists(t, cwd) // 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 - missingCwd bool - flagError string + name string + args []string + help bool + flagError string }{ {name: "missing project extension"}, - {name: "missing cwd", missingCwd: true}, {name: "help", args: []string{"--help"}, help: true}, { name: "invalid flag", @@ -268,10 +282,6 @@ func TestExecuteWithAutoInstall_InteractiveRequirementBeforeExtensions(t *testin originalArgs := os.Args t.Cleanup(func() { os.Args = originalArgs }) os.Args = append([]string{"azd", "pipeline", "config", "--no-prompt"}, tt.args...) - cwd := filepath.Join(t.TempDir(), "not-created") - if tt.missingCwd { - os.Args = append(os.Args, "--cwd", cwd) - } opts := &internal.GlobalCommandOptions{} require.NoError(t, ParseGlobalFlags(os.Args[1:], opts)) container := ioc.NewNestedContainer(nil) @@ -285,9 +295,6 @@ func TestExecuteWithAutoInstall_InteractiveRequirementBeforeExtensions(t *testin root.SetErr(&stderr) root.SetArgs(os.Args[1:]) result := executeWithAutoInstallCommand(t.Context(), container, root, opts, &ExecuteResult{}) - if tt.missingCwd { - require.NoDirExists(t, cwd) - } // Help and flag errors take precedence over the interactive-mode error. switch { @@ -304,11 +311,12 @@ func TestExecuteWithAutoInstall_InteractiveRequirementBeforeExtensions(t *testin require.Equal(t, "Run 'azd pipeline config --no-prompt=false' in an interactive terminal.", suggestionErr.Suggestion) - require.Empty(t, stdout.String()) - require.Equal(t, "ERROR: interactive mode required: azd pipeline config can't run with prompts disabled. "+ + // 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", - stderr.String()) + "Suggestion: Run 'azd pipeline config --no-prompt=false' in an interactive terminal.\n\n", + stdout.String()) } }) } diff --git a/cli/azd/cmd/middleware/interactive_guard.go b/cli/azd/cmd/middleware/interactive_guard.go index 81d266cd916..9b5f76edac0 100644 --- a/cli/azd/cmd/middleware/interactive_guard.go +++ b/cli/azd/cmd/middleware/interactive_guard.go @@ -31,14 +31,11 @@ func (m *InteractiveGuardMiddleware) Run(ctx context.Context, next NextFn) (*act if m.console.IsNoPromptMode() { return nil, &internal.ErrorWithSuggestion{ Err: fmt.Errorf( - "%s requires interactive input and cannot be run with --no-prompt: %w", - m.options.CommandPath, - internal.ErrInteractiveRequired, - ), - Message: fmt.Sprintf( - "%s requires interactive input and cannot be run with --no-prompt. No changes were made.", - m.options.CommandPath, + "%w: %s can't run with prompts disabled. Prompts are disabled by --no-prompt, "+ + "and automatically in CI/CD and AI-agent environments.", + internal.ErrInteractiveRequired, m.options.CommandPath, ), + Suggestion: fmt.Sprintf("Run '%s --no-prompt=false' in an interactive terminal.", m.options.CommandPath), } } diff --git a/cli/azd/cmd/middleware/interactive_guard_test.go b/cli/azd/cmd/middleware/interactive_guard_test.go index 804c61dcea9..96960bfb7bd 100644 --- a/cli/azd/cmd/middleware/interactive_guard_test.go +++ b/cli/azd/cmd/middleware/interactive_guard_test.go @@ -31,14 +31,9 @@ func TestInteractiveGuard_RejectsNoPrompt(t *testing.T) { 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) - require.EqualError(t, err, - "azd pipeline config requires interactive input and cannot be run with --no-prompt: "+ - "interactive mode required") - suggestionErr, ok := errors.AsType[*internal.ErrorWithSuggestion](err) require.True(t, ok) - require.Contains(t, suggestionErr.Message, "No changes were made") - require.Empty(t, suggestionErr.Suggestion) + require.Equal(t, "Run 'azd pipeline config --no-prompt=false' in an interactive terminal.", suggestionErr.Suggestion) } func TestInteractiveGuard_AllowsInteractive(t *testing.T) { diff --git a/cli/azd/cmd/root.go b/cli/azd/cmd/root.go index 8d8292642f7..86ca50301f5 100644 --- a/cli/azd/cmd/root.go +++ b/cli/azd/cmd/root.go @@ -29,7 +29,6 @@ import ( "github.com/azure/azure-dev/cli/azd/internal/cmd/show" "github.com/azure/azure-dev/cli/azd/internal/telemetry" "github.com/azure/azure-dev/cli/azd/pkg/output" - outputux "github.com/azure/azure-dev/cli/azd/pkg/output/ux" "github.com/azure/azure-dev/cli/azd/pkg/ux" "github.com/spf13/cobra" ) @@ -89,27 +88,6 @@ func newRootCmd( Use: "azd", Short: fmt.Sprintf("%s is an open-source tool that helps onboard and manage your project on Azure", productName), PersistentPreRunE: func(cmd *cobra.Command, args []string) error { - if blockedByNoPrompt(cmd, opts) { - err := &internal.ErrorWithSuggestion{ - Err: fmt.Errorf( - "%w: %s can't run with prompts disabled. Prompts are disabled by --no-prompt, "+ - "and automatically in CI/CD and AI-agent environments.", - internal.ErrInteractiveRequired, cmd.CommandPath(), - ), - Suggestion: fmt.Sprintf("Run '%s --no-prompt=false' in an interactive terminal.", cmd.CommandPath()), - } - - // This runs before the UX middleware, which normally renders suggestions, so render it here - // and keep Cobra from printing the bare message a second time. - cmd.SilenceErrors = true - fmt.Fprint(cmd.ErrOrStderr(), (&outputux.ErrorWithSuggestion{ - Err: err.Err, - Suggestion: err.Suggestion, - }).ToString("")) - - return err - } - // If there was a platform configuration error report it to the user until it is resolved // Using fmt.Printf directly here since we can't leverage our IoC container to resolve a console instance if errors.Is(platform.Error, platform.ErrPlatformNotSupported) { @@ -581,10 +559,6 @@ func newRootCmd( return cmd } -func blockedByNoPrompt(cmd *cobra.Command, opts *internal.GlobalCommandOptions) bool { - return opts.NoPrompt && cmd.Annotations[actions.AnnotationRequireInteractive] == "true" -} - func registerGlobalMiddleware(root *actions.ActionDescriptor) { root. UseMiddleware("debug", middleware.NewDebugMiddleware). @@ -596,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 5eaf1f783ca..02260762c0e 100644 --- a/cli/azd/cmd/root_test.go +++ b/cli/azd/cmd/root_test.go @@ -26,7 +26,7 @@ func TestRegisterGlobalMiddleware(t *testing.T) { } require.Equal(t, []string{ - "debug", "ux", "telemetry", "error", "cancellation", "loginGuard", + "debug", "ux", "telemetry", "error", "cancellation", "interactiveGuard", "loginGuard", }, names) require.NotContains(t, names, "toolFirstRun") require.NotContains(t, names, "toolUpdateCheck") From 6ad0770f965412c62a8f94a2fd414f3092164a72 Mon Sep 17 00:00:00 2001 From: ripark Date: Fri, 20 Nov 2026 14:50:45 -0800 Subject: [PATCH 6/6] Pass the interesting test in errors_test.go - it actually inspects the Go source and expects it to conform. Also, made the error message a bit more clear. --- cli/azd/cmd/middleware/interactive_guard.go | 4 ++-- cli/azd/internal/cmd/errors_test.go | 25 ++++++++++++++------- 2 files changed, 19 insertions(+), 10 deletions(-) diff --git a/cli/azd/cmd/middleware/interactive_guard.go b/cli/azd/cmd/middleware/interactive_guard.go index 9b5f76edac0..73d5a65132e 100644 --- a/cli/azd/cmd/middleware/interactive_guard.go +++ b/cli/azd/cmd/middleware/interactive_guard.go @@ -31,9 +31,9 @@ func (m *InteractiveGuardMiddleware) Run(ctx context.Context, next NextFn) (*act if m.console.IsNoPromptMode() { return nil, &internal.ErrorWithSuggestion{ Err: fmt.Errorf( - "%w: %s can't run with prompts disabled. Prompts are disabled by --no-prompt, "+ - "and automatically in CI/CD and AI-agent environments.", + "%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), } 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