Skip to content

feat: Add GitHub Actions format to atmos auth env - #1984

Merged
Andriy Knysh (aknysh) merged 20 commits into
mainfrom
osterman/auth-env-github-format
Apr 7, 2026
Merged

Andriy Knysh (aknysh) merged 20 commits into
mainfrom
osterman/auth-env-github-format

Conversation

@osterman

@osterman Erik Osterman (Cloud Posse) (osterman) commented Jan 16, 2026 •

Copy link
Copy Markdown
Member

what

  • Added --format=github option to atmos auth env command
  • Added --output flag for explicit file output (appends mode)
  • Automatically detects $GITHUB_ENV environment variable when using github format
  • Supports single-line values as KEY=value and multiline values with heredoc syntax

why

This eliminates the need for complex shell pipelines like atmos auth env ... | grep "^export " | sed 's/^export //' >> $GITHUB_ENV. Users can now directly output to GitHub Actions $GITHUB_ENV file with proper formatting and multiline value handling.

references

Closes issue related to GitHub Actions integration workflow simplification.

Summary by CodeRabbit

  • New Features

    • GitHub Actions format for atmos auth env: Export credentials directly to $GITHUB_ENV with --format=github
    • New --output-file flag to redirect output to a file
    • Automatic $GITHUB_ENV detection when using GitHub format without explicit output file specification
  • Documentation

    • Updated CLI help and documentation to reflect new format and flag options
    • Added blog post about GitHub Actions format integration

@github-actions github-actions Bot added the size/m Medium size PR label Jan 16, 2026
@github-actions

github-actions Bot commented Jan 16, 2026 •

Copy link
Copy Markdown

Dependency Review

✅ No vulnerabilities or license issues found.

Snapshot Warnings

⚠️: No snapshots were found for the head SHA b189c6e.
Ensure that dependencies are being submitted on PR branches and consider enabling retry-on-snapshot-warnings. See the documentation for more information and troubleshooting advice.

Scanned Files

None

@coderabbitai

coderabbitai Bot commented Jan 16, 2026 •

Copy link
Copy Markdown
Contributor

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

This PR adds GitHub Actions format support to atmos auth env, introducing a unified environment variable output API via pkg/env/output.go. The change consolidates per-format logic, adds --output-file flag for explicit routing, and auto-detects $GITHUB_ENV for GitHub format output.

Changes

Cohort / File(s) Summary
Command-Line Interface
cmd/auth_env.go, cmd/auth_env_test.go
Refactored to Viper-driven approach with new --output-file flag and GitHub format support. Removed legacy SupportedFormats export. Added GitHub Actions env auto-detection and multiline value handling. New TestGitHubEnvAutoDetect tests validate env file operations.
Environment Output System
pkg/env/output.go, pkg/env/output_test.go
New unified output API with constants DefaultOutputFileMode and CredentialFileMode, OutputOption pattern, and public Output function. Consolidated JSON, bash, dotenv, and github format handling. Comprehensive test suite covering all formats, multiline values, append behavior, and file modes.
Integration and Utilities
cmd/env/env.go, cmd/env/env_test.go, pkg/env/file.go
Simplified flag registration to "output-file" with ATMOS_ENV_OUTPUT_FILE binding. Removed convertToAnyMap in favor of envfmt.ConvertMapStringToAny. Centralized error handling in file.go using error utilities. Updated test assertions to use ErrOpenFile sentinel.
Format and Completion Tests
cmd/auth_integration_test.go, pkg/env/format_test.go, cmd/terraform/output_test.go
Updated completion assertions to include github format in expected set. Changed error validation from substring matching to ErrorIs checks with sentinel values.
Documentation
website/docs/cli/commands/auth/auth-env.mdx, website/blog/2026-01-16-auth-env-github-format.mdx
Added github format option and --output-file flag to command docs. New blog post documenting GitHub Actions integration, GITHUB_ENV auto-detection, heredoc multiline support, and workflow examples.
Roadmap and Test Expectations
website/src/data/roadmap.js, tests/snapshots/*, tests/test-cases/*
Updated CI/CD milestone progress and added GitHub Actions auth format milestone. Refreshed golden snapshots and test case expectations to reflect unquoted env values and updated error messages.

Sequence Diagram

sequenceDiagram
    participant CLI as CLI Command
    participant Cmd as cmd/auth_env
    participant Output as pkg/env/output
    participant Fmt as env/format
    participant GitHub as GitHub Actions
    participant File as File System

    CLI->>Cmd: Execute auth env --format=github
    Cmd->>Cmd: Parse flags via Viper
    Cmd->>Output: Output(envVars, "github", outputFile?, opts)
    Output->>Output: Check if format is github & no outputFile
    alt GitHub format with auto-detection
        Output->>Output: actions.GetEnvPath() → $GITHUB_ENV
        Output->>File: Append to detected GITHUB_ENV file
    else GitHub format with explicit file
        Output->>File: Append to specified outputFile
    else Other formats
        Output->>Fmt: FormatData(envVars, format)
        Fmt-->>Output: Formatted output
        Output->>File: writeToFileWithMode or stdout
    end
    File-->>GitHub: Environment variables available
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Suggested reviewers

  • aknysh
  • milldr
🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately and concisely summarizes the main change: adding GitHub Actions format support to the atmos auth env command.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch osterman/auth-env-github-format

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai

coderabbitai Bot commented Jan 16, 2026

Copy link
Copy Markdown
Contributor

Caution

Review failed

The head commit changed during the review from a16eb4e to 1fd7fd9.

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch osterman/auth-env-github-format

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🤖 Fix all issues with AI agents
In `@cmd/auth_env_test.go`:
- Around line 388-555: Add a RunE‑level test that uses t.Setenv("GITHUB_ENV",
filePath) to verify auto‑detect and append behavior: create a temp file with
initial content, call the CLI entrypoint (invoke the command's RunE or root
command Execute so the code path that would call
writeAuthEnvToFile/formatAuthGitHub runs), then read the file and assert it was
appended to (not overwritten) and that multiline values are formatted the same
as writeAuthEnvToFile when using formatAuthGitHub; use t.Setenv for
setup/teardown and reuse writeAuthEnvToFile and formatAuthGitHub as references
to expected formatting.

In `@cmd/auth_env.go`:
- Around line 21-30: The default file mode constant defaultAuthFileMode
currently uses 0o644 which leaves created auth files world-readable; change
defaultAuthFileMode to an owner-only permission (e.g., 0o600) and update its
comment to reflect owner-only access so newly created credential files are not
world-readable; ensure any code that relies on defaultAuthFileMode (e.g., file
creation or write routines) continues to use this constant.
- Around line 228-239: In formatAuthGitHub, the heredoc delimiter
ATMOS_EOF_<key> can collide with the value; change the logic to generate a
delimiter that is guaranteed not to appear in the value (e.g., append a
random/unique token or UUID to the delimiter and retry if
strings.Contains(value, delimiter) is true) and then use that safe delimiter for
both the opening marker and closing marker; update the heredoc construction in
formatAuthGitHub to use the computed safe delimiter and ensure the containment
check uses that same delimiter before writing the heredoc.
- Around line 40-48: The current code reads flags directly using
cmd.Flags().GetString for "format" and "output" which bypasses Viper bindings
and ignores ATMOS_AUTH_ENV_* env overrides; replace those reads with
viper.GetString("auth_env_format") and viper.GetString("auth_env_output")
(preserving the validation against SupportedFormats and the error return using
errUtils.ErrInvalidArgumentError) so the values bound in init() are honored
(refer to the format/output variables and the SupportedFormats check in the
auth_env command).
🧹 Nitpick comments (1)
cmd/auth_env.go (1)

272-288: Consider migrating new flag bindings to StandardParser.

This command still wires flags via viper.BindEnv/BindPFlag. The repo convention is flags.NewStandardParser() to avoid manual binding and keep precedence behavior consistent. As per coding guidelines, follow the standard parser pattern for cmd flags.

Comment thread cmd/auth_env_test.go Resolved
Comment thread cmd/auth_env.go Resolved
Comment thread cmd/auth_env.go Resolved
Comment thread cmd/auth_env.go Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
cmd/auth_env.go (1)

277-287: Refactor to use flags.NewStandardParser() instead of direct Viper binds.

The direct viper.BindEnv() and viper.BindPFlag() calls in init() violate the mandatory StandardParser pattern. Refactor the command to define flags via StandardParser with .WithStringFlag(), register them via parser.RegisterFlags(), and bind them in RunE via parser.BindFlagsToViper() (see cmd/toolchain/get.go for the pattern).

🤖 Fix all issues with AI agents
In `@cmd/auth_env.go`:
- Around line 21-27: The constant defaultAuthFileMode currently sets new
credential file permissions to 0o644 which allows world-readable access; change
defaultAuthFileMode in cmd/auth_env.go to 0o600 (owner read/write only) so
exported credentials are created with restrictive permissions suitable for
secret material.
- Around line 251-258: The file I/O error returns in cmd/auth_env.go should use
static sentinel errors from errors/errors.go instead of raw string literals; add
two new sentinel errors (e.g., ErrFileOpen and ErrFileWrite) to
errors/errors.go, import that package into cmd/auth_env.go, and replace the
current fmt.Errorf calls (the open error and the f.WriteString error) to wrap
the sentinel with the underlying error and context using %w (for example:
fmt.Errorf("%w: failed to open file '%s': %v", errors.ErrFileOpen, filePath,
err) and similarly for ErrFileWrite), keeping the existing message/context and
preserving error wrapping so callers can check errors.Is(err,
errors.ErrFileOpen) or errors.Is(err, errors.ErrFileWrite).
- Around line 236-239: The heredoc currently uses a fixed delimiter
"ATMOS_EOF_<key>" which can collide if value contains that line; change the
logic in the block handling multiline values (where variables key, value, sb are
used) to generate a unique delimiter not present in value by e.g. appending a
random or incremental suffix and looping until strings.Contains(value,
delimiter) is false, then use that delimiter in the fmt.Sprintf write instead of
the fixed "ATMOS_EOF_%s"; ensure the new delimiter variable replaces the
existing hard-coded delimiter in the sb.WriteString call.

Comment thread cmd/auth_env.go Resolved
Comment thread cmd/auth_env.go Resolved
Comment thread cmd/auth_env.go Resolved
coderabbitai[bot]
coderabbitai Bot previously approved these changes Jan 20, 2026
@mergify

mergify Bot commented Jan 21, 2026

Copy link
Copy Markdown
Contributor

💥 This pull request now has conflicts. Could you fix it Erik Osterman (Cloud Posse) (@osterman)? 🙏

Comment thread cmd/auth_env.go Fixed
Comment thread pkg/env/output.go Dismissed
coderabbitai[bot]
coderabbitai Bot previously approved these changes Jan 21, 2026
@mergify

mergify Bot commented Jan 24, 2026

Copy link
Copy Markdown
Contributor

💥 This pull request now has conflicts. Could you fix it Erik Osterman (Cloud Posse) (@osterman)? 🙏

@mergify mergify Bot added the conflict This PR has conflicts label Jan 24, 2026
Resolve merge conflicts:
- cmd/auth_env.go: Accept cliConfigPath parameter for createAuthManager
- cmd/auth_integration_test.go: Keep explicit format assertions for github format support

Co-Authored-By: Claude Opus 4.6 <[email protected]>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (1)
cmd/auth_env.go (1)

138-139: Fix the stale JSON comment.

json is no longer handled in this command; it is handled inside env.Output. The current comment points readers at the wrong layer.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@cmd/auth_env.go` around lines 138 - 139, The comment above the format
completion registration is stale: remove the line claiming "JSON is handled
separately in the command, not via pkg/env" and replace it with a brief note
that JSON formatting is handled by env.Output (so this registration only covers
pkg/env-supported formats); update the comment near the "Register format
completion" text to reference pkg/env and env.Output so readers are directed to
the correct layer.
🤖 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 121-123: The --format flag help on authEnvCmd currently lists
"bash, dotenv, github, json" but omits the supported "env" option; update the
StringP call for the "format" flag (authEnvCmd.Flags().StringP("format", "f",
...)) to include "env" in the help string so the flag description reads
something like "Output format: bash, dotenv, env, github, json" (adjust ordering
to match completion if desired).
- Around line 131-136: Replace the direct viper.BindEnv/BindPFlag calls for the
auth_env command with the standard flag parser pattern: create a parser via
flags.NewStandardParser(), register the "output-file" and "format" flags with
WithStringFlag (and any boolean flags with WithBoolFlag if present), call
WithEnvVars to map ATMOS_AUTH_ENV_OUTPUT_FILE (and the existing ENV for format)
and then call BindToViper() to bind into viper; update the code that currently
references authEnvCmd.Flags().Lookup("output-file") to use the parser
registration flow and ensure the parser is invoked before relying on viper
values.

---

Nitpick comments:
In `@cmd/auth_env.go`:
- Around line 138-139: The comment above the format completion registration is
stale: remove the line claiming "JSON is handled separately in the command, not
via pkg/env" and replace it with a brief note that JSON formatting is handled by
env.Output (so this registration only covers pkg/env-supported formats); update
the comment near the "Register format completion" text to reference pkg/env and
env.Output so readers are directed to the correct layer.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: b0b8b547-a679-408f-9cbe-39f693c6d395

📥 Commits

Reviewing files that changed from the base of the PR and between 33ab708 and 7b32d7a.

📒 Files selected for processing (2)
  • cmd/auth_env.go
  • cmd/auth_integration_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • cmd/auth_integration_test.go

Comment thread cmd/auth_env.go Resolved
Comment thread cmd/auth_env.go Resolved
…rage

Address PR review feedback:
- Refactor cmd/auth_env.go to use flags.NewStandardParser() instead of
  direct viper.BindEnv/BindPFlag calls (mandatory per coding guidelines)
- Add missing "env" format to --format flag help text
- Add tests for JSON output with/without AtmosConfig, env format,
  writeToFileWithMode error path, and WithFormatOptions passthrough

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@github-actions github-actions Bot added size/l Large size PR and removed size/m Medium size PR labels Mar 17, 2026
Update snapshot to reflect StandardParser flag output:
- Added "env" to format list
- Boolean flag default display matches Cobra convention

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@aknysh
Andriy Knysh (aknysh) merged commit c44a8f6 into main Apr 7, 2026
92 of 93 checks passed
@aknysh
Andriy Knysh (aknysh) deleted the osterman/auth-env-github-format branch April 7, 2026 22:06
@github-actions

github-actions Bot commented Apr 8, 2026

Copy link
Copy Markdown

These changes were released in v1.215.0-rc.4.

Andriy Knysh (aknysh) added a commit that referenced this pull request May 7, 2026
Resolves conflicts after rebase against main. Key resolutions:

- cmd/aws/ecr/login.go: accepted main's renamed/modified version (HEAD's
  auth refactor moved ECR out; main moved cmd/auth_ecr_login.go here).
- cmd/auth_*.go: accepted HEAD's deletion (refactored to cmd/auth/*.go).
  Moved auth_profile_fallback.go, auth_profile_fallback_test.go, and
  auth_identity_flow_test.go into cmd/auth/ (package change). Removed
  cmd/auth_config.go (superseded by cmd/auth/helpers.go::BuildConfigAndStacksInfo).
- cmd/auth/console.go: combined HEAD's StandardParser flag pattern with
  main's browser-isolation feature (--isolated, consoleSessionDir,
  resolveConsoleIsolated). Extended initializeAuthManager to also return
  *schema.AtmosConfiguration for isolation config access.
- cmd/auth/list.go: ported main's suggestProfilesForAuth helper. Updated
  loadAuthManagerForList to also return atmos config.
- cmd/auth/whoami.go, cmd/auth/logout.go: kept HEAD's signatures using
  BuildConfigAndStacksInfo(cmd, v) instead of newAuthConfigAndStacksInfo.
- cmd/auth/shell.go: changed prepareShellEnvironment to return []string
  (sanitized env list) to match main's ExecAuthShellCommand signature
  from the IRSA fix (#2143).
- internal/exec/terraform_utils.go: accepted main's refactored
  executeTerraformAffectedComponentInDepOrder (uses affectedDepOrderParams).
- Qualified bare IdentityFlagName references with cfg.IdentityFlagName
  in cmd/describe_*.go and cmd/identity_helpers.go after the symbol moved
  to cmd/auth.
- Golden snapshots took HEAD's content; will need regeneration to reflect
  added --isolated flag.

Features still missing in cmd/auth (need follow-up porting):
- auth env --format=github / --output-file (#1984)
- auth env --format=env (#1984)

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Andriy Knysh (aknysh) added a commit that referenced this pull request May 7, 2026
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]>
Andriy Knysh (aknysh) added a commit that referenced this pull request May 12, 2026
…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>

This branch was successfully deployed

1 active deployment
preview — b189c6ed Deployed Apr 7, 2026 by github-actions[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

minor New features that do not break anything size/l Large size PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants