Skip to content

feat: implement auth realm isolation with credential separation - #2043

Merged
Andriy Knysh (aknysh) merged 26 commits into
mainfrom
Benbentwo/auth-realm-isolation
Feb 10, 2026
Merged

Andriy Knysh (aknysh) merged 26 commits into
mainfrom
Benbentwo/auth-realm-isolation

Conversation

@Benbentwo

@Benbentwo Ben (Benbentwo) commented Jan 30, 2026 •

Copy link
Copy Markdown
Contributor

What

Implement credential realm isolation for Auth to prevent credential collisions when engineers work with multiple repositories using identical identity names. Credentials are now stored in realm-isolated directories (~/.config/atmos/{realm}/), with realm computed from environment variables, configuration, or the config path hash.

Why

When multiple customer repositories use the same identity names (e.g., "aws-user", "dev-role"), Atmos credentials for different environments collide. Realm isolation ensures that credentials for "dev-role" from customer-A and customer-B are kept separate, preventing authentication failures and security issues.

Changes

  • Add SetRealm() method to Identity and Provider interfaces
  • Manager propagates realm to all identities/providers after construction
  • All keyring backends include realm in credential keys (atmos:{realm}:{alias})
  • AWS file paths now always include realm: ~/.config/atmos/{realm}/aws/{provider}/{credentials,config}
  • Add --all-realms flag to atmos auth logout to clear all Atmos credentials across all realms
  • Display realm and source in atmos auth whoami output
  • Non-breaking: existing credentials in non-realm paths are discovered via workspace, users must re-authenticate

References

Summary by CodeRabbit

  • New Features

    • Realm-scoped credential isolation to prevent credential collisions across repositories.
    • New --all-realms flag to logout from all realms.
    • CLI now shows active Realm (and its source) in atmos auth login and atmos auth whoami.
  • Configuration

    • Realm precedence: ATMOS_AUTH_REALM env var → auth.realm in atmos.yaml → auto-generated from CLI config path.
  • Documentation

    • Blog post and roadmap entry added.
  • Breaking Changes

    • Credential storage/paths changed — re-authenticate with atmos auth login.

Implement credential realm isolation for Auth to prevent credential collisions
when engineers work with multiple repositories using identical identity names.

- Add SetRealm() method to Identity and Provider interfaces for realm propagation
- Manager propagates computed realm to all identities and providers after construction
- Update all keyring implementations to include realm in credential keys
- Update AWS file manager to always use realm: ~/.config/atmos/{realm}/aws/{provider}/*
- Add --all-realms flag to logout command to clear all Atmos credentials across realms
- Update whoami output to display current realm and its source (env/config/auto)
- Realm computed from: ATMOS_AUTH_REALM env var → auth.realm config → SHA256(CliConfigPath)[:8]
- Non-backward compatible: users must re-authenticate to store credentials under new realm paths

Co-Authored-By: Claude Haiku 4.5 <[email protected]>
@github-actions github-actions Bot added the size/xl Extra large size PR label Jan 30, 2026
@mergify

mergify Bot commented Jan 30, 2026

Copy link
Copy Markdown
Contributor

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.
Consider refactoring it into smaller, more focused PRs to facilitate a smoother review process.

@github-actions

github-actions Bot commented Jan 30, 2026 •

Copy link
Copy Markdown

Dependency Review

✅ No vulnerabilities or license issues found.

Scanned Files

None

@Benbentwo Ben (Benbentwo) added the major Breaking changes (or first stable release) label Feb 2, 2026
@github-actions

github-actions Bot commented Feb 2, 2026

Copy link
Copy Markdown

Warning

Release Documentation Required

This PR is labeled minor or major and requires documentation updates:

  • Changelog entry ✅
  • Roadmap update - Update website/src/data/roadmap.js with the new milestone

Alternatively: If this change doesn't require release documentation, remove the minor or major label.

Update CLI test snapshots to include the new realm information
displayed in auth commands (login, whoami, validate).

Co-Authored-By: Claude Opus 4.5 <[email protected]>
@github-actions

github-actions Bot commented Feb 2, 2026

Copy link
Copy Markdown

Warning

Release Documentation Required

This PR is labeled minor or major and requires documentation updates:

  • Changelog entry ✅
  • Roadmap update - Update website/src/data/roadmap.js with the new milestone

Alternatively: If this change doesn't require release documentation, remove the minor or major label.

- Add changelog blog post explaining the feature and breaking change
- Add roadmap milestone for auth realm isolation feature

Co-Authored-By: Claude Opus 4.5 <[email protected]>
Set ATMOS_AUTH_REALM=test-realm environment variable in auth tests
to ensure the realm is deterministic across different CI runners.
Previously, the auto-generated realm hash varied by absolute path.

Co-Authored-By: Claude Opus 4.5 <[email protected]>
Add deterministic realm environment variable to the duplicate test
in auth-cli.yaml that was missing it.

Co-Authored-By: Claude Opus 4.5 <[email protected]>
@codecov

codecov Bot commented Feb 2, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 79.78261% with 93 lines in your changes missing coverage. Please review.
✅ Project coverage is 76.27%. Comparing base (f4e244c) to head (9b9353a).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
cmd/auth_logout.go 75.00% 19 Missing and 7 partials ⚠️
pkg/auth/manager_logout.go 22.72% 13 Missing and 4 partials ⚠️
cmd/auth_user.go 0.00% 4 Missing ⚠️
pkg/auth/identities/azure/subscription.go 42.85% 4 Missing ⚠️
pkg/auth/manager.go 73.33% 3 Missing and 1 partial ⚠️
pkg/auth/providers/azure/device_code.go 0.00% 4 Missing ⚠️
pkg/config/config.go 0.00% 2 Missing and 2 partials ⚠️
internal/exec/terraform_output_utils.go 0.00% 3 Missing ⚠️
pkg/auth/cloud/aws/files.go 81.25% 2 Missing and 1 partial ⚠️
pkg/auth/cloud/azure/msal_cache.go 40.00% 1 Missing and 2 partials ⚠️
... and 13 more
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main    #2043      +/-   ##
==========================================
+ Coverage   76.21%   76.27%   +0.06%     
==========================================
  Files         799      800       +1     
  Lines       75021    75331     +310     
==========================================
+ Hits        57175    57460     +285     
- Misses      14281    14289       +8     
- Partials     3565     3582      +17     
Flag Coverage Δ
unittests 76.27% <79.78%> (+0.06%) ⬆️

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

Files with missing lines Coverage Δ
cmd/auth_env.go 56.96% <100.00%> (ø)
cmd/auth_exec.go 85.32% <100.00%> (ø)
cmd/auth_list.go 73.91% <100.00%> (ø)
cmd/auth_login.go 74.82% <100.00%> (+1.33%) ⬆️
cmd/auth_shell.go 60.00% <100.00%> (ø)
cmd/auth_whoami.go 71.97% <100.00%> (+0.92%) ⬆️
cmd/cmd_utils.go 55.75% <100.00%> (ø)
cmd/devcontainer/helpers.go 56.52% <100.00%> (ø)
errors/errors.go 100.00% <ø> (ø)
internal/exec/workflow_utils.go 70.50% <100.00%> (ø)
... and 40 more

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

@Benbentwo
Ben (Benbentwo) marked this pull request as ready for review February 2, 2026 22:18
@Benbentwo
Ben (Benbentwo) requested review from a team as code owners February 2, 2026 22:18

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 681c855f29

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "Codex (@codex) review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "Codex (@codex) address that feedback".

Comment thread cmd/auth_ecr_login.go Resolved
Comment thread pkg/auth/credentials/store.go Resolved
@coderabbitai

coderabbitai Bot commented Feb 2, 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

Compute an authentication realm (env/config/auto) and propagate realm + cliConfigPath through AuthManager, providers, identities, credential stores, and file managers; make keyring and on-disk storage realm-scoped; add logout --all-realms, many interface signature changes, tests, snapshots, and docs.

Changes

Cohort / File(s) Summary
Realm core
pkg/auth/realm/realm.go, pkg/auth/realm/realm_test.go
New realm package: GetRealm, Validate, RealmInfo, auto SHA256-based realm, validation rules and comprehensive tests.
Auth manager & orchestration
pkg/auth/manager.go, pkg/auth/hooks.go, pkg/auth/manager_*, pkg/devcontainer/*, internal/exec/*
NewAuthManager/newAuthManager now accept cliConfigPath; manager computes/stores m.realm, exposes GetRealm(), propagates realm to providers/identities and into PostAuthenticate/whoami flows.
Interfaces & types
pkg/auth/types/interfaces.go, pkg/auth/types/mock_interfaces.go, pkg/auth/types/whoami.go
Interfaces extended for realm (Provider/Identity SetRealm, AuthManager GetRealm); WhoamiInfo gains Realm/RealmSource; mocks updated.
Credential store API
pkg/auth/credentials/store.go, pkg/auth/credentials/*
Added key-building helpers/constants and made CredentialStore API realm-aware: Store/Retrieve/Delete/List/IsExpired signatures changed and consumers updated.
Keyring implementations & tests
pkg/auth/credentials/keyring_*.go, pkg/auth/credentials/*_test.go
File/system/memory/noop keyrings accept realm, use realm-qualified keys, filter List by realm, update IsExpired; tests adapted.
AWS & Azure file managers
pkg/auth/cloud/aws/files.go, pkg/auth/cloud/aws/setup.go, pkg/auth/cloud/azure/*
File managers and SetupFiles accept realm; on-disk paths include realm when provided; constructors and tests adjusted.
Providers & identities
pkg/auth/providers/..., pkg/auth/identities/..., pkg/auth/providers/mock/*
Providers/identities gain realm fields and SetRealm methods; PostAuthenticate/SetupFiles now pass realm; identity flows read/write realm-scoped credentials.
CLI call sites & UX
cmd/* (auth_login.go, auth_logout.go, auth_whoami.go, tests)
createAuthManager/NewAuthManager call sites pass atmosConfig.CliConfigPath; whoami/login display Realm; logout adds --all-realms and realm discovery.
Logout helpers & behavior
cmd/auth_logout.go, pkg/auth/manager_logout.go, cmd/auth_logout_test.go
New discoverRealms and performLogoutAllRealms; logout deletes realm-scoped keys and attempts legacy empty-realm cleanup; tests expanded for multi-realm flows.
Manager-chain & caching
pkg/auth/manager_chain.go, pkg/auth/manager_*_test.go
Credential caching/retrieval now pass realm; load/caching flows updated to use realm parameter.
Schema, errors & config
pkg/schema/schema_auth.go, errors/errors.go, pkg/config/config.go
AuthConfig.Realm added; new realm-related sentinel errors; minor verbose env/flag log handling tweak.
Docs, tests, fixtures & snapshots
website/blog/*, website/src/data/roadmap.js, tests/*, tests/snapshots/*
Blog + roadmap entry added; many tests, fixtures and golden snapshots updated to include ATMOS_AUTH_REALM and realm display.

Sequence Diagram(s)

sequenceDiagram
    autonumber
    participant CLI as CLI
    participant Manager as AuthManager
    participant RealmPkg as Realm
    participant Identity as Identity
    participant Store as CredentialStore
    participant Keyring as Keyring

    CLI->>Manager: NewAuthManager(config, credStore, validator, stackInfo, cliConfigPath)
    Manager->>RealmPkg: GetRealm(config.Realm, cliConfigPath)
    RealmPkg-->>Manager: RealmInfo{Value, Source}
    Manager->>Manager: set m.realm
    Manager->>Identity: SetRealm(m.realm.Value)

    CLI->>Manager: Authenticate(provider, identity)
    Manager->>Identity: Authenticate()
    Identity->>Store: Store(alias, creds, realm)
    Store->>Keyring: persist realm-qualified key
    Keyring-->>Store: OK
    Store-->>Manager: stored
    Manager-->>CLI: Display success + Realm info
Loading
sequenceDiagram
    autonumber
    participant CLI as CLI (logout --all-realms)
    participant Helper as performLogoutAllRealms
    participant FS as Filesystem
    participant Store as CredentialStore

    CLI->>Helper: performLogoutAllRealms(ctx, config, ...)
    Helper->>FS: discoverRealms(baseDir)
    FS-->>Helper: [realm1, realm2...]
    loop per realm
      Helper->>Store: Delete(alias, realm)
      Store-->>Helper: ok / err
      Helper->>Store: Delete(alias, "")  rgba(0,0,0,0.5)
    end
    Helper-->>CLI: aggregated result per realm
Loading

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~120 minutes

Possibly related PRs

Suggested reviewers

  • osterman
🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 28.82% 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 Title clearly describes the main feature: auth realm isolation with credential separation. It's specific, concise, and directly reflects the primary change across the changeset.

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

✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch Benbentwo/auth-realm-isolation

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

Caution

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

⚠️ Outside diff range comments (9)
website/src/data/roadmap.js (1)

141-141: ⚠️ Potential issue | 🟡 Minor

Recalculate the initiative progress percentage.

The auth initiative shows 115 shipped milestones out of 141 total (81.6%), but the progress field remains at 85%. If milestones were added or modified in this PR, verify the progress percentage reflects the actual completion rate. The current 85% appears higher than the shipped/total calculation would suggest—update it to match the actual milestone status.

pkg/auth/providers/azure/oidc.go (1)

60-66: ⚠️ Potential issue | 🟠 Major

Add a trailing period to satisfy godot.
The inline field comment lacks a period and will fail godot linting.

✅ Suggested fix
-	realm         string // Credential isolation realm set by auth manager
+	realm         string // Credential isolation realm set by auth manager.
As per coding guidelines: All comments must end with periods (enforced by `godot` linter).
cmd/auth_whoami.go (1)

124-129: ⚠️ Potential issue | 🟠 Major

Honor global config-selection flags before computing cliConfigPath.
InitCliConfig is invoked with an empty ConfigAndStacksInfo, so --config, --config-path, --base-path, and --profile are ignored. With realm derived from cliConfigPath, this can hash the wrong path and isolate credentials incorrectly. Please populate ConfigAndStacksInfo via flags.ParseGlobalFlags before calling InitCliConfig.
Based on learnings: In Atmos, when calling cfg.InitCliConfig, you must first populate the schema.ConfigAndStacksInfo struct with global flag values using flags.ParseGlobalFlags(cmd, v) rather than passing an empty struct.

cmd/auth_shell.go (1)

61-69: ⚠️ Potential issue | 🟠 Major

Honor global config-selection flags before computing cliConfigPath.
InitCliConfig is invoked with an empty ConfigAndStacksInfo, so --config, --config-path, --base-path, and --profile are ignored. With realm derived from cliConfigPath, this can hash the wrong path and isolate credentials incorrectly. Please populate ConfigAndStacksInfo via flags.ParseGlobalFlags before calling InitCliConfig.
Based on learnings: In Atmos, when calling cfg.InitCliConfig, you must first populate the schema.ConfigAndStacksInfo struct with global flag values using flags.ParseGlobalFlags(cmd, v) rather than passing an empty struct.

cmd/auth_env.go (1)

40-47: ⚠️ Potential issue | 🟠 Major

Populate ConfigAndStacksInfo before InitCliConfig so realm respects CLI flags.
Right now InitCliConfig(schema.ConfigAndStacksInfo{}, false) ignores --config, --config-path, --base-path, and --profile. With realm derived from CliConfigPath, this can compute the wrong realm and point at the wrong auth config. Please parse global flags into schema.ConfigAndStacksInfo (see the pattern used in cmd/terraform/plan_diff.go) before calling InitCliConfig.

Based on learnings: In Atmos, when calling cfg.InitCliConfig, you must first populate the schema.ConfigAndStacksInfo struct with global flag values using flags.ParseGlobalFlags(cmd, v) rather than passing an empty struct.

cmd/auth_list.go (1)

371-376: ⚠️ Potential issue | 🟠 Major

Populate ConfigAndStacksInfo before InitCliConfig so realm is derived from the intended config path.
InitCliConfig(schema.ConfigAndStacksInfo{}, false) ignores config-selection flags. With realm derived from CliConfigPath, this can compute the wrong realm and load the wrong auth config for auth list. Please parse global flags into schema.ConfigAndStacksInfo (see cmd/terraform/plan_diff.go) before calling InitCliConfig.

Based on learnings: In Atmos, when calling cfg.InitCliConfig, you must first populate the schema.ConfigAndStacksInfo struct with global flag values using flags.ParseGlobalFlags(cmd, v) rather than passing an empty struct.

pkg/auth/types/interfaces.go (1)

116-125: ⚠️ Potential issue | 🟡 Minor

Add a trailing period to the inline comment.

This trips the godot linter.
As per coding guidelines, All comments must end with periods (enforced by godot linter).

🛠️ Suggested fix
-	Realm        string      // Credential isolation realm for file storage
+	Realm        string      // Credential isolation realm for file storage.
pkg/auth/identities/aws/assume_root.go (2)

45-53: ⚠️ Potential issue | 🟡 Minor

Add a trailing period to the inline comment.

This trips the godot linter.
As per coding guidelines, All comments must end with periods (enforced by godot linter).

🛠️ Suggested fix
-	realm            string // Credential isolation realm set by auth manager
+	realm            string // Credential isolation realm set by auth manager.

304-311: ⚠️ Potential issue | 🟠 Major

Use the computed realm for AWS file paths.

Passing "" to NewAWSFileManager points to legacy paths and can miss realm-scoped credentials written by this identity (notably for noop keyring or post-auth PrepareEnvironment). Use i.realm for path resolution and, if needed, fall back explicitly to legacy paths when the realm path is missing.

🔧 Suggested fix (apply similarly in the other call sites)
-	awsFileManager, err := awsCloud.NewAWSFileManager("", "")
+	awsFileManager, err := awsCloud.NewAWSFileManager("", i.realm)

Also applies to: 348-352, 493-499, 556-561

🤖 Fix all issues with AI agents
In `@cmd/auth_logout.go`:
- Around line 587-599: The current keychain deletion loop only removes aliases
found in atmosConfig.Auth.Identities, so --all-realms --keychain won’t clear
entries from other repos; update the deleteKeychain flow (around deleteKeychain,
atmosConfig.Auth.Identities, credentials.NewCredentialStoreWithConfig,
store.Delete) to first check whether the credential store exposes a List(realm
string) (or similar) method and, if present, call store.List(realmName) to
enumerate all aliases for that realm and delete each; if List is not available,
retain the existing loop but emit a clear warning/log that full cleanup isn’t
possible and adjust/help-text for --all-realms --keychain to reflect the
limitation.
- Around line 630-635: The os.ReadDir(baseDir) error branch currently returns
the raw err; update that to wrap the err using the static errors defined in
errors/errors.go (use errors.Join to combine the static error with the original
err). Replace the plain "return nil, err" in the ReadDir error path with a
wrapped error like errors.Join(errUtils.<STATIC_ERR_NAME>, err) (or
fmt.Errorf("%w: %v", errUtils.<STATIC_ERR_NAME>, err) if joining isn’t
appropriate) so all ReadDir failures (the err from os.ReadDir) are returned
consistently wrapped; keep the os.IsNotExist(err) early-return unchanged.

In `@pkg/auth/cloud/aws/files_test.go`:
- Around line 92-94: Several new inline comments in the aws files tests are
missing trailing periods, which fails the godot linter; update the comment text
near the assertions that reference credsPath and cfgPath (and similar comments
around the other reported spots) to end with a period. Locate the comments in
the test that describe the "New path structure" and any other test comments
referencing credsPath, cfgPath, or the surrounding test helper names, and add a
trailing period to each sentence-ending comment so they conform to the godot
rule.

In `@pkg/auth/credentials/keyring_file_test.go`:
- Around line 504-509: The test expects an error when calling
store.Delete("non-existent", "test-realm") but the keyring Delete implementation
treats not-found as success (returns nil for keyring.ErrKeyNotFound) and other
tests expect idempotent deletes; update the assertion in keyring_file_test.go to
assert.NoError(t, err) for the non-existent delete case so it matches the
behavior of store.Delete and the keyring.ErrKeyNotFound handling in the Delete
implementation.

In `@pkg/auth/credentials/keyring_memory.go`:
- Around line 114-135: List currently returns raw s.items keys when realm==""
which leaves the KeyringRealmPrefix (e.g., "atmos:") on aliases; update
memoryKeyringStore.List to mirror the non-empty-realm branch by detecting the
empty-realm prefix produced by buildKeyringKey and stripping KeyringRealmPrefix
+ ":" when present so callers always get bare aliases. Locate the List method
and modify the else branch to, for each key in s.items, if it starts with
KeyringRealmPrefix+":" append key[len(prefix):] else append key.

In `@pkg/auth/credentials/store.go`:
- Around line 34-42: The function buildKeyringKey returns the fallback format
"atmos:{alias}" (it prefixes KeyringRealmPrefix even when realm is empty) but
the comment mistakenly says the fallback is just "{alias}"; update the comment
to describe the actual behavior (fallback: "atmos:{alias}") so it matches
buildKeyringKey and references KeyringRealmPrefix and buildKeyringKey to avoid
confusion, or alternatively change the function to return just alias if you
really want backward‑compatibility with "{alias}"—pick and apply one consistent
approach.

In `@pkg/auth/identities/aws/user.go`:
- Around line 42-45: The inline comment on the struct field "realm" (in the type
containing fields name, config, realm) is missing a trailing period; update the
comment "Credential isolation realm set by auth manager" to end with a period so
it complies with the godot linter (ensure the comment for realm ends with a '.'
while leaving the rest unchanged).

In `@pkg/auth/identities/azure/subscription.go`:
- Line 23: The inline comment for the struct field realm in subscription.go is
missing a trailing period; update the comment "Credential isolation realm set by
auth manager" to end with a period so it reads "Credential isolation realm set
by auth manager." and satisfies the godot linter.
- Around line 71-74: SetRealm currently stores i.realm but never applies it;
update subscriptionIdentity so calls to SetupFiles, SetAuthContext, and
NewAzureFileManager receive the realm-scoped path (thread i.realm or the
canonical realm base path derived from i.realm) instead of passing "" so
credential storage/reads are realm-scoped. Locate uses of SetupFiles,
SetAuthContext, and NewAzureFileManager in the subscriptionIdentity methods and
replace the empty-string arg with i.realm (or a helper like realmBase(i.realm)
if a canonical path is required), ensuring any called functions accept the realm
parameter (update their signatures if necessary) so the identity uses
realm-scoped file locations. Ensure all references to the previous "" behavior
are changed so i.realm is consistently passed through.

In `@pkg/auth/manager_helpers.go`:
- Around line 115-117: createAuthManagerInstance currently hardcodes an empty
cliConfigPath when calling NewAuthManager, which collapses realms; modify
createAuthManagerInstance (and its caller
CreateAndAuthenticateManagerWithAtmosConfig) to accept and forward the actual
CLI config path instead of "" and pass that value into the NewAuthManager call
(the cliConfigPath fourth/final arg shown in NewAuthManager(..., authStackInfo,
"")) so realm hashing uses the real CLI path when present.

In `@pkg/auth/providers/aws/saml.go`:
- Around line 51-52: The inline comment for the struct field realm (the "realm
string" field in pkg/auth/providers/aws/saml.go) is missing a trailing period;
update the comment to end with a period (e.g., change "// Credential isolation
realm set by auth manager" to "// Credential isolation realm set by auth
manager.") so it conforms to the godot linter rule requiring punctuation.

In `@pkg/auth/providers/aws/sso_test.go`:
- Line 313: Update the inline comment on the test case where expected is set
(the `expected` value in the aws SSO test) to end with a period: change the
comment after `expected: "atmos",` so the text "XDG path contains atmos (aws is
added in subdirectories)" ends with a trailing period to satisfy the godot
linter.

In `@pkg/auth/providers/aws/sso.go`:
- Around line 51-52: The inline comment for the struct field realm in
pkg/auth/providers/aws/sso.go is missing a trailing period; update the comment
for the realm field (realm string // Credential isolation realm set by auth
manager) to end with a period so it becomes "...auth manager." to satisfy the
godot linter.

In `@pkg/auth/providers/azure/device_code.go`:
- Around line 117-120: The SetRealm implementation stores p.realm but Azure
providers never use it for credential isolation; update the Azure file manager
and MSAL cache creation to accept and use a realm, then pass p.realm where those
are constructed. Concretely, change NewAzureFileManager(basePath string) and
NewMSALCache(cachePath string) to accept a realm parameter (e.g.,
NewAzureFileManager(basePath, realm) and NewMSALCache(cachePath, realm)), then
update deviceCodeProvider.Paths() and deviceCodeProvider.createMSALClient() to
pass p.realm into those constructors so credential files are isolated per realm
(ensure any call sites of NewAzureFileManager/NewMSALCache are updated
accordingly).

In `@pkg/auth/providers/github/oidc.go`:
- Around line 23-27: The inline comment on the realm field in the oidcProvider
struct is missing a terminal period; update the comment for the realm field in
type oidcProvider (struct with fields name, config, realm) so it ends with a
period (e.g., change "Credential isolation realm set by auth manager" to
"Credential isolation realm set by auth manager."). Ensure the punctuation fix
complies with the godot linter.

In `@pkg/auth/providers/mock/aws/provider.go`:
- Around line 31-34: The inline comment on the struct field "realm" in the
provider struct (symbol: realm) is missing a trailing period and fails godot
linting; update the comment "Credential isolation realm set by auth manager" to
include a final period so it reads "Credential isolation realm set by auth
manager." ensuring the comment ends with a period.

In `@pkg/config/config.go`:
- Around line 85-92: The code currently lets ATMOS_VERBOSE override flags;
change the logic so flags take precedence: if flagKeyValue contains the
logs-level flag or the "verbose" flag (e.g., check flagKeyValue["logs-level"]
and flagKeyValue["verbose"]) use those to set atmosConfig.Logs.Level (mapping
"true" verbose to "Debug" as needed), otherwise fall back to checking
os.Getenv("ATMOS_VERBOSE") and only then set atmosConfig.Logs.Level to "Debug".
Also update the surrounding comments to be full sentences ending with periods to
satisfy godot. Reference symbols: flagKeyValue, atmosConfig.Logs.Level, and
os.Getenv("ATMOS_VERBOSE").

In `@pkg/schema/schema_auth.go`:
- Around line 5-9: Update the doc comment for the Realm field in
pkg/schema/schema_auth.go to clarify that the default is a SHA256 hash (first 8
characters) of the CLI config path (the path provided via --config-path or the
default config location), not specifically the atmos.yaml directory; keep
mention that it can be overridden via the ATMOS_AUTH_REALM environment variable
and that env/config/CLI precedence still applies. Reference: the Realm struct
field declaration.
🧹 Nitpick comments (7)
pkg/auth/providers/mock/provider.go (1)

33-33: Inline comment needs a period.

The godot linter requires all comments to end with periods.

Proposed fix
-	realm  string // Credential isolation realm set by auth manager
+	realm  string // Credential isolation realm set by auth manager.

As per coding guidelines: "All comments must end with periods (enforced by godot linter)".

pkg/auth/providers/azure/device_code.go (1)

42-42: Comment missing trailing period.

Per coding guidelines, all comments must end with periods.

-	realm          string // Credential isolation realm set by auth manager
+	realm          string // Credential isolation realm set by auth manager.
pkg/auth/cloud/aws/files_test.go (1)

527-531: Consider a realm‑specific isolation test.
With realm now in the constructor signature, a small test that uses different realm values would lock in the new behavior.

As per coding guidelines, “Every new feature must include comprehensive unit tests targeting >80% code coverage for all packages”.

pkg/auth/manager_test.go (1)

277-307: Consider keying testStore data by realm + alias.
Realm is currently ignored, so a future non‑empty realm test could mask collisions; folding realm into the key would keep the stub closer to production behavior.

pkg/auth/providers/mock/identity.go (1)

65-68: Consider using realm in mock credential paths.

The realm field is stored but never read. The getCredentialsFilePath() method at line 51-56 doesn't incorporate the realm into the path, unlike real providers.

For test isolation, consider updating the path to include realm:

♻️ Optional: Incorporate realm into mock credential path
 func (i *Identity) getCredentialsFilePath() string {
 	tmpDir := os.TempDir()
-	return filepath.Join(tmpDir, "atmos-mock-"+i.name+".json")
+	if i.realm != "" {
+		return filepath.Join(tmpDir, "atmos-mock-"+i.realm+"-"+i.name+".json")
+	}
+	return filepath.Join(tmpDir, "atmos-mock-"+i.name+".json")
 }

This would enable proper realm isolation in tests. However, if tests always use the same realm or don't test cross-realm scenarios with mocks, current behavior is acceptable.

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

22-24: Add a realm-specific SetupFiles test case.

All current calls pass an empty realm, so the new realm-scoped path layout isn’t exercised. A small test with a non-empty realm would lock in the new behavior.

As per coding guidelines, Every new feature must include comprehensive unit tests targeting >80% code coverage for all packages.

pkg/auth/credentials/keyring_memory_test.go (1)

138-163: Consider adding cross-realm isolation test.

This test verifies two independent memory stores are isolated. You might also want a test that verifies credentials stored in one realm aren't visible when listing/retrieving from a different realm within the same store instance.

Comment thread cmd/auth_logout.go Resolved
Comment thread cmd/auth_logout.go Resolved
Comment thread pkg/auth/cloud/aws/files_test.go Resolved
Comment thread pkg/auth/credentials/keyring_memory.go Resolved
Comment thread pkg/auth/providers/azure/device_code.go Resolved
Comment thread pkg/auth/providers/github/oidc.go Resolved
Comment thread pkg/auth/providers/mock/aws/provider.go Resolved
Comment thread pkg/config/config.go Resolved
Comment thread pkg/schema/schema_auth.go Resolved
@coderabbitai

coderabbitai Bot commented Feb 2, 2026

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This PR introduces realm-based credential isolation across the entire authentication system. It adds a new realm package for computing and validating isolation scopes, extends credential store APIs with realm parameters, propagates realms through auth managers and providers, updates AWS file management for realm-scoped paths, and adds cross-realm logout capabilities via a new --all-realms flag.

Changes

Cohort / File(s) Summary
Realm Infrastructure
pkg/auth/realm/realm.go, pkg/auth/realm/realm_test.go
New realm package implementing GetRealm() with precedence (env var → config → auto-hash), validation rules, and RealmInfo struct for isolation scoping.
Core Credential Store APIs
pkg/auth/credentials/store.go, pkg/auth/credentials/keyring_*.go, pkg/auth/credentials/keyring_*_test.go, pkg/auth/credentials/store_test.go, pkg/auth/credentials/suite_test.go
All credential store methods (Store, Retrieve, Delete, List, IsExpired) now accept realm parameter; keyring implementations updated to build realm-scoped keys and support realm filtering.
Auth Manager Core
pkg/auth/manager.go, pkg/auth/manager_*.go
Added GetRealm() method, realm propagation to providers/identities, extended NewAuthManager signature with cliConfigPath, realm included in PostAuthenticateParams and WhoamiInfo.
Auth Manager Tests
pkg/auth/manager_*_test.go
Mock stores updated to accept realm, NewAuthManager calls extended with cliConfigPath parameter, multiple test types gain SetRealm() methods.
Type System & Interfaces
pkg/auth/types/interfaces.go, pkg/auth/types/mock_interfaces.go, pkg/auth/types/whoami.go, pkg/auth/types/whoami_test.go
Added SetRealm() to Provider/Identity interfaces, GetRealm() to AuthManager, Realm/RealmSource fields to WhoamiInfo, all CredentialStore method signatures extended with realm parameter.
AWS Provider & Identity Implementations
pkg/auth/providers/aws/saml.go, pkg/auth/providers/aws/sso.go, pkg/auth/identities/aws/assume_*.go, pkg/auth/identities/aws/user.go, pkg/auth/identities/aws/permission_set.go, pkg/auth/cloud/aws/files.go, pkg/auth/cloud/aws/setup.go
Added realm field and SetRealm() to all AWS providers/identities; AWS file manager now realm-aware with realm-scoped path construction and cleanup isolation.
Azure & GitHub Providers
pkg/auth/providers/azure/cli.go, pkg/auth/providers/azure/device_code.go, pkg/auth/providers/azure/oidc.go, pkg/auth/providers/github/oidc.go
Added realm field and SetRealm() method to all Azure and GitHub provider types.
Mock Provider Implementations
pkg/auth/providers/mock/provider.go, pkg/auth/providers/mock/identity.go, pkg/auth/providers/mock/aws/provider.go, pkg/auth/providers/mock/aws/identity.go
Added realm field and SetRealm() to mock provider and identity types; AWS mock identity propagates realm through PostAuthenticate.
Logout Enhancements
cmd/auth_logout.go, cmd/auth_logout_test.go, pkg/auth/manager_logout.go, pkg/auth/manager_logout_test.go
New --all-realms flag with discoverRealms() and performLogoutAllRealms() handlers; realm-scoped Delete() calls with backward-compatible legacy entry cleanup.
Command-Line Interface Updates
cmd/auth_*.go (multiple files)
createAuthManager and NewAuthManager calls updated to pass cliConfigPath; auth_login shows Realm in displayAuthSuccess; auth_whoami displays realm with source.
Credential Provider Helpers
cmd/auth_user.go, cmd/auth_console.go, cmd/auth_console_test.go, cmd/auth_caching_test.go
Credential store calls updated with realm parameter; mock auth managers gain GetRealm() methods.
Helper & Hook Paths
pkg/auth/hooks.go, pkg/auth/hooks_test.go, pkg/auth/manager_helpers.go, pkg/auth/manager_helpers_test.go, pkg/devcontainer/identity.go, cmd/devcontainer/helpers.go, internal/exec/...
NewAuthManager calls extended with cliConfigPath; authContextWrapper gains GetRealm() method; realm propagated through terraform/workflow execution paths.
Configuration & Schema
pkg/schema/schema_auth.go
New Realm field added to AuthConfig struct with YAML/JSON/mapstructure tags and environment variable precedence documentation.
Tests & Fixtures
cmd/auth_*_test.go, tests/test-cases/auth-*.yaml, tests/snapshots/TestCLICommands_*
Test environment variables set ATMOS_AUTH_REALM; credential store mocks and identities updated with realm parameters; golden snapshots include Realm output in auth login/whoami.
Documentation
website/blog/2026-02-02-auth-realm-isolation.mdx, website/src/data/roadmap.js, tests/fixtures/scenarios/complete/.../README.md
New blog post documenting realm isolation feature, realm computation precedence, new --all-realms flag, and migration guidance; roadmap updated with shipped milestone.

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~100+ minutes

This PR introduces breaking API changes to the credential store interface affecting 80+ files. The changes are heterogeneous, spanning realm computation logic, credential store implementations, auth manager orchestration, provider/identity realm propagation, AWS file path isolation, logout enhancements, and widespread call-site updates. Dense logic in the realm package, complex propagation patterns, and potential backward-compatibility concerns require careful review.

Possibly related PRs

Suggested reviewers

  • osterman
🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 42.74% 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 clearly and specifically captures the main objective: implementing realm isolation for credential separation in the auth system.

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

✨ 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 Benbentwo/auth-realm-isolation

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

Note

Due to the large number of review comments, Critical, Major severity comments were prioritized as inline comments.

Caution

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

⚠️ Outside diff range comments (3)
pkg/auth/providers/azure/oidc.go (1)

60-66: ⚠️ Potential issue | 🟡 Minor

End the inline realm field comment with a period.

This will keep godot happy for comment punctuation.

Proposed fix
-	realm         string // Credential isolation realm set by auth manager
+	realm         string // Credential isolation realm set by auth manager.
As per coding guidelines: All comments must end with periods (enforced by godot linter).
cmd/auth_whoami.go (1)

124-130: ⚠️ Potential issue | 🟠 Major

Honor config-selection flags when initializing the auth manager.
loadAuthManager calls InitCliConfig with an empty ConfigAndStacksInfo, so --config, --config-path, --base-path, and --profile are ignored. With realms derived from cliConfigPath, this can resolve the wrong realm and credentials. Plumb a populated ConfigAndStacksInfo (via flags.ParseGlobalFlags) into InitCliConfig here.
Based on learnings: In the Atmos codebase, when calling cfg.InitCliConfig, you must first populate the schema.ConfigAndStacksInfo struct with global flag values using flags.ParseGlobalFlags(cmd, v) rather than passing an empty struct.

pkg/auth/credentials/keyring_file_test.go (1)

573-585: ⚠️ Potential issue | 🟡 Minor

Use a realm‑scoped key when inserting corrupted data.
Right now the test writes a raw "corrupted" key but retrieves with "test-realm", so it misses the item and won’t exercise the JSON-unmarshal error path.

🛠️ Suggested fix
-	_ = store.ring.Set(keyring.Item{
-		Key:  "corrupted",
-		Data: []byte("this is not valid JSON"),
-	})
+	realmKey := buildKeyringKey("corrupted", "test-realm")
+	_ = store.ring.Set(keyring.Item{
+		Key:  realmKey,
+		Data: []byte("this is not valid JSON"),
+	})
🤖 Fix all issues with AI agents
In `@cmd/auth_ecr_login.go`:
- Around line 142-150: The auth.NewAuthManager call is passing an empty string
for the cliConfigPath which forces an auto-generated constant realm; change the
call to pass the actual cliConfigPath variable (instead of "") so ECR logins get
an isolated realm. Update the invocation in the block that constructs
authStackInfo/credStore/validator to use cliConfigPath (and, if the surrounding
function does not currently accept or have cliConfigPath, add/propagate a
cliConfigPath parameter into that function/caller) so NewAuthManager(authConfig,
credStore, validator, authStackInfo, cliConfigPath) is used.

In `@cmd/auth_user.go`:
- Around line 134-142: The realm.GetRealm error should be wrapped with a static
sentinel from errors/errors.go instead of returning a raw fmt error; replace the
line returning fmt.Errorf("failed to compute realm: %w", err) with a wrapped
sentinel (e.g. use the project sentinel errors.ErrRealmCompute — add it to
errors/errors.go if missing) and wrap the original error either via
fmt.Errorf("%w: %v", errors.ErrRealmCompute, err) or
errors.Join(errors.ErrRealmCompute, err); update imports to reference the
project errors package and ensure callers can use errors.Is/errors.Join for
checks.

In `@pkg/auth/identities/aws/assume_role.go`:
- Around line 674-677: Logout currently constructs the AWS file manager with an
empty realm causing DeleteIdentity to delete from the wrong directory; change
the awsCloud.NewAWSFileManager call in assumeRoleIdentity.Logout to pass i.realm
(not ""), matching PostAuthenticate's storage path ({realm}/aws/{provider}/) and
ensure the comment is updated to reflect that realm-scoped storage must be used;
reference functions/types: assumeRoleIdentity, Logout, PostAuthenticate,
SetRealm, i.realm, awsCloud.NewAWSFileManager, DeleteIdentity, and
userIdentity.Logout().

In `@pkg/auth/identities/aws/assume_root_test.go`:
- Around line 1481-1483: The test contains a handwritten mockAuthManager (and
its GetRealm method) that should be removed and replaced with the generated
MockAuthManager from mock_interfaces.go; delete the mockAuthManager struct and
its methods, update the test to use the generated MockAuthManager symbol instead
of mockAuthManager, and adjust imports/instantiation to reference the generated
mock type (and its package) so future interface changes are handled by mockgen.
Ensure all occurrences of mockAuthManager are replaced with MockAuthManager and
the test constructs the generated mock appropriately.

In `@pkg/auth/identities/aws/assume_root.go`:
- Around line 556-557: The Logout implementation uses NewAWSFileManager("", "")
which mismatches user.go's realm-isolated behavior; update Logout to pass
i.realm (not empty string) when creating the awsCloud.NewAWSFileManager so it
will remove credentials stored under the same realm path used by
PostAuthenticate, and adjust the comment to reflect that Logout respects realm
isolation; alternatively, if you intentionally store assume_root credentials
globally, make the change in PostAuthenticate to use "" instead—prefer using
i.realm to align with user.go's credential isolation.

In `@pkg/auth/identities/aws/permission_set.go`:
- Around line 183-185: The code is creating an AWSFileManager with an empty
realm which bypasses realm-scoped paths; update calls to
awsCloud.NewAWSFileManager("", "") (and the other call sites noted) to pass the
resolved realm i.realm (set by the manager) instead of "" so pre-auth credential
lookup and logout use the realm-scoped paths; keep cross-realm deletion logic
only for the explicit --all-realms flow. Ensure you update each occurrence
(e.g., in permission_set.go around the awsFileManager creation sites) to use
i.realm.

In `@pkg/auth/identities/azure/subscription.go`:
- Around line 71-74: SetRealm currently stores realm on subscriptionIdentity but
never applies it to Azure file operations; update every Azure file manager/setup
call in this type (where "" is being passed) to pass i.realm instead so
credential file paths are built per-realm. Locate uses of subscriptionIdentity
that create or open Azure credential files or call the Azure file manager/setup
functions and replace the empty-realm argument with i.realm, ensuring path
construction and any cache keys incorporate i.realm to enforce isolation.

In `@pkg/auth/manager_helpers.go`:
- Around line 115-117: The helper currently calls NewAuthManager(authConfig,
credStore, validator, authStackInfo, "") which passes an empty cliConfigPath and
causes a shared auto‑realm; change the helper (e.g., in
CreateAndAuthenticateManagerWithAtmosConfig) to accept and forward the actual
cliConfigPath parameter into NewAuthManager instead of "", ensuring each
helper-built manager gets the repository-specific cliConfigPath to preserve
isolation.

In `@pkg/auth/realm/realm.go`:
- Around line 53-84: GetRealm and Validate currently return raw fmt.Errorf
errors; update both to wrap validation failures and any contextual errors using
the static error values defined in errors/errors.go (use the appropriate
exported error like ErrInvalidRealm or the matching static error from that file)
so callers can use errors.Is; combine multiple errors with errors.Join where
appropriate and keep fmt.Errorf("%s: %w", msg, err) for contextual wrapping;
apply the same change to any other places in this file that return raw
fmt.Errorf (including the Validate implementation and any other error returns in
this file) so all errors are wrapped with the repository's static error types.
🟡 Minor comments (16)
pkg/auth/identities/azure/subscription.go-23-23 (1)

23-23: ⚠️ Potential issue | 🟡 Minor

End inline comment with a period.

The new inline comment doesn’t end with a period, which will trip godot.
As per coding guidelines: All comments must end with periods (enforced by godot linter).

🔧 Minimal fix
-	realm          string // Credential isolation realm set by auth manager
+	realm          string // Credential isolation realm set by auth manager.
tests/test-cases/auth-mock.yaml-26-26 (1)

26-26: ⚠️ Potential issue | 🟡 Minor

Add ATMOS_AUTH_REALM to all memory keyring tests for consistent isolation.

The realm is currently set only for login and whoami tests, but env, exec, and logout tests also use ATMOS_KEYRING_TYPE: "memory" without it. All memory keyring tests should consistently set the same realm to ensure deterministic credential isolation across the test suite.

tests/fixtures/scenarios/complete/components/terraform/infra/vpc-flow-logs-bucket/README.md-94-94 (1)

94-94: ⚠️ Potential issue | 🟡 Minor

Revert branch name to match upstream default.

The link should use main as the branch, not master. The upstream cloudposse/terraform-aws-components repository uses main as its default branch.

pkg/auth/cloud/aws/files_test.go-92-92 (1)

92-92: ⚠️ Potential issue | 🟡 Minor

Add trailing periods to new inline comments.
Godot will fail when comments don’t end with a period.
As per coding guidelines, "All comments must end with periods (enforced by godot linter)."

Also applies to: 107-107, 415-416, 446-447, 481-482, 587-587, 631-631

pkg/auth/providers/mock/aws/provider.go-30-34 (1)

30-34: ⚠️ Potential issue | 🟡 Minor

End the inline realm field comment with a period.

This keeps comment punctuation consistent with godot.

Proposed fix
-	realm  string // Credential isolation realm set by auth manager
+	realm  string // Credential isolation realm set by auth manager.
As per coding guidelines: All comments must end with periods (enforced by godot linter).
pkg/auth/manager_shell_env_test.go-228-228 (1)

228-228: ⚠️ Potential issue | 🟡 Minor

Add a doc comment for SetRealm.

This keeps exported method documentation consistent and lint-friendly.

Proposed fix
+// SetRealm sets the credential isolation realm for this identity.
 func (m *mockIdentityForShellEnv) SetRealm(_ string) {}
As per coding guidelines: Document all exported functions, types, and methods following Go's documentation conventions.
pkg/auth/hooks_test.go-131-133 (1)

131-133: ⚠️ Potential issue | 🟡 Minor

Add a doc comment for GetRealm.

This avoids golangci-lint doc warnings for exported methods.

Proposed fix
+// GetRealm returns the realm info for this stub auth manager.
 func (s *stubAuthManager) GetRealm() realm.RealmInfo {
 	return realm.RealmInfo{}
 }
As per coding guidelines: Document all exported functions, types, and methods following Go's documentation conventions.
pkg/auth/providers/mock/provider.go-30-34 (1)

30-34: ⚠️ Potential issue | 🟡 Minor

Add a trailing period to the realm field comment.

This will satisfy the godot linter.

🛠️ Suggested update
 type Provider struct {
 	name   string
 	config *schema.Provider
-	realm  string // Credential isolation realm set by auth manager
+	realm  string // Credential isolation realm set by auth manager.
 }

As per coding guidelines, all comments must end with periods (enforced by godot linter).

pkg/auth/providers/mock/identity.go-33-37 (1)

33-37: ⚠️ Potential issue | 🟡 Minor

Add a period to the field comment and use realm in mock credential paths.

The inline comment will fail godot lint, and the stored realm isn’t reflected in the mock credentials file path, which can cause cross‑realm collisions in tests.

🛠️ Suggested update
 type Identity struct {
 	name   string
 	config *schema.Identity
-	realm  string // Credential isolation realm set by auth manager
+	realm  string // Credential isolation realm set by auth manager.
 }
 func (i *Identity) getCredentialsFilePath() string {
 	// Use a temp directory that's cleaned up by the OS.
 	// In production, real providers would use XDG directories like ~/.config/atmos/aws/{provider}/.
 	tmpDir := os.TempDir()
-	return filepath.Join(tmpDir, "atmos-mock-"+i.name+".json")
+	fileName := "atmos-mock-" + i.name + ".json"
+	if i.realm != "" {
+		fileName = "atmos-mock-" + i.realm + "-" + i.name + ".json"
+	}
+	return filepath.Join(tmpDir, fileName)
 }

As per coding guidelines, all comments must end with periods (enforced by godot linter).

Also applies to: 65-68

website/src/data/roadmap.js-162-162 (1)

162-162: ⚠️ Potential issue | 🟡 Minor

Update auth initiative progress/PR index to reflect this shipped milestone.

The milestone is added, but the auth initiative progress is still 85 and the PR list doesn’t include 2043. Please confirm the intended progress and add the PR entry if required for the major‑PR roadmap rule.

🛠️ Suggested PR list entry
       prs: [
         { number: 1894, title: 'Add Azure OIDC/Workload Identity Federation provider' },
         { number: 1859, title: 'Add ECR authentication' },
         { number: 1884, title: 'Add EKS kubeconfig authentication integration PRD' },
         { number: 1887, title: 'Add PRD for aws/login provider (native SDK auth)' },
         { number: 1683, title: 'Update auth docs and implement GitHub providers' },
+        { number: 2043, title: 'feat: implement auth realm isolation with credential separation' },
       ],

As per coding guidelines, PRs labeled minor/major MUST update website/src/data/roadmap.js with milestone status, changelog link, PR link, and initiative progress percentage.

pkg/auth/credentials/store.go-34-43 (1)

34-43: ⚠️ Potential issue | 🟡 Minor

Doc comment doesn't match fallback behavior.

Line 36 says fallback is "{alias}" but line 42 returns "atmos:{alias}". The comment should reflect the actual format.

📝 Proposed doc fix
 // buildKeyringKey creates a realm-scoped keyring key.
 // Format: "atmos:{realm}:{alias}" when realm is provided.
-// Falls back to just "{alias}" for backward compatibility when realm is empty.
+// Falls back to "atmos:{alias}" for backward compatibility when realm is empty.
 func buildKeyringKey(alias, realm string) string {
pkg/auth/providers/mock/aws/identity.go-38-38 (1)

38-38: ⚠️ Potential issue | 🟡 Minor

Comment should end with a period.

Per coding guidelines, all comments must end with periods.

📝 Fix
-	realm  string // Credential isolation realm set by auth manager
+	realm  string // Credential isolation realm set by auth manager.
pkg/auth/identities/aws/user.go-42-45 (1)

42-45: ⚠️ Potential issue | 🟡 Minor

Add a period to the inline comment for godot.
The inline comment on the realm field needs a trailing period.

Suggested fix
-	realm  string // Credential isolation realm set by auth manager
+	realm  string // Credential isolation realm set by auth manager.
As per coding guidelines: All comments must end with periods (enforced by `godot` linter).
pkg/auth/types/interfaces.go-99-105 (1)

99-105: ⚠️ Potential issue | 🟡 Minor

Add trailing periods to new doc comment lines.
Several new comment lines are missing periods and will trip godot. As per coding guidelines: All comments must end with periods (enforced by godot linter).

✍️ Suggested fixes
-	// Called by the auth manager after provider construction to propagate the realm
+	// Called by the auth manager after provider construction to propagate the realm.
@@
-	Realm        string      // Credential isolation realm for file storage
+	Realm        string      // Credential isolation realm for file storage.
@@
-	// Called by the auth manager after identity construction to propagate the realm
+	// Called by the auth manager after identity construction to propagate the realm.
@@
-// All methods that operate on credentials require a realm parameter to ensure
+// All methods that operate on credentials require a realm parameter to ensure.
@@
-// The realm provides credential isolation - the same alias in different realms
+// The realm provides credential isolation - the same alias in different realms.

Also applies to: 116-125, 168-183, 328-336

pkg/auth/credentials/keyring_file.go-298-320 (1)

298-320: ⚠️ Potential issue | 🟡 Minor

Align the List doc comment with actual behavior and add periods.
The function already filters when realm is set; the comment implies callers must filter. Also one line lacks a trailing period. As per coding guidelines: All comments must end with periods (enforced by godot linter).

✍️ Suggested fix
-// List returns all stored credential aliases within the specified realm.
-// Note: The file keyring stores keys with realm prefix, so this returns all keys
-// and callers should filter by realm prefix if needed.
+// List returns all stored credential aliases within the specified realm.
+// When realm is provided, keys are filtered by realm prefix and the prefix is stripped.
+// When realm is empty, raw keys (including any realm prefixes) are returned.
pkg/auth/realm/realm.go-46-107 (1)

46-107: ⚠️ Potential issue | 🟡 Minor

Add periods to list‑item comments to satisfy godot.
The precedence list and validation rules include lines without trailing periods. As per coding guidelines: All comments must end with periods (enforced by godot linter).

✍️ Example fix (apply to all list items)
-//  1. ATMOS_AUTH_REALM environment variable (highest priority)
+//  1. ATMOS_AUTH_REALM environment variable (highest priority).
@@
-//   - Must not exceed MaxLength (64) characters
+//   - Must not exceed MaxLength (64) characters.
🧹 Nitpick comments (7)
pkg/auth/cloud/aws/files_logout_test.go (1)

95-193: TestAWSFileManager_CleanupAll may have inconsistent expectations.

The CleanupAll implementation removes {baseDir}/{realm}/. With an empty realm (as in these tests), it removes {baseDir}/ itself. The test at line 188 verifies baseDir is removed, which aligns with this behavior when realm is empty.

However, the setup at lines 103-116 creates directories directly under baseDir (e.g., provider1, provider2) rather than under baseDir/aws/. This means CleanupAll would succeed but the cleanup verification is testing a different path structure than Cleanup tests.

Consider aligning the directory setup with the new realm-aware structure if these tests should mirror production paths.

cmd/auth_logout_test.go (2)

10-12: Add cmd.NewTestKit(t) to keep RootCmd state isolated.
These cmd tests don’t initialize NewTestKit(t), so RootCmd flags/args can leak across cases. Please add it per test (or via a shared helper) to align with the cmd test guideline.
As per coding guidelines: cmd//*_test.go**: ALWAYS use cmd.NewTestKit(t) for cmd tests to auto-clean RootCmd state (flags, args).


40-40: Prefer realm.SourceAuto for mock RealmInfo.Source.
Using the exported constant avoids string drift and keeps tests aligned with realm semantics.

Suggested change (apply across all GetRealm expectations)
-m.EXPECT().GetRealm().Return(realm.RealmInfo{Value: "test-realm", Source: "auto"})
+m.EXPECT().GetRealm().Return(realm.RealmInfo{Value: "test-realm", Source: realm.SourceAuto})

Also applies to: 84-84, 100-100, 166-166, 281-281, 446-446, 525-525, 540-540, 590-590, 608-608, 653-653, 666-666, 1135-1135, 1154-1154, 1171-1171

cmd/auth_logout.go (1)

524-605: Consider clarifying the keychain deletion scope.

The keychain deletion loop (lines 590-600) only removes entries for identities defined in the current atmos.yaml. If a user has credentials from other repositories with different identity names, those keychain entries won't be removed.

This is probably acceptable given the alternative (enumerating all keyring entries) isn't supported by the underlying library. The debug log at line 597 captures failures gracefully.

Worth documenting this limitation in user-facing docs or the help text.

pkg/auth/credentials/keyring_file_test.go (1)

278-318: Consider table‑driven coverage for the expiry scenarios.
Expired/fresh/missing are three scenarios; a table‑driven test would keep this aligned with the test conventions and make future cases easier to add. As per coding guidelines: Use table-driven tests for testing multiple scenarios in Go.

pkg/auth/manager_caching_test.go (1)

176-202: Consider mockgen‑generated mocks for these updated stubs.
The manual mocks now need extra methods (e.g., SetRealm) to stay in sync. Migrating them to mockgen would reduce drift as interfaces evolve. As per coding guidelines: Use interfaces and dependency injection for testability - Generate mocks with go.uber.org/mock/mockgen using //go:generate directives, never manual mocks.

Also applies to: 256-258

pkg/auth/manager_test.go (1)

149-157: Redundant defer block with t.Setenv.

t.Setenv automatically restores the original value on test cleanup. The defer block duplicates that behavior.

🧹 Simplify by removing the redundant defer
 func TestManager_GetDefaultIdentity_MultipleDefaultsOrder(t *testing.T) {
 	// Test that multiple defaults are returned in a consistent order.
 	identities := map[string]schema.Identity{
 		"zebra":   {Kind: "aws/user", Default: true},
 		"alpha":   {Kind: "aws/user", Default: true},
 		"beta":    {Kind: "aws/user", Default: false},
 		"charlie": {Kind: "aws/user", Default: true},
 	}

 	// Set CI mode to get deterministic error message.
-	origCI, hadCI := os.LookupEnv("CI")
 	t.Setenv("CI", "true")
-	defer func() {
-		if hadCI {
-			os.Setenv("CI", origCI)
-		} else {
-			os.Unsetenv("CI")
-		}
-	}()
 	manager := &manager{

Comment thread cmd/auth_ecr_login.go Resolved
Comment thread cmd/auth_user.go Resolved
Comment thread pkg/auth/identities/aws/assume_role.go Resolved
Comment thread pkg/auth/identities/aws/assume_root.go Resolved
Comment thread pkg/auth/manager_helpers.go Resolved
Comment thread pkg/auth/realm/realm.go Resolved
- Fix ECR login to pass cliConfigPath for proper realm isolation
- Add realm parameter to Azure file manager and MSAL cache
- Fix Azure subscription identity to use realm in credential paths
- Fix keyring memory List() to strip prefix when realm is empty
- Fix keyring file Delete() to handle os.IsNotExist as idempotent
- Fix ATMOS_VERBOSE env precedence (flags > env > config)
- Wrap ReadDir error with errUtils.ErrReadDirectory
- Fix store.go comment to match actual behavior (atmos:{alias})
- Update schema_auth.go doc to say "CLI config path" not "atmos.yaml"
- Add trailing periods to all realm field comments (godot linter)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
Address remaining CodeRabbit review feedback:
- Use i.realm instead of empty string in assume_root.go Logout
- Use i.realm in all permission_set.go methods (Environment,
  PrepareEnvironment, CredentialsExist, Logout)
- Add static errors ErrFailedToComputeRealm and ErrInvalidRealm
- Wrap realm validation errors with static error types in realm.go
- Use static error wrapping in auth_user.go for realm errors

Co-Authored-By: Claude Opus 4.5 <[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: 3

Caution

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

⚠️ Outside diff range comments (2)
pkg/auth/cloud/azure/files.go (1)

82-100: ⚠️ Potential issue | 🟠 Major

Realm is ignored when basePath is set.
If users configure a base path, realm isolation is bypassed and collisions can return. Consider appending realm under the custom base path when provided.

Suggested fix
-	if basePath != "" {
-		baseDir = basePath
-	} else {
+	if basePath != "" {
+		baseDir = basePath
+		if realm != "" {
+			baseDir = filepath.Join(basePath, realm)
+		}
+	} else {
 		homeDir, err := homedir.Dir()
 		if err != nil {
 			return nil, errors.Join(ErrGetHomeDir, err)
 		}
pkg/auth/providers/mock/aws/identity.go (1)

38-72: ⚠️ Potential issue | 🟡 Minor

Use i.realm as a fallback when params.Realm is empty.
Right now SetRealm is effectively unused and realm isolation can be skipped if params is nil or missing the value.

Suggested fix
-	realm := ""
-	if params != nil {
-		realm = params.Realm
-	}
+	realm := i.realm
+	if params != nil && params.Realm != "" {
+		realm = params.Realm
+	}

Also applies to: 174-194

🤖 Fix all issues with AI agents
In `@cmd/auth_logout.go`:
- Around line 529-584: The performLogoutAllRealms code returns raw fmt.Errorf
errors for getting the XDG config dir, discovering realms, and removing a realm;
update these returns to wrap with static sentinel errors from errors/errors.go
(or add new sentinels) so callers can use errors.Is. Specifically, in
performLogoutAllRealms replace the fmt.Errorf("failed to get config directory:
%w", err) return with wrapping using a sentinel like
errors.ErrFailedGetXDGConfigDir (or define ErrFailedGetXDGConfigDir), replace
fmt.Errorf("failed to discover realms: %w", err) with
errors.ErrFailedDiscoverRealms wrapping, and replace fmt.Errorf("failed to
remove realm %s: %w", realmName, err) with a sentinel such as
errors.ErrFailedRemoveRealm (including realmName in the wrapped message). Ensure
the new sentinels are declared in errors/errors.go and used with fmt.Errorf("%w:
%v", errors.Err..., err) or errors.WithMessage to preserve the original error.

In `@pkg/auth/credentials/keyring_file.go`:
- Around line 299-323: fileKeyringStore.List returns raw keyring keys when realm
== "" which leaks the KeyringRealmPrefix; update the empty-realm branch to strip
the base prefix (KeyringRealmPrefix + ":") from any keys that start with it and
return the bare aliases (leave keys that don’t have the prefix unchanged) so
behavior matches the realm-filtered branch and the in-memory store; locate the
logic in fileKeyringStore.List and replace the direct return keys with a small
loop that checks strings.HasPrefix(key, basePrefix) and appends either
key[len(basePrefix):] or key accordingly before returning.

In `@pkg/auth/identities/aws/assume_root.go`:
- Around line 304-307: The pre-auth code is creating AWSFileManager with empty
realm (calling awsCloud.NewAWSFileManager("", "")) which causes path resolution
to ignore the identity realm; change those NewAWSFileManager calls to pass the
identity's realm (use i.realm) so stored credentials are resolved under
realm-scoped directories—update each occurrence (e.g., around the Environment()
pre-auth section and the blocks at the other two locations referenced) to
construct the AWSFileManager with i.realm and preserve the existing second
argument behavior.
🧹 Nitpick comments (1)
pkg/auth/cloud/azure/msal_cache_test.go (1)

35-35: Consider adding a test case for non-empty realm.

The tests pass empty realm consistently, which is valid. Adding a test case verifying the realm-isolated path (~/.azure/atmos/{realm}/msal_token_cache.json) would strengthen coverage for the new behavior.

Example test case
{
    name:          "default path with realm",
    cachePath:     "",
    realm:         "test-realm",
    expectDefault: true,
    checkPath: func(t *testing.T, path string) {
        assert.Contains(t, path, "atmos")
        assert.Contains(t, path, "test-realm")
    },
},

Comment thread cmd/auth_logout.go Resolved
Comment thread pkg/auth/credentials/keyring_file.go Resolved
Comment thread pkg/auth/identities/aws/assume_root.go Resolved
coderabbitai[bot]
coderabbitai Bot previously approved these changes Feb 5, 2026
Comment thread cmd/auth_logout.go Resolved
Comment thread cmd/auth_logout.go Resolved
Comment thread cmd/auth_logout.go Resolved
…n auth logout

Replace u.PrintfMessageToTUI with theme.Styles.Checkmark/XMark patterns
with the proper ui.Success() and ui.Error() helpers. This follows the
CLAUDE.md mandatory I/O and UI patterns and removes the theme import.

Co-Authored-By: Claude Opus 4.5 <[email protected]>
@aknysh
Andriy Knysh (aknysh) merged commit c0ba043 into main Feb 10, 2026
58 checks passed
@aknysh
Andriy Knysh (aknysh) deleted the Benbentwo/auth-realm-isolation branch February 10, 2026 18:53
@github-actions

Copy link
Copy Markdown

These changes were released in v1.206.0-rc.5.

Andriy Knysh (aknysh) added a commit that referenced this pull request Feb 12, 2026
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]>
Andriy Knysh (aknysh) added a commit that referenced this pull request Feb 13, 2026
* fix: resolve auth realm isolation issues (#2071, #2072)

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]>

* fix: use i.realm in assumeRoleIdentity Environment/PrepareEnvironment/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]>

* feat: add realm mismatch warning and improve auth test coverage

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]>

* fix: address PR review feedback and increase realm mismatch test coverage

- 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]>

* fix: remove private repo link that fails link checker

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

---------

Co-authored-by: Claude Opus 4.6 <[email protected]>

This branch was successfully deployed

1 active deployment
preview — 9b9353a4 Deployed Feb 10, 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/xl Extra large size PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants