Documentation
¶
Index ¶
- Constants
- Variables
- func AKSServerScopeFromContext(ctx context.Context) string
- func BuildARMClientOptions(cloudEnv *CloudEnvironment) *arm.ClientOptions
- func BuildAzureCredentialFromCreds(creds types.ICredentials) (azcore.TokenCredential, error)
- func BuildKubeClusterInfo(info *AKSClusterInfo, identityName string) *kube.ClusterInfo
- func BuildRegistryURL(name string) string
- func ContextWithAKSServerID(ctx context.Context, serverID string) context.Context
- func CopyAtmosRefreshTokensInto(azCache map[string]interface{}, home, realm, homeAccountID string)
- func GetToken(creds types.ICredentials) (string, time.Time, error)
- func IsACRRegistry(registryURL string) bool
- func KnownCloudEnvironments() []string
- func LoadDefaultAzureCredentials(ctx context.Context) (*types.AzureCredentials, error)
- func NewMSALCache(cachePath string, realm string) (cache.ExportReplace, error)
- func ParseRegistryURL(registryURL string) (name string, err error)
- func PrepareEnvironment(cfg PrepareEnvironmentConfig) map[string]string
- func ResolveDestination(dest string, azureCreds *types.AzureCredentials) (string, error)
- func SetAuthContext(params *SetAuthContextParams) error
- func SetEnvironmentVariables(authContext *schema.AuthContext, stackInfo *schema.ConfigAndStacksInfo) error
- func SetupFiles(providerName, identityName string, creds types.ICredentials, basePath string, ...) error
- func UpdateAzureCLIFiles(creds types.ICredentials, tenantID, subscriptionID, cloudEnvName, realm string) error
- func UpdateSubscriptionsInProfile(profile map[string]interface{}, params ProfileUpdateParams) []interface{}
- func ValidateCloudEnvironment(name string) error
- type ACRAuthResult
- type AKSClient
- type AKSClusterInfo
- type AzureFileManager
- func (m *AzureFileManager) Cleanup(providerName string) error
- func (m *AzureFileManager) CredentialsExist(providerName string) bool
- func (m *AzureFileManager) GetCredentialsPath(providerName string) string
- func (m *AzureFileManager) LoadCredentials(providerName string) (*types.AzureCredentials, error)
- func (m *AzureFileManager) WriteCredentials(providerName, identityName string, creds *types.AzureCredentials) error
- type CloudEnvironment
- type ConsoleURLGenerator
- type PrepareEnvironmentConfig
- type ProfileUpdateParams
- type SetAuthContextParams
Constants ¶
const ( // DirPermissions is the permission mode for Azure cache directories (owner read/write/execute only). DirPermissions = 0o700 // FilePermissions is the permission mode for Azure credential files (owner read/write only). FilePermissions = 0o600 )
File permissions.
const ( // BomMarker is the first byte of UTF-8 BOM. BomMarker = 0xEF // BomSecondByte is the second byte of UTF-8 BOM. BomSecondByte = 0xBB // BomThirdByte is the third byte of UTF-8 BOM. BomThirdByte = 0xBF )
BOM (Byte Order Mark) constants for UTF-8.
const ( FieldHomeAccountID = "home_account_id" FieldEnvironment = "environment" FieldRealm = "realm" FieldUsername = "username" FieldLocalID = "local_account_id" FieldAccessToken = "AccessToken" FieldUser = "user" )
MSAL cache field names used in azureProfile.json and MSAL cache. Exported for use by device_code_cache.go.
const ( IntFormat = "%d" // Format string for integer output. StrconvDecimal = 10 // Decimal base for string conversion. Int64BitSize = 64 // Bit size for int64 conversion. )
String format and conversion constants.
const ( LogFieldIdentity = "identity" // Log field for identity name. LogFieldSubscription = "subscription" // Log field for subscription ID. LogFieldTenantID = "tenantID" // Log field for tenant ID. LogFieldExpiresOn = "expiresOn" // Log field for token expiration. LogFieldKey = "key" // Log field for cache key. )
Logging field names.
const ( AKSServerAppID = "6dae42f8-4368-4678-94ff-3960e28e3630" AKSServerScope = AKSServerAppID + "/.default" )
AKS server AAD application constants. AKSServerAppID is the well-known application ID for AKS-managed AAD server apps (the "aks" first-party app), the same GUID across public/government/china clouds — only the token issuer endpoint (CloudEnvironment.LoginEndpoint) varies. Used as a login-time speculative token acquisition; the update-kubeconfig path prefers the cluster-specific server ID parsed from ListClusterUserCredentials when a cluster is already known.
const ( PermissionRWX = 0o700 PermissionRW = 0o600 )
const ( // AzureDefaultSessionDuration is the default session duration (Azure tokens are typically valid for 1 hour). AzureDefaultSessionDuration = 1 * time.Hour )
Variables ¶
var ( ErrGetHomeDir = errors.New("failed to get home directory") ErrCreateCredentialsFile = errors.New("failed to create credentials file") ErrLoadCredentialsFile = errors.New("failed to load credentials file") ErrWriteCredentialsFile = errors.New("failed to write credentials file") ErrSetCredentialsFilePermissions = errors.New("failed to set credentials file permissions") ErrCleanupAzureFiles = errors.New("failed to cleanup Azure files") ErrFileLockTimeout = errors.New("failed to acquire file lock within timeout") ErrRemoveProfile = errors.New("failed to remove profile") )
var AzurePortalURL = PublicCloud.PortalURL
AzurePortalURL returns the Azure Portal base URL for the public cloud. For sovereign clouds, use GetCloudEnvironment(name).PortalURL instead.
var PublicCloud = cloudEnvironments["public"]
PublicCloud is the default Azure public cloud environment.
Functions ¶
func AKSServerScopeFromContext ¶
AKSServerScopeFromContext returns the requested AKS AAD scope, falling back to the well-known AKS server application when no cluster-specific ID exists.
func BuildARMClientOptions ¶
func BuildARMClientOptions(cloudEnv *CloudEnvironment) *arm.ClientOptions
BuildARMClientOptions maps a CloudEnvironment to the ARM SDK client options needed to target the correct sovereign cloud (public, usgovernment, china). A nil cloudEnv defaults to the public cloud.
func BuildAzureCredentialFromCreds ¶
func BuildAzureCredentialFromCreds(creds types.ICredentials) (azcore.TokenCredential, error)
BuildAzureCredentialFromCreds wraps an already-acquired Atmos Azure access token as an azcore.TokenCredential, for constructing ARM SDK clients (AKS, ACR) from Atmos credentials the same way pkg/auth/cloud/aws.BuildAWSConfigFromCreds bridges AWS credentials to an aws.Config.
func BuildKubeClusterInfo ¶
func BuildKubeClusterInfo(info *AKSClusterInfo, identityName string) *kube.ClusterInfo
BuildKubeClusterInfo adapts an AKSClusterInfo + identity name into the cloud-agnostic kube.ClusterInfo, building the "azure aks token" exec-plugin command line that kube.BuildClusterConfig embeds verbatim.
func BuildRegistryURL ¶
BuildRegistryURL constructs an ACR login server URL from a registry name.
func ContextWithAKSServerID ¶
ContextWithAKSServerID records the cluster's AAD server application ID for the Azure provider that authenticates the kubeconfig exec-plugin request.
func CopyAtmosRefreshTokensInto ¶
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 GetToken ¶
GetToken returns the AKS-scoped bearer token for kubectl. The token itself is acquired at identity-authentication time by the credential's provider (device-code, OIDC, or Azure CLI — see pkg/auth/providers/azure), since Azure AAD tokens are scope-bound at issuance, unlike AWS SigV4 signing.
func IsACRRegistry ¶
IsACRRegistry checks if a URL is an ACR registry login server URL.
func KnownCloudEnvironments ¶ added in v1.210.0
func KnownCloudEnvironments() []string
KnownCloudEnvironments returns the names of all known cloud environments.
func LoadDefaultAzureCredentials ¶
func LoadDefaultAzureCredentials(ctx context.Context) (*types.AzureCredentials, error)
LoadDefaultAzureCredentials loads Azure credentials from the ambient environment (the Azure SDK default credential chain: environment variables, managed identity, workload identity, Azure CLI). Used for explicit-registry mode where the caller wants to use ambient Azure credentials instead of Atmos identities.
func NewMSALCache ¶
func NewMSALCache(cachePath string, realm string) (cache.ExportReplace, error)
NewMSALCache creates a new MSAL cache instance. If cachePath is empty, uses the default Azure CLI location (~/.azure/atmos/{realm}/msal_token_cache.json). The realm parameter provides credential isolation between different repositories.
func ParseRegistryURL ¶
ParseRegistryURL extracts the registry name from an ACR login server URL. Returns error if the URL is not a valid ACR registry URL.
func PrepareEnvironment ¶
func PrepareEnvironment(cfg PrepareEnvironmentConfig) map[string]string
PrepareEnvironment configures environment variables for Azure SDK when using Atmos auth.
This function:
- Clears direct Azure credential env vars to prevent conflicts with Atmos-managed credentials
- Sets AZURE_SUBSCRIPTION_ID, AZURE_TENANT_ID, AZURE_LOCATION
- Sets ARM_* variables for Terraform provider compatibility
- Sets ARM_USE_CLI=true (for CLI/device-code auth) or ARM_USE_OIDC=true (for OIDC auth)
For OIDC authentication (service principal with federated credentials), it sets:
- ARM_USE_OIDC=true
- ARM_CLIENT_ID
- AZURE_FEDERATED_TOKEN_FILE (if token file path is provided)
For CLI/device-code authentication, it sets ARM_USE_CLI=true which tells Terraform to use the MSAL cache populated by Atmos.
Note: Other cloud provider credentials (AWS, GCP) are NOT cleared to support multi-cloud scenarios such as using S3 backend for Terraform state while deploying to Azure.
Returns a NEW map with modifications - does not mutate the input.
func ResolveDestination ¶
func ResolveDestination(dest string, azureCreds *types.AzureCredentials) (string, error)
ResolveDestination resolves destination aliases to full Azure Portal URLs.
Supports the following destination formats:
- Empty string or "home" → Tenant home page
- "subscription" → Subscription overview
- "resourcegroups" or "rg" → Resource groups blade
- "vm" or "virtualmachines" → Virtual Machines blade
- "storage" or "storageaccounts" → Storage Accounts blade
- "network" or "vnet" → Virtual Networks blade
- "cosmosdb" → Cosmos DB blade
- "sql" → SQL Databases blade
- "keyvault" → Key Vaults blade
- "monitor" → Azure Monitor blade
- Full URL starting with https:// → Pass through unchanged
All resolved URLs include tenant context for proper navigation.
func SetAuthContext ¶
func SetAuthContext(params *SetAuthContextParams) error
SetAuthContext populates the Azure auth context with Atmos-managed credential paths. This enables in-process Azure SDK calls to use Atmos-managed credentials.
func SetEnvironmentVariables ¶
func SetEnvironmentVariables(authContext *schema.AuthContext, stackInfo *schema.ConfigAndStacksInfo) error
SetEnvironmentVariables derives Azure environment variables from AuthContext. This populates ComponentEnvSection/ComponentEnvList for spawned processes. The auth context is the single source of truth; this function derives from it.
Uses PrepareEnvironment helper to ensure consistent environment setup across all commands. This clears conflicting credential env vars and sets Azure subscription/tenant/location.
Parameters:
- authContext: Runtime auth context containing Azure credentials
- stackInfo: Stack configuration to populate with environment variables
func SetupFiles ¶
func SetupFiles(providerName, identityName string, creds types.ICredentials, basePath string, realm string) error
SetupFiles sets up Azure credentials files for the given identity. BasePath specifies the base directory for Azure files (from provider's files.base_path). If empty, uses the default ~/.azure/atmos/{realm} path. The realm parameter provides credential isolation between different repositories.
func UpdateAzureCLIFiles ¶
func UpdateAzureCLIFiles(creds types.ICredentials, tenantID, subscriptionID, cloudEnvName, realm string) error
UpdateAzureCLIFiles updates Azure CLI files (MSAL cache and azureProfile.json) so Terraform providers can use them. This makes Atmos authentication work exactly like `az login`. This should be called from PostAuthenticate to ensure CLI compatibility. The cloudEnvName selects the Azure cloud environment ("public", "usgovernment", "china"). If empty, defaults to "public".
func UpdateSubscriptionsInProfile ¶
func UpdateSubscriptionsInProfile(profile map[string]interface{}, params ProfileUpdateParams) []interface{}
UpdateSubscriptionsInProfile updates the subscriptions array in an Azure profile. It sets the specified subscription as default and marks all others as not default.
func ValidateCloudEnvironment ¶ added in v1.210.0
ValidateCloudEnvironment validates that a cloud environment name is known. Empty string is valid (defaults to "public"). Unknown non-empty values return an error.
Types ¶
type ACRAuthResult ¶
type ACRAuthResult struct {
Username string // Always acrLoginUsername.
Password string //nolint:gosec // G117: This is an OAuth2 refresh token, not a hardcoded password secret.
Registry string // The registry login server, e.g. myregistry.azurecr.io.
ExpiresAt time.Time // Refresh token expiration time.
}
ACRAuthResult contains ACR authorization information for Docker login.
func GetAuthorizationToken ¶
func GetAuthorizationToken(ctx context.Context, creds types.ICredentials, loginServer string) (*ACRAuthResult, error)
GetAuthorizationToken exchanges an AAD access token for an ACR refresh token via the registry's OAuth2 endpoint, following the same username/password Docker login contract as `az acr login`. See: https://github.com/Azure/acr/blob/main/docs/AAD-OAuth.md
type AKSClient ¶
type AKSClient interface {
Get(ctx context.Context, resourceGroupName, resourceName string, options *armcontainerservice.ManagedClustersClientGetOptions) (armcontainerservice.ManagedClustersClientGetResponse, error)
ListClusterUserCredentials(ctx context.Context, resourceGroupName, resourceName string, options *armcontainerservice.ManagedClustersClientListClusterUserCredentialsOptions) (armcontainerservice.ManagedClustersClientListClusterUserCredentialsResponse, error)
}
AKSClient defines the interface for AKS API calls (for testability).
func NewAKSClient ¶
func NewAKSClient(ctx context.Context, creds types.ICredentials, subscriptionID string) (AKSClient, error)
NewAKSClient creates a new AKS ManagedClusters client from Atmos credentials. SubscriptionID overrides the credential's subscription when non-empty.
type AKSClusterInfo ¶
type AKSClusterInfo struct {
Name string
ResourceGroup string
// SubscriptionID is the subscription the cluster was addressed under, used
// to build the exec-plugin --subscription-id argument.
SubscriptionID string
// ID is the ARM resource ID, used as the kubeconfig cluster map key (the
// AKS equivalent of an EKS cluster ARN).
ID string
Endpoint string
// CertificateAuthorityData is base64-encoded, matching EKS's
// EKSClusterInfo convention — kube.BuildClusterConfig decodes it.
CertificateAuthorityData string
// ServerID is the AAD server application ID this cluster's AAD
// integration expects tokens to be scoped to, parsed from the
// kubelogin exec args embedded in the exec-format kubeconfig. Empty for
// clusters where the exec args couldn't be parsed (falls back to the
// well-known AKSServerAppID).
ServerID string
// TenantID is the AAD tenant ID parsed from the same exec args.
TenantID string
}
AKSClusterInfo contains cluster data needed for kubeconfig generation.
func DescribeCluster ¶
func DescribeCluster(ctx context.Context, client AKSClient, subscriptionID, resourceGroup, name string) (*AKSClusterInfo, error)
DescribeCluster retrieves cluster information needed for kubeconfig.
It calls Get for the ARM resource ID, then ListClusterUserCredentials with Format: exec to obtain a ready-made kubeconfig whose single cluster entry carries the server endpoint and CA data, and whose single auth-info entry carries the kubelogin exec args this specific cluster expects (--server-id, --tenant-id) — parsed out and reused to scope `atmos azure aks token`, rather than invoking kubelogin itself, so no external binary is required.
type AzureFileManager ¶
type AzureFileManager struct {
// contains filtered or unexported fields
}
AzureFileManager provides helpers to manage Azure credentials files.
func NewAzureFileManager ¶
func NewAzureFileManager(basePath string, realm string) (*AzureFileManager, error)
NewAzureFileManager creates a new Azure file manager. If basePath is empty, uses default ~/.azure/atmos/{realm} path. The realm parameter provides credential isolation between different repositories.
func (*AzureFileManager) Cleanup ¶
func (m *AzureFileManager) Cleanup(providerName string) error
Cleanup removes Azure files for the given provider.
func (*AzureFileManager) CredentialsExist ¶
func (m *AzureFileManager) CredentialsExist(providerName string) bool
CredentialsExist checks if credentials file exists for the given provider.
func (*AzureFileManager) GetCredentialsPath ¶
func (m *AzureFileManager) GetCredentialsPath(providerName string) string
GetCredentialsPath returns the path to the credentials file for the given provider.
func (*AzureFileManager) LoadCredentials ¶
func (m *AzureFileManager) LoadCredentials(providerName string) (*types.AzureCredentials, error)
LoadCredentials loads Azure credentials from a JSON file.
func (*AzureFileManager) WriteCredentials ¶
func (m *AzureFileManager) WriteCredentials(providerName, identityName string, creds *types.AzureCredentials) error
WriteCredentials writes Azure credentials to a JSON file.
type CloudEnvironment ¶ added in v1.210.0
type CloudEnvironment struct {
// Name is the canonical name of the cloud environment.
Name string
// LoginEndpoint is the Azure AD / Entra ID authority host (e.g., "login.microsoftonline.com").
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.
KeyVaultScope string
// BlobStorageSuffix is the blob storage URL suffix (e.g., "blob.core.windows.net").
BlobStorageSuffix string
// PortalURL is the Azure Portal base URL.
PortalURL string
// AzureProfileEnvName is the environment name used in azureProfile.json (e.g., "AzureCloud").
AzureProfileEnvName string
}
CloudEnvironment defines the endpoints for a specific Azure cloud (public, government, China).
func GetCloudEnvironment ¶ added in v1.210.0
func GetCloudEnvironment(name string) *CloudEnvironment
GetCloudEnvironment returns the endpoint set for the given cloud name. Returns the "public" environment if name is empty. Unknown non-empty values are rejected by ValidateCloudEnvironment before calling this function.
type ConsoleURLGenerator ¶
type ConsoleURLGenerator struct{}
ConsoleURLGenerator generates Azure Portal URLs with authentication context.
func NewConsoleURLGenerator ¶
func NewConsoleURLGenerator() *ConsoleURLGenerator
NewConsoleURLGenerator creates a new ConsoleURLGenerator.
func (*ConsoleURLGenerator) GetConsoleURL ¶
func (g *ConsoleURLGenerator) GetConsoleURL(ctx context.Context, creds types.ICredentials, options types.ConsoleURLOptions) (string, time.Duration, error)
GetConsoleURL generates an Azure Portal sign-in URL with authentication context.
Azure Portal URLs support deep linking with tenant context:
- Base portal: https://portal.azure.com/
- Tenant-specific: https://portal.azure.com/#@{tenant}
- Resource-specific: https://portal.azure.com/#@{tenant}/resource/subscriptions/{sub}/...
Unlike AWS federation (which requires a signin token), Azure Portal authentication uses browser-based OAuth with the same credentials used to access Azure APIs. The Portal will automatically pick up the user's authenticated session.
References:
func (*ConsoleURLGenerator) SupportsConsoleAccess ¶
func (g *ConsoleURLGenerator) SupportsConsoleAccess() bool
SupportsConsoleAccess returns true (Azure Console URL generator supports console access).
type PrepareEnvironmentConfig ¶
type PrepareEnvironmentConfig struct {
Environ map[string]string // Current environment variables
SubscriptionID string // Azure subscription ID
TenantID string // Azure tenant ID
Location string // Azure location/region (optional)
CloudEnvironment string // Azure cloud environment name ("public", "usgovernment", "china")
// OIDC-specific configuration for Terraform ARM_USE_OIDC support.
UseOIDC bool // Use OIDC instead of CLI authentication
ClientID string // Azure AD application (client) ID
TokenFilePath string // Path to OIDC token file (optional)
}
PrepareEnvironmentConfig holds configuration for Azure environment preparation.
type ProfileUpdateParams ¶ added in v1.210.0
type ProfileUpdateParams struct {
Username string
TenantID string
SubscriptionID string
IsServicePrincipal bool
AzureProfileEnvName string
}
ProfileUpdateParams contains the parameters for updating an Azure profile subscription entry.
type SetAuthContextParams ¶
type SetAuthContextParams struct {
AuthContext *schema.AuthContext
StackInfo *schema.ConfigAndStacksInfo
ProviderName string
IdentityName string
Credentials types.ICredentials
BasePath string
Realm string
}
SetAuthContextParams contains parameters for SetAuthContext.