Repository navigation
fix(auth): prevent Azure CLI cache corruption for guest users - #2861
Conversation
After `atmos auth login`, the Azure CLI cache write-back created an MSAL
Account entry with home_account_id derived as "{oid}.{target-tenant}" and
hardcoded account_source "device_code". For guest (B2B) users the home
tenant differs from the target tenant, so az ended up with two Account
entries for the same username and failed every subsequent command with
"Found multiple accounts with the same username" (azure-cli#20168) --
including `az account get-access-token`, which the azure/cli provider
itself depends on.
- Record the originating auth method on AzureCredentials (cli /
device_code / oidc) and skip the CLI file write-back entirely for
azure/cli-sourced credentials: az's own cache is authoritative, and
writing back what came from az is what corrupted it.
- Capture MSAL's real home account ID in the device-code provider
(silent and interactive flows) and use it in both cache writers
(UpdateAzureCLIFiles and the provider-level updateAzureCLICache),
falling back to the previous derivation when unavailable.
- Replace the azure/subscription identity's field-by-field credential
copy with a struct copy plus explicit overrides: the field list silently
dropped AuthMethod/HomeAccountID before they reached the cache writer
(found by end-to-end testing against a real guest-user tenant), and a
reflection-based regression test now fails if any future field is
dropped by the wrap.
- Isolate TestNewMSALCache's default-path case from the real ~/.azure.
Co-Authored-By: Claude Fable 5 <[email protected]>
|
Tip Atmos Pro
No affected stacks workflow was detected for this pull request. |
Dependency Review✅ No vulnerabilities or license issues found.Scanned FilesNone |
📝 WalkthroughWalkthroughAzure authentication now records the authentication method and MSAL ChangesAzure authentication
Estimated code review effort: 3 (Moderate) | ~25 minutes Sequence Diagram(s)sequenceDiagram
participant DeviceCodeProvider
participant MSAL
participant AzureCredentials
participant AzureCLICache
DeviceCodeProvider->>MSAL: acquire token and read HomeAccountID
DeviceCodeProvider->>AzureCredentials: set AuthMethod and HomeAccountID
DeviceCodeProvider->>AzureCLICache: update tokens with HomeAccountID
AzureCLICache->>AzureCLICache: preserve home account ID, target-tenant OID, and realm
Possibly related PRs
Suggested reviewers: 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@pkg/auth/providers/azure/device_code_cache.go`:
- Line 213: Update the HomeAccountID field comment to end with a period after
“users”, leaving the comment text otherwise unchanged.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: 1c37eb74-1e35-48d3-a471-db7a631d0138
📒 Files selected for processing (11)
pkg/auth/cloud/azure/msal_cache_test.gopkg/auth/cloud/azure/setup.gopkg/auth/cloud/azure/setup_test.gopkg/auth/identities/azure/subscription.gopkg/auth/identities/azure/subscription_test.gopkg/auth/providers/azure/cli.gopkg/auth/providers/azure/device_code.gopkg/auth/providers/azure/device_code_cache.gopkg/auth/providers/azure/device_code_cache_test.gopkg/auth/providers/azure/oidc.gopkg/auth/types/azure_credentials.go
|
CodeRabbit (@coderabbitai) full review please |
|
✅ Action performedFull review finished. |
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #2861 +/- ##
==========================================
+ Coverage 82.26% 82.36% +0.09%
==========================================
Files 1810 1810
Lines 175728 175753 +25
==========================================
+ Hits 144566 144755 +189
+ Misses 23444 23266 -178
- Partials 7718 7732 +14
Flags with carried forward coverage won't be shown. Click here to find out more.
🚀 New features to boost your workflow:
|
Codecov flagged the guest-user cache fix at 55.7% patch coverage. Add targeted tests for the previously untested changed paths: - azure/cli Authenticate end to end via a stubbed `az` executable on PATH: credentials built from the az JSON response (AuthMethod "cli", subscription fallback from the response) and the not-logged-in error. - device-code createCredentials (all tokens + management-only), trySilentTokenAcquisition (no accounts / no tenant match / matching account with local silent failure), acquireAdditionalTokens silent failures, headless Authenticate refusal, and findAccountForTenant. - Extract captureHomeAccountID into a directly testable helper (the guest home-account-ID capture in the device code flow). - azure/subscription PostAuthenticate happy path: credentials file written, auth context populated, ARM env vars derived, and no az CLI cache files created for CLI-sourced credentials. Remaining uncovered changed lines are MSAL success paths that require a live identity provider (successful silent/device-code token acquisition). Co-Authored-By: Claude Fable 5 <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
pkg/auth/identities/azure/subscription_test.go (1)
263-275: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winUse
filepath.Joinfor filesystem paths.Lines 263 and 274 construct filesystem paths with literal
/separators. Build both paths withfilepath.Joinso the test follows the cross-platform path contract.As per coding guidelines,
**/*_test.gorequiresfilepath.Join()for paths and forbids hardcoded platform-specific separators.Proposed fix
+ "path/filepath" + - credsPath := tmpHome + "/.azure/atmos/test-realm/azure-cli/credentials.json" + credsPath := filepath.Join(tmpHome, ".azure", "atmos", "test-realm", "azure-cli", "credentials.json") @@ - _, msalErr := os.Stat(tmpHome + "/.azure/msal_token_cache.json") + _, msalErr := os.Stat(filepath.Join(tmpHome, ".azure", "msal_token_cache.json"))🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@pkg/auth/identities/azure/subscription_test.go` around lines 263 - 275, Update the filesystem path construction in the test around SetupFiles and the MSAL cache assertion to use filepath.Join for both paths, preserving the existing path components and assertions while removing hardcoded "/" separators.Source: Coding guidelines
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@pkg/auth/providers/azure/auth_flows_coverage_test.go`:
- Around line 22-31: Update stubAz to work on Windows instead of skipping there:
generate platform-appropriate executable wrappers that emit the supplied JSON
and exit with the requested code, while preserving PATH-based discovery by
exec.CommandContext. Move the helper to the shared test location requested by
the coverage setup and add the Windows wrapper equivalent so Azure CLI cases run
on both supported platforms.
- Around line 142-173: Update TestDeviceCodeProvider_TrySilentTokenAcquisition
to use table-driven cases for the account-selection scenarios across the
specified test range, with expected accessToken and homeAccountID fields
asserted for every case. Add an explicit empty homeAccountID assertion for the
unmatched-account case, and preserve the expected empty values when silent
acquisition fails; apply the same table-driven structure to the sibling scenario
range in the same test file.
---
Nitpick comments:
In `@pkg/auth/identities/azure/subscription_test.go`:
- Around line 263-275: Update the filesystem path construction in the test
around SetupFiles and the MSAL cache assertion to use filepath.Join for both
paths, preserving the existing path components and assertions while removing
hardcoded "/" separators.
🪄 Autofix
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: cef1c0a6-09fe-4dc2-9f64-8caf383f6940
📒 Files selected for processing (3)
pkg/auth/identities/azure/subscription_test.gopkg/auth/providers/azure/auth_flows_coverage_test.gopkg/auth/providers/azure/device_code.go
🚧 Files skipped from review as they are similar to previous changes (1)
- pkg/auth/providers/azure/device_code.go
- Use filepath.Join for all filesystem paths in the subscription PostAuthenticate test (cross-platform path contract). - Make the az PATH stub cross-platform: output moves to a data file (no shell quoting), with a POSIX script on Unix and az.bat on Windows (resolved via PATHEXT), removing the Windows skip. - Convert the silent-acquisition scenarios to a table and assert homeAccountID stays empty in every non-success case. Co-Authored-By: Claude Fable 5 <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@pkg/auth/providers/azure/auth_flows_coverage_test.go`:
- Around line 23-25: Update the final line of the comment block near the
shell-quoting explanation to end with a period after the closing parenthesis,
leaving the preceding comment lines unchanged.
🪄 Autofix
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: d24fc799-fde9-42a1-9361-7ff8cd925dc9
📒 Files selected for processing (2)
pkg/auth/identities/azure/subscription_test.gopkg/auth/providers/azure/auth_flows_coverage_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
- pkg/auth/identities/azure/subscription_test.go
|
Tip Atmos Pro
No affected stacks workflow was detected for this pull request. |
|
These changes were released in v1.225.0-rc.7. |
) * feat(auth): add azure/interactive browser authentication provider Adds a new `azure/interactive` provider kind implementing MSAL interactive browser authentication (authorization code + PKCE on a localhost redirect) -- the same flow `az login` uses, and MSAL's own name for it (AcquireTokenInteractive). Why a third user-auth kind: Microsoft-managed Conditional Access policies now block the device code flow in many tenants (AADSTS 530035), and the azure/cli provider requires a pre-existing `az login` session. The interactive flow gives one-command `atmos auth login` that Conditional Access allows, because the browser session carries full CA context. - interactiveProvider embeds deviceCodeProvider, reusing the MSAL client, silent token acquisition (refresh tokens make repeat logins silent), Graph/KeyVault token fan-out, and the Azure CLI cache write-back with the correct guest home account ID. - The shared machinery is parameterized by auth method: interactive credentials persist auth_method "interactive", and the MSAL cache account_source now mirrors az's own labels ("authorization_code" for the browser flow, "device_code" otherwise) instead of a hardcoded value. - Verified end to end against a real tenant as a guest (B2B) user with device code blocked by policy: one command opens the browser, SSO completes, and afterwards the az CLI works without ever running `az login` -- the write-back reconstructs a valid az session, making atmos auth a drop-in replacement. Docs: provider reference, Azure authentication tutorial (interactive flow recommended for humans; device code reframed as fallback with the Conditional Access caveat), auth kind lists, blog post (azure-interactive-auth), a shipped roadmap milestone, and the fix doc for #2861 (docs/fixes/2026-08-03-azure-cli-cache-corruption-guest-users.md). Also includes the PRD (docs/prd/azure-interactive-auth.md) and test coverage at ~92% of changed lines: the provider exposes two injection seams (acquireInteractive, checkInteractive) per the repo's DI convention, since the real MSAL interactive flow needs a live IdP and a browser; tests cover the success path, acquisition failure, and headless refusal against a sandboxed HOME. Builds on the AuthMethod/HomeAccountID plumbing from #2861. Co-Authored-By: Claude Fable 5 <[email protected]> * chore(docs): fix editorconfig indentation in azure/interactive PRD * fix(auth): address review feedback on azure/interactive tests and docs * fix(auth): address review feedback on azure/interactive tests and docs --------- Co-authored-by: Claude Fable 5 <[email protected]>
what
azure/cliprovider — az's own cache is authoritative, and writing back what came from az is what corrupted it.AzureCredentials(cli/device_code/oidc) so the write-back can be gated per provider kind.azure/device-codeprovider (silent and interactive flows) and use it in both Azure CLI cache writers (UpdateAzureCLIFilesand the provider-levelupdateAzureCLICache), falling back to the previous{oid}.{tenant}derivation when unavailable.azure/subscriptionidentity's field-by-field credential copy with a struct copy plus explicit overrides, and add a reflection-based regression test that fails if any futureAzureCredentialsfield is dropped by the wrap.TestNewMSALCache's default-path case from the real~/.azure.why
atmos auth login, the Azure CLI cache write-back created an MSAL Account entry withhome_account_idderived as{oid}.{target-tenant}and hardcodedaccount_source: "device_code". For guest (B2B) users the home tenant differs from the target tenant, so az ended up with two Account entries for the same username and failed every subsequent command withFound multiple accounts with the same username(azure-cli#20168) — includingaz account get-access-token, which theazure/cliprovider itself shells out to. In other words, oneatmos auth loginbroke both az and the next atmos login for any guest user.az login→atmos auth login→ az broken; after the fix, az stays healthy, the cache keeps exactly one Account entry, and the persisted credentials carryauth_methodso the gate holds across credential caching.references
Summary by CodeRabbit
New Features
Bug Fixes