Repository navigation
fix: resolve auth realm isolation issues - #2075
Conversation
Fix three issues introduced by the auth realm isolation feature (PR #2043): 1. Empty realm for backward compatibility: GetRealm() now returns an empty realm when no explicit configuration is set, instead of auto-generating a SHA256 hash. This preserves backward-compatible credential paths for CI/CD environments that don't use realm isolation. 2. Conflicting stack defaults detection: LoadStackAuthDefaults() now detects when different stack files define different default identities and returns an empty map instead of non-deterministic results (#2072). 3. Better error for profile/identity confusion: When ATMOS_PROFILE is set to an auth identity name, the error now includes hints suggesting to use ATMOS_IDENTITY instead (#2071). Co-Authored-By: Claude Opus 4.6 <[email protected]>
…/CredentialsExist
The assumeRoleIdentity type hardcoded empty realm ("") in three methods
instead of using i.realm, causing credential path mismatches that led to
ECR Docker push 403 errors in CI/CD after upgrading to v1.206.0.
PostAuthenticate wrote credentials to {baseDir}/{realm}/aws/{provider}/
but Environment returned paths pointing to {baseDir}/aws/{provider}/
(without realm), so the AWS SDK couldn't find the credentials file.
Adds 6 regression tests verifying realm propagation in credential paths.
Co-Authored-By: Claude Opus 4.6 <[email protected]>
Add realm mismatch detection that warns users when credentials exist under a different realm than the current one, helping diagnose issues after changing auth.realm or ATMOS_AUTH_REALM. Also rename and rewrite auth_defaults_test.go with behavior-descriptive test names and expanded coverage for clearExistingDefaults, findProfileDirectory, hasAnyDefault, applyStackDefaults, and getAllStackFiles. Document realm isolation in the auth configuration guide. Co-Authored-By: Claude Opus 4.6 <[email protected]>
|
Warning This PR exceeds the recommended limit of 1,000 lines.Large PRs are difficult to review and may be rejected due to their size. Please verify that this PR does not address multiple issues. |
|
Important Cloud Posse Engineering Team Review RequiredThis pull request modifies files that require Cloud Posse's review. Please be patient, and a core maintainer will review your changes. To expedite this process, reach out to us on Slack in the |
Dependency Review✅ No vulnerabilities or license issues found.Scanned FilesNone |
📝 WalkthroughWalkthroughFixes auth realm isolation issues: makes realm isolation opt-in (auto = empty), preserves backward-compatible credential paths, prevents loading unrelated stack defaults, aligns assume-role credential paths with identity realms, adds realm-mismatch detection/warning, and expands tests + docs for regressions Changes
Sequence Diagram(s)sequenceDiagram
participant Manager as Manager
participant Keyring as Keyring Store
participant FS as XDG Config FS
participant Logger as Logger
Manager->>Keyring: checkRealmMismatchKeyring(currentRealm)
alt keyring has alternate creds
Keyring-->>Manager: alternateRealm
Manager->>Logger: logRealmMismatchWarning(currentRealm, alternateRealm)
else keyring no match
Keyring-->>Manager: none
Manager->>FS: checkRealmMismatchFiles(currentRealm)
alt FS finds alternate realm
FS-->>Manager: alternateRealm
Manager->>Logger: logRealmMismatchWarning(currentRealm, alternateRealm)
else no alternate
FS-->>Manager: none
end
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Suggested reviewers
🚥 Pre-merge checks | ✅ 5 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches
🧪 Generate unit tests (beta)
No actionable comments were generated in the recent review. 🎉 🧹 Recent nitpick comments
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Fix all issues with AI agents
In `@docs/fixes/2026-02-12-auth-realm-isolation-issues.md`:
- Around line 87-90: Add a language specifier to the fenced code block that
contains the ECR push error example (the block starting with "ERROR: failed to
push <account>..."), e.g., change the opening fence from ``` to ```text or
```log so the markdown linter MD040 is satisfied; update the fence surrounding
the error message in the docs/fixes/2026-02-12-auth-realm-isolation-issues.md
file accordingly.
In `@pkg/auth/realm_mismatch_test.go`:
- Around line 13-32: The test
TestCheckRealmMismatchFiles_NonEmptyRealm_FindsNoRealmCreds contains dead setup:
you create credentials under baseDir and set ATMOS_XDG_CONFIG_HOME to
filepath.Dir(baseDir) but then overwrite ATMOS_XDG_CONFIG_HOME with parent so
the initial baseDir work is never used; fix by removing the unused baseDir block
(lines that create baseDir, providerDir and write credentials) or by
consolidating so both credential files live under the same XDG config path used
by checkRealmMismatchFiles (i.e., ensure ATMOS_XDG_CONFIG_HOME is set only once
and both credential locations are placed under that directory), referencing the
test function name and the ATMOS_XDG_CONFIG_HOME env var and
checkRealmMismatchFiles helper to locate the code to change.
🧹 Nitpick comments (6)
pkg/auth/realm/realm.go (1)
53-85: Empty auto-realm is the right call for backward compatibility.This directly addresses the CI/CD breakage from
#2071. Opt-in isolation via explicit config is the safer default.Note:
cliConfigPathis now unused in the function body (was previously needed for hash computation). Not urgent since removing it would be a breaking API change, but worth tracking for a future cleanup pass.pkg/config/auth_defaults_test.go (1)
246-263: Minor test duplication withstack_auth_loader_test.go.
hasAnyDefaultis also tested inTestHasAnyDefault_AllFalse,TestHasAnyDefault_Empty, andTestHasAnyDefault_OneTruein the sibling test file. Not a problem — just noting it. Having both isn't harmful; the table-driven version here is more concise.Also applies to: 428-445
pkg/auth/realm_mismatch.go (1)
64-75: Avoid creating config directory in a read-only diagnostic path.
GetXDGConfigDiralways callsos.MkdirAll()on line 85 ofpkg/xdg/xdg.go, so it creates the directory as a side effect. For a read-only check likecheckRealmMismatchFiles, this is unnecessary. Since there can't be credentials to find if the directory doesn't exist, skip the directory creation altogether:Suggested approach
func checkRealmMismatchFiles(currentRealm string) string { - baseDir, err := xdg.GetXDGConfigDir("", xdgDirPermissions) - if err != nil { - return "" - } + baseDir, err := os.UserConfigDir() + if err != nil { + return "" + } + baseDir = filepath.Join(baseDir, "atmos")Low-risk change — the directory almost certainly exists by the time we hit this credential-not-found path.
pkg/auth/realm_mismatch_test.go (3)
63-92: Consider consolidatinghasCredentialFilestests into a table-driven test.Four separate test functions exercise the same helper with different directory setups. A single table-driven test would reduce boilerplate and make adding new cases easier. As per coding guidelines: "Use table-driven tests for testing multiple scenarios in Go."
Sketch
func TestHasCredentialFiles(t *testing.T) { tests := []struct { name string setup func(t *testing.T) string // returns awsDir expect bool }{ { name: "credentials file present", setup: func(t *testing.T) string { awsDir := filepath.Join(t.TempDir(), "aws") providerDir := filepath.Join(awsDir, "my-provider") require.NoError(t, os.MkdirAll(providerDir, 0o700)) require.NoError(t, os.WriteFile(filepath.Join(providerDir, "credentials"), []byte("test"), 0o600)) return awsDir }, expect: true, }, { name: "no provider dirs", setup: func(t *testing.T) string { awsDir := filepath.Join(t.TempDir(), "aws") require.NoError(t, os.MkdirAll(awsDir, 0o700)) return awsDir }, expect: false, }, { name: "provider dir but no credentials file", setup: func(t *testing.T) string { awsDir := filepath.Join(t.TempDir(), "aws") require.NoError(t, os.MkdirAll(filepath.Join(awsDir, "my-provider"), 0o700)) return awsDir }, expect: false, }, { name: "nonexistent dir", setup: func(t *testing.T) string { return filepath.Join(t.TempDir(), "nonexistent") }, expect: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { assert.Equal(t, tt.expect, hasCredentialFiles(tt.setup(t))) }) } }
104-117: This test validatessync.Oncesemantics, not the production warning path.Resetting and calling
realmMismatchWarningOnce.Dodirectly only proves Go'ssync.Onceworks. It doesn't exercise the actual code that fires the warning (presumably something that callslogRealmMismatchWarninginside.Do). Consider testing the real entry point instead, or drop this test if the intent is already covered elsewhere.
94-102: Smoke-testing "doesn't panic" is fine, but capturing log output would strengthen coverage.Right now these two tests only confirm no panic. If
logRealmMismatchWarningis supposed to emit a specific message, asserting on captured log output would catch regressions in the message text or level.
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #2075 +/- ##
==========================================
+ Coverage 76.28% 76.32% +0.04%
==========================================
Files 801 802 +1
Lines 75410 75521 +111
==========================================
+ Hits 57524 57641 +117
+ Misses 14300 14297 -3
+ Partials 3586 3583 -3
Flags with carried forward coverage won't be shown. Click here to find out more.
🚀 New features to boost your workflow:
|
…rage - Use read-only LookupXDGConfigDir to avoid creating directories in diagnostic path (xdg.go) - Consolidate hasCredentialFiles tests into table-driven format - Remove sync.Once test that only tested Go stdlib - Add tests for emitRealmMismatchWarning, checkRealmMismatchKeyring, scanForRealmCredentials, and checkNoRealmCredentials - Add fenced code block language specifier in fixes doc - Remove dead setup code in NonEmptyRealm test Co-Authored-By: Claude Opus 4.6 <[email protected]>
Co-Authored-By: Claude Opus 4.6 <[email protected]>
|
CodeRabbit (@coderabbitai) please check that your recent comments were correctly addressed |
|
Tip For best results, initiate chat on the files or code changes. 🧩 Analysis chain🏁 Script executed: Length of output: 2 🏁 Script executed: Length of output: 2 🏁 Script executed: Length of output: 2
Since there are no active comments to verify, there's nothing that needs to be checked for being addressed. Would you like me to perform a fresh review of the changes in this PR instead? 🧠 Learnings used |
|
These changes were released in v1.206.1. |
|
These changes were released in v1.207.0. |
|
These changes were released in v1.208.0-rc.0. |
|
These changes were released in v1.208.0-test.15. |
what
why
After merging PR #2043 (auth realm isolation with credential separation), several critical regressions were reported:
Issue 1: Profile Incorrectly Required for Default Identity (#2071)
Problem: After upgrading to v1.206.0, any atmos command (including
atmos version) fails with a "profile not found" error whenATMOS_PROFILEis set to an auth identity name (e.g.,ATMOS_PROFILE=root-admin).Cause: Users set
ATMOS_PROFILEthinking it controls auth identity selection, but it controls configuration profiles. When set to an identity name that doesn't match any profile directory,loadProfiles()fails.Fix: Enhanced the "profile not found" error to detect when the profile name matches an auth identity name and suggest using
ATMOS_IDENTITYor--identityinstead.Issue 2: Realm-Scoped Credential Paths Break CI/CD Workflows
Problem: CI/CD pipelines fail with AWS credential errors because credential file paths changed from
{baseDir}/aws/{provider}/credentialsto{baseDir}/{realm}/aws/{provider}/credentials.Cause: PR #2043 auto-generated a realm from a SHA256 hash of the CLI config path, making realm isolation always-on.
Fix: Made realm isolation opt-in. When
auth.realmis not configured andATMOS_AUTH_REALMis not set, credentials use the backward-compatible path with no realm subdirectory. Also fixedCleanupAll()to safely handle empty realm.Issue 3: Loading Unrelated Stack Files for Auth Defaults (#2072)
Problem: Running a command scoped to a specific stack causes a "multiple default identities" error when different stacks define different defaults.
Cause:
LoadStackAuthDefaults()scanned ALL stack files without knowing which stack is the target.Fix: When different stack files define conflicting default identities, the defaults are discarded (returns empty) rather than raising an error. The per-stack default is resolved after full stack processing.
Issue 4: ECR Docker Push Fails with 403 After Upgrading
Problem: GitHub Actions CI/CD fails with
403 Forbiddenwhen pushing to AWS ECR. Docker login succeeds but push fails. Pinning to v1.205.1 resolves it.Cause:
assumeRoleIdentityhardcoded empty realm""inEnvironment(),PrepareEnvironment(), andCredentialsExist()instead of usingi.realm. This causedAuthenticate()to write credentials to the realm-scoped path whileGetEnvironmentVariables()returned the non-realm path, so the AWS SDK fell back to the runner's default IAM role.Fix: Changed all three
NewAWSFileManager("", "")calls toNewAWSFileManager("", i.realm)to match the pattern used by all other identity types.Realm Mismatch Warning (new)
Added detection that warns users when credentials exist under a different realm than the current one. This helps diagnose issues after changing
auth.realmorATMOS_AUTH_REALM. Only runs on credential-not-found failure paths (zero happy-path overhead).Realm Documentation (new)
Added "Credential Realm Isolation" section to the auth configuration guide covering: configuration, precedence, credential storage paths, naming rules, and usage.
references
Summary by CodeRabbit
New Features
Bug Fixes
Documentation
Tests