-
-
Notifications
You must be signed in to change notification settings - Fork 174
fix(auth): cover legacy ARM audience and seed refresh token in Azure CLI cache #2890
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Andriy Knysh (aknysh)
wants to merge
3
commits into
main
Choose a base branch
from
aknysh/fix-azure-atmos-auth-2
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
53 changes: 53 additions & 0 deletions
53
docs/fixes/2026-08-06-azure-cli-cache-legacy-audience-refresh-token.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,53 @@ | ||
| # Fix: Seeded Azure CLI cache misses the legacy ARM audience and carries no refresh token | ||
|
|
||
| **Date:** 2026-08-06 | ||
|
|
||
| ## Summary | ||
|
|
||
| After `atmos auth login` (device-code or interactive), the Azure CLI cache write-back | ||
| seeded access tokens only under the modern ARM scope | ||
| (`https://management.azure.com/.default`) and seeded no refresh token. Two field | ||
| failures followed: `azapi`-based Terraform modules (all modern Azure Verified Modules) | ||
| died mid-apply with `AzureCLICredential: ERROR: Can't find token from MSAL cache`, | ||
| because azidentity/az request the **legacy** ARM audience | ||
| (`https://management.core.windows.net/`) by default; and after ~1 hour every az-side | ||
| lookup failed the same way, because az had no refresh token to self-mint replacements. | ||
| The management token entry now carries the legacy audience scope forms in its MSAL | ||
| `target`, and the refresh token MSAL persists in the Atmos realm cache is copied into | ||
| the az cache. | ||
|
|
||
| ## Context | ||
|
|
||
| Reproduced end to end during a real engagement: `azurerm` provider resources applied | ||
| fine (its az shell-out requests the modern scope) while the `azapi` resource in the | ||
| same apply failed — `az account get-access-token` (default → legacy resource) missed | ||
| the cache while `--scope https://management.azure.com/.default` hit it. The failure is | ||
| cache-*lookup*, not token validity: ARM accepts both audience forms interchangeably, | ||
| and MSAL matches requested scopes as a subset of an entry's space-separated `target`. | ||
| So one seeded management token entry listing all ARM scope forms | ||
| (`management.azure.com/.default`, plus the legacy single- and double-slash forms az | ||
| derives from the trailing-slash resource) satisfies every lookup. | ||
|
|
||
| The refresh-token gap is fixable because Atmos authenticates with the Azure CLI public | ||
| client: the refresh token MSAL persists in `~/.azure/atmos/<realm>/msal_token_cache.json` | ||
| is exactly the credential az's own login would have stored. | ||
|
|
||
| ## Changes | ||
|
|
||
| - `pkg/auth/cloud/azure/cloud_environments.go`: `CloudEnvironment` gains | ||
| `LegacyManagementScopes` (public/usgovernment/china variants, single- and | ||
| double-slash forms). | ||
| - `pkg/auth/providers/azure/device_code_cache.go` and | ||
| `pkg/auth/cloud/azure/setup.go`: the seeded management token's `target` now joins | ||
| the modern scope with the legacy forms. | ||
| - `pkg/auth/cloud/azure/refresh_token.go` (new): `CopyAtmosRefreshTokensInto` copies | ||
| the account's refresh-token entries from the Atmos realm cache into the az cache | ||
| (skipped for service principals, empty realms, or unknown home account IDs). | ||
| Both cache writers invoke it; `UpdateAzureCLIFiles` gains a `realm` parameter. | ||
| - Regression tests (`token_audience_test.go`) reproduce both field failures and pin | ||
| the fix; the sovereign-cloud test now asserts the multi-audience `target`. | ||
|
|
||
| ## Recovery (pre-fix versions) | ||
|
|
||
| `az login --tenant <tenant-id>` gives az its own refresh token; keep such a session | ||
| alongside `atmos auth login` when applying azapi/AVM-based components. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,81 @@ | ||
| package azure | ||
|
|
||
| import ( | ||
| "encoding/json" | ||
| "os" | ||
| "path/filepath" | ||
|
|
||
| log "github.com/cloudposse/atmos/pkg/logger" | ||
| "github.com/cloudposse/atmos/pkg/perf" | ||
| ) | ||
|
|
||
| // CopyAtmosRefreshTokensInto copies refresh-token entries for the given account | ||
| // from the Atmos realm MSAL cache into an Azure CLI MSAL cache map. | ||
| // | ||
| // The Atmos providers authenticate with the Azure CLI public client, so the | ||
| // refresh token MSAL persists in the realm cache is directly usable by az. | ||
| // Seeding it lets az self-mint tokens for ANY audience (including the legacy | ||
| // ARM audience azidentity/azapi request) and survive access-token expiry — | ||
| // without it, az fails with "Can't find token from MSAL cache" as soon as a | ||
| // lookup misses the seeded access tokens. | ||
| func CopyAtmosRefreshTokensInto(azCache map[string]interface{}, home, realm, homeAccountID string) { | ||
| defer perf.Track(nil, "pkg/auth/cloud/azure.CopyAtmosRefreshTokensInto")() | ||
|
|
||
| if realm == "" || homeAccountID == "" { | ||
| // Without a realm the Atmos cache path IS the az cache (self-copy); | ||
| // without a home account ID entries can't be matched safely. | ||
| return | ||
| } | ||
|
|
||
| source := loadAtmosRefreshTokens(home, realm) | ||
| if len(source) == 0 { | ||
| return | ||
| } | ||
|
|
||
| dest, ok := azCache["RefreshToken"].(map[string]interface{}) | ||
| if !ok { | ||
| dest = map[string]interface{}{} | ||
| azCache["RefreshToken"] = dest | ||
| } | ||
|
|
||
| if copied := copyMatchingRefreshTokens(dest, source, homeAccountID); copied > 0 { | ||
| log.Debug("Copied refresh tokens into Azure CLI cache", "count", copied) | ||
| } | ||
| } | ||
|
aknysh marked this conversation as resolved.
|
||
|
|
||
| // loadAtmosRefreshTokens reads the RefreshToken section of the Atmos realm | ||
| // MSAL cache; missing or unparsable caches are non-fatal (empty result). | ||
| func loadAtmosRefreshTokens(home, realm string) map[string]interface{} { | ||
| atmosCachePath := filepath.Join(home, ".azure", "atmos", realm, "msal_token_cache.json") | ||
| data, err := os.ReadFile(atmosCachePath) | ||
| if err != nil { | ||
| log.Debug("No Atmos MSAL cache to copy refresh tokens from", "path", atmosCachePath, "error", err) | ||
| return nil | ||
| } | ||
|
|
||
| var atmosCache map[string]interface{} | ||
| if err := json.Unmarshal(data, &atmosCache); err != nil { | ||
| log.Debug("Failed to parse Atmos MSAL cache", "error", err) | ||
| return nil | ||
| } | ||
|
|
||
| source, _ := atmosCache["RefreshToken"].(map[string]interface{}) | ||
| return source | ||
| } | ||
|
|
||
| // copyMatchingRefreshTokens copies entries whose home_account_id matches. | ||
| func copyMatchingRefreshTokens(dest, source map[string]interface{}, homeAccountID string) int { | ||
| copied := 0 | ||
| for key, raw := range source { | ||
| entry, ok := raw.(map[string]interface{}) | ||
| if !ok { | ||
| continue | ||
| } | ||
| if hid, _ := entry["home_account_id"].(string); hid != homeAccountID { | ||
| continue | ||
| } | ||
| dest[key] = entry | ||
| copied++ | ||
| } | ||
| return copied | ||
|
aknysh marked this conversation as resolved.
|
||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.