Skip to content

fix(auth): prevent Azure CLI cache corruption for guest users - #2861

Merged
Andriy Knysh (aknysh) merged 3 commits into
mainfrom
aknysh/fix-azure-auth-cli-cache-corruption
Aug 4, 2026
Merged

Andriy Knysh (aknysh) merged 3 commits into
mainfrom
aknysh/fix-azure-auth-cli-cache-corruption

Conversation

@aknysh

@aknysh Andriy Knysh (aknysh) commented Aug 4, 2026 •

Copy link
Copy Markdown
Member

what

  • Skip the Azure CLI cache write-back entirely when credentials originated from the azure/cli provider — az's own cache is authoritative, and writing back what came from az is what corrupted it.
  • Record the originating auth method on AzureCredentials (cli / device_code / oidc) so the write-back can be gated per provider kind.
  • Capture MSAL's real home account ID in the azure/device-code provider (silent and interactive flows) and use it in both Azure CLI cache writers (UpdateAzureCLIFiles and the provider-level updateAzureCLICache), falling back to the previous {oid}.{tenant} derivation when unavailable.
  • Replace the azure/subscription identity's field-by-field credential copy with a struct copy plus explicit overrides, and add a reflection-based regression test that fails if any future AzureCredentials field is dropped by the wrap.
  • Isolate TestNewMSALCache's default-path case from the real ~/.azure.

why

  • 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 shells out to. In other words, one atmos auth login broke both az and the next atmos login for any guest user.
  • Reproduced and verified end to end against a real tenant where the operator is a B2B guest: before the fix, az login → atmos auth login → az broken; after the fix, az stays healthy, the cache keeps exactly one Account entry, and the persisted credentials carry auth_method so the gate holds across credential caching.
  • The subscription identity's field-by-field copy silently dropped the new fields before they reached the cache writer (found only by the end-to-end test), which is why the copy is now structural and guarded by a reflection test.

references

Summary by CodeRabbit

New Features

  • Azure credentials now retain authentication method and account identity details.
  • Improved support for guest and cross-tenant Azure accounts during authentication and token caching.
  • Subscription-based authentication preserves provider credential settings while applying subscription-specific values.

Bug Fixes

  • Azure CLI authentication no longer unexpectedly modifies CLI credential cache files.
  • Corrected account identification and tenant details for guest-user authentication.
  • Improved cache path handling across different environments.

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]>
@aknysh
Andriy Knysh (aknysh) requested a review from a team as a code owner August 4, 2026 05:37
@atmos-pro

atmos-pro Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Tip

Atmos Pro  

No affected stacks workflow was detected for this pull request.
If this is expected, no action is needed.
Learn More. Ask AI.

@github-actions github-actions Bot added the size/m Medium size PR label Aug 4, 2026
@github-actions

github-actions Bot commented Aug 4, 2026

Copy link
Copy Markdown

Dependency Review

✅ No vulnerabilities or license issues found.

Scanned Files

None

@aknysh Andriy Knysh (aknysh) self-assigned this Aug 4, 2026
@aknysh Andriy Knysh (aknysh) added the patch A minor, backward compatible change label Aug 4, 2026
@coderabbitai

coderabbitai Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Azure authentication now records the authentication method and MSAL HomeAccountID. Device-code and Azure CLI cache updates preserve guest-account identifiers. CLI-originated credentials skip duplicate cache and profile writes. Subscription identities preserve provider credential fields.

Changes

Azure authentication

Layer / File(s) Summary
Credential metadata and provider propagation
pkg/auth/types/azure_credentials.go, pkg/auth/providers/azure/*
AzureCredentials stores AuthMethod and HomeAccountID. CLI, device-code, and OIDC providers populate authentication metadata. Authentication-flow tests cover credential mapping, silent acquisition, tenant matching, and headless behavior.
Subscription credential preservation
pkg/auth/identities/azure/subscription.go, pkg/auth/identities/azure/subscription_test.go
Subscription authentication copies all provider credential fields, then overrides the subscription ID and optional location. Post-authentication tests verify environment population and CLI cache suppression.
CLI cache home-account handling
pkg/auth/providers/azure/device_code_cache.go, pkg/auth/providers/azure/device_code_cache_test.go
CLI cache updates use the supplied MSAL home-account ID and retain target-tenant OID and realm values.
Azure CLI file update behavior
pkg/auth/cloud/azure/setup.go, pkg/auth/cloud/azure/setup_test.go, pkg/auth/cloud/azure/msal_cache_test.go
CLI-originated credentials skip duplicate cache and profile writes. Other updates preserve guest-account identifiers. Cache-path tests use a temporary home directory.

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
Loading

Possibly related PRs

Suggested reviewers: osterman, goruha, johncblandii

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 4.76% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the primary fix for Azure CLI cache corruption affecting guest users.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch aknysh/fix-azure-auth-cli-cache-corruption

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 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

📥 Commits

Reviewing files that changed from the base of the PR and between 7c43da4 and 34a37df.

📒 Files selected for processing (11)
  • pkg/auth/cloud/azure/msal_cache_test.go
  • pkg/auth/cloud/azure/setup.go
  • pkg/auth/cloud/azure/setup_test.go
  • pkg/auth/identities/azure/subscription.go
  • pkg/auth/identities/azure/subscription_test.go
  • pkg/auth/providers/azure/cli.go
  • pkg/auth/providers/azure/device_code.go
  • pkg/auth/providers/azure/device_code_cache.go
  • pkg/auth/providers/azure/device_code_cache_test.go
  • pkg/auth/providers/azure/oidc.go
  • pkg/auth/types/azure_credentials.go

coderabbitai[bot]
coderabbitai Bot previously approved these changes Aug 4, 2026
@aknysh

Copy link
Copy Markdown
Member Author

CodeRabbit (@coderabbitai) full review please

@coderabbitai

coderabbitai Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

@aknysh I will perform a complete review of pull request #2861.

✅ Action performed

Full review finished.

@codecov

codecov Bot commented Aug 4, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 85.71429% with 9 lines in your changes missing coverage. Please review.
✅ Project coverage is 82.36%. Comparing base (7c43da4) to head (0f7f1b5).

Files with missing lines Patch % Lines
pkg/auth/providers/azure/device_code.go 55.00% 9 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            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     
Flag Coverage Δ
unittests 82.36% <85.71%> (+0.09%) ⬆️

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

Files with missing lines Coverage Δ
pkg/auth/cloud/azure/setup.go 84.63% <100.00%> (+0.30%) ⬆️
pkg/auth/identities/azure/subscription.go 77.70% <100.00%> (+11.44%) ⬆️
pkg/auth/providers/azure/cli.go 96.26% <100.00%> (+30.61%) ⬆️
pkg/auth/providers/azure/device_code_cache.go 73.64% <100.00%> (+1.74%) ⬆️
pkg/auth/providers/azure/oidc.go 91.10% <100.00%> (+0.16%) ⬆️
pkg/auth/types/azure_credentials.go 79.54% <ø> (ø)
pkg/auth/providers/azure/device_code.go 60.82% <55.00%> (+34.47%) ⬆️

... and 6 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (1)
pkg/auth/identities/azure/subscription_test.go (1)

263-275: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use filepath.Join for filesystem paths.

Lines 263 and 274 construct filesystem paths with literal / separators. Build both paths with filepath.Join so the test follows the cross-platform path contract.

As per coding guidelines, **/*_test.go requires filepath.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

📥 Commits

Reviewing files that changed from the base of the PR and between 34a37df and ed1924d.

📒 Files selected for processing (3)
  • pkg/auth/identities/azure/subscription_test.go
  • pkg/auth/providers/azure/auth_flows_coverage_test.go
  • pkg/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]>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 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

📥 Commits

Reviewing files that changed from the base of the PR and between ed1924d and 0f7f1b5.

📒 Files selected for processing (2)
  • pkg/auth/identities/azure/subscription_test.go
  • pkg/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

@aknysh
Andriy Knysh (aknysh) merged commit a330649 into main Aug 4, 2026
81 checks passed
@aknysh
Andriy Knysh (aknysh) deleted the aknysh/fix-azure-auth-cli-cache-corruption branch August 4, 2026 14:32
@atmos-pro

atmos-pro Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Tip

Atmos Pro  

No affected stacks workflow was detected for this pull request.
If this is expected, no action is needed.
Learn More. Ask AI.

@github-actions

github-actions Bot commented Aug 5, 2026

Copy link
Copy Markdown

These changes were released in v1.225.0-rc.7.

Andriy Knysh (aknysh) added a commit that referenced this pull request Aug 5, 2026
)

* 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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

patch A minor, backward compatible change size/m Medium size PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants