Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions cli/azd/cmd/actions/action_descriptor.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
10 changes: 9 additions & 1 deletion cli/azd/cmd/auto_install.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
128 changes: 127 additions & 1 deletion cli/azd/cmd/auto_install_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,15 @@ package cmd
import (
"bytes"
"encoding/json"
"errors"
"io"
"os"
"path/filepath"
"testing"

"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"
Expand Down Expand Up @@ -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")
Expand All @@ -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.
Expand Down
7 changes: 7 additions & 0 deletions cli/azd/cmd/cobra_builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -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{
Expand Down
43 changes: 43 additions & 0 deletions cli/azd/cmd/middleware/interactive_guard.go
Original file line number Diff line number Diff line change
@@ -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)
}
52 changes: 52 additions & 0 deletions cli/azd/cmd/middleware/interactive_guard_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
11 changes: 11 additions & 0 deletions cli/azd/cmd/pipeline.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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."),
})
}

Expand Down
15 changes: 15 additions & 0 deletions cli/azd/cmd/pipeline_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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
Expand Down
9 changes: 9 additions & 0 deletions cli/azd/cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 3 additions & 1 deletion cli/azd/cmd/root_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}
Expand Down
Loading
Loading