Repository navigation
feat(auth): interactive profile suggestion + profiles.default - #2333
Conversation
When an identity or auth command can't find its config in the base `atmos.yaml` but one or more profiles define it, Atmos now prompts (interactive) or enriches the error with hints (non-interactive) to suggest switching profiles. Covers `--identity <name>` lookups and the identity-agnostic `atmos auth login/exec/shell/env/console/whoami` flows. Also adds `profiles.default` config. Co-Authored-By: Claude Opus 4.7 <[email protected]>
|
Tip Atmos Pro
No affected stacks workflow was detected for this pull request. |
|
Important Cloud Posse Engineering Team Review RequiredThis pull request modifies files that require Cloud Posse's review. Please be patient, and a core maintainer will review your changes. To expedite this process, reach out to us on Slack in the |
Dependency Review✅ No vulnerabilities or license issues found.Scanned FilesNone |
The global --interactive flag was registered with env-var binding but
its cobra pflag was never bound to the global viper. As a result,
viper.GetBool("interactive") always returned the default true, and
passing --interactive=false on the command line was silently ignored
by callers that read the flag via viper (e.g. pkg/auth.isInteractive).
Mirror the existing --mask binding so CLI precedence works.
Co-Authored-By: Claude Opus 4.7 <[email protected]>
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughAdds interactive and non-interactive profile-fallback flows for auth failures, a Changes
Sequence Diagram(s)sequenceDiagram
participant User
participant CLI as Auth Command
participant AuthMgr as AuthManager
participant Profiles as Profile System
participant OS as OS Exec
User->>CLI: atmos auth login --identity missing-id
CLI->>AuthMgr: Authenticate(ctx, "missing-id")
AuthMgr->>AuthMgr: resolve identity -> not found
AuthMgr->>AuthMgr: maybeOfferProfileFallback(ctx, "missing-id")
AuthMgr->>Profiles: ProfilesWithIdentity("missing-id")
Profiles-->>AuthMgr: ["profile-a","profile-b"]
alt Interactive (TTY)
AuthMgr->>User: prompt select profile
User-->>AuthMgr: "profile-a"
AuthMgr->>OS: re-exec with [atmos, --profile, profile-a, ...], set ATMOS_REEXEC_DEPTH=1
OS->>OS: exec (process replaced)
else Non-Interactive
AuthMgr->>AuthMgr: build enriched ErrIdentityNotFound with profile hints
AuthMgr-->>CLI: return enriched error
end
sequenceDiagram
participant User
participant CLI as Auth Command
participant AuthMgr as AuthManager
participant Profiles as Profile System
participant OS as OS Exec
User->>CLI: atmos auth console
CLI->>AuthMgr: detect no identities
CLI->>AuthMgr: MaybeOfferAnyProfileFallback(ctx)
AuthMgr->>Profiles: ProfilesWithAuthConfig()
Profiles-->>AuthMgr: ["dev-profile","prod-profile"]
alt Interactive (TTY)
AuthMgr->>User: prompt select profile
User-->>AuthMgr: "dev-profile"
AuthMgr->>OS: re-exec with [atmos, --profile, dev-profile, ...], set ATMOS_REEXEC_DEPTH=1
OS->>OS: exec (process replaced)
else Non-Interactive
AuthMgr->>AuthMgr: build enriched ErrNoIdentitiesAvailable with hints
AuthMgr-->>CLI: return enriched error
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~50 minutes Possibly related PRs
Suggested reviewers
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 10
🧹 Nitpick comments (6)
pkg/config/profiles_identity_helpers_test.go (1)
146-148: Misplacedt.Helper()in a test function.
t.Helper()is meaningful only inside test helpers — inside the test function itself it's a no-op and a bit misleading.♻️ Proposed tweak
func TestProfilesWithIdentity_SortedOutput(t *testing.T) { - t.Helper() tmpDir := t.TempDir()🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@pkg/config/profiles_identity_helpers_test.go` around lines 146 - 148, The TestProfilesWithIdentity_SortedOutput function contains a misplaced t.Helper() call which is only meaningful inside helper functions; remove the t.Helper() invocation from TestProfilesWithIdentity_SortedOutput (or move it into any real helper function used by the test) so the test function itself does not call t.Helper(); locate the t.Helper() line in TestProfilesWithIdentity_SortedOutput and delete or relocate it to the appropriate helper function.pkg/auth/profile_fallback.go (3)
136-142:_ = ctxdead assignment reads as a compiler appeasement.
ctxis accepted but never consulted — no cancellation, no deadline respected during the (potentially blocking)form.Run(). Either plumb it through (e.g., an interrupt channel tied toctx.Done()) or drop the_ = ctxlines; the parameter is still part of the interface contract, but the unused-assignment nudge isn't earning its keep.Also applies to: 311-317
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@pkg/auth/profile_fallback.go` around lines 136 - 142, The `_ = ctx` lines are dead-assignment appeasements; either actually honor the passed context by wiring ctx.Done() into the interactive form to allow cancellation (e.g., create an interrupt channel watched by form.Run() and close it when ctx.Done() fires, or pass a context-aware reader/handler into form.Run()), or remove the unused `_ = ctx` assignments entirely; update the function(s) that accept ctx (referencing reExecWithProfile, the call to form.Run(), and the other occurrence around the 311–317 block) so the code either plumbs ctx through to form.Run() (or a cancelable interrupt channel) or drops the unused assignment.
437-446:os.Args[0]is the invocation name, not the re-exec target.You pass
exe(fromos.Executable()) toexecFuncasargv0, which is correct, butnewArgs[0]reusesos.Args[0]. That's usually fine, yet if the user invoked atmos via a symlink/alias (ato,atmos-dev), the child sees the aliased name in its ownos.Args[0]. Usually harmless, but worth a brief comment — or normalize tofilepath.Base(exe)for consistency across platforms.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@pkg/auth/profile_fallback.go` around lines 437 - 446, os.Args[0] (used as newArgs[0]) may be a symlink/alias name while exe (from os.Executable()) is the real binary passed to execFunc; normalize the argv0 passed to the re-exec by replacing newArgs[0] with filepath.Base(exe) (or at least document the choice) so the child process sees a consistent invocation name; update the construction of newArgs (and any comments) near where exe, newArgs and execFunc are used to use filepath.Base(exe) as the first arg instead of os.Args[0] (or add a brief comment explaining why keeping os.Args[0] is acceptable).
213-218:ErrUnsupportedInputTypeis a strange wrapper for generichuh.Form.Runerrors.The four
form.Run()error sites all wrap any non-ErrUserAbortederror asErrUnsupportedInputType, which is semantically misleading — a TTY resize, a rendering failure, or any other internal huh error has nothing to do with "unsupported input type." Consider a more generic sentinel (e.g.,ErrPromptFailed) or just wrap with%wagainst a purpose-fit error.Also applies to: 242-247, 381-386, 410-415
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@pkg/auth/profile_fallback.go` around lines 213 - 218, Replace the misleading ErrUnsupportedInputType wrapper used around huh.Form.Run errors with a purpose-built, generic sentinel (e.g., errUtils.ErrPromptFailed) and wrap the original error with %w using the existing errUtils.ErrWrapFormat; specifically update the error handling in the huh.Form.Run blocks (the checks that currently compare errors.Is(err, huh.ErrUserAborted) then return fmt.Errorf(errUtils.ErrWrapFormat, errUtils.ErrUnsupportedInputType, err)) to instead return fmt.Errorf(errUtils.ErrWrapFormat, errUtils.ErrPromptFailed, err) (or wrap with %w) for all occurrences referenced (the form.Run sites including the blocks around the symbols handling user abort and non-abort errors).website/blog/2026-04-16-interactive-profile-suggestion.mdx (1)
78-88:### Generic fallback for all auth commandsis nested under## Guardrails.That H3 describes a feature, not a guardrail — readers skimming the TOC will miss it. Consider promoting it to an H2 so it sits alongside "What Changed" / "Why This Matters" / "Guardrails".
♻️ Suggested
-### Generic fallback for all auth commands +## Generic fallback for all auth commands🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@website/blog/2026-04-16-interactive-profile-suggestion.mdx` around lines 78 - 88, The heading "### Generic fallback for all auth commands" is currently nested under "## Guardrails" but describes a feature and should be promoted to a top-level section; change that H3 to an H2 (replace "###" with "##" for the "Generic fallback for all auth commands" heading) and move it so it sits alongside other H2 sections like "What Changed" / "Why This Matters" / "Guardrails" to ensure it appears in the TOC as a primary section.pkg/config/profiles.go (1)
386-403: Redundant per-profile location discovery inside the loop.
ProfilesWithIdentity(andProfilesWithAuthConfigat 469–481) iterateavailableand callProfileDefinesIdentity/ProfileDefinesAuthConfigper profile, each of which re-runsdiscoverProfileLocations+findProfileDirectory. For N profiles that's O(N²) location scans and duplicateos.Statwork. Harmless for typical sizes, but easy to tighten: inline the viper load against theprofileDiryou already know fromavailable, or factor a shared helper that takes the prebuiltlocationsslice.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@pkg/config/profiles.go` around lines 386 - 403, ProfilesWithIdentity (and ProfilesWithAuthConfig) currently loop over available profiles and call ProfileDefinesIdentity/ProfileDefinesAuthConfig which re-run discoverProfileLocations + findProfileDirectory causing O(N²) scans; instead, avoid rediscovering per-profile by reusing the profileDir from available (or precomputing a shared locations slice) and loading the profile viper directly from that directory: refactor ProfilesWithIdentity and ProfilesWithAuthConfig to pass the known profileDir or locations into a new helper (or into ProfileDefinesIdentity/ProfileDefinesAuthConfig signature) so you only call discoverProfileLocations/findProfileDirectory once and then perform viper reads per profile without repeated os.Stat work.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@cmd/auth_env.go`:
- Around line 69-70: The wrapped error passed into
maybeOfferProfileFallbackOnAuthConfigError currently loses the
ErrNoDefaultIdentity sentinel because it uses fmt.Errorf with a string; change
the wrapping to use errUtils.ErrWrapFormat (the same pattern used in
auth_shell.go and auth_exec.go) so the returned error preserves the
ErrNoDefaultIdentity sentinel and isNoAuthConfigError can detect it; update the
code that creates wrapped (the fmt.Errorf line) to call
errUtils.ErrWrapFormat(ctxError, "no default identity configured and no identity
specified: %w", err) (or the equivalent ErrWrapFormat signature used in the
repo) so maybeOfferProfileFallbackOnAuthConfigError will trigger the profile
fallback correctly.
In `@cmd/auth_login.go`:
- Around line 82-89: The fallback path in cmd/auth_login.go calls
cfg.InitCliConfig with an empty schema.ConfigAndStacksInfo which causes
--profile and other global flags to be ignored and the re-exec to reload the
base config; instead, before routing into
maybeOfferProfileFallbackOnAuthConfigError ensure you pass the already-populated
global config state (or populate a schema.ConfigAndStacksInfo with the current
global flag values such as --profile, --config, --config-path, --base-path) into
cfg.InitCliConfig so the restarted command honors the selected profile; update
the code paths around AuthenticateProvider,
maybeOfferProfileFallbackOnAuthConfigError, and the InitCliConfig invocation to
use that populated ConfigAndStacksInfo rather than an empty struct.
In `@cmd/auth_whoami.go`:
- Around line 53-56: identityFromFlagOrDefault currently wraps
GetDefaultIdentity errors with ErrInvalidAuthConfig, which prevents
isNoAuthConfigError from recognizing the underlying ErrNoDefaultIdentity and
stops maybeOfferProfileFallbackOnAuthConfigError from triggering; change the
wrapping in identityFromFlagOrDefault so that when GetDefaultIdentity returns an
ErrNoDefaultIdentity (or related no-auth errors) you wrap/top-level return using
ErrNoDefaultIdentity (same pattern used in auth_shell.go and auth_exec.go) so
isNoAuthConfigError will detect it and allow
maybeOfferProfileFallbackOnAuthConfigError to run.
In `@pkg/auth/manager.go`:
- Around line 227-236: The new gate using types.SuppressAuthErrors(ctx) prevents
profile-fallback hints for auth whoami because Whoami() wraps Authenticate()
with types.WithSuppressAuthErrors(..., true); to fix, decouple suppression of
error printing from running profile fallback by changing the condition to a
distinct check (e.g., add and use a new context flag like
types.SuppressAuthProfileFallback(ctx) or invert the logic to always call
m.maybeOfferProfileFallback(ctx, identityName) unless a new explicit "suppress
fallback" flag is set); update callers or WithSuppressAuthErrors to not set the
new flag and ensure Authenticate() still respects the original
types.WithSuppressAuthErrors for printing while maybeOfferProfileFallback is
allowed to run via the new check referencing maybeOfferProfileFallback,
Authenticate, types.WithSuppressAuthErrors, and types.SuppressAuthErrors/
types.SuppressAuthProfileFallback.
In `@pkg/auth/profile_fallback.go`:
- Around line 51-53: The variable execFunc currently points to syscall.Exec
which is a stub on Windows and returns EWINDOWS at runtime; fix by making
execFunc platform-specific: create a unix build file that keeps var execFunc =
syscall.Exec (build tag //go:build unix) and a windows build file (//go:build
windows) that implements execFunc using os/exec to spawn the same binary with
os.Args and os.Environ, wait for the child, propagate its exit status (os.Exit
with child exit code) or return a clear error; alternatively, if you prefer
one-file change, add a runtime OS check around execFunc usage to return a
descriptive error when runtime.GOOS == "windows". Ensure you update the symbol
execFunc accordingly so tests can still mock it.
In `@pkg/config/load_profiles_default_test.go`:
- Around line 23-25: Replace the silent skip when the scenario fixture is
missing with a hard assertion: instead of using os.Stat(...)/os.IsNotExist(...)
and t.Skipf, call the testify/require helpers (e.g., require.NoError(t,
os.Stat(absFixture)) or require.DirExists(t, absFixture)) in the tests in
load_profiles_default_test.go so the test fails loudly when the fixture is
absent; apply the same change to the two other test cases in this file that use
the same os.Stat + t.Skipf pattern.
In `@pkg/config/profiles.go`:
- Around line 327-364: Add deferred perf tracking to each exported function that
performs I/O: insert defer perf.Track(atmosConfig,
"pkg.ProfileDefinesIdentity")() (followed by a blank line) at the top of
ProfileDefinesIdentity and do the same for ProfilesWithIdentity,
ProfileDefinesAuthConfig, and ProfilesWithAuthConfig using their respective
names ("pkg.ProfilesWithIdentity", "pkg.ProfileDefinesAuthConfig",
"pkg.ProfilesWithAuthConfig"); ensure the defer uses the atmosConfig parameter
and is placed immediately after function start (before heavy I/O like
discoverProfileLocations/loadProfileFiles).
In `@website/docs/cli/configuration/profiles.mdx`:
- Around line 52-59: There are two identical "### Precedence" headings causing
duplicate anchors and stale content; remove or rename the older section that
only mentions flag vs env (the one that omits "profiles.default") and either
merge any unique example text into the new full Precedence block (which lists:
--profile, ATMOS_PROFILE, profiles.default, No profile) or rename the old
heading to "### Flag vs. Environment Variable" and delete the redundant rule so
only the canonical "### Precedence" section (including mention of
profiles.default) remains.
In `@website/src/data/roadmap.js`:
- Line 220: Update the roadmap entry object for "Interactive profile suggestion
for missing identities" by adding a pr property set to 2333 (i.e. pr: 2333)
inside that existing object literal (the entry that has label 'Interactive
profile suggestion for missing identities' and status 'shipped'), and while
you’re editing confirm the changelog field 'interactive-profile-suggestion'
remains correct and update the related initiative's progress percentage if
required by the new shipped milestone.
---
Nitpick comments:
In `@pkg/auth/profile_fallback.go`:
- Around line 136-142: The `_ = ctx` lines are dead-assignment appeasements;
either actually honor the passed context by wiring ctx.Done() into the
interactive form to allow cancellation (e.g., create an interrupt channel
watched by form.Run() and close it when ctx.Done() fires, or pass a
context-aware reader/handler into form.Run()), or remove the unused `_ = ctx`
assignments entirely; update the function(s) that accept ctx (referencing
reExecWithProfile, the call to form.Run(), and the other occurrence around the
311–317 block) so the code either plumbs ctx through to form.Run() (or a
cancelable interrupt channel) or drops the unused assignment.
- Around line 437-446: os.Args[0] (used as newArgs[0]) may be a symlink/alias
name while exe (from os.Executable()) is the real binary passed to execFunc;
normalize the argv0 passed to the re-exec by replacing newArgs[0] with
filepath.Base(exe) (or at least document the choice) so the child process sees a
consistent invocation name; update the construction of newArgs (and any
comments) near where exe, newArgs and execFunc are used to use
filepath.Base(exe) as the first arg instead of os.Args[0] (or add a brief
comment explaining why keeping os.Args[0] is acceptable).
- Around line 213-218: Replace the misleading ErrUnsupportedInputType wrapper
used around huh.Form.Run errors with a purpose-built, generic sentinel (e.g.,
errUtils.ErrPromptFailed) and wrap the original error with %w using the existing
errUtils.ErrWrapFormat; specifically update the error handling in the
huh.Form.Run blocks (the checks that currently compare errors.Is(err,
huh.ErrUserAborted) then return fmt.Errorf(errUtils.ErrWrapFormat,
errUtils.ErrUnsupportedInputType, err)) to instead return
fmt.Errorf(errUtils.ErrWrapFormat, errUtils.ErrPromptFailed, err) (or wrap with
%w) for all occurrences referenced (the form.Run sites including the blocks
around the symbols handling user abort and non-abort errors).
In `@pkg/config/profiles_identity_helpers_test.go`:
- Around line 146-148: The TestProfilesWithIdentity_SortedOutput function
contains a misplaced t.Helper() call which is only meaningful inside helper
functions; remove the t.Helper() invocation from
TestProfilesWithIdentity_SortedOutput (or move it into any real helper function
used by the test) so the test function itself does not call t.Helper(); locate
the t.Helper() line in TestProfilesWithIdentity_SortedOutput and delete or
relocate it to the appropriate helper function.
In `@pkg/config/profiles.go`:
- Around line 386-403: ProfilesWithIdentity (and ProfilesWithAuthConfig)
currently loop over available profiles and call
ProfileDefinesIdentity/ProfileDefinesAuthConfig which re-run
discoverProfileLocations + findProfileDirectory causing O(N²) scans; instead,
avoid rediscovering per-profile by reusing the profileDir from available (or
precomputing a shared locations slice) and loading the profile viper directly
from that directory: refactor ProfilesWithIdentity and ProfilesWithAuthConfig to
pass the known profileDir or locations into a new helper (or into
ProfileDefinesIdentity/ProfileDefinesAuthConfig signature) so you only call
discoverProfileLocations/findProfileDirectory once and then perform viper reads
per profile without repeated os.Stat work.
In `@website/blog/2026-04-16-interactive-profile-suggestion.mdx`:
- Around line 78-88: The heading "### Generic fallback for all auth commands" is
currently nested under "## Guardrails" but describes a feature and should be
promoted to a top-level section; change that H3 to an H2 (replace "###" with
"##" for the "Generic fallback for all auth commands" heading) and move it so it
sits alongside other H2 sections like "What Changed" / "Why This Matters" /
"Guardrails" to ensure it appears in the TOC as a primary section.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: c2945bae-9f0b-4693-b489-6c687d09a3ce
📒 Files selected for processing (31)
cmd/auth_console.gocmd/auth_console_test.gocmd/auth_env.gocmd/auth_exec.gocmd/auth_login.gocmd/auth_profile_fallback.gocmd/auth_shell.gocmd/auth_whoami.godocs/prd/interactive-profile-suggestion.mdinternal/exec/terraform_output_utils.gopkg/auth/hooks_test.gopkg/auth/identities/aws/assume_role_test.gopkg/auth/identities/aws/assume_root_test.gopkg/auth/manager.gopkg/auth/profile_fallback.gopkg/auth/profile_fallback_test.gopkg/auth/providers/aws/saml_test.gopkg/auth/types/interfaces.gopkg/auth/types/mock_interfaces.gopkg/config/load.gopkg/config/load_profiles_default_test.gopkg/config/profiles.gopkg/config/profiles_identity_helpers_test.gopkg/schema/schema.gotests/fixtures/scenarios/config-profiles-default/atmos.yamltests/fixtures/scenarios/config-profiles-default/profiles/developer/settings.yamltests/fixtures/scenarios/config-profiles-default/profiles/production/settings.yamltools/lintroller/rule_os_args.gowebsite/blog/2026-04-16-interactive-profile-suggestion.mdxwebsite/docs/cli/configuration/profiles.mdxwebsite/src/data/roadmap.js
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #2333 +/- ##
==========================================
+ Coverage 77.30% 77.38% +0.07%
==========================================
Files 1084 1089 +5
Lines 102466 102828 +362
==========================================
+ Hits 79212 79569 +357
+ Misses 18890 18887 -3
- Partials 4364 4372 +8
Flags with carried forward coverage won't be shown. Click here to find out more.
🚀 New features to boost your workflow:
|
Consolidate duplicated re-exec and --chdir argv/env stripping logic from three independent call sites into a new pkg/reexec package: - StripChdirArgs handles all five flag forms (--chdir VAL, --chdir=VAL, -C VAL, -C=VAL, and the previously-missing concatenated -Cvalue form) - FilterChdirEnv removes ATMOS_CHDIR and appends an empty override so a child cannot re-apply the parent's value via env precedence - Exec provides a platform-neutral syscall.Exec on Unix and an exec.Command().Run() + os.Exit(code) shim on Windows, injectable via the package-level var for tests Migrates three call sites to the shared package: - pkg/version/reexec.go (fixes missing Windows shim and -Cvalue bug) - pkg/auth/profile_fallback.go (fixes --chdir double-apply in re-exec'd child) - cmd/cmd_utils.go alias re-exec Also includes related interactive-profile-select branch work for auth manager, config profiles, and whoami/env commands. Co-Authored-By: Claude Opus 4.7 <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (6)
cmd/auth_whoami.go (1)
50-55: Considercmd.Context()for cancellation propagation.Small nit —
auth_env.gousescmd.Context()for the same fallback call, which carries Cobra's cancellation signal (Ctrl+C handling during the interactive prompt). Usingcontext.Background()here works but drops that plumbing. Since the fallback path can launch an interactive prompt, propagating the command context would be a touch friendlier.♻️ Optional tweak
- ctx := context.Background() - + ctx := cmd.Context() + // Determine identity. identityName, err := identityFromFlagOrDefault(cmd, authManager) if err != nil { return maybeOfferProfileFallbackOnAuthConfigError(ctx, authManager, err) }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@cmd/auth_whoami.go` around lines 50 - 55, Replace the local background context with the Cobra command's context so cancellation/interrupts propagate into the fallback interactive flow: in cmd/auth_whoami.go, use cmd.Context() instead of context.Background() when creating ctx before calling identityFromFlagOrDefault and maybeOfferProfileFallbackOnAuthConfigError so the interactive prompt in maybeOfferProfileFallbackOnAuthConfigError receives the command cancellation signal.website/docs/cli/configuration/profiles.mdx (1)
291-315: Interactive Profile Suggestion section reads well and is implementation-accurate.The two flows (identity-specific vs. generic auth fallback), the interactive-vs-non-interactive split, the "explicit
--profile/ATMOS_PROFILEsuppresses prompts butprofiles.defaultdoes not", and theATMOS_PROFILE_FALLBACK=1loop guard all matchpkg/auth/profile_fallback.go(loopGuardActive,reexecWithProfileAndGuard,maybeOfferAnyProfileFallback).One tiny wording nit you can take or leave: line 299 says the picked profile is "prepended to your original arguments", but
setOrAddProfileArgreplaces an existing--profilein argv if present and otherwise adds it — so "prepended or replacing any existing--profile" would be marginally more precise. Not a blocker.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@website/docs/cli/configuration/profiles.mdx` around lines 291 - 315, The doc text claiming the picked profile is "prepended to your original arguments" is slightly inaccurate because the implementation (setOrAddProfileArg) will replace an existing --profile arg instead of always prepending; update the wording in the "Identity-specific suggestion" sentence to say something like "prepended or replacing any existing --profile" to match setOrAddProfileArg and the re-exec behavior (see setOrAddProfileArg and reexecWithProfileAndGuard for reference).cmd/alias_test.go (1)
84-138: Subtest name no longer matches what's being tested.The subtest is labeled
"filterChdirArgs removes chdir flags"but the call is nowreexec.StripChdirArgs. Same story for"filterChdirEnv removes ATMOS_CHDIR from environment"below. Harmless, but future grep-by-name will miss it.🏷️ Proposed rename
- t.Run("filterChdirArgs removes chdir flags", func(t *testing.T) { + t.Run("StripChdirArgs removes chdir flags", func(t *testing.T) { ... - t.Run("filterChdirEnv removes ATMOS_CHDIR from environment", func(t *testing.T) { + t.Run("FilterChdirEnv removes ATMOS_CHDIR from environment", func(t *testing.T) {Also note: this test duplicates coverage already in
pkg/reexec/chdir_test.go. Keeping an alias-level smoke test is fine, but you could slim it to one case per function and rely on the reexec package tests for exhaustive coverage.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@cmd/alias_test.go` around lines 84 - 138, Rename the subtest labels to match the functions under test and optionally reduce duplication: update the t.Run main description from "filterChdirArgs removes chdir flags" to reference reexec.StripChdirArgs (e.g., "StripChdirArgs removes chdir flags") and similarly rename the other subtest currently saying "filterChdirEnv removes ATMOS_CHDIR from environment" to reference reexec.StripChdirEnv; if desired, shrink the test matrix to one representative case per alias-level test since pkg/reexec/chdir_test.go already has exhaustive coverage. Ensure the referenced symbols reexec.StripChdirArgs and reexec.StripChdirEnv are used in the renamed subtest names so future grep-by-name finds them.pkg/reexec/chdir.go (1)
41-45: Short-flag prefix check is greedy enough to risk future collisions.
strings.HasPrefix(arg, "-C") && len(arg) > 2matches every short-flag token starting with-C(e.g., a hypothetical-Color,-Credentials). Atmos doesn't have such flags today, but if one is ever added under a subcommand withDisableFlagParsing, this will silently strip it.A cheap hardening: require the next rune to look like a value (anything non-alpha) or simply document the constraint. Optional, not blocking.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@pkg/reexec/chdir.go` around lines 41 - 45, The short-flag prefix check in the arg loop is too greedy; replace the condition (strings.HasPrefix(arg, "-C") && len(arg) > 2) with a guarded check that the character/rune after "-C" looks like a value (not an ASCII/Unicode letter) to avoid stripping longer flags like "-Color"; e.g. decode the next rune (utf8.DecodeRuneInString(arg[2:])) and only treat it as a "-C" value form when that rune is not a letter (use unicode.IsLetter) or when it is '='; update pkg/reexec/chdir.go accordingly and add the required imports (unicode, utf8).pkg/version/reexec_test.go (1)
772-796: LGTM.Good that the concatenated
-C../foocase is now asserted end-to-end throughreexec.StripChdirArgs+stripUseVersionFlags. If you adopt the--separator fix inpkg/reexec/chdir.go, consider adding one case here with a trailing--to lock in pass-through behavior across the combined pipeline.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@pkg/version/reexec_test.go` around lines 772 - 796, Add one more subcase to TestStripBothChdirAndUseVersionFlags that includes a trailing "--" separator to verify pass-through behavior when combining reexec.StripChdirArgs and stripUseVersionFlags; construct args similar to the existing cases but include "--" before the command (e.g. "atmos", "--chdir=...", "--use-version=...", "--", "terraform", "plan"), run result := reexec.StripChdirArgs(args) then result = stripUseVersionFlags(result) and assert the output equals []string{"atmos", "terraform", "plan"} to lock in the separator handling across the pipeline.pkg/version/reexec.go (1)
48-52: LGTM on the alias-with-deprecation.Type alias keeps source compatibility while steering new code to
reexec.ExecFunc. Consider adding a//lint:ignoreor follow-up issue tag to actually remove it on the next minor bump so the deprecation doesn't linger forever.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@pkg/version/reexec.go` around lines 48 - 52, Add a short TODO + tracking note and (optionally) a lint-ignore above the type alias to mark it for removal later: place a comment immediately above the ExecFunc alias that says something like "TODO: remove ExecFunc alias in next minor release (follow-up issue `#NNN`)" and, if you want to suppress deprecation/lint noise, add a lint-ignore directive on the same comment (e.g. "//lint:ignore <rule> keep alias for source compatibility") referencing the ExecFunc = reexec.ExecFunc alias so future maintainers know to remove it.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@pkg/reexec/chdir.go`:
- Around line 28-58: StripChdirArgs currently continues scanning past the
end-of-flags marker ("--") and may drop or consume positional args that should
be forwarded; update StripChdirArgs to detect a literal "--" token and, when
seen, append that token and all remaining args unchanged to filtered and break
out of the loop so no further flag-stripping or skipNext consumption occurs;
ensure this preserves behavior of the existing handling for "--chdir", "-C", and
their values when encountered before the "--" marker.
---
Nitpick comments:
In `@cmd/alias_test.go`:
- Around line 84-138: Rename the subtest labels to match the functions under
test and optionally reduce duplication: update the t.Run main description from
"filterChdirArgs removes chdir flags" to reference reexec.StripChdirArgs (e.g.,
"StripChdirArgs removes chdir flags") and similarly rename the other subtest
currently saying "filterChdirEnv removes ATMOS_CHDIR from environment" to
reference reexec.StripChdirEnv; if desired, shrink the test matrix to one
representative case per alias-level test since pkg/reexec/chdir_test.go already
has exhaustive coverage. Ensure the referenced symbols reexec.StripChdirArgs and
reexec.StripChdirEnv are used in the renamed subtest names so future
grep-by-name finds them.
In `@cmd/auth_whoami.go`:
- Around line 50-55: Replace the local background context with the Cobra
command's context so cancellation/interrupts propagate into the fallback
interactive flow: in cmd/auth_whoami.go, use cmd.Context() instead of
context.Background() when creating ctx before calling identityFromFlagOrDefault
and maybeOfferProfileFallbackOnAuthConfigError so the interactive prompt in
maybeOfferProfileFallbackOnAuthConfigError receives the command cancellation
signal.
In `@pkg/reexec/chdir.go`:
- Around line 41-45: The short-flag prefix check in the arg loop is too greedy;
replace the condition (strings.HasPrefix(arg, "-C") && len(arg) > 2) with a
guarded check that the character/rune after "-C" looks like a value (not an
ASCII/Unicode letter) to avoid stripping longer flags like "-Color"; e.g. decode
the next rune (utf8.DecodeRuneInString(arg[2:])) and only treat it as a "-C"
value form when that rune is not a letter (use unicode.IsLetter) or when it is
'='; update pkg/reexec/chdir.go accordingly and add the required imports
(unicode, utf8).
In `@pkg/version/reexec_test.go`:
- Around line 772-796: Add one more subcase to
TestStripBothChdirAndUseVersionFlags that includes a trailing "--" separator to
verify pass-through behavior when combining reexec.StripChdirArgs and
stripUseVersionFlags; construct args similar to the existing cases but include
"--" before the command (e.g. "atmos", "--chdir=...", "--use-version=...", "--",
"terraform", "plan"), run result := reexec.StripChdirArgs(args) then result =
stripUseVersionFlags(result) and assert the output equals []string{"atmos",
"terraform", "plan"} to lock in the separator handling across the pipeline.
In `@pkg/version/reexec.go`:
- Around line 48-52: Add a short TODO + tracking note and (optionally) a
lint-ignore above the type alias to mark it for removal later: place a comment
immediately above the ExecFunc alias that says something like "TODO: remove
ExecFunc alias in next minor release (follow-up issue `#NNN`)" and, if you want to
suppress deprecation/lint noise, add a lint-ignore directive on the same comment
(e.g. "//lint:ignore <rule> keep alias for source compatibility") referencing
the ExecFunc = reexec.ExecFunc alias so future maintainers know to remove it.
In `@website/docs/cli/configuration/profiles.mdx`:
- Around line 291-315: The doc text claiming the picked profile is "prepended to
your original arguments" is slightly inaccurate because the implementation
(setOrAddProfileArg) will replace an existing --profile arg instead of always
prepending; update the wording in the "Identity-specific suggestion" sentence to
say something like "prepended or replacing any existing --profile" to match
setOrAddProfileArg and the re-exec behavior (see setOrAddProfileArg and
reexecWithProfileAndGuard for reference).
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: f4990b7f-b709-4613-87ed-b8c206fe39b9
📒 Files selected for processing (20)
cmd/alias_test.gocmd/auth_env.gocmd/auth_whoami.gocmd/cmd_utils.gocmd/cmd_utils_test.gopkg/auth/manager.gopkg/auth/profile_fallback.gopkg/auth/profile_fallback_test.gopkg/config/load_profiles_default_test.gopkg/config/profiles.gopkg/reexec/chdir.gopkg/reexec/chdir_test.gopkg/reexec/exec.gopkg/reexec/exec_test.gopkg/reexec/exec_unix.gopkg/reexec/exec_windows.gopkg/version/reexec.gopkg/version/reexec_test.gowebsite/docs/cli/configuration/profiles.mdxwebsite/src/data/roadmap.js
✅ Files skipped from review due to trivial changes (6)
- pkg/reexec/exec.go
- cmd/cmd_utils_test.go
- website/src/data/roadmap.js
- pkg/reexec/chdir_test.go
- pkg/auth/profile_fallback_test.go
- pkg/auth/profile_fallback.go
🚧 Files skipped from review as they are similar to previous changes (3)
- pkg/auth/manager.go
- pkg/config/load_profiles_default_test.go
- pkg/config/profiles.go
Replace two separate re-exec loop-guard env vars with a single shared ATMOS_REEXEC_DEPTH counter in pkg/reexec: - ATMOS_PROFILE_FALLBACK (auth) — binary "we re-exec'd, don't loop" - ATMOS_REEXEC_GUARD (version) — version-string match check The new Depth/CurrentDepth/NextEnv helpers let both call sites detect "am I inside a re-exec'd child?" with identical semantics. Version's guard loses its version-string-matching precision, but gains a harder guarantee: depth > 0 prevents any further re-exec regardless of what the child's atmos.yaml asks for, eliminating loop risk. "Fallback" was a misleading name for what is really a loop-guard depth counter, and having two separate env vars doing the same job was pure duplication. Co-Authored-By: Claude Opus 4.7 <[email protected]>
There was a problem hiding this comment.
🧹 Nitpick comments (3)
pkg/reexec/depth_test.go (1)
95-110: Nit:strings.HasPrefixwould mirror the production check.
depth.go:55usesstrings.HasPrefix(kv, DepthEnvVar+"="); using the same idiom here makes the intent obvious and drops the length arithmetic.+ prefix := DepthEnvVar + "=" for _, kv := range result { - if len(kv) >= len(DepthEnvVar)+1 && kv[:len(DepthEnvVar)+1] == DepthEnvVar+"=" { + if strings.HasPrefix(kv, prefix) { count++ lastDepth = kv } } ... for _, kv := range tt.input { - if len(kv) >= len(DepthEnvVar)+1 && kv[:len(DepthEnvVar)+1] == DepthEnvVar+"=" { + if strings.HasPrefix(kv, prefix) { continue } assert.Contains(t, result, kv, "non-depth entry must be preserved") }(Would require adding the
stringsimport.)🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@pkg/reexec/depth_test.go` around lines 95 - 110, Replace the manual prefix check "len(kv) >= len(DepthEnvVar)+1 && kv[:len(DepthEnvVar)+1] == DepthEnvVar+\"=\" " with strings.HasPrefix(kv, DepthEnvVar+\"=\") in the loops that inspect kv (used alongside variables result and lastDepth) so the test mirrors the production check in depth.go; add the strings import to the test file imports. Ensure both places (the counting loop and the non-depth-preservation loop) use strings.HasPrefix(kv, DepthEnvVar+"=").pkg/version/reexec.go (1)
242-264: Considerreexec.NextEnvinstead ofSetEnv+Environ()for depth propagation.The new
pkg/reexecpackage already shipsNextEnv(used bypkg/auth/profile_fallback.go:446) that handles the increment/collapse semantics on a local env slice without mutating the parent process. Two downsides of the current approach:
cfg.SetEnv(defaultos.Setenv) mutates the parent's env, so ifcfg.ExecFnreturns an error on L261 the counter stays incremented in the orphaned parent.- Two call sites now express the same guard two different ways, which makes future changes to the semantics brittle.
♻️ Proposed shape
- // Increment re-exec depth so the child knows it's inside a re-exec and - // must not attempt another version switch. - nextDepth := reexec.Depth(cfg.GetEnv(reexec.DepthEnvVar)) + 1 - if err := cfg.SetEnv(reexec.DepthEnvVar, strconv.Itoa(nextDepth)); err != nil { - log.Warn("Failed to set re-exec depth", "error", err) - return false - } - // Re-exec with the new binary. ui.Successf("Switching to Atmos version `%s`", requestedVersion) // Strip flags that shouldn't be passed to the target version. args := reexec.StripChdirArgs(cfg.Args) args = stripUseVersionFlags(args) - if err := cfg.ExecFn(binaryPath, args, cfg.Environ()); err != nil { + if err := cfg.ExecFn(binaryPath, args, reexec.NextEnv(cfg.Environ())); err != nil { ui.Errorf("Failed to exec %s: %v", binaryPath, err) return false }This also lets you drop the
strconvimport and theSetEnvtouch inTestCheckAndReexecWithConfig_GuardIsSet(the depth would instead be asserted by inspectingenvvinExecFn).🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@pkg/version/reexec.go` around lines 242 - 264, Replace the current SetEnv+Environ depth propagation with reexec.NextEnv to avoid mutating the parent env and to centralize depth semantics: compute nextDepth using reexec.Depth(cfg.GetEnv(reexec.DepthEnvVar))+1, then call reexec.NextEnv(cfg.Environ(), reexec.DepthEnvVar, strconv.Itoa(nextDepth)) (or equivalent NextEnv overload) and pass that returned slice into cfg.ExecFn(binaryPath, args, envSlice) instead of calling cfg.SetEnv and cfg.Environ(); keep the same guard variables (reexec.DepthEnvVar, reexec.Depth) and preserve argv stripping (reexec.StripChdirArgs / stripUseVersionFlags) and error handling around cfg.ExecFn so behavior is unchanged but parent env is not mutated.pkg/auth/profile_fallback.go (1)
84-137: Unusedctxparameter — consider dropping it (or wiring it in).Both
maybeOfferProfileFallbackandmaybeOfferAnyProfileFallbackaccept actx context.Contextthat's never consulted — the_ = ctxafter the unreachable re-exec (L135, L310) makes it explicit. Per the coding guideline,context.Contextshould be used for cancellation/deadlines, not carried around for its own sake.Two options:
- Drop
ctxfrom the unexported helpers.MaybeOfferAnyProfileFallback(ctx)can keep it for its public shape and simply not forward it.- Forward it into
cfg.ProfilesWith…and the promptform.Run()path once those helpers support cancellation.Not a blocker for this PR — flagging for hygiene.
As per coding guidelines: "Use
context.ContextONLY for cancellation signals, deadlines/timeouts, and request-scoped values ... Do NOT use context for ... avoiding proper function parameters."🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@pkg/auth/profile_fallback.go` around lines 84 - 137, The ctx parameter is unused in maybeOfferProfileFallback (and maybeOfferAnyProfileFallback); either remove it from these unexported helpers or thread it into cancelable calls — specifically, delete the ctx argument from manager.maybeOfferProfileFallback and manager.maybeOfferAnyProfileFallback and update all internal callers to call the no-ctx variants (keeping the public MaybeOfferAnyProfileFallback(ctx) signature if needed), or alternatively pass ctx into cfg.ProfilesWithIdentity and into promptForProfileSelection/form.Run if those APIs are changed to accept cancellation; locate uses by the function names maybeOfferProfileFallback, maybeOfferAnyProfileFallback, cfg.ProfilesWithIdentity, and promptForProfileSelection to make the minimal edits and update call sites accordingly.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@pkg/auth/profile_fallback.go`:
- Around line 84-137: The ctx parameter is unused in maybeOfferProfileFallback
(and maybeOfferAnyProfileFallback); either remove it from these unexported
helpers or thread it into cancelable calls — specifically, delete the ctx
argument from manager.maybeOfferProfileFallback and
manager.maybeOfferAnyProfileFallback and update all internal callers to call the
no-ctx variants (keeping the public MaybeOfferAnyProfileFallback(ctx) signature
if needed), or alternatively pass ctx into cfg.ProfilesWithIdentity and into
promptForProfileSelection/form.Run if those APIs are changed to accept
cancellation; locate uses by the function names maybeOfferProfileFallback,
maybeOfferAnyProfileFallback, cfg.ProfilesWithIdentity, and
promptForProfileSelection to make the minimal edits and update call sites
accordingly.
In `@pkg/reexec/depth_test.go`:
- Around line 95-110: Replace the manual prefix check "len(kv) >=
len(DepthEnvVar)+1 && kv[:len(DepthEnvVar)+1] == DepthEnvVar+\"=\" " with
strings.HasPrefix(kv, DepthEnvVar+\"=\") in the loops that inspect kv (used
alongside variables result and lastDepth) so the test mirrors the production
check in depth.go; add the strings import to the test file imports. Ensure both
places (the counting loop and the non-depth-preservation loop) use
strings.HasPrefix(kv, DepthEnvVar+"=").
In `@pkg/version/reexec.go`:
- Around line 242-264: Replace the current SetEnv+Environ depth propagation with
reexec.NextEnv to avoid mutating the parent env and to centralize depth
semantics: compute nextDepth using
reexec.Depth(cfg.GetEnv(reexec.DepthEnvVar))+1, then call
reexec.NextEnv(cfg.Environ(), reexec.DepthEnvVar, strconv.Itoa(nextDepth)) (or
equivalent NextEnv overload) and pass that returned slice into
cfg.ExecFn(binaryPath, args, envSlice) instead of calling cfg.SetEnv and
cfg.Environ(); keep the same guard variables (reexec.DepthEnvVar, reexec.Depth)
and preserve argv stripping (reexec.StripChdirArgs / stripUseVersionFlags) and
error handling around cfg.ExecFn so behavior is unchanged but parent env is not
mutated.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 85cc560e-d9f2-41ac-a9b5-8dc7bb383045
📒 Files selected for processing (7)
pkg/auth/profile_fallback.gopkg/auth/profile_fallback_test.gopkg/auth/types/interfaces.gopkg/reexec/depth.gopkg/reexec/depth_test.gopkg/version/reexec.gopkg/version/reexec_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
- pkg/auth/types/interfaces.go
Tokens after the POSIX `--` separator are positional and must be forwarded verbatim to downstream tools (terraform, helmfile, packer, custom commands). Previously StripChdirArgs kept scanning past `--`, so a user-supplied `-C`, `-Cfile`, `--chdir`, or `--chdir=...` meant for the child tool would be silently dropped or consumed along with the following token. Once `--` is encountered, forward it and every remaining arg unchanged. Co-Authored-By: Claude Opus 4.7 <[email protected]>
Replace back-to-back CheckErrorAndPrint + CheckErrorPrintAndExit with a single rich error built via errUtils.Build, carrying the explanation, hint, context, and exit code. Prior behavior printed two nearly- identical error blocks; a recent SuppressAuthErrors gate hid the inner block entirely, leaving only a bare "identity not found" line. Co-Authored-By: Claude Opus 4.7 <[email protected]>
… subcommands
Every auth subcommand passed an empty schema.ConfigAndStacksInfo{} to
InitCliConfig, silently dropping the parent's already-parsed
--config, --base-path, and --config-path flags. After the profile-picker
re-exec, the child process therefore couldn't find the custom config file
that the parent used, reproducing the same ErrInvalidAuthConfig that
triggered the picker in the first place.
Introduce newAuthConfigAndStacksInfo(cmd) in cmd/auth_config.go that reads
the three global flags via the existing flags.ParseGlobalFlags helper
(same pattern as cmd/auth_list.go). Route every auth subcommand's
InitCliConfig call through it.
Co-Authored-By: Claude Opus 4.7 <[email protected]>
Adds targeted tests for the fallback dispatcher, the new newAuthConfigAndStacksInfo helper, the shared identity-resolution helper that every auth subcommand relies on, and the public profile-discovery helpers in pkg/config. Coverage improvements: - cmd/auth_config.go: 100% - cmd/auth_profile_fallback.go: 100% (isNoAuthConfigError + dispatcher) - pkg/auth/profile_fallback.go: MaybeOfferAnyProfileFallback 0->100%, newProfileFallbackKeyMap 0->100%, plus reExecWithProfile regression guards that verify --chdir is stripped from argv and ATMOS_CHDIR is emitted as an empty override (not inherited) on re-exec - pkg/config/profiles.go: ProfilesWithIdentity 78.9->89.5%, ProfilesWithAuthConfig 78.9->89.5%, ProfileDefinesAuthConfig 86.4->90.9% The identity-flow test drives GetIdentityFromFlags through cobra and viper rather than os.Args to avoid global-state races across tests. Co-Authored-By: Claude Opus 4.7 <[email protected]>
Addressing CodeRabbit feedbackPushed Claim 1:
|
There was a problem hiding this comment.
🧹 Nitpick comments (5)
pkg/config/profiles_public_test.go (1)
1-239: LGTM — solid coverage for the new profile-discovery helpers.Fixture is compact and reused cleanly across all three helper tests, nil/whitespace/not-found contracts are exercised, sorted-output expectations match the
sort.Stringsbehavior inpkg/config/profiles.go, and the malformed-YAML skip paths are asserted by outcome (valid profiles still returned) rather than by coupling to loader internals. Table-driven classification test at lines 217-238 is a nice touch.One tiny optional thought: the two malformed-YAML blocks (lines 102-108 and 163-169) are identical — if a third caller shows up, consider extracting a
writeBrokenProfile(t, tmpDir, name)helper. Not worth doing for just two call sites.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@pkg/config/profiles_public_test.go` around lines 1 - 239, Two identical malformed-YAML test setups are duplicated in TestProfilesWithIdentity and TestProfilesWithAuthConfig; extract a small helper (e.g., writeBrokenProfile(t *testing.T, tmpDir, name string)) and use it from both tests to create the "broken" profile directory and atmos.yaml so duplication is removed; update the two call sites to call writeBrokenProfile and keep existing assertions and temp-dir usage (references: profilesPublicTestFixture, TestProfilesWithIdentity, TestProfilesWithAuthConfig).cmd/auth_identity_flow_test.go (3)
139-142: Minor:assert.Sameis a tighter fit thanassert.Equalhere.
maybeOfferProfileFallbackOnAuthConfigErrorreturns the fallback error instance unchanged, so identity equality is the actual contract.assert.Same(t, fallbackInvoked, result, ...)expresses that intent directly and would catch an accidental wrap/copy thatassert.Equalon*errors.errorStringmight still let through in edge cases.- assert.Equal(t, fallbackInvoked, result, - "when the fallback returns an error, it must propagate to the caller unchanged") + assert.Same(t, fallbackInvoked, result, + "when the fallback returns an error, it must propagate to the caller unchanged")🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@cmd/auth_identity_flow_test.go` around lines 139 - 142, The test should assert identity equality rather than value equality: in the assertion for the fallback error returned by maybeOfferProfileFallbackOnAuthConfigError, replace assert.Equal(t, fallbackInvoked, result, ...) with assert.Same(t, fallbackInvoked, result, ...) so the test verifies the exact same error instance (fallbackInvoked) is propagated unchanged by maybeOfferProfileFallbackOnAuthConfigError.
48-107: Missing coverage for theforceSelect(__SELECT__) branch.
identityFromFlagOrDefaulthas three distinct branches driven byGetIdentityFromFlags:
- explicit identity (covered ✅),
- flag unset → default identity (covered ✅),
- flag equals
IdentityFlagSelectValue(__SELECT__) →forceSelect=true, which bypasses the early return and callsGetDefaultIdentity(true)(not covered).The third branch has distinct behavior — it forces interactive selection and passes
trueinstead offalse— and is precisely the kind of recovery/opt-in path the guidelines ask to pin down with a negative/positive pair. Consider adding a subtest:♻️ Suggested subtest
t.Run("flag set to __SELECT__ calls GetDefaultIdentity(true) for interactive selection", func(t *testing.T) { _ = NewTestKit(t) resetIdentityViper(t) ctrl := gomock.NewController(t) defer ctrl.Finish() m := types.NewMockAuthManager(ctrl) m.EXPECT().GetDefaultIdentity(true).Return("picked-id", nil) cmd := newIdentityFlowTestCmd(t) require.NoError(t, cmd.Flags().Set(IdentityFlagName, IdentityFlagSelectValue)) got, err := identityFromFlagOrDefault(cmd, m) require.NoError(t, err) assert.Equal(t, "picked-id", got) })Based on learnings: "Include negative-path tests for recovery logic: whenever a test verifies that a recovery/fallback triggers under condition X, add a corresponding test that verifies the recovery does NOT trigger when condition X is absent."
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@cmd/auth_identity_flow_test.go` around lines 48 - 107, Missing coverage for the branch where the identity flag is set to IdentityFlagSelectValue (__SELECT__), which should set forceSelect=true and call m.GetDefaultIdentity(true); add a subtest to TestIdentityFromFlagOrDefault that resets viper (resetIdentityViper), creates a mock AuthManager (types.NewMockAuthManager) expecting GetDefaultIdentity(true).Return("picked-id", nil), sets the flag on the command (newIdentityFlowTestCmd and cmd.Flags().Set(IdentityFlagName, IdentityFlagSelectValue)), calls identityFromFlagOrDefault(cmd, m) and asserts no error and the returned value equals "picked-id".
33-39: Global viper mutation — worth a heads-up comment about parallelism.
resetIdentityVipermutates the globalviper.GetViper()singleton. That's fine today because these subtests don't callt.Parallel(), but the helper's doc block on lines 18–23 actively encourages driving through viper. If a future contributor addst.Parallel()to any subtest here (or to another test in thecmdpackage that touches theidentitykey), the restore-on-cleanup contract becomes racy.Consider a one-liner in the doc comment making that invariant explicit, e.g. "callers must not use
t.Parallel()", so the constraint is discoverable at the call site.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@cmd/auth_identity_flow_test.go` around lines 33 - 39, The helper resetIdentityViper mutates the global viper.GetViper() singleton and relies on t.Cleanup to restore IdentityFlagName, so update its top doc comment (the existing block around lines 18–23) to add a single explicit sentence: callers must not call t.Parallel() (or otherwise run in parallel) when using resetIdentityViper because it mutates the global viper state and relies on serial test execution to restore IdentityFlagName.cmd/auth_profile_fallback_test.go (1)
118-126: Prefererrors.Is/assert.Sameover string equality for the pass-through cases.For the "original error returned" cases,
gotis the exact same instance astt.err(the function returns the caller's err unchanged), so comparing.Error()strings works but is indirect and brittle. For the "ErrNoIdentitiesAvailable triggers fallback" case at lines 100–107,wantErris a freshly constructedfmt.Errorfthat happens to format identically — a silent regression in the pass-through semantics (e.g., re-wrapping) wouldn't be caught. Per coding guidelines, prefererrors.Is()for error checking in tests.♻️ Proposed tweak
- got := maybeOfferProfileFallbackOnAuthConfigError(ctx, m, tt.err) - - if tt.wantErr == nil { - require.NoError(t, got) - return - } - require.Error(t, got) - assert.Equal(t, tt.wantErr.Error(), got.Error()) + got := maybeOfferProfileFallbackOnAuthConfigError(ctx, m, tt.err) + + if tt.wantErr == nil { + require.NoError(t, got) + return + } + require.Error(t, got) + // Pass-through cases must return the exact same error instance. + // Fallback-propagation cases must surface the fallback sentinel via errors.Is. + if tt.err != nil && tt.wantErr != tt.err { + assert.ErrorIs(t, got, tt.wantErr) + } else { + assert.Same(t, tt.err, got) + }For this to work cleanly, tighten the "ErrNoIdentitiesAvailable" row so
wantErris the same instance aserr(extract it to a local var likewrappedNoIdentities).🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@cmd/auth_profile_fallback_test.go` around lines 118 - 126, Update the test to use identity-based error checks instead of string equality: for pass-through cases of maybeOfferProfileFallbackOnAuthConfigError use errors.Is(got, tt.wantErr) or assert.Same(t, tt.err, got) so the test detects re-wrapping, and make the "ErrNoIdentitiesAvailable" case supply the exact same error instance (e.g., extract wrappedNoIdentities := fmt.Errorf(...); set both err and wantErr to wrappedNoIdentities) so the comparison with errors.Is/assert.Same verifies the original instance is returned.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@cmd/auth_identity_flow_test.go`:
- Around line 139-142: The test should assert identity equality rather than
value equality: in the assertion for the fallback error returned by
maybeOfferProfileFallbackOnAuthConfigError, replace assert.Equal(t,
fallbackInvoked, result, ...) with assert.Same(t, fallbackInvoked, result, ...)
so the test verifies the exact same error instance (fallbackInvoked) is
propagated unchanged by maybeOfferProfileFallbackOnAuthConfigError.
- Around line 48-107: Missing coverage for the branch where the identity flag is
set to IdentityFlagSelectValue (__SELECT__), which should set forceSelect=true
and call m.GetDefaultIdentity(true); add a subtest to
TestIdentityFromFlagOrDefault that resets viper (resetIdentityViper), creates a
mock AuthManager (types.NewMockAuthManager) expecting
GetDefaultIdentity(true).Return("picked-id", nil), sets the flag on the command
(newIdentityFlowTestCmd and cmd.Flags().Set(IdentityFlagName,
IdentityFlagSelectValue)), calls identityFromFlagOrDefault(cmd, m) and asserts
no error and the returned value equals "picked-id".
- Around line 33-39: The helper resetIdentityViper mutates the global
viper.GetViper() singleton and relies on t.Cleanup to restore IdentityFlagName,
so update its top doc comment (the existing block around lines 18–23) to add a
single explicit sentence: callers must not call t.Parallel() (or otherwise run
in parallel) when using resetIdentityViper because it mutates the global viper
state and relies on serial test execution to restore IdentityFlagName.
In `@cmd/auth_profile_fallback_test.go`:
- Around line 118-126: Update the test to use identity-based error checks
instead of string equality: for pass-through cases of
maybeOfferProfileFallbackOnAuthConfigError use errors.Is(got, tt.wantErr) or
assert.Same(t, tt.err, got) so the test detects re-wrapping, and make the
"ErrNoIdentitiesAvailable" case supply the exact same error instance (e.g.,
extract wrappedNoIdentities := fmt.Errorf(...); set both err and wantErr to
wrappedNoIdentities) so the comparison with errors.Is/assert.Same verifies the
original instance is returned.
In `@pkg/config/profiles_public_test.go`:
- Around line 1-239: Two identical malformed-YAML test setups are duplicated in
TestProfilesWithIdentity and TestProfilesWithAuthConfig; extract a small helper
(e.g., writeBrokenProfile(t *testing.T, tmpDir, name string)) and use it from
both tests to create the "broken" profile directory and atmos.yaml so
duplication is removed; update the two call sites to call writeBrokenProfile and
keep existing assertions and temp-dir usage (references:
profilesPublicTestFixture, TestProfilesWithIdentity,
TestProfilesWithAuthConfig).
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: ecce493c-0d86-4ca2-aa9b-070c5b1ec13e
📒 Files selected for processing (15)
cmd/auth_config.gocmd/auth_config_test.gocmd/auth_console.gocmd/auth_env.gocmd/auth_exec.gocmd/auth_identity_flow_test.gocmd/auth_login.gocmd/auth_logout.gocmd/auth_profile_fallback_test.gocmd/auth_shell.gocmd/auth_user.gocmd/auth_validate.gocmd/auth_whoami.gopkg/auth/profile_fallback_test.gopkg/config/profiles_public_test.go
✅ Files skipped from review due to trivial changes (1)
- pkg/auth/profile_fallback_test.go
🚧 Files skipped from review as they are similar to previous changes (3)
- cmd/auth_exec.go
- cmd/auth_whoami.go
- cmd/auth_login.go
… assertions
Production code (minimal, test-only seams):
pkg/auth/profile_fallback.go
- Add two package-scoped variables so the huh-based interactive paths
and the isInteractive() gate can be exercised headlessly in tests:
* runForm wraps form.Run() — huh has no headless mode and a real
form requires a TTY, so tests stub this var to inject outcomes
(ErrUserAborted, non-abort form errors, successful submission).
* interactiveCheck aliases isInteractive() but is scoped to this
file only — the 5 other isInteractive() call sites in manager.go
are untouched so we don't widen the blast radius.
- Production code never reassigns either var. Documented inline.
Test coverage — pkg/auth/profile_fallback.go: 44.7% → 91.5%
16 new tests in pkg/auth/profile_fallback_test.go:
- Empty-list early returns for promptForProfileSelection and
promptForAnyProfileSelection (ErrNoIdentitiesAvailable).
- User-aborted / non-abort error / successful-submission branches
for every prompt + confirm function. Also pins the contract that
huh.Select defaults the bound value to the first sorted option
when form.Run returns nil.
- Interactive-branch tests for maybeOfferProfileFallback and
maybeOfferAnyProfileFallback: user aborts → ErrUserAborted;
prompt errors (non-abort) → wrapped with ErrUnsupportedInputType;
reexec.Exec fails → "failed to re-exec" propagated. Each test
stubs interactiveCheck + runForm + reexec.Exec so the full
interactive path runs headless.
Per-function coverage (before → after):
- promptForProfileSelection 0.0% → 100.0%
- confirmSingleProfileSelection 0.0% → 90.9%
- promptForAnyProfileSelection 0.0% → 100.0%
- confirmSingleAnyProfileSelection 0.0% → 90.9%
- maybeOfferProfileFallback 52.0% → 84.0%
- maybeOfferAnyProfileFallback 52.0% → 84.0%
Review-feedback cleanups (no behavior change):
cmd/auth_identity_flow_test.go
- assert.Equal → assert.Same for the fallback-error propagation
contract. Identity equality is the actual contract;
assert.Equal could silently accept a wrap/copy.
- New subtest for the __SELECT__ branch of identityFromFlagOrDefault:
--identity without a value → forceSelect=true →
GetDefaultIdentity(true). Pins the previously-uncovered branch.
- Documented the parallel-safety invariant on resetIdentityViper:
callers must NOT use t.Parallel() because the helper mutates the
global viper.GetViper() singleton with a t.Cleanup restore.
cmd/auth_profile_fallback_test.go
- Rewrote TestMaybeOfferProfileFallbackOnAuthConfigError with an
assertMode enum. Pass-through cases use assert.Same to catch
silent re-wrap regressions plus errors.Is against sentinels.
Fallback-return cases use assert.Same against the fallback
instance. Replaces the previous .Error()-string equality check.
Platform hygiene:
pkg/auth/profile_fallback_test.go
- TestBuildFallbackAtmosConfig_PopulatesPaths: replaced a hardcoded
`/some/cli/config/path` Unix literal with filepath.Join("some",
"cli", "config", "path") per CLAUDE.md ("NEVER hardcode Unix
paths in expected values"). Round-trip contract is unchanged.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@cmd/auth_identity_flow_test.go`:
- Around line 161-165: The comment block describing the auth subcommand pattern
must be godot-safe (end with a period); locate the comment around the pattern
using the symbols identityFromFlagOrDefault,
maybeOfferProfileFallbackOnAuthConfigError, cmd and authManager and either
rephrase the fragment-style comment into a complete sentence or append a final
sentence that ends with a period so the comment group no longer ends with `}`.
- Around line 169-176: Add a companion negative-path test for
maybeOfferProfileFallbackOnAuthConfigError that verifies the fallback is NOT
invoked for unrelated errors: create a test similar to the existing one but pass
a non-ErrNoDefaultIdentity error, set the mock expectation that
MaybeOfferAnyProfileFallback is not called (e.g.,
mock.EXPECT().MaybeOfferAnyProfileFallback(gomock.Any()).Times(0) or use
gomock.InOrder with no call), call maybeOfferProfileFallbackOnAuthConfigError
with that error, assert the returned error equals the original error
(assert.Same like fallbackInvoked check), and ensure the test fails if the
fallback is invoked.
- Around line 3-16: Update the tests to exercise the real no-value `--identity`
flag path instead of setting the sentinel directly: modify
newIdentityFlowTestCmd to set the Cobra flag's NoOptDefVal for the `--identity`
flag, then in the test pass the `--identity` flag without a value (so Cobra
populates NoOptDefVal) rather than manually injecting the sentinel value;
additionally add a negative-path test asserting that
maybeOfferProfileFallbackOnAuthConfigError does NOT invoke the fallback when the
error is nil (success case) to cover the non-trigger branch.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 89fe638a-6086-4dcb-bfd5-e6a8e2bd49e4
📒 Files selected for processing (4)
cmd/auth_identity_flow_test.gocmd/auth_profile_fallback_test.gopkg/auth/profile_fallback.gopkg/auth/profile_fallback_test.go
✅ Files skipped from review due to trivial changes (3)
- cmd/auth_profile_fallback_test.go
- pkg/auth/profile_fallback.go
- pkg/auth/profile_fallback_test.go
cmd/auth_identity_flow_test.go
- Swap the direct-sentinel injection in the __SELECT__ subtest for a
real Cobra NoOptDefVal flow: wire NoOptDefVal on the test cmd,
set os.Args to include `--identity` (no value), and call
cmd.ParseFlags([]string{"--identity"}). Renamed the subtest to
"--identity without value (NoOptDefVal) calls GetDefaultIdentity(true)".
Added withIdentityFlowArgs helper with t.Cleanup restore so the
swap is test-scoped and doesn't leak into siblings.
- Add TestAuthCmd_IdentityFlagNoOptDefVal — a tiny regression fence
that inspects authCmd.PersistentFlags().Lookup(IdentityFlagName).
NoOptDefVal directly. The previous NoOptDefVal test exercises the
MECHANISM against a test-owned cmd, so it cannot catch a future
edit that deletes the wiring from cmd/auth.go's init(). This test
catches exactly that regression.
- Add TestIdentityFromFlagOrDefault_NoErrorSkipsFallbackDispatcher —
negative-path companion to the ErrorReachesFallbackDispatcher test.
Uses gomock's strict "no expectation = fail" semantics to prove
MaybeOfferAnyProfileFallback is never invoked when
identityFromFlagOrDefault succeeds. Also explicitly calls the
dispatcher with nil to assert the short-circuit at the dispatcher
layer. Pairs with the existing trigger-path test per CLAUDE.md
"negative-path for recovery logic" rule.
- Add TestMaybeOfferProfileFallbackOnAuthConfigError_IgnoresNonAuthErrors —
colocated negative companion for the non-auth-config-error path.
Uses assert.AnError + strict gomock to prove unrelated errors
pass through verbatim without triggering the fallback. This case
is also covered in auth_profile_fallback_test.go; duplicated here
so readers of the identity-flow tests see the positive and
negative paths side-by-side.
- Godot fixes: rewrote the snippet-style block comment inside
TestIdentityFromFlagOrDefault_ErrorReachesFallbackDispatcher
(ended with literal `// }`) as a one-sentence prose description.
Capitalized sentence-initial "identityFromFlagOrDefault" / "gomock"
in three doc blocks so godot accepts them.
- Parallel-safety heads-up on resetIdentityViper: callers must NOT
use t.Parallel() because the helper mutates the global
viper.GetViper() singleton with a t.Cleanup restore — a parallel
subtest elsewhere that touches IdentityFlagName would race the
cleanup. Documented at the helper.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
Warning Release Documentation RequiredThis PR is labeled
|
|
These changes were released in v1.216.0. |
Backports features from main's cmd/auth_*.go that were not yet present in HEAD's refactored cmd/auth/* tree. Each item references the upstream PR. cmd/auth/env.go (#1984): - Add `--format=github` for $GITHUB_ENV with heredoc multiline support. - Add `--format=env` (lowercase env-style key=value). - Add `-o, --output-file` flag (with $GITHUB_ENV auto-detect for github). - Route formatting through pkg/env.Output() while keeping outputEnvAsExport and outputEnvAsDotenv helpers for unit-test coverage. - Bind ATMOS_AUTH_ENV_FORMAT and ATMOS_AUTH_ENV_OUTPUT_FILE env vars. - Extract loadAuthManagerForEnv, resolveIdentityNameForEnv, loginIfNeeded, resolveEnvOutputTarget, and resolveEnvOutputFile helpers to keep executeAuthEnvCommand within complexity and length budgets. cmd/auth/login.go (provider fallback, #2333): - Change authenticateIdentity signature to (whoami, needsProviderFallback, err). On ErrNoIdentitiesAvailable / ErrNoDefaultIdentity, return the fallback flag instead of wrapping; caller routes to provider auth. - Treat ErrUserAborted as a clean abort (no ErrAuthenticationFailed wrap). - Add getProviderForFallback / promptForProvider / isInteractive helpers for the auto-provision-identities first-login path. - Wire maybeOfferProfileFallbackOnAuthConfigError around identity-flow errors. cmd/auth/exec.go, cmd/auth/shell.go: - Surface identity-resolution errors through maybeOfferProfileFallbackOnAuthConfigError so a stale base profile no longer dead-ends with `no default identity`. Tests: - env_test.go: add TestGitHubEnvAutoDetect (auto-detect $GITHUB_ENV + heredoc framing), update TestSupportedFormats to expect 5 formats. - login_test.go: update TestAuthenticateIdentity for the new needsProviderFallback signal; add ErrNoIdentitiesAvailable case. - integration_test.go (new): TestAuthEnvFormatCompletion, TestAuthWhoamiOutputCompletion, TestAuthCommandCompletion_FlagInheritance. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…1919) * Fix markdown code fence in Nerd Fonts installation instructions (#1917) * Simplify Nerd Fonts installation instructions Removed Homebrew tap and search commands from installation instructions. Cask-fonts has been deprecated. * Fix markdown code fence formatting The previous commit accidentally removed the opening code fence when deleting the deprecated Homebrew tap commands. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <[email protected]> --------- Co-authored-by: Matt Topper <[email protected]> Co-authored-by: Claude Opus 4.5 <[email protected]> Co-authored-by: Andriy Knysh <[email protected]> * Address PR review comments for auth registry refactor - Fix Comment #3: Parse global flags before InitCliConfig in all auth commands by adding BuildConfigAndStacksInfo helper to pkg/flags and cmd/auth/helpers.go - Fix Comment #4: Add guard for empty selectable array in configure.go to prevent index out of bounds when no AWS user identities found - Fix Comment #5: Remove duplicate IdentityFlagName constants by using cfg.IdentityFlagName from pkg/config/const.go as canonical source - Remove unused schema imports from login.go, exec.go, shell.go - Remove unnecessary nolint:gosec directives from env.go 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <[email protected]> * Fix NoOptDefVal preprocessing for identity flag in auth commands The identity flag uses Cobra's NoOptDefVal feature which only works with equals syntax (--identity=value), not space-separated syntax (--identity value). This caused explicit identity values to be ignored, falling back to interactive selection which fails without a TTY. Fix by adding NoOptDefVal preprocessing in preprocessCompatibilityFlags() to rewrite --identity value → --identity=value before Cobra parses. This ensures explicit identity values work correctly in all environments (CI, piped output, redirected stdin). Fixes: - TestInteractiveIdentitySelection/explicit_identity_value_should_work_even_with_piped_output - TestExplicitIdentityAlwaysWorks/with_CI=true 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <[email protected]> * Add documentation for --identity flag placement best practices Document recommended usage patterns for the --identity flag: - Use equals syntax (--identity=admin) for clarity - Place flag before -- separator and positional arguments - Both auth and terraform command docs updated 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <[email protected]> * Address PR review comments: constants and security annotations 1. Remove redundant constant aliases in cmd/identity_helpers.go - Use cfg.IdentityFlagName and cfg.IdentityFlagSelectValue directly - Eliminates duplicate definitions (CodeRabbit feedback) 2. Add CodeQL suppression comments in cmd/auth/env.go - Document intentional credential output for shell sourcing - Add codeql[go/clear-text-logging] annotations - Similar to aws configure export-credentials behavior 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <[email protected]> * Add --identity flag documentation to global flags reference Document the --identity flag in the Command-Specific Flags section: - Available in auth, terraform, and describe commands - Supports multiple modes: explicit value, interactive selector, disabled - Add ATMOS_IDENTITY environment variable reference - Include flag placement best practice tip (equals syntax recommended) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <[email protected]> * Refactor preprocessing architecture with preprocessArgs orchestrator Separate NoOptDefVal preprocessing and compatibility flag translation into sibling operations orchestrated by a new preprocessArgs() function. Architecture: - preprocessArgs() orchestrates all argument preprocessing - preprocessNoOptDefValFlags() rewrites --flag value → --flag=value for NoOptDefVal flags - preprocessCompatibilityFlags() separates Atmos flags from pass-through flags Key fixes: - Call SetArgs when NoOptDefVal changes args but no compat flags exist - This ensures --identity value works correctly for auth commands New pkg/flags/preprocess/ package: - Pipeline interface for extensible preprocessing - NoOptDefValPreprocessor with fixed hasSeparatedValue() using strings.Contains - FlagInfo interface to avoid circular imports Tests: - All auth tests pass (29 tests) - All preprocess package tests pass - Pager tests skip gracefully when TTY unavailable Also fixes pre-existing lint errors in: - errors/errors.go: Add ErrComponentPathNotFound sentinel - internal/exec/helmfile.go: Use sentinel errors instead of dynamic errors - internal/exec/stack_processor_merge.go: Use %w instead of %v for errors - pkg/downloader/file_downloader.go: Use %w instead of %v for errors - internal/exec/path_utils_test.go: Use constants for paths with separators 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <[email protected]> * Address PR review comments - cmd/auth/shell.go: Use envpkg.MergeGlobalEnv() for consistency with exec.go (addresses CodeRabbit comment #3 about env merging inconsistency) - cmd/auth/whoami.go: Use %w for error wrapping to preserve error chain (addresses CodeRabbit comment #4 about error wrapping) - tests/cli_describe_component_test.go: Use cross-platform TTY detection with term.IsTTYSupportForStdout() and close file handle properly (addresses CodeRabbit comments #5, #6) - tests/describe_test.go: Add skipIfNoTTY helper with cross-platform TTY detection and proper file handle cleanup (addresses CodeRabbit comments #7, #8) Note: Comments #1 and #2 (codeql clear-text logging) are false positives - the atmos auth env command intentionally outputs credentials for shell sourcing, similar to `aws configure export-credentials`. Suppression comments are already in place. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <[email protected]> * Add unit tests for cmd/auth package to improve coverage Add 15 new test files covering pure functions and mock-based tests: - helpers_test.go: formatDuration, displayAuthSuccess, BuildConfigAndStacksInfo - whoami_test.go: redactHomeDir, sanitizeEnvMap, buildWhoamiTableRows, validateCredentials - list_test.go: parseCommaSeparatedNames, filter functions, render functions - env_test.go: outputEnvAsExport, outputEnvAsDotenv - login_test.go: authenticateIdentity with MockAuthManager - shell_test.go: getSeparatedArgs, viper fallback tests - exec_test.go: getSeparatedArgsForExec, executeCommandWithEnv - console_test.go: resolveIdentityName, retrieveCredentials, resolveConsoleDuration - auth_test.go: AuthCommandProvider, GetIdentityFromFlags - completion_test.go: completion functions - validate_test.go: command structure - identity_resolution_test.go: shared identity resolution test helper - user/user_test.go: AuthUserCmd structure - user/configure_test.go: command structure - user/helpers_test.go: selectAWSUserIdentities, extractAWSUserInfo Coverage improved from ~25.57% to ~36.2% for cmd/auth package. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <[email protected]> * Fix cross-platform compatibility for exec tests - Replace Unix-specific "true" command with cross-platform "go version" - Move "false" command test to exec_unix_test.go with build constraint - Addresses CodeRabbit review comment about Windows compatibility 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <[email protected]> * test: Add tests for --profile flag in auth commands (fixes #1973) Add tests to verify that the --profile global flag is properly extracted into ProfilesFromArg when using auth exec and auth shell commands. Test cases: - Single profile (--profile dev) - Multiple profiles (--profile dev --profile staging) - No profile - Profile with special characters (us-east-1/prod) - Environment variable fallback (ATMOS_PROFILE) These tests verify the fix for issue #1973 where --profile didn't work with auth exec and auth shell commands. Co-Authored-By: Claude Opus 4.5 <[email protected]> * docs: Reorganize terraform usage examples into distinct sections Split the "Clean Examples" section into three distinct subsections: - Clean Examples: terraform clean commands only - Workspace Examples: terraform workspace commands - Additional Flag Examples: plan commands with --/--append-user-agent flags This improves documentation readability by grouping related commands together. Addresses CodeRabbit review comment on PR #1919. Co-Authored-By: Claude Opus 4.5 <[email protected]> * test: Regenerate auth command golden snapshots Update snapshots for auth command refactoring: - auth exec --help: Updated usage format and added aws CLI example - auth invalid-command: Removed ecr-login from valid subcommands list Co-Authored-By: Claude Opus 4.5 <[email protected]> * fix: Windows test failures and website build - Make TestRedactHomeDir cross-platform using filepath.Join - Make TestRedactHomeDirWithOsPathSeparator use consistent path construction - Fix TestFormatExpiration flaky assertion (timing-dependent) - Add missing File component import to terraform/usage.mdx Co-Authored-By: Claude Opus 4.5 <[email protected]> * fix: Add IsExperimental method to AuthCommandProvider The CommandProvider interface now requires IsExperimental() after main branch updates. This fixes CI build failures across Linux, macOS, and Windows by implementing the required interface method. Auth commands return true as they are part of Pro Features. Co-Authored-By: Claude Opus 4.5 <[email protected]> * [autofix.ci] apply automated fixes * [autofix.ci] apply automated fixes (attempt 2/3) * [autofix.ci] apply automated fixes (attempt 3/3) * [autofix.ci] apply automated fixes * fix: Address CodeRabbit review comments for auth-registry-refactor - Remove undocumented IDENTITY env var fallback (comment #10) Only ATMOS_IDENTITY is documented and should be used - Make HOME path test cases OS-portable (comment #11) Use filepath.Join instead of hardcoded Unix paths in tests Co-Authored-By: Claude Opus 4.5 <[email protected]> * chore: Regenerate golden snapshots for experimental auth command The auth command now returns IsExperimental() = true, which adds: - [EXPERIMENTAL] tag in command listings - Experimental feature warning message in stderr output Regenerated all affected golden snapshots to match the new output. Co-Authored-By: Claude Opus 4.5 <[email protected]> * fix: Address CodeRabbit review findings in auth commands - console.go: Use data.Writeln/ui.Writef/ui.Success/ui.Warning instead of fmt.Fprintf(os.Stdout/Stderr) to follow Atmos I/O conventions - env.go: Wrap config/manager init errors with sentinel errors (ErrFailedToInitializeAtmosConfig, ErrFailedToInitializeAuthManager) - exec.go: Remove duplicate os.Environ() in executeCommandWithEnv; use envpkg.ConvertMapToSlice since prepareAuthenticatedEnv already includes the full OS environment - helpers.go: Stop scanning for --help at "--" separator so pass-through commands like `atmos auth exec -- terraform --help` work correctly - logout.go: Fix misleading --all-realms flag description to accurately reflect keychain cleanup scope Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix: Migrate auth commands from legacy u.Print* to ui/data layer and fix test failures Replace all antiquated u.PrintfMarkdownToTUI/u.PrintfMessageToTUI calls in auth commands with the proper ui.MarkdownMessagef/ui.Writef functions. Replace u.PrintAsJSON with data.WriteJSON. Add missing Realm row to displayAuthSuccess output. Regenerate golden snapshots to match corrected stderr output. Co-Authored-By: Claude Opus 4.6 <[email protected]> * feat(auth): port main features to refactored cmd/auth package Backports features from main's cmd/auth_*.go that were not yet present in HEAD's refactored cmd/auth/* tree. Each item references the upstream PR. cmd/auth/env.go (#1984): - Add `--format=github` for $GITHUB_ENV with heredoc multiline support. - Add `--format=env` (lowercase env-style key=value). - Add `-o, --output-file` flag (with $GITHUB_ENV auto-detect for github). - Route formatting through pkg/env.Output() while keeping outputEnvAsExport and outputEnvAsDotenv helpers for unit-test coverage. - Bind ATMOS_AUTH_ENV_FORMAT and ATMOS_AUTH_ENV_OUTPUT_FILE env vars. - Extract loadAuthManagerForEnv, resolveIdentityNameForEnv, loginIfNeeded, resolveEnvOutputTarget, and resolveEnvOutputFile helpers to keep executeAuthEnvCommand within complexity and length budgets. cmd/auth/login.go (provider fallback, #2333): - Change authenticateIdentity signature to (whoami, needsProviderFallback, err). On ErrNoIdentitiesAvailable / ErrNoDefaultIdentity, return the fallback flag instead of wrapping; caller routes to provider auth. - Treat ErrUserAborted as a clean abort (no ErrAuthenticationFailed wrap). - Add getProviderForFallback / promptForProvider / isInteractive helpers for the auto-provision-identities first-login path. - Wire maybeOfferProfileFallbackOnAuthConfigError around identity-flow errors. cmd/auth/exec.go, cmd/auth/shell.go: - Surface identity-resolution errors through maybeOfferProfileFallbackOnAuthConfigError so a stale base profile no longer dead-ends with `no default identity`. Tests: - env_test.go: add TestGitHubEnvAutoDetect (auto-detect $GITHUB_ENV + heredoc framing), update TestSupportedFormats to expect 5 formats. - login_test.go: update TestAuthenticateIdentity for the new needsProviderFallback signal; add ErrNoIdentitiesAvailable case. - integration_test.go (new): TestAuthEnvFormatCompletion, TestAuthWhoamiOutputCompletion, TestAuthCommandCompletion_FlagInheritance. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * updates * [autocommit] formatting fixes * test(auth): add regression tests for issues #1973 and #2392 Both issues are addressed by the cmd/auth/* registry refactor + terraform StandardParser registration of --identity. These tests guard the contracts so a future regression cannot reintroduce either silent flag-drop bug. Issue #1973 (--profile global flag silently dropped on auth exec/shell): - cmd/auth/exec_test.go::TestAuthExec_ProfileFlagAppliedToConfig - cmd/auth/shell_test.go::TestAuthShell_ProfileFlagAppliedToConfig Both call BuildConfigAndStacksInfo(cmd, v) — the helper that exec.go and shell.go now use before cfg.InitCliConfig — and assert that the --profile values round-trip into ConfigAndStacksInfo.ProfilesFromArg for single, multiple, and absent profile cases. Issue #2392 (--identity silently dropped on atmos terraform plan): - internal/exec/cli_utils_test.go::TestProcessCommandLineArgs_TerraformIdentityFlag_Issue2392 Reproduces the bug-report arg shape verbatim — `terraform plan account-map -s core-gbl-root --identity core-root/admin` — and asserts ProcessCommandLineArgs populates info.Identity = "core-root/admin". - internal/exec/terraform_execute_helpers_auth_test.go::TestSetupTerraformAuth_IdentityFlagPropagatesToAuthCreator Builds a merged auth config containing both a `default: true` identity ("core-identity/devops") and a non-default identity ("core-root/admin") and asserts that setupTerraformAuth passes the explicit --identity value verbatim to the auth manager creator — not the profile default. This is the exact override that the issue described as silently happening at v1.216.0. - internal/exec/terraform_execute_helpers_auth_test.go::TestSetupTerraformAuth_EmptyIdentity_AllowsAutoDetection Inverse guard: with no --identity flag, info.Identity is empty and the creator receives the empty string so pkg/auth.resolveIdentityName can auto-detect the profile default. Prevents an over-eager fix from breaking the default-identity path. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * updates * test(auth): boost cmd/auth coverage from 33% to 47% Adds focused unit tests for the testable helpers exposed by the cmd/auth registry refactor. Targets the lowest-coverage files flagged by Codecov: cmd/auth/auth.go (CommandProvider getters): - TestAuthCommandProvider_OptionalMethods covers GetPositionalArgsBuilder, GetCompatibilityFlags, GetAliases, IsExperimental. - TestGetAuthCmd_ReturnsAuthCmd guards the public accessor used by cmd/ai to attach subcommands. cmd/auth/env.go (env command helpers): - TestResolveEnvOutputFile covers all four branches of the GitHub auto- detect: non-github pass-through, explicit output-file, $GITHUB_ENV detect, and the missing-GITHUB_ENV error sentinel. - TestResolveEnvOutputTarget exercises viper-backed format/output-file resolution including the bash default and the github auto-detect. - TestLoginIfNeeded covers cache-hit (no Authenticate), missing-cache (Authenticate triggered), ErrUserAborted unwrapping, and generic- error wrapping with ErrAuthenticationFailed. - TestResolveIdentityNameForEnv covers the explicit-flag, viper-fallback, default-auto-detect, and __SELECT__ interactive paths. cmd/auth/console.go (browser isolation helpers): - TestConsoleSessionDir asserts the deterministic XDG path is stable across calls, diverges by identity, and diverges by realm. - TestResolveConsoleIsolated covers default false, auth.console.isolated config honoured, flag overrides config in both directions. - TestPrintConsoleHelpers smoke-covers printConsoleURL and printConsoleInfo with full + showURL=true paths. - TestRetrieveCredentials_NoCredentialsAvailable covers the ErrAuthConsole sentinel for the no-credentials-anywhere branch. cmd/auth/login.go (provider-fallback helpers): - TestGetProviderForFallback covers ErrNoProvidersAvailable for empty list, single-provider auto-select (no prompt), and multi-provider non-interactive ErrNoDefaultProvider. - TestIsInteractive guards determinism (same env → same answer). cmd/auth/whoami.go (whoami helpers): - TestAddGCPReauthExplanation covers nil pass-through, unrelated-error pass-through, invalid_grant alone (no enrichment), and invalid_grant + invalid_rapt enrichment with gcloud reauth hint. - TestPrintWhoamiJSON_RedactsCredentials guards the contract that the JSON output never mutates the caller's Environment map. - TestPrintWhoamiHuman covers valid/invalid/no-expiration table render. cmd/auth/list.go (list command helpers): - TestParseFilterFlags covers the default, --providers (with comma list), --identities (with comma list), and the mutually-exclusive ErrMutuallyExclusiveFlags branch. - TestRenderOutput_InvalidFormatErrors guards the default-case ErrInvalidFlag path. - TestListFlagCompletions_NoConfig covers the no-atmos.yaml early-return path of listProvidersFlagCompletion / listIdentitiesFlagCompletion. cmd/auth/logout.go (new logout_test.go): - TestBuildKeychainDeletionMessage covers the pure prompt formatter. - TestConfirmKeychainDeletion_ForceShortCircuit covers --force bypass. - TestConfirmKeychainDeletion_NonTTYWithoutForceErrors covers the ErrKeychainDeletionRequiresConfirmation branch. - TestDetectExternalCredentials covers GCP/Azure/AWS env-var detection. - TestBuildLogoutOptions covers the empty-config, identities+providers, and provider-cascade-label branches. - TestExecuteLogoutOption_InvalidType covers ErrInvalidLogoutOption. - TestDiscoverRealms covers missing dir (no error), no-provider-subdir filter, and aws/azure realm reporting. cmd/auth/completion.go (completion helpers): - TestIdentityFlagCompletion covers the no-atmos.yaml branch. - TestAddIdentityCompletion_NoFlag covers the no-flag-registered no-op. cmd/auth/user/helpers.go (form-builder helper): - TestBuildCredentialFormField covers all six branches: YAML-managed Note, DefaultValue pre-fill, password mode, optional, custom ValidateFunc wired, description message wired. Infra: - New testmain_test.go initialises pkg/data and pkg/ui formatters once for the package so tests that exercise printWhoamiJSON/printWhoamiHuman don't panic with "data.InitWriter() must be called". - Snapshot tests/snapshots/TestCLICommands_atmos_auth_validate_--verbose picks up an env-dependent debug line drop (gh CLI not authenticated). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * style: apply gofumpt v0.10 multiline call wrapping CI's pre-commit hook installs `gofumpt@latest` which is now v0.10.0. That release tightened the multiline-call rule: when arguments span multiple lines, the function name + opening paren go on their own line and the closing paren goes on its own line as well. Local toolchain was on v0.9.1 which didn't enforce this, so the changes only surfaced on CI. Files affected (only PR-touched files reformatted): - cmd/auth/env.go: env.Output(...) call. - cmd/describe_dependents.go: getRunnableDescribeDependentsCmd(...) call. - cmd/describe_stacks.go: PersistentFlags().StringP(...) call. No behaviour change. Matches the auto-fix diff produced by the cloudposse/github-action-pre-commit job. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * test(auth): boost cmd/auth coverage from 47% to 69% Adds smoke and branch-coverage tests across the auth command tree to lift patch coverage from the post-merge baseline (47.8%) to ~69%. Orchestrator smoke tests (no-atmos.yaml tempdir, no-panic contract): - TestExecuteAuthLoginCommand_SmokeNoConfig - TestExecuteAuthWhoamiCommand_SmokeNoConfig - TestExecuteAuthListCommand_SmokeNoConfig - TestExecuteAuthValidateCommand_SmokeNoConfig - TestExecuteAuthConsoleCommand_SmokeNoConfig - TestExecuteAuthEnvCommand_SmokeNoConfig - TestExecuteAuthExecCommand_SmokeNoConfig - TestExecuteAuthShellCommand_SmokeNoConfig - TestExecuteAuthLogoutCommand_SmokeNoConfig - TestExecuteAuthUserConfigureCommand_SmokeNoConfig (cmd/auth/user) These cover the config-load error wrap path in each orchestrator and guard against panics for invalid setup. Where a specific error sentinel is documented (e.g. ErrInvalidAuthConfig, ErrFailedToInitializeAtmosConfig, ErrAuthConsole), the test asserts the wrap when an error surfaces. loadAuthManager* helpers (config init + auth manager init): - TestLoadAuthManager_SmokeFromEmptyTempDir (whoami) - TestLoadAuthManagerForEnv_SmokeFromEmptyTempDir (env) - TestLoadAuthManagerForList_SmokeFromEmptyTempDir (list) - TestInitializeAuthManager_SmokeFromEmptyTempDir (console) - TestSuggestProfilesForAuth_NoProfilesReturnsNil prepareShellEnvironment (cmd/auth/shell.go) — mocked-AuthManager test covering cache-hit, fresh-auth-success, ErrUserAborted, generic-error wrap with ErrAuthenticationFailed, PrepareShellEnvironment error, and atmosConfig.Env propagation through MergeGlobalEnv: - TestPrepareShellEnvironment (six subtests) prepareAuthenticatedEnv (cmd/auth/exec.go) — smoke from empty tempdir: - TestPrepareAuthenticatedEnv_SmokeNoConfig Display + handleBrowserOpen helpers (smoke): - TestDisplayExternalCredentialWarnings (with-warnings + clean branch) - TestDisplayBrowserWarning (first-call + cached-skip branches) - TestHandleBrowserOpen (skipOpen=true, nil opener, success, error) Logout perform helpers — mocked AuthManager branch coverage: - TestPerformIdentityLogout_NotFound (ErrIdentityNotInConfig) - TestPerformIdentityLogout_DryRun (no Logout call) - TestPerformProviderLogout_NotFound (missing provider in config) - TestPerformLogoutAll_DryRun (no LogoutAll call) - TestPerformLogoutAll_Success (happy path, two identities) renderOutput dispatcher coverage: - TestRenderOutput_AllValidFormats covers all 9 valid format branches (table/tree/json/yaml/graphviz/dot/mermaid/markdown/md). Coverage summary: - cmd/auth: 47.6% → 69.7% - cmd/auth/user: 51.0% → 58.7% - combined: 47.8% → 68.9% Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * test(auth): address review comments and push coverage from 47% to 78% Addresses CodeRabbit review comments and substantially increases test coverage of the cmd/auth package using a shared mock-auth fixture. Review fixes: - cmd/auth/completion.go, cmd/auth/list.go: all five shell-completion helpers now honour --base-path, --config, --config-path, and --profile by routing through BuildConfigAndStacksInfo(cmd, v) instead of using an empty ConfigAndStacksInfo{}. - cmd/auth/console.go: --print-only now propagates the data.Writeln write error so broken-pipe / stdout failures exit non-zero. The empty-identity branch of resolveIdentityName now uses multi-%w so ErrNoDefaultIdentity stays in the chain for the profile-fallback dispatcher. - cmd/auth/exec.go: prepareAuthenticatedEnv now returns []string directly (was []string → map → []string round-trip) so environment ordering is preserved and Windows drive-scoped vars (=C:=...) don't collide on the empty key. - cmd/auth/shell.go: fail fast when positional args are not preceded by `--` (`atmos auth shell bash` previously silently dropped "bash"). - cmd/auth/logout.go: add cobra.MaximumNArgs(1) so extra positional args are rejected up front. - cmd/auth/validate.go: wrap config-load failure with the static ErrFailedToInitializeAtmosConfig sentinel. - cmd/auth/login.go: introduce isInteractiveFn package var so getProviderForFallback tests can force the non-interactive branch deterministically. - cmd/auth/markdown/*.md: every opening fence now has the `shell` language identifier (MD040). The `$ ` prefix on commands is kept for consistency with the rest of cmd/markdown/. - cmd/auth/user/configure.go: switch user-facing messages from fmt.Fprintf(cmd.ErrOrStderr()) to ui.Writef / ui.Writeln per the I/O layer convention. - cmd/identity_helpers.go: add the missing perf.Track in CreateAuthManagerFromIdentityWithStackScan to match its sibling helpers. Coverage improvements (cmd/auth 47.6% → 79.3%; combined 47.8% → 77.8%): New shared helpers (helpers_test.go): - setupMockAuthFixture(t): writes a minimal atmos.yaml wired to the mock/aws provider and isolates keyring + XDG env to a tempdir, used by 9 deep-coverage tests to exercise the full orchestrator pipeline without touching the host's credential store. - runProfileFlagAppliedRegressionTest(t, commandName): shared table-driven driver for the issue #1973 regression so the exec_test.go and shell_test.go wrappers feed the same cases through one body (and dupl-lint stays clean). - newTestCommandWithGlobalParser: parser-returning variant of the global-flags helper so regression tests can drive the real Cobra → Viper binding path (cmd.ParseFlags → BindFlagsToViper). End-to-end orchestrator tests against the mock fixture: - TestExecuteAuthEnvCommand_WithMockAuth - TestExecuteAuthLoginCommand_WithMockAuth - TestExecuteAuthListCommand_WithMockAuth / _JSONFormat - TestExecuteAuthValidateCommand_WithMockAuth - TestExecuteAuthWhoamiCommand_WithMockAuth - TestExecuteAuthConsoleCommand_WithMockAuth (covers ErrProviderNotSupported for mock/aws) - TestExecuteAuthLogoutCommand_WithMockAuthDryRun - TestPrepareAuthenticatedEnv_WithMockAuth (asserts AWS_PROFILE + AWS_REGION injection) - TestExecuteAuthExecCommand_NoCommand (ErrNoCommandSpecified guard) Logout perform-helper branch coverage: - TestPerformIdentityLogout_Success / _PartialLogout / _LogoutError - TestPerformProviderLogout_Success / _DryRun - TestExecuteLogoutOption_DispatchAll / _DispatchIdentity / _DispatchProvider - TestPerformInteractiveLogout_NoIdentities (empty-identities branch) - TestPerformLogoutAllRealms_NoRealms / _DryRun / _RealRemove Pure / smoke helpers: - TestRetrieveCredentials_InlineCredentials (success path) - TestPromptForProvider_EmptyList (ErrNoProvidersAvailable guard) - TestExecuteCommandWithEnv_NonZeroExit (errUtils.ExitCodeError propagation via the test-binary subprocess pattern) - TestExecuteCommandWithEnv_WithValidCommand rewritten to use os.Executable() + _ATMOS_AUTH_TEST_EXIT_OK=1 (cross-platform, no PATH dependency on `go` / `true` / `false`). - Subprocess env-flag handlers added to TestMain. Test infrastructure: - TestAuthExec_ProfileFlagAppliedToConfig and the shell equivalent now use --profile=devops style CLI args + ParseFlags + BindFlagsToViper, exercising the full production binding chain rather than seeding viper directly. - Identity-resolution shared test table gains a "flag takes precedence over env" case so the precedence rule (flags > env > default) is regression-covered for both auth shell and auth exec. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * test(auth): address review comments — fence repair, helpers, sentinel Addresses six CodeRabbit review comments from the latest batch: 1. cmd/auth/console_test.go — drop tautological constant tests. TestConsoleLabelWidth and TestConsoleOutputFormat just asserted that a literal equals itself. The constants are exported but only used internally; not part of an external API contract. 2. cmd/auth/console_test.go — fragile test-name dispatch. TestResolveConsoleDuration's "invalid provider duration format" case keyed its assertion off tt.name. Renaming the case would silently skip the error check. Added an explicit `expectParseError bool` field; switch case now keys off that. 3. cmd/auth/exec_test.go — single-case table replaced. TestGetSeparatedArgsForExec was a one-case table that duplicated the sibling TestGetSeparatedArgsForExec_EmptyCommand. Rewrote with five meaningful cases (no separator, positional-without-sep, separator+ single command, separator+command+args, separator-only). Deleted the now-redundant sibling test. 4. cmd/auth/env_test.go — safe stdout-capture helper. Five sites used the same fragile capture pattern: if require.NoError aborted before restoration, os.Stdout stayed redirected and the read end of os.Pipe was never closed. Added captureStdout(t) helper in helpers_test.go that registers t.Cleanup to guarantee restoration and close both pipe ends even when intervening assertions abort. All five sites now use `read := captureStdout(t)` / `output := read()`. 5. cmd/auth/env_test.go — replace hardcoded Unix paths with t.TempDir(). Three paths (/tmp/out.sh, /explicit/path, /path/to/.env) replaced with filepath.Join(t.TempDir(), ...) so the tests don't bake in a Unix separator. 6. cmd/auth/markdown/atmos_auth_console_usage.md + cmd/auth/markdown/atmos_auth_logout_usage.md — fix malformed closers. An earlier awk script that added the shell language identifier to opening fences had a state-machine flaw on files that already mixed labeled/unlabeled fences; six closing fences across two files were rewritten as ```shell instead of plain ```. Repaired to keep the rest of the doc rendering correctly. Audited all four auth markdown files; the other two were already correctly paired. 7. cmd/auth/logout_test.go + sibling _WithMockAuth tests — add a cmd-state isolation helper. Tests that mutate package-level auth*Cmd via ParseFlags could leak flag.Changed / flag values to subsequent tests. cmd.NewTestKit isn't reachable from cmd/auth without a circular import, so added a local equivalent resetAuthCmdFlags(t, cmd) that snapshots and restores every flag's (Value, Changed) pair via t.Cleanup. Applied to all 8 tests that ParseFlags a shared cmd: TestExecuteAuthLogoutCommand_SmokeNoConfig and _WithMockAuthDryRun (the two reviewer-flagged sites), plus _WithMockAuth variants for console, env, exec (TestPrepareAuthenticatedEnv_WithMockAuth + TestExecuteAuthExecCommand_NoCommand), list (tree + JSON), login, validate, whoami. 8. cmd/auth/shell.go — tighten the pre-dash arg check and fix the hint. The previous check only caught the no-separator case; `atmos auth shell bash -- -lc env` had ArgsLenAtDash() == 1 and slipped through while getSeparatedArgs silently dropped "bash". Condition is now `dashIndex == -1 || dashIndex > 0` so positional args appearing before "--" are also rejected. The error message no longer suggests `-- bash` (which would just feed "bash" as the first arg to the default shell) — it points at `--shell` for the shell-binary override and "--" only for the shell args. Extracted into validateAuthShellArgs to keep executeAuthShellCommand under the 60-line revive limit. Added TestValidateAuthShellArgs with 5 subtests covering the three acceptable and two rejected arg shapes plus the ErrInvalidArguments sentinel contract. 9. cmd/auth/shell.go + cmd/auth/exec.go — wrap PrepareShellEnvironment failures with a static sentinel. Both helpers had a raw fmt.Errorf("failed to prepare ...: %w", err) that didn't satisfy the repo-wide "All errors MUST be wrapped using static errors defined in errors/errors.go" rule. Added new sentinel errUtils.ErrPrepareShellEnvironment and applied to both call sites. Updated TestPrepareShellEnvironment to assert the sentinel is in the chain (errors.Is) plus the original underlying error. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * test(auth): apply resetAuthCmdFlags across all smoke tests for state isolation Add `resetAuthCmdFlags(t, cmd)` to every test that uses a package-level `auth*Cmd` so flag/Changed state cannot leak across tests under shuffled runs. This is the in-package equivalent of `cmd.NewTestKit(t)` — `cmd/auth` cannot import `cmd` (cmd/root.go blank-imports cmd/auth) and `NewTestKit` is `_test.go`-scoped, so the local helper enforces the same auto-cleanup contract via t.Cleanup. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> --------- Co-authored-by: Matt Topper <[email protected]> Co-authored-by: Claude Opus 4.5 <[email protected]> Co-authored-by: Andriy Knysh <[email protected]> Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com> Co-authored-by: aknysh <[email protected]> Co-authored-by: atmos-pro[bot] <atmos-pro[bot]@users.noreply.github.com>
what
atmos.yamllacks the auth config the user is asking for:atmos … --identity foowhenfooisn't defined in the base config but exists in one or more profiles.atmos auth login/exec/shell/env/console/whoamiwhen the base config has noauth.identities/auth.providersat all but at least one profile does.huhprompt (yes/no for a single match, select list for multiple). Picking a profile re-execs Atmos with--profile <picked>prepended to the original argv.--profile <name>flag to re-run.profiles.defaultconfig field — implicit default profile loaded when--profileandATMOS_PROFILEare unset; explicit selection always wins; nested defaults are ignored to prevent recursion.ATMOS_PROFILE_FALLBACK=1prevents infinite re-prompt cycles when the picked profile also fails to resolve the identity.User aborted.message instead of cascading identity-not-found / authentication-failed errors.ui.FormatInline()so backticks render as styled inline code, matching the rest of Atmos.cfg.ProfilesWithIdentity()andcfg.ProfilesWithAuthConfig()helpers (scoped Viper, no global state pollution) to discover candidate profiles.AuthManager.MaybeOfferAnyProfileFallback()interface method called by every relevant auth command before returning the terminal "no identity" error.why
cloudposse/infra-livepatterns) put allauth.identities/auth.providersinsideprofiles/<name>/atmos.yamland leave the rootatmos.yamlminimal. Runningatmos auth loginthere errored withno providers availableand no actionable next step — users had to read source / docs to discover they needed--profile.profiles.defaultlets teams pin a sensible profile (e.g.developer) without forcing every shell to exportATMOS_PROFILE, while keeping explicit overrides authoritative.references
docs/prd/interactive-profile-suggestion.mdwebsite/blog/2026-04-16-interactive-profile-suggestion.mdxwebsite/docs/cli/configuration/profiles.mdxSummary by CodeRabbit
New Features
Bug Fixes
Documentation
Tests