Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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.
56 changes: 32 additions & 24 deletions pkg/auth/cloud/azure/cloud_environments.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,11 @@ type CloudEnvironment struct {
LoginEndpoint string
// ManagementScope is the Azure Resource Manager API scope.
ManagementScope string
// LegacyManagementScopes are the legacy ARM audience scope forms
// (management.core.*) that az and azidentity derive by default. ARM accepts
// both audiences interchangeably, so the seeded management token is stored
// with all forms in its MSAL `target` for cache-lookup coverage.
LegacyManagementScopes []string
// GraphAPIScope is the Microsoft Graph API scope.
GraphAPIScope string
// KeyVaultScope is the Azure KeyVault API scope.
Expand All @@ -31,34 +36,37 @@ type CloudEnvironment struct {
// Well-known Azure cloud environments.
var cloudEnvironments = map[string]*CloudEnvironment{
"public": {
Name: "public",
LoginEndpoint: "login.microsoftonline.com",
ManagementScope: "https://management.azure.com/.default",
GraphAPIScope: "https://graph.microsoft.com/.default",
KeyVaultScope: "https://vault.azure.net/.default",
BlobStorageSuffix: "blob.core.windows.net",
PortalURL: "https://portal.azure.com/",
AzureProfileEnvName: "AzureCloud",
Name: "public",
LoginEndpoint: "login.microsoftonline.com",
ManagementScope: "https://management.azure.com/.default",
LegacyManagementScopes: []string{"https://management.core.windows.net/.default", "https://management.core.windows.net//.default"},
GraphAPIScope: "https://graph.microsoft.com/.default",
KeyVaultScope: "https://vault.azure.net/.default",
BlobStorageSuffix: "blob.core.windows.net",
PortalURL: "https://portal.azure.com/",
AzureProfileEnvName: "AzureCloud",
},
"usgovernment": {
Name: "usgovernment",
LoginEndpoint: "login.microsoftonline.us",
ManagementScope: "https://management.usgovcloudapi.net/.default",
GraphAPIScope: "https://graph.microsoft.us/.default",
KeyVaultScope: "https://vault.usgovcloudapi.net/.default",
BlobStorageSuffix: "blob.core.usgovcloudapi.net",
PortalURL: "https://portal.azure.us/",
AzureProfileEnvName: "AzureUSGovernment",
Name: "usgovernment",
LoginEndpoint: "login.microsoftonline.us",
ManagementScope: "https://management.usgovcloudapi.net/.default",
LegacyManagementScopes: []string{"https://management.core.usgovcloudapi.net/.default", "https://management.core.usgovcloudapi.net//.default"},
GraphAPIScope: "https://graph.microsoft.us/.default",
KeyVaultScope: "https://vault.usgovcloudapi.net/.default",
BlobStorageSuffix: "blob.core.usgovcloudapi.net",
PortalURL: "https://portal.azure.us/",
AzureProfileEnvName: "AzureUSGovernment",
},
"china": {
Name: "china",
LoginEndpoint: "login.chinacloudapi.cn",
ManagementScope: "https://management.chinacloudapi.cn/.default",
GraphAPIScope: "https://microsoftgraph.chinacloudapi.cn/.default",
KeyVaultScope: "https://vault.azure.cn/.default",
BlobStorageSuffix: "blob.core.chinacloudapi.cn",
PortalURL: "https://portal.azure.cn/",
AzureProfileEnvName: "AzureChinaCloud",
Name: "china",
LoginEndpoint: "login.chinacloudapi.cn",
ManagementScope: "https://management.chinacloudapi.cn/.default",
LegacyManagementScopes: []string{"https://management.core.chinacloudapi.cn/.default", "https://management.core.chinacloudapi.cn//.default"},
GraphAPIScope: "https://microsoftgraph.chinacloudapi.cn/.default",
KeyVaultScope: "https://vault.azure.cn/.default",
BlobStorageSuffix: "blob.core.chinacloudapi.cn",
PortalURL: "https://portal.azure.cn/",
AzureProfileEnvName: "AzureChinaCloud",
Comment thread
aknysh marked this conversation as resolved.
},
}

Expand Down
7 changes: 7 additions & 0 deletions pkg/auth/cloud/azure/cloud_environments_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ func TestGetCloudEnvironment(t *testing.T) {
expectedName string
expectedLogin string
expectedMgmt string
expectedLegacyMgmt []string
expectedGraph string
expectedKeyVault string
expectedBlobSufx string
Expand All @@ -30,6 +31,7 @@ func TestGetCloudEnvironment(t *testing.T) {
expectedName: "public",
expectedLogin: "login.microsoftonline.com",
expectedMgmt: "https://management.azure.com/.default",
expectedLegacyMgmt: []string{"https://management.core.windows.net/.default", "https://management.core.windows.net//.default"},
expectedGraph: "https://graph.microsoft.com/.default",
expectedKeyVault: "https://vault.azure.net/.default",
expectedBlobSufx: "blob.core.windows.net",
Expand All @@ -42,6 +44,7 @@ func TestGetCloudEnvironment(t *testing.T) {
expectedName: "usgovernment",
expectedLogin: "login.microsoftonline.us",
expectedMgmt: "https://management.usgovcloudapi.net/.default",
expectedLegacyMgmt: []string{"https://management.core.usgovcloudapi.net/.default", "https://management.core.usgovcloudapi.net//.default"},
expectedGraph: "https://graph.microsoft.us/.default",
expectedKeyVault: "https://vault.usgovcloudapi.net/.default",
expectedBlobSufx: "blob.core.usgovcloudapi.net",
Expand All @@ -54,6 +57,7 @@ func TestGetCloudEnvironment(t *testing.T) {
expectedName: "china",
expectedLogin: "login.chinacloudapi.cn",
expectedMgmt: "https://management.chinacloudapi.cn/.default",
expectedLegacyMgmt: []string{"https://management.core.chinacloudapi.cn/.default", "https://management.core.chinacloudapi.cn//.default"},
expectedGraph: "https://microsoftgraph.chinacloudapi.cn/.default",
expectedKeyVault: "https://vault.azure.cn/.default",
expectedBlobSufx: "blob.core.chinacloudapi.cn",
Expand All @@ -66,6 +70,7 @@ func TestGetCloudEnvironment(t *testing.T) {
expectedName: "public",
expectedLogin: "login.microsoftonline.com",
expectedMgmt: "https://management.azure.com/.default",
expectedLegacyMgmt: []string{"https://management.core.windows.net/.default", "https://management.core.windows.net//.default"},
expectedGraph: "https://graph.microsoft.com/.default",
expectedKeyVault: "https://vault.azure.net/.default",
expectedBlobSufx: "blob.core.windows.net",
Expand All @@ -78,6 +83,7 @@ func TestGetCloudEnvironment(t *testing.T) {
expectedName: "public",
expectedLogin: "login.microsoftonline.com",
expectedMgmt: "https://management.azure.com/.default",
expectedLegacyMgmt: []string{"https://management.core.windows.net/.default", "https://management.core.windows.net//.default"},
expectedGraph: "https://graph.microsoft.com/.default",
expectedKeyVault: "https://vault.azure.net/.default",
expectedBlobSufx: "blob.core.windows.net",
Expand All @@ -93,6 +99,7 @@ func TestGetCloudEnvironment(t *testing.T) {
assert.Equal(t, tt.expectedName, env.Name)
assert.Equal(t, tt.expectedLogin, env.LoginEndpoint)
assert.Equal(t, tt.expectedMgmt, env.ManagementScope)
assert.Equal(t, tt.expectedLegacyMgmt, env.LegacyManagementScopes)
assert.Equal(t, tt.expectedGraph, env.GraphAPIScope)
assert.Equal(t, tt.expectedKeyVault, env.KeyVaultScope)
assert.Equal(t, tt.expectedBlobSufx, env.BlobStorageSuffix)
Expand Down
81 changes: 81 additions & 0 deletions pkg/auth/cloud/azure/refresh_token.go
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)
}
}
Comment thread
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
Comment thread
aknysh marked this conversation as resolved.
}
Loading
Loading