Skip to content

Improve auth login with identity selection - #1655

Merged
Andriy Knysh (aknysh) merged 48 commits into
mainfrom
feature/dev-3707-show-user-selector-when-no-identity-is-passed-in-atmos-auth
Oct 22, 2025
Merged

Andriy Knysh (aknysh) merged 48 commits into
mainfrom
feature/dev-3707-show-user-selector-when-no-identity-is-passed-in-atmos-auth

Conversation

@osterman

@osterman Erik Osterman (Cloud Posse) (osterman) commented Oct 17, 2025 •

Copy link
Copy Markdown
Member

what

  • Modified the auth login command to automatically prompt for an identity when no --identity flag is provided.
  • This leverages the existing authManager.GetDefaultIdentity() which handles interactive selection and fallback logic.
  • Updated documentation to reflect this new behavior.

why

  • Users were prompted to manually select an identity in interactive sessions when no default was set.
  • This change simplifies the login process by automatically invoking the interactive selector or using the default identity when available, improving user experience and reducing manual input.

references

  • No specific issue linked - this is a user experience enhancement.

@github-actions github-actions Bot added the size/m Medium size PR label Oct 17, 2025
@coderabbitai

coderabbitai Bot commented Oct 17, 2025 •

Copy link
Copy Markdown
Contributor

Warning

Rate limit exceeded

Erik Osterman (Cloud Posse) (@osterman) has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 9 minutes and 7 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 7d25970 and 14f0c6c.

📒 Files selected for processing (1)
  • pkg/auth/cloud/aws/setup.go (2 hunks)

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

📝 Walkthrough

Walkthrough

This pull request introduces interactive identity selection for atmos auth login, implements AWS SAML driver detection with Playwright auto-download logic, refactors error wrapping throughout the auth module for proper error chaining, and adds test infrastructure improvements including a new linter rule for os.Args usage in tests.

Changes

Cohort / File(s) Summary
Auth Login Command Enhancement
cmd/auth_login.go
Adds fallback identity retrieval via GetDefaultIdentity when no identity flag provided; introduces timing instrumentation via perf.Track; replaces plain errors with wrapped errors using ErrFailedToInitConfig, ErrFailedToInitializeAuthManager, ErrAuthenticationFailed; uses viper for flag retrieval.
Auth Login Tests
cmd/auth_login_test.go
Removes os import and os.Args manipulation; converts TestCreateAuthManager to table-driven approach with scenarios for valid/nil/empty config; adds TestExecuteAuthLoginCommand for login command execution path with error scenarios and identity flag handling.
Error Wrapping Updates (Consistent Pattern)
pkg/auth/cloud/aws/env.go, pkg/auth/cloud/aws/setup.go, pkg/auth/identities/aws/permission_set.go, pkg/auth/identities/aws/user.go, pkg/auth/providers/aws/sso.go, pkg/auth/types/aws_credentials.go, pkg/auth/validation/validator.go
Replaces error formatting verbs from %v to %w across multiple error returns to preserve error chains and enable proper error unwrapping.
Auth Manager Refactoring
pkg/auth/manager.go
Converts error-joining patterns to fmt.Errorf with %w wrapping; updates error context strings and labels; introduces sorting of identities in promptForIdentity for deterministic output; removes errors package usage in favor of wrapped errors; expands error contexts with identity/provider names.
AWS SAML Driver Detection
pkg/auth/providers/aws/saml.go
Introduces driver detection via getDriver() replacing getProviderType(); adds browser auto-download flow with shouldDownloadBrowser(); implements Playwright driver validation and detection across OS-specific paths; adds granular checks for driver presence with fallback logic; updates SAML configuration to use driver instead of provider type.
AWS SAML Tests
pkg/auth/providers/aws/saml_test.go
Updates test calls from getProviderType() to getDriver(); adds TestSAMLProvider_shouldDownloadBrowser for download logic validation; adds TestSAMLProvider_Validate_URLFormats for URL format validation; adds TestSAMLProvider_Environment_AutoDownload for environment variable behavior.
AWS SAML Driver Detection Tests
pkg/auth/providers/aws/saml_driver_detection_test.go
Adds new test file with table-driven tests for Playwright driver detection: TestHasValidPlaywrightDrivers, TestHasPlaywrightDriversOrCanDownload, TestGetDriver_WithPlaywrightDrivers covering multiple scenarios with filesystem setup.
Test Infrastructure
cmd/testing_helpers_test.go, cmd/testkit_test.go
Adds os import and osArgs field to cmdStateSnapshot; captures and restores os.Args in snapshotRootCmdState and restoreRootCmdState; adds TestTestKit_OsArgsRestoration to verify os.Args restoration after subtests.
Linter Rule for os.Args Usage
tools/lintroller/rule_os_args.go, tools/lintroller/plugin.go
Introduces OsArgsInTestRule to detect os.Args usage in test files; adds to Settings struct and BuildAnalyzers; excludes benchmark functions from checks via findBenchmarks helper; advises using cmd.SetArgs() instead.
Linter Test Data
tools/lintroller/testdata/src/a/bad_test.go
Adds TestBadOsArgs with linter directive comments indicating expected errors; adds BenchmarkGoodOsArgs with OK comments to validate benchmark allowance.
Auth Manager Tests
pkg/auth/manager_test.go
Updates test expectations from ErrInitializingProviders to ErrInvalidProviderConfig and ErrInitializingIdentities to ErrInvalidIdentityConfig.
Validator Tests
pkg/auth/validation/validator_test.go
Adds TestValidateAuthConfig_ErrorWrapping table-driven test covering invalid logs config, provider, identity, and identity chain with error wrapping validation.
Schema Changes
pkg/schema/schema_auth.go
Adds new public Driver field to Provider struct; retains ProviderType as deprecated alias with comment for backward compatibility.
Authentication Configuration
.golangci.yml
Enables errorlint linter with settings for non-wrapping fmt.Errorf verbs, multi-verb wrapping, errors.As suggestions, and errors.Is suggestions.
Documentation
website/docs/cli/commands/auth/auth-login.mdx
Clarifies behavior when --identity omitted (prompts if no default, auto-use if one default, error in CI/non-interactive); expands --identity/alias (-i) description with interactive selection and environment variable precedence (ATMOS_IDENTITY, IDENTITY); adds Interactive Identity Selection section; adds Notes on credentials caching and selector navigation.
SAML Provider Documentation
website/docs/cli/commands/auth/usage.mdx
Adds driver field documentation under AWS SAML provider; adds "SAML Driver Options" section detailing Browser, GoogleApps, Okta, ADFS; documents auto-selection behavior; includes Playwright installation snippets; removes CLI example line.
Blog Post
website/blog/2025-10-17-interactive-identity-selection.md
Introduces blog post detailing interactive identity selector enhancement; documents behavior for interactive mode (auto-use one default, selector for none/multiple defaults) and CI/CD mode (error if no default); emphasizes backward compatibility and user interaction details.

Sequence Diagram(s)

sequenceDiagram
    participant user as User/CLI
    participant cmd as auth_login cmd
    participant mgr as AuthManager
    participant prompt as Interactive Prompt
    participant auth as Identity Authenticator

    user->>cmd: atmos auth login [--identity flag?]
    
    alt identity flag provided
        cmd->>auth: Authenticate(identity)
    else no identity flag
        cmd->>cmd: Check default identity
        
        alt exactly one default
            cmd->>auth: Authenticate(default)
        else zero defaults
            rect rgb(200, 220, 255)
            note right of cmd: Interactive Mode Only
            cmd->>prompt: Show identity selector
            prompt-->>user: Arrow keys to navigate
            user-->>prompt: Press Enter
            prompt-->>cmd: Selected identity
            cmd->>auth: Authenticate(selected)
            end
        else multiple defaults
            rect rgb(200, 220, 255)
            note right of cmd: Interactive Mode Only
            cmd->>prompt: Show filtered defaults
            prompt-->>user: Arrow keys to navigate
            user-->>prompt: Press Enter
            prompt-->>cmd: Selected identity
            cmd->>auth: Authenticate(selected)
            end
        else CI/non-interactive env
            rect rgb(255, 200, 200)
            note right of cmd: Error Path
            cmd-->>user: Error: no default identity found
            end
        end
    end
    
    auth->>auth: Execute auth flow
    auth-->>cmd: Credentials
    cmd-->>user: Success
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~75 minutes

This includes: substantial AWS SAML driver detection logic with multiple helper functions and detection paths; widespread but repetitive error wrapping changes (%v to %w conversions) across 7+ files; new linter rule with AST traversal and benchmark exclusion logic; test infrastructure modifications for os.Args handling; interactive identity selection feature in auth manager; and corresponding test coverage additions. The repetitive error wrapping changes reduce per-file effort, but the driver detection logic and linter rule are dense and require careful review.

Possibly related PRs

Suggested reviewers

  • osterman

Pre-merge checks and finishing touches

❌ Failed checks (3 warnings)
Check name Status Explanation Resolution
Linked Issues Check ⚠️ Warning The PR claims to close issue #123, which requests configurable analytics settings (components_enabled, auto_crash_log_send_enabled, commands_enabled) in atmos.yaml. However, the actual code changes are entirely focused on improving the auth login command with identity selection and do not implement any analytics configuration objectives. No changes to analytics settings, atmos.yaml configuration structures, or telemetry controls appear in the changeset—making this PR fundamentally misaligned with issue #123's requirements. Verify the correct issue should be linked to this PR. If this PR is intended to address auth login improvements, link a different issue that describes identity selection enhancements. If #123 is the correct issue, this PR needs to include analytics configuration implementation to satisfy the stated objectives before merging.
Out of Scope Changes Check ⚠️ Warning While most changes support the auth login identity selection feature (error wrapping improvements, SAML driver detection, documentation), the pull request introduces a substantial new linting subsystem (tools/lintroller/rule_os_args.go, plugin updates, and corresponding test data) for detecting os.Args usage in test files. Although this touches testing infrastructure, the os.Args linting rule appears to be a separate capability that goes beyond supporting the core identity selection feature and should arguably be addressed in a distinct PR focused on test quality enforcement. Consider extracting the lintroller os.Args rule (tools/lintroller/rule_os_args.go, plugin.go changes, and testdata) into a separate PR to maintain clear scope. Alternatively, document why this linting capability is essential to the auth login identity selection feature and should be included in this changeset.
Docstring Coverage ⚠️ Warning Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Title Check ✅ Passed The PR title "Improve auth login with identity selection" directly reflects the primary change in the pull request—enhancing the auth login command to present interactive identity selection when no --identity flag is provided. The title is concise, specific, and clearly communicates the main improvement without vague terminology. It accurately summarizes the author's intent based on the core changes to auth_login.go, auth documentation, and blog post introducing this feature.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

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: 1

Caution

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

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

28-28: Add performance tracking.

Per coding guidelines, public functions should include defer perf.Track() at the start, followed by a blank line. This function is missing performance tracking.

Apply this diff:

 func executeAuthLoginCommand(cmd *cobra.Command, args []string) error {
+	defer perf.Track()
+
 	handleHelpRequest(cmd, args)

Note: You'll need to import the perf package if not already imported.

Based on coding guidelines.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 6e04105 and 24bd8ca.

📒 Files selected for processing (3)
  • cmd/auth_login.go (1 hunks)
  • cmd/auth_login_test.go (1 hunks)
  • website/docs/cli/commands/auth/auth-login.mdx (2 hunks)
🧰 Additional context used
📓 Path-based instructions (8)
cmd/**/*.go

📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)

cmd/**/*.go: Use Cobra's recommended command structure with a root command and subcommands
Implement each CLI command in a separate file under cmd/
Use Viper for managing configuration, environment variables, and flags in the CLI
Keep separation of concerns between CLI interface (cmd) and business logic
Use kebab-case for command-line flags
Provide comprehensive help text for all commands and flags
Include examples in Cobra command help
Use Viper for configuration management; support files, env vars, and flags with precedence flags > env > config > defaults
Follow single responsibility; separate command interface from business logic
Provide meaningful user feedback and include progress indicators for long-running operations
Provide clear error messages to users and troubleshooting hints where appropriate

cmd/**/*.go: Use utils.PrintfMarkdown() to render embedded markdown content for CLI command help/examples.
One Cobra command per file in cmd/; keep files focused and small.

Files:

  • cmd/auth_login.go
  • cmd/auth_login_test.go
**/*.go

📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)

**/*.go: All code must pass golangci-lint checks
Follow Go error handling idioms and use meaningful error messages
Wrap errors with context using fmt.Errorf("context: %w", err)
Consider custom error types for domain-specific errors
Follow standard Go coding style; run gofmt and goimports
Use snake_case for environment variables
Document complex logic with inline comments

**/*.go: All Go comments must end with periods; applies to single-line, multi-line, inline, and documentation comments (golangci-lint godot).
Group imports into three sections (stdlib, 3rd-party, Atmos), separated by blank lines; sort alphabetically within each group; preserve existing aliases.
Configuration loading must use Viper with precedence CLI → ENV → files → defaults; bind config name atmos and add path, AutomaticEnv, and ATMOS prefix.
All errors must be wrapped using static errors (defined in errors/errors.go); use errors.Join for multiple errors; fmt.Errorf with %w for context; use errors.Is for checks; never compare error strings.
Distinguish structured logging from UI output: UI prompts/status/errors to stderr; data/results to stdout; never use logging for UI.
Most text UI must go to stderr; only data/results to stdout; prefer utils.PrintfMessageToTUI for UI messages.
All new configurations must support Go templating using existing utilities and available template functions.
Prefer SDKs over external binaries for cross-platform support; use filepath/os/runtime for portability.
For non-standard execution paths, capture telemetry via telemetry.CaptureCmd or telemetry.CaptureCmdString without user data.
80% minimum coverage on new/changed lines and include unit tests for new features; add integration tests for CLI using tests/ fixtures.
Always bind environment variables with viper.BindEnv and provide ATMOS_ alternatives for every env var.
Use structured logging with levels (Fatal>Error>Warn>Debug>Trace); avoid string interpolation and ensure logging does not affect execution.
Prefer re...

Files:

  • cmd/auth_login.go
  • cmd/auth_login_test.go
**/!(*_test).go

📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)

Document all exported functions, types, and methods with Go doc comments

Add defer perf.Track() to all public functions and critical private functions; include a blank line after the call; use package-prefixed names; pass atmosConfig when present, else nil.

Files:

  • cmd/auth_login.go
website/**

📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)

website/**: Update website documentation in website/ when adding features
Ensure consistency between CLI help text and website documentation
Follow the website's documentation structure and style
Keep website code in website/ and follow its architecture/style; test changes locally
Keep CLI and website documentation in sync; document new features with examples and use cases

Before committing documentation/site changes, run npm run build in website/ and fix errors, broken links, and missing images.

Files:

  • website/docs/cli/commands/auth/auth-login.mdx
website/docs/cli/commands/**/*.mdx

📄 CodeRabbit inference engine (CLAUDE.md)

Document all new commands/flags/parameters in Docusaurus under website/docs/cli/commands/, using definition lists for args/flags and the prescribed frontmatter and sections.

Files:

  • website/docs/cli/commands/auth/auth-login.mdx
website/docs/**

📄 CodeRabbit inference engine (CLAUDE.md)

website/docs/**: After modifying any docs under website/docs/, build the website (npm run build) and ensure no errors.
Document user-facing template functions in the website if applicable.

Files:

  • website/docs/cli/commands/auth/auth-login.mdx
**/*_test.go

📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)

**/*_test.go: Every new feature must include comprehensive unit tests
Test both happy paths and error conditions
Use table-driven tests for multiple scenarios

**/*_test.go: Use table-driven unit tests for pure functions and focus on behavior; co-locate tests; target >80% coverage for pkg/ and internal/exec/.
Always use t.Skipf() with a clear reason; never use t.Skip() or t.Skipf without a reason.

Files:

  • cmd/auth_login_test.go
cmd/**/*_test.go

📄 CodeRabbit inference engine (CLAUDE.md)

Command tests live under cmd/ alongside command implementations.

Files:

  • cmd/auth_login_test.go
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (8)
  • GitHub Check: Build (ubuntu-latest, linux)
  • GitHub Check: Build (windows-latest, windows)
  • GitHub Check: Build (macos-latest, macos)
  • GitHub Check: Run pre-commit hooks
  • GitHub Check: Lint (golangci)
  • GitHub Check: Analyze (go)
  • GitHub Check: website-deploy-preview
  • GitHub Check: Summary
🔇 Additional comments (3)
cmd/auth_login.go (1)

46-52: Good default identity resolution.

The logic correctly retrieves the default identity when none is specified, with proper error wrapping. The implementation aligns well with the PR objective.

cmd/auth_login_test.go (1)

224-225: Good punctuation fix.

Comment now properly ends with a period per guidelines.

website/docs/cli/commands/auth/auth-login.mdx (1)

26-71: Documentation content is valid; production build verification needed.

The auth-login.mdx file has valid syntax and follows documentation guidelines properly. The build failure stems from a sandbox environment limitation (missing fetch API for the fetch-latest-release plugin), not from your documentation changes. The fetch-latest-release plugin wasn't modified in this PR—the build error is pre-existing in this sandbox.

Manually verify the website builds without errors in your local environment before merging.

@osterman Erik Osterman (Cloud Posse) (osterman) added the minor New features that do not break anything label Oct 17, 2025
@github-actions

Copy link
Copy Markdown

Warning

Changelog Entry Required

This PR is labeled minor or major but doesn't include a changelog entry.

Action needed: Add a new blog post in website/blog/ to announce this change.

Example filename: website/blog/2025-10-17-feature-name.mdx

Alternatively: If this change doesn't require a changelog entry, remove the minor or major label.

@codecov

codecov Bot commented Oct 17, 2025 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 70.14925% with 60 lines in your changes missing coverage. Please review.
✅ Project coverage is 66.65%. Comparing base (be58d99) to head (14f0c6c).
⚠️ Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
pkg/auth/manager.go 60.37% 21 Missing ⚠️
pkg/auth/providers/aws/saml.go 81.41% 16 Missing and 5 partials ⚠️
pkg/auth/identities/aws/user.go 16.66% 5 Missing ⚠️
pkg/auth/providers/aws/sso.go 0.00% 4 Missing ⚠️
cmd/auth_login.go 76.92% 3 Missing ⚠️
pkg/auth/identities/aws/permission_set.go 0.00% 3 Missing ⚠️
pkg/auth/cloud/aws/setup.go 0.00% 2 Missing ⚠️
pkg/auth/cloud/aws/env.go 50.00% 1 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main    #1655      +/-   ##
==========================================
+ Coverage   66.57%   66.65%   +0.08%     
==========================================
  Files         359      359              
  Lines       41780    41893     +113     
==========================================
+ Hits        27816    27925     +109     
- Misses      11908    11911       +3     
- Partials     2056     2057       +1     
Flag Coverage Δ
unittests 66.65% <70.14%> (+0.08%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
pkg/auth/types/aws_credentials.go 100.00% <100.00%> (ø)
pkg/auth/validation/validator.go 80.14% <100.00%> (+6.61%) ⬆️
pkg/auth/cloud/aws/env.go 93.18% <50.00%> (ø)
pkg/auth/cloud/aws/setup.go 43.75% <0.00%> (ø)
cmd/auth_login.go 25.53% <76.92%> (+17.39%) ⬆️
pkg/auth/identities/aws/permission_set.go 55.30% <0.00%> (ø)
pkg/auth/providers/aws/sso.go 49.43% <0.00%> (ø)
pkg/auth/identities/aws/user.go 63.59% <16.66%> (ø)
pkg/auth/manager.go 85.62% <60.37%> (-0.64%) ⬇️
pkg/auth/providers/aws/saml.go 77.99% <81.41%> (+3.08%) ⬆️

... and 4 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Copilot AI 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.

Pull Request Overview

This PR enhances the auth login command to automatically prompt users for identity selection when no --identity flag is provided, improving the user experience by reducing manual input requirements while maintaining support for CI/CD environments.

Key Changes:

  • Added automatic invocation of authManager.GetDefaultIdentity() when no identity flag is specified
  • Updated documentation to reflect interactive identity selection behavior and provide CI/CD guidance
  • Added test coverage for the new identity resolution logic

Reviewed Changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 1 comment.

File Description
cmd/auth_login.go Implements automatic identity resolution by calling GetDefaultIdentity() when no --identity flag is provided
cmd/auth_login_test.go Adds test cases verifying the new identity selection behavior with and without the identity flag
website/docs/cli/commands/auth/auth-login.mdx Updates documentation to describe interactive identity selection and clarifies behavior in different environments

Tip: Customize your code reviews with copilot-instructions.md. Create the file or learn how to get started.

Comment thread website/docs/cli/commands/auth/auth-login.mdx Outdated

@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

Caution

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

⚠️ Outside diff range comments (2)
cmd/auth_login.go (2)

79-85: Add perf tracking to createAuthManager.

This is a critical helper on the execution path.

 func createAuthManager(authConfig *schema.AuthConfig) (auth.AuthManager, error) {
+  //nolint:revive
+  defer perf.Track("cmd.auth.createAuthManager", nil)
+
   credStore := credentials.NewCredentialStore()
   validator := validation.NewValidator()
 
   return auth.NewAuthManager(authConfig, credStore, validator, nil)
 }

As per coding guidelines.


3-16: Add perf.Track() and doc comment to public functions in cmd/auth_login.go.

The file has two critical violations:

  1. executeAuthLoginCommand (line 31): Public function missing both defer perf.Track() with blank line after, and a Go doc comment. Add:

    // executeAuthLoginCommand authenticates using a configured identity.
    func executeAuthLoginCommand(cmd *cobra.Command, args []string) error {
        defer perf.Track()
        
        handleHelpRequest(cmd, args)
  2. createAuthManager (line 77): Public function missing defer perf.Track() with blank line after. Add after opening brace:

    func createAuthManager(authConfig *schema.AuthConfig) (auth.AuthManager, error) {
        defer perf.Track()
        
        credStore := credentials.NewCredentialStore()

Imports are sorted correctly (stdlib → 3rd-party → Atmos, alphabetically within each group).

🧹 Nitpick comments (3)
cmd/auth_login.go (3)

47-54: Guard against empty identity after GetDefaultIdentity.

If GetDefaultIdentity ever returns "", nil, Authenticate("") will be ambiguous. Add a defensive check.

   if identityName == "" {
     identityName, err = authManager.GetDefaultIdentity()
     if err != nil {
       return errors.Join(errUtils.ErrDefaultIdentity, err)
     }
+    if identityName == "" {
+      return errors.Join(errUtils.ErrDefaultIdentity, errors.New("no identity configured or selected"))
+    }
   }

55-60: Use cmd.Context() to support cancellation/timeout.

Propagate the command’s context instead of context.Background().

-  ctx := context.Background()
+  ctx := cmd.Context()

As per coding guidelines.


18-27: Add Examples to command help.

Cobra Examples improve discoverability; include identityless and explicit-identity cases.

 var authLoginCmd = &cobra.Command{
   Use:   "login",
   Short: "Authenticate using a configured identity",
   Long:  "Authenticate to cloud providers using an identity defined in `atmos.yaml`.",
+  Example: `
+  # Prompt to select a default identity (interactive)
+  atmos auth login
+
+  # Use a specific identity
+  atmos auth login --identity admin
+  atmos auth login -i admin
+  `,

As per coding guidelines.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 24bd8ca and fb3158f.

📒 Files selected for processing (1)
  • cmd/auth_login.go (2 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
cmd/**/*.go

📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)

cmd/**/*.go: Use Cobra's recommended command structure with a root command and subcommands
Implement each CLI command in a separate file under cmd/
Use Viper for managing configuration, environment variables, and flags in the CLI
Keep separation of concerns between CLI interface (cmd) and business logic
Use kebab-case for command-line flags
Provide comprehensive help text for all commands and flags
Include examples in Cobra command help
Use Viper for configuration management; support files, env vars, and flags with precedence flags > env > config > defaults
Follow single responsibility; separate command interface from business logic
Provide meaningful user feedback and include progress indicators for long-running operations
Provide clear error messages to users and troubleshooting hints where appropriate

cmd/**/*.go: Use utils.PrintfMarkdown() to render embedded markdown content for CLI command help/examples.
One Cobra command per file in cmd/; keep files focused and small.

Files:

  • cmd/auth_login.go
**/*.go

📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)

**/*.go: All code must pass golangci-lint checks
Follow Go error handling idioms and use meaningful error messages
Wrap errors with context using fmt.Errorf("context: %w", err)
Consider custom error types for domain-specific errors
Follow standard Go coding style; run gofmt and goimports
Use snake_case for environment variables
Document complex logic with inline comments

**/*.go: All Go comments must end with periods; applies to single-line, multi-line, inline, and documentation comments (golangci-lint godot).
Group imports into three sections (stdlib, 3rd-party, Atmos), separated by blank lines; sort alphabetically within each group; preserve existing aliases.
Configuration loading must use Viper with precedence CLI → ENV → files → defaults; bind config name atmos and add path, AutomaticEnv, and ATMOS prefix.
All errors must be wrapped using static errors (defined in errors/errors.go); use errors.Join for multiple errors; fmt.Errorf with %w for context; use errors.Is for checks; never compare error strings.
Distinguish structured logging from UI output: UI prompts/status/errors to stderr; data/results to stdout; never use logging for UI.
Most text UI must go to stderr; only data/results to stdout; prefer utils.PrintfMessageToTUI for UI messages.
All new configurations must support Go templating using existing utilities and available template functions.
Prefer SDKs over external binaries for cross-platform support; use filepath/os/runtime for portability.
For non-standard execution paths, capture telemetry via telemetry.CaptureCmd or telemetry.CaptureCmdString without user data.
80% minimum coverage on new/changed lines and include unit tests for new features; add integration tests for CLI using tests/ fixtures.
Always bind environment variables with viper.BindEnv and provide ATMOS_ alternatives for every env var.
Use structured logging with levels (Fatal>Error>Warn>Debug>Trace); avoid string interpolation and ensure logging does not affect execution.
Prefer re...

Files:

  • cmd/auth_login.go
**/!(*_test).go

📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)

Document all exported functions, types, and methods with Go doc comments

Add defer perf.Track() to all public functions and critical private functions; include a blank line after the call; use package-prefixed names; pass atmosConfig when present, else nil.

Files:

  • cmd/auth_login.go
🧬 Code graph analysis (1)
cmd/auth_login.go (3)
pkg/config/config.go (1)
  • InitCliConfig (25-62)
pkg/schema/schema.go (1)
  • ConfigAndStacksInfo (460-539)
errors/errors.go (4)
  • ErrFailedToInitConfig (238-238)
  • ErrFailedToInitializeAuthManager (342-342)
  • ErrDefaultIdentity (335-335)
  • ErrAuthenticationFailed (332-332)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: Build (windows-latest, windows)
  • GitHub Check: Build (ubuntu-latest, linux)
  • GitHub Check: Lint (golangci)
  • GitHub Check: Analyze (go)
  • GitHub Check: website-deploy-preview
  • GitHub Check: Summary
🔇 Additional comments (2)
cmd/auth_login.go (2)

38-42: Auth manager init + error wrapping looks good.

Static sentinel + errors.Join aligns with repo error policy.


62-74: Success UI is clear and uses TUI output.

Conditional fields and TUI are on-point.

Comment thread cmd/auth_login.go
Comment thread cmd/auth_login.go

@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: 0

🧹 Nitpick comments (1)
website/blog/2025-10-17-interactive-identity-selection.md (1)

27-39: Consider adding an example for ATMOS_IDENTITY environment variable.

Line 27 mentions the ATMOS_IDENTITY env var for CI/CD, but the example (lines 29–39) only shows interactive selection. Adding a CI/CD example would help readers understand the non-interactive path.

Consider adding a CI/CD example:

 ## Example

 ```bash
 # No identity specified - shows interactive selector
 $ atmos auth login

 # Use arrow keys to navigate and Enter to select:
 > dev-admin
   prod-readonly
   staging-deploy

+CI/CD environments:
+bash +# Pass identity explicitly or use environment variable +$ atmos auth login --identity prod-readonly + +# Or set environment variable +$ ATMOS_IDENTITY=prod-readonly atmos auth login +


</blockquote></details>

</blockquote></details>

<details>
<summary>📜 Review details</summary>

**Configuration used**: Path: .coderabbit.yaml

**Review profile**: CHILL

**Plan**: Pro

**Disabled knowledge base sources:**

- Linear integration is disabled by default for public repositories

> You can enable these sources in your CodeRabbit configuration.

<details>
<summary>📥 Commits</summary>

Reviewing files that changed from the base of the PR and between fb3158ff9b02c619c4b76f5d41b6ed5b7b217007 and 437af06792dfab5dd0e2ffb56f84ab090b90b4ee.

</details>

<details>
<summary>📒 Files selected for processing (1)</summary>

* `website/blog/2025-10-17-interactive-identity-selection.md` (1 hunks)

</details>

<details>
<summary>🧰 Additional context used</summary>

<details>
<summary>📓 Path-based instructions (2)</summary>

<details>
<summary>website/**</summary>


**📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)**

> `website/**`: Update website documentation in website/ when adding features
> Ensure consistency between CLI help text and website documentation
> Follow the website's documentation structure and style
> Keep website code in website/ and follow its architecture/style; test changes locally
> Keep CLI and website documentation in sync; document new features with examples and use cases
> 
> Before committing documentation/site changes, run npm run build in website/ and fix errors, broken links, and missing images.

Files:
- `website/blog/2025-10-17-interactive-identity-selection.md`

</details>
<details>
<summary>website/blog/*.md</summary>


**📄 CodeRabbit inference engine (CLAUDE.md)**

> `website/blog/*.md`: For PRs labeled minor or major, include a blog post in website/blog/YYYY-MM-DD-*.md following the template and include <!--truncate--> after the introduction.
> Tag blog posts appropriately: user-facing (feature/enhancement/bugfix) or contributor (contributors) plus relevant technical tags.

Files:
- `website/blog/2025-10-17-interactive-identity-selection.md`

</details>

</details>

</details>

<details>
<summary>⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (8)</summary>

* GitHub Check: Build (windows-latest, windows)
* GitHub Check: Build (macos-latest, macos)
* GitHub Check: Build (ubuntu-latest, linux)
* GitHub Check: Run pre-commit hooks
* GitHub Check: website-deploy-preview
* GitHub Check: Lint (golangci)
* GitHub Check: Analyze (go)
* GitHub Check: Summary

</details>

<details>
<summary>🔇 Additional comments (3)</summary><blockquote>

<details>
<summary>website/blog/2025-10-17-interactive-identity-selection.md (3)</summary><blockquote>

`1-10`: **Blog post structure and format look solid.**

Front matter is complete, tags are appropriate for a user-facing feature, and `<!--truncate-->` is correctly placed. The introduction clearly conveys the enhancement.

---

`16-27`: **Interactive and CI/CD behavior is well-documented.**

Clear breakdown of the three interactive scenarios (single default, multiple defaults, no defaults) and explicit note about CI/CD mode requiring explicit identity or env var. Good distinction.

---

`53-53`: **Verify documentation link path.**

The link references `/cli/commands/auth/auth-login`. Ensure this path matches the actual file location in the repository (the AI summary mentions `website/docs/cli/commands/auth/auth-login.mdx`).

</blockquote></details>

</blockquote></details>

</details>

<!-- This is an auto-generated comment by CodeRabbit for review status -->

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
coderabbitai[bot]
coderabbitai Bot previously approved these changes Oct 18, 2025

@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: 0

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

35-40: Consider aligning perf tracking name with command hierarchy.

The parameter order and usage are correct. However, using "cmd.auth.login" instead of "cmd.executeAuthLoginCommand" would better match the command structure and make metrics more intuitive.

-	defer perf.Track(&atmosConfig, "cmd.executeAuthLoginCommand")()
+	defer perf.Track(&atmosConfig, "cmd.auth.login")()
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between bf0e202 and 51af9f0.

📒 Files selected for processing (2)
  • cmd/auth_login.go (2 hunks)
  • cmd/auth_login_test.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • cmd/auth_login_test.go
🧰 Additional context used
📓 Path-based instructions (3)
cmd/**/*.go

📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)

cmd/**/*.go: Use Cobra's recommended command structure with a root command and subcommands
Implement each CLI command in a separate file under cmd/
Use Viper for managing configuration, environment variables, and flags in the CLI
Keep separation of concerns between CLI interface (cmd) and business logic
Use kebab-case for command-line flags
Provide comprehensive help text for all commands and flags
Include examples in Cobra command help
Use Viper for configuration management; support files, env vars, and flags with precedence flags > env > config > defaults
Follow single responsibility; separate command interface from business logic
Provide meaningful user feedback and include progress indicators for long-running operations
Provide clear error messages to users and troubleshooting hints where appropriate

cmd/**/*.go: Use utils.PrintfMarkdown() to render embedded markdown content for CLI command help/examples.
One Cobra command per file in cmd/; keep files focused and small.

Files:

  • cmd/auth_login.go
**/*.go

📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)

**/*.go: All code must pass golangci-lint checks
Follow Go error handling idioms and use meaningful error messages
Wrap errors with context using fmt.Errorf("context: %w", err)
Consider custom error types for domain-specific errors
Follow standard Go coding style; run gofmt and goimports
Use snake_case for environment variables
Document complex logic with inline comments

**/*.go: All Go comments must end with periods; applies to single-line, multi-line, inline, and documentation comments (golangci-lint godot).
Group imports into three sections (stdlib, 3rd-party, Atmos), separated by blank lines; sort alphabetically within each group; preserve existing aliases.
Configuration loading must use Viper with precedence CLI → ENV → files → defaults; bind config name atmos and add path, AutomaticEnv, and ATMOS prefix.
All errors must be wrapped using static errors (defined in errors/errors.go); use errors.Join for multiple errors; fmt.Errorf with %w for context; use errors.Is for checks; never compare error strings.
Distinguish structured logging from UI output: UI prompts/status/errors to stderr; data/results to stdout; never use logging for UI.
Most text UI must go to stderr; only data/results to stdout; prefer utils.PrintfMessageToTUI for UI messages.
All new configurations must support Go templating using existing utilities and available template functions.
Prefer SDKs over external binaries for cross-platform support; use filepath/os/runtime for portability.
For non-standard execution paths, capture telemetry via telemetry.CaptureCmd or telemetry.CaptureCmdString without user data.
80% minimum coverage on new/changed lines and include unit tests for new features; add integration tests for CLI using tests/ fixtures.
Always bind environment variables with viper.BindEnv and provide ATMOS_ alternatives for every env var.
Use structured logging with levels (Fatal>Error>Warn>Debug>Trace); avoid string interpolation and ensure logging does not affect execution.
Prefer re...

Files:

  • cmd/auth_login.go
**/!(*_test).go

📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)

Document all exported functions, types, and methods with Go doc comments

Add defer perf.Track() to all public functions and critical private functions; include a blank line after the call; use package-prefixed names; pass atmosConfig when present, else nil.

Files:

  • cmd/auth_login.go
🧠 Learnings (5)
📓 Common learnings
Learnt from: Benbentwo
PR: cloudposse/atmos#1452
File: cmd/auth_login.go:43-44
Timestamp: 2025-09-07T18:07:00.549Z
Learning: In the atmos project, the identity flag is defined as a persistent flag on the auth root command (cmd/auth.go), making it available to all auth subcommands without needing to be redefined in each individual subcommand.
📚 Learning: 2025-10-16T15:18:00.319Z
Learnt from: CR
PR: cloudposse/atmos#0
File: CLAUDE.md:0-0
Timestamp: 2025-10-16T15:18:00.319Z
Learning: Applies to **/!(*_test).go : Add `defer perf.Track()` to all public functions and critical private functions; include a blank line after the call; use package-prefixed names; pass atmosConfig when present, else nil.

Applied to files:

  • cmd/auth_login.go
📚 Learning: 2025-09-23T02:30:42.362Z
Learnt from: CR
PR: cloudposse/atmos#0
File: .cursor/rules/atmos-rules.mdc:0-0
Timestamp: 2025-09-23T02:30:42.362Z
Learning: Applies to cmd/**/*.go : Use Viper for managing configuration, environment variables, and flags in the CLI

Applied to files:

  • cmd/auth_login.go
📚 Learning: 2025-09-23T02:30:42.362Z
Learnt from: CR
PR: cloudposse/atmos#0
File: .cursor/rules/atmos-rules.mdc:0-0
Timestamp: 2025-09-23T02:30:42.362Z
Learning: Applies to cmd/**/*.go : Use Viper for configuration management; support files, env vars, and flags with precedence flags > env > config > defaults

Applied to files:

  • cmd/auth_login.go
📚 Learning: 2025-09-07T18:07:00.549Z
Learnt from: Benbentwo
PR: cloudposse/atmos#1452
File: cmd/auth_login.go:43-44
Timestamp: 2025-09-07T18:07:00.549Z
Learning: In the atmos project, the identity flag is defined as a persistent flag on the auth root command (cmd/auth.go), making it available to all auth subcommands without needing to be redefined in each individual subcommand.

Applied to files:

  • cmd/auth_login.go
🧬 Code graph analysis (1)
cmd/auth_login.go (5)
pkg/config/config.go (1)
  • InitCliConfig (25-62)
pkg/schema/schema.go (1)
  • ConfigAndStacksInfo (460-539)
errors/errors.go (4)
  • ErrFailedToInitConfig (241-241)
  • ErrFailedToInitializeAuthManager (345-345)
  • ErrDefaultIdentity (338-338)
  • ErrAuthenticationFailed (335-335)
pkg/perf/perf.go (1)
  • Track (121-138)
cmd/auth.go (1)
  • IdentityFlagName (11-11)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: Build (macos-latest, macos)
  • GitHub Check: Build (windows-latest, windows)
  • GitHub Check: website-deploy-preview
  • GitHub Check: Analyze (go)
  • GitHub Check: Lint (golangci)
  • GitHub Check: Summary
🔇 Additional comments (5)
cmd/auth_login.go (5)

3-19: Import organization looks solid.

The three-group structure (stdlib, 3rd-party, Atmos) with blank line separators and alphabetical sorting within groups follows the guidelines perfectly.


42-46: Auth manager initialization follows best practices.

Error wrapping with errors.Join and static error codes is exactly right.


48-57: Identity fallback logic implements the PR objective cleanly.

When no identity is provided via flag, the code correctly invokes GetDefaultIdentity() which handles interactive selection. Viper usage ensures proper precedence, and error wrapping is consistent.


59-64: Authentication error handling provides clear context.

Wrapping the error with both a static code and the identity name makes debugging straightforward.


66-78: Success output correctly uses stderr for UI feedback.

The use of PrintfMessageToTUI for authentication result messages aligns with the guideline to send UI output to stderr.

…-user-selector-when-no-identity-is-passed-in-atmos-auth
Added comprehensive unit tests for executeAuthLoginCommand and createAuthManager:
- TestCreateAuthManager: Tests valid config, nil config, and empty config scenarios (100% coverage)
- TestExecuteAuthLoginCommand: Tests error paths including missing identity config (40.7% coverage)

Coverage improvements:
- executeAuthLoginCommand: 0% → 40.7%
- createAuthManager: 0% → 100%

The remaining 59.3% of executeAuthLoginCommand requires real cloud authentication
and is tested via integration tests and manual testing.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Tests were manipulating os.Args but never using it - the proper Cobra
way is to use cmd.SetArgs() which was already being used. This is dead
code that can be safely removed.

Changes:
- Removed os.Args save/restore in TestAuthLoginCmd
- Removed unused os import

The Cobra way to handle args in tests:
✅ Use cmd.SetArgs([]string{...})
❌ Don't manipulate os.Args directly

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
@github-actions

github-actions Bot commented Oct 22, 2025 •

Copy link
Copy Markdown

Dependency Review

✅ No vulnerabilities or license issues or OpenSSF Scorecard issues found.

Scanned Files

None

@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: 1

🧹 Nitpick comments (2)
pkg/auth/providers/aws/saml_test.go (2)

60-77: Nit: rename test to reflect method under test.

The test is named TestSAMLProvider_GetProviderType but asserts getDriver(). Consider renaming for clarity.


558-634: Playwright drivers heuristic: consider reducing OS/path sensitivity.

Creating ~/.cache/ms-playwright/chromium-1084 with a dummy file works, but can be brittle across platforms/versions. Suggest injecting the driver-dir resolver or gating via a helper to avoid hardcoding versioned paths in tests.

Would you like a small refactor to make the driver path discoverable via a func var and add a focused unit test?

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 887a47d and 7d25970.

📒 Files selected for processing (12)
  • .golangci.yml (2 hunks)
  • cmd/auth_login.go (2 hunks)
  • pkg/auth/cloud/aws/env.go (1 hunks)
  • pkg/auth/cloud/aws/setup.go (2 hunks)
  • pkg/auth/identities/aws/permission_set.go (3 hunks)
  • pkg/auth/identities/aws/user.go (5 hunks)
  • pkg/auth/manager.go (15 hunks)
  • pkg/auth/manager_test.go (1 hunks)
  • pkg/auth/providers/aws/saml.go (13 hunks)
  • pkg/auth/providers/aws/saml_test.go (4 hunks)
  • pkg/auth/providers/aws/sso.go (4 hunks)
  • website/docs/cli/commands/auth/auth-login.mdx (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (5)
  • pkg/auth/identities/aws/user.go
  • .golangci.yml
  • pkg/auth/manager_test.go
  • pkg/auth/identities/aws/permission_set.go
  • pkg/auth/providers/aws/sso.go
🧰 Additional context used
📓 Path-based instructions (6)
pkg/**/*.go

📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)

Place business logic in pkg rather than in cmd

Files:

  • pkg/auth/cloud/aws/setup.go
  • pkg/auth/providers/aws/saml_test.go
  • pkg/auth/manager.go
  • pkg/auth/providers/aws/saml.go
  • pkg/auth/cloud/aws/env.go
**/*.go

📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)

**/*.go: All code must pass golangci-lint checks
Follow Go error handling idioms and use meaningful error messages
Wrap errors with context using fmt.Errorf("context: %w", err)
Consider custom error types for domain-specific errors
Follow standard Go coding style; run gofmt and goimports
Use snake_case for environment variables
Document complex logic with inline comments

**/*.go: Define interfaces for major functionality (interface-driven design) to enable testability and decoupling
Generate mocks with go.uber.org/mock/mockgen using //go:generate directives; do not write manual mocks
Prefer the functional Options pattern to avoid functions with many parameters
Use context.Context only for cancellation, deadlines/timeouts, and sparing request-scoped values; never for config or dependencies
When used, context.Context must be the first parameter of functions
All comments must end with periods (godot linter)
Organize imports in three groups (stdlib, third-party, atmos) separated by blank lines and sorted alphabetically; maintain aliases cfg, log, u, errUtils
Add defer perf.Track(atmosConfig, "pkg.FuncName")() with a blank line in all public functions (use nil if no atmosConfig)
Use Viper for configuration loading with precedence: CLI flags → ENV vars → config files → defaults
Use static errors from errors/errors.go; wrap with fmt.Errorf and errors.Join; check with errors.Is; never compare error strings or create dynamic errors
Add //go:generate mockgen directives near interfaces and generate mocks; never hand-write mocks
Keep files focused and under 600 lines; one cmd/impl per file; co-locate tests; never disable revive file-length limit
Bind environment variables with viper.BindEnv and use ATMOS_ prefix
UI (prompts/status) must be written to stderr; data to stdout; logging only for system events, never for UI
Ensure cross-platform compatibility (Linux/macOS/Windows); use SDKs over binaries and filepath.Join() for paths

Files:

  • pkg/auth/cloud/aws/setup.go
  • pkg/auth/providers/aws/saml_test.go
  • pkg/auth/manager.go
  • cmd/auth_login.go
  • pkg/auth/providers/aws/saml.go
  • pkg/auth/cloud/aws/env.go
**/!(*_test).go

📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)

Document all exported functions, types, and methods with Go doc comments

Files:

  • pkg/auth/cloud/aws/setup.go
  • pkg/auth/manager.go
  • cmd/auth_login.go
  • pkg/auth/providers/aws/saml.go
  • pkg/auth/cloud/aws/env.go
**/*_test.go

📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)

**/*_test.go: Every new feature must include comprehensive unit tests
Test both happy paths and error conditions
Use table-driven tests for multiple scenarios

**/*_test.go: Use table-driven tests for coverage and clarity
Test behavior, not implementation; avoid tautological/stub tests; use DI for testability
Tests must call actual production code paths; never duplicate logic in tests
Use t.Skipf("reason") with clear context when skipping tests; CLI tests auto-build temp binaries

Files:

  • pkg/auth/providers/aws/saml_test.go
cmd/**/*.go

📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)

cmd/**/*.go: Use Cobra's recommended command structure with a root command and subcommands
Implement each CLI command in a separate file under cmd/
Use Viper for managing configuration, environment variables, and flags in the CLI
Keep separation of concerns between CLI interface (cmd) and business logic
Use kebab-case for command-line flags
Provide comprehensive help text for all commands and flags
Include examples in Cobra command help
Use Viper for configuration management; support files, env vars, and flags with precedence flags > env > config > defaults
Follow single responsibility; separate command interface from business logic
Provide meaningful user feedback and include progress indicators for long-running operations
Provide clear error messages to users and troubleshooting hints where appropriate

cmd/**/*.go: New CLI commands must use the Command Registry pattern and register via the CommandProvider interface
Telemetry: RootCmd.ExecuteC() auto-captures; for non-standard paths use telemetry.CaptureCmd(); never capture user data

Files:

  • cmd/auth_login.go
website/**

📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)

website/**: Update website documentation in website/ when adding features
Ensure consistency between CLI help text and website documentation
Follow the website's documentation structure and style
Keep website code in website/ and follow its architecture/style; test changes locally
Keep CLI and website documentation in sync; document new features with examples and use cases

Files:

  • website/docs/cli/commands/auth/auth-login.mdx
🧠 Learnings (7)
📚 Learning: 2025-09-25T01:02:48.697Z
Learnt from: Benbentwo
PR: cloudposse/atmos#1475
File: pkg/auth/manager.go:304-312
Timestamp: 2025-09-25T01:02:48.697Z
Learning: The auth manager in pkg/auth/manager.go should remain cloud-agnostic and not contain AWS-specific logic or references to specific cloud providers. Keep the manager generic and extensible.

Applied to files:

  • pkg/auth/manager.go
📚 Learning: 2025-09-10T22:38:42.212Z
Learnt from: Benbentwo
PR: cloudposse/atmos#1475
File: pkg/auth/identities/aws/user.go:141-145
Timestamp: 2025-09-10T22:38:42.212Z
Learning: ErrWrappingFormat is correctly defined as "%w: %w" in the errors package and is used throughout the codebase to wrap two error types together. The usage fmt.Errorf(errUtils.ErrWrappingFormat, errUtils.ErrAuthAwsFileManagerFailed, err) is the correct pattern when both arguments are error types.

Applied to files:

  • pkg/auth/manager.go
📚 Learning: 2025-09-10T22:38:42.212Z
Learnt from: Benbentwo
PR: cloudposse/atmos#1475
File: pkg/auth/identities/aws/user.go:141-145
Timestamp: 2025-09-10T22:38:42.212Z
Learning: The user confirmed that the errors package has an error string wrapping format, contradicting the previous learning about ErrWrappingFormat being invalid. The current usage of fmt.Errorf(errUtils.ErrWrappingFormat, errUtils.ErrAuthAwsFileManagerFailed, err) appears to be the correct pattern.

Applied to files:

  • pkg/auth/manager.go
📚 Learning: 2025-09-23T02:30:42.362Z
Learnt from: CR
PR: cloudposse/atmos#0
File: .cursor/rules/atmos-rules.mdc:0-0
Timestamp: 2025-09-23T02:30:42.362Z
Learning: Applies to cmd/**/*.go : Use Viper for managing configuration, environment variables, and flags in the CLI

Applied to files:

  • cmd/auth_login.go
📚 Learning: 2025-09-23T02:30:42.362Z
Learnt from: CR
PR: cloudposse/atmos#0
File: .cursor/rules/atmos-rules.mdc:0-0
Timestamp: 2025-09-23T02:30:42.362Z
Learning: Applies to cmd/**/*.go : Use Viper for configuration management; support files, env vars, and flags with precedence flags > env > config > defaults

Applied to files:

  • cmd/auth_login.go
📚 Learning: 2025-09-07T18:07:00.549Z
Learnt from: Benbentwo
PR: cloudposse/atmos#1452
File: cmd/auth_login.go:43-44
Timestamp: 2025-09-07T18:07:00.549Z
Learning: In the atmos project, the identity flag is defined as a persistent flag on the auth root command (cmd/auth.go), making it available to all auth subcommands without needing to be redefined in each individual subcommand.

Applied to files:

  • cmd/auth_login.go
  • website/docs/cli/commands/auth/auth-login.mdx
📚 Learning: 2025-10-10T23:51:36.597Z
Learnt from: osterman
PR: cloudposse/atmos#1599
File: internal/exec/terraform.go:394-402
Timestamp: 2025-10-10T23:51:36.597Z
Learning: In Atmos (internal/exec/terraform.go), when adding OpenTofu-specific flags like `--var-file` for `init`, do not gate them based on command name (e.g., checking if `info.Command == "tofu"` or `info.Command == "opentofu"`) because command names don't reliably indicate the actual binary being executed (symlinks, aliases). Instead, document the OpenTofu requirement in code comments and documentation, trusting users who enable the feature (e.g., `PassVars`) to ensure their terraform command points to an OpenTofu binary.

Applied to files:

  • website/docs/cli/commands/auth/auth-login.mdx
🧬 Code graph analysis (6)
pkg/auth/cloud/aws/setup.go (1)
errors/errors.go (1)
  • ErrAwsAuth (361-361)
pkg/auth/providers/aws/saml_test.go (2)
pkg/auth/types/interfaces.go (1)
  • Provider (13-42)
pkg/auth/providers/aws/saml.go (1)
  • NewSAMLProvider (53-73)
pkg/auth/manager.go (2)
errors/error_funcs.go (1)
  • CheckErrorAndPrint (32-55)
errors/errors.go (9)
  • ErrNilParam (370-370)
  • ErrAuthenticationFailed (357-357)
  • ErrInvalidAuthConfig (352-352)
  • ErrNoCredentialsFound (368-368)
  • ErrExpiredCredentials (369-369)
  • ErrNoIdentitiesAvailable (380-380)
  • ErrUnsupportedInputType (41-41)
  • ErrInvalidProviderConfig (356-356)
  • ErrInvalidIdentityConfig (354-354)
cmd/auth_login.go (5)
pkg/config/config.go (1)
  • InitCliConfig (25-62)
pkg/schema/schema.go (1)
  • ConfigAndStacksInfo (488-567)
errors/errors.go (4)
  • ErrFailedToInitConfig (263-263)
  • ErrFailedToInitializeAuthManager (367-367)
  • ErrDefaultIdentity (360-360)
  • ErrAuthenticationFailed (357-357)
pkg/perf/perf.go (1)
  • Track (121-138)
cmd/auth.go (1)
  • IdentityFlagName (11-11)
pkg/auth/providers/aws/saml.go (3)
pkg/logger/log.go (4)
  • Info (34-36)
  • Debug (24-26)
  • Errorf (59-61)
  • Warn (44-46)
errors/errors.go (3)
  • ErrInvalidProviderConfig (356-356)
  • ErrAwsSAMLDecodeFailed (363-363)
  • ErrAuthenticationFailed (357-357)
pkg/schema/schema_auth.go (1)
  • Provider (11-24)
pkg/auth/cloud/aws/env.go (1)
errors/errors.go (1)
  • ErrLoadAwsConfig (68-68)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (10)
  • GitHub Check: Analyze (go)
  • GitHub Check: Lint (golangci)
  • GitHub Check: Build (windows)
  • GitHub Check: Build (macos)
  • GitHub Check: autofix
  • GitHub Check: Analyze (go)
  • GitHub Check: Lint (golangci)
  • GitHub Check: Run pre-commit hooks
  • GitHub Check: website-deploy-preview
  • GitHub Check: Summary
🔇 Additional comments (12)
cmd/auth_login.go (1)

40-46: Identity precedence + default selection + perf tracking look solid.

  • Uses Viper for identity (flags > env > config).
  • Falls back to authManager.GetDefaultIdentity() when empty.
  • Error contexts use sentinels with joins.
  • Adds perf.Track defer.

LGTM.

Also applies to: 47-51, 53-62, 64-69

website/docs/cli/commands/auth/auth-login.mdx (1)

27-35: Docs match behavior and clarify precedence; examples improved.

Interactive/default identity logic and env var precedence are clear and consistent with the code. LGTM.

Also applies to: 48-57, 60-68, 72-73

pkg/auth/providers/aws/saml_test.go (1)

677-728: URL validation and env propagation tests look good.

Table-driven, clear assertions, no external calls. LGTM.

Also applies to: 813-853

pkg/auth/cloud/aws/env.go (1)

111-117: Fix double-%w wrapping; prefer errors.Join for chaining.

Two %w verbs are invalid. Join sentinel and cause; keep context if desired.

Option A (preferred):

- return aws.Config{}, fmt.Errorf("%w: %w", errUtils.ErrLoadAwsConfig, isolateErr)
+ return aws.Config{}, errors.Join(fmt.Errorf("%w: isolated env load", errUtils.ErrLoadAwsConfig), isolateErr)

- return aws.Config{}, fmt.Errorf("%w: %w", errUtils.ErrLoadAwsConfig, err)
+ return aws.Config{}, errors.Join(fmt.Errorf("%w: load default config", errUtils.ErrLoadAwsConfig), err)

Note: add import "errors" to this file.
As per coding guidelines.

⛔ Skipped due to learnings
Learnt from: Benbentwo
PR: cloudposse/atmos#1475
File: pkg/auth/identities/aws/user.go:141-145
Timestamp: 2025-09-10T22:38:42.212Z
Learning: ErrWrappingFormat is correctly defined as "%w: %w" in the errors package and is used throughout the codebase to wrap two error types together. The usage fmt.Errorf(errUtils.ErrWrappingFormat, errUtils.ErrAuthAwsFileManagerFailed, err) is the correct pattern when both arguments are error types.
pkg/auth/manager.go (3)

88-91: Excellent error wrapping with context.

Provider and identity initialization errors are now properly wrapped, preserving the error chain while adding helpful context. This makes debugging significantly easier.

Also applies to: 95-98


244-254: Smart addition of deterministic ordering.

Sorting identities alphabetically before presenting them ensures a consistent user experience across sessions. The copy-before-sort approach correctly preserves the original slice.


128-130: Comprehensive error context in authentication flow.

The authentication chain now properly wraps all errors with identity context, making it straightforward to diagnose which step failed. The consistent pattern of wrapping with identity names and operation context is solid.

Also applies to: 138-141, 148-155

pkg/auth/providers/aws/saml.go (5)

316-355: Well-structured driver selection with sensible fallbacks.

The priority cascade (explicit config → deprecated field → Playwright availability → URL-based inference → Browser with auto-download) handles multiple scenarios gracefully. The deprecation warning for provider_type is a nice touch for backward compatibility.


399-437: Robust cross-platform driver detection.

The driver detection checks standard Playwright cache locations for Linux, macOS, and Windows using filepath.Join for proper path construction. The two-method split (playwrightDriversInstalled for detection, hasPlaywrightDriversOrCanDownload for availability-or-download check) is clear and maintainable.


438-478: Thorough validation of driver installations.

Going beyond simple directory existence to verify browser binaries are actually present prevents false positives from empty cache directories. The nested directory traversal checking for version subdirectories with content is a practical heuristic.


480-507: Smart auto-download logic respects user intent.

The logic correctly differentiates between user-configured behavior, driver types that don't need browsers (GoogleApps/Okta), and automatic enablement only when Browser driver is selected but drivers are missing. This prevents unnecessary downloads while ensuring Browser driver works out of the box.


134-134: Consistent error wrapping preserves context.

All error paths now properly wrap underlying errors with %w, maintaining the error chain for errors.Is/errors.As inspection while adding operation-specific context. This aligns perfectly with the coding guidelines.

Also applies to: 145-145, 149-149, 153-153, 164-164, 209-209, 267-267, 282-282

Comment thread pkg/auth/cloud/aws/setup.go Outdated
Replace fmt.Errorf with two %w verbs (invalid) with single %w wrapping
that preserves both the sentinel error message and the underlying error.

- Line 30: Use %s for sentinel, %w for underlying error
- Line 40: Use %s for sentinel, %w for underlying error
…-passed-in-atmos-auth' of https://github.com/cloudposse/atmos into feature/dev-3707-show-user-selector-when-no-identity-is-passed-in-atmos-auth
@aknysh
Andriy Knysh (aknysh) merged commit ecbf1cf into main Oct 22, 2025
54 checks passed
@aknysh
Andriy Knysh (aknysh) deleted the feature/dev-3707-show-user-selector-when-no-identity-is-passed-in-atmos-auth branch October 22, 2025 03:55
@github-actions

Copy link
Copy Markdown

These changes were released in v1.196.0-rc.0.

This branch was successfully deployed

1 active deployment
preview — 14f0c6ca Deployed Oct 22, 2025 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/xl Extra large size PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants