package aws import ( "context" "encoding/base64" "errors" "fmt" "net/url" "os" "path/filepath" "runtime" "strings" "time" aws "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/sts" "github.com/spf13/viper" errUtils "github.com/cloudposse/atmos/errors" awsCloud "github.com/cloudposse/atmos/pkg/auth/cloud/aws" "github.com/cloudposse/atmos/pkg/auth/providers/aws/saml2aws" "github.com/cloudposse/atmos/pkg/auth/providers/aws/saml2aws/cfg" "github.com/cloudposse/atmos/pkg/auth/providers/aws/saml2aws/creds" "github.com/cloudposse/atmos/pkg/auth/types" "github.com/cloudposse/atmos/pkg/config/homedir" "github.com/cloudposse/atmos/pkg/duration" log "github.com/cloudposse/atmos/pkg/logger" "github.com/cloudposse/atmos/pkg/perf" "github.com/cloudposse/atmos/pkg/schema" "github.com/cloudposse/atmos/pkg/xdg" ) const ( samlTimeoutSeconds = 30 samlDefaultSessionSec = 3600 logFieldRole = "role" logFieldDriver = "driver" minSTSSeconds = 900 maxSTSSeconds = 43200 playwrightCacheDir = "ms-playwright" playwrightCacheDirPermissions = 0o755 ) type assumeRoleWithSAMLClient interface { AssumeRoleWithSAML(ctx context.Context, params *sts.AssumeRoleWithSAMLInput, optFns ...func(*sts.Options)) (*sts.AssumeRoleWithSAMLOutput, error) } // samlProvider implements AWS SAML authentication using saml2aws. type samlProvider struct { name string config *schema.Provider url string region string // RoleToAssumeFromAssertion is set by PreAuthenticate based on the next identity in the chain. RoleToAssumeFromAssertion string realm string // Credential isolation realm set by auth manager. } // NewSAMLProvider creates a new AWS SAML provider. func NewSAMLProvider(name string, config *schema.Provider) (types.Provider, error) { if config.Kind != "aws/saml" { return nil, fmt.Errorf("%w: invalid provider kind for SAML provider: %s", errUtils.ErrInvalidProviderKind, config.Kind) } if config.URL == "" { return nil, fmt.Errorf("%w: url is required for AWS SAML provider", errUtils.ErrInvalidProviderConfig) } if config.Region == "" { return nil, fmt.Errorf("%w: region is required for AWS SAML provider", errUtils.ErrInvalidProviderConfig) } return &samlProvider{ name: name, config: config, url: config.URL, region: config.Region, RoleToAssumeFromAssertion: "", }, nil } // Kind returns the provider kind. func (p *samlProvider) Kind() string { return "aws/saml" } // Name returns the configured provider name. func (p *samlProvider) Name() string { return p.name } // SetRealm sets the credential isolation realm for this provider. func (p *samlProvider) SetRealm(realm string) { p.realm = realm } // PreAuthenticate records a hint (next identity name) to help role selection. func (p *samlProvider) PreAuthenticate(manager types.AuthManager) error { // chain: [provider, identity1, identity2, ...] chain := manager.GetChain() log.Debug("SAML pre-auth: chain", "chain", chain) if len(chain) > 1 { identities := manager.GetIdentities() identity, exists := identities[chain[1]] log.Debug("SAML pre-auth: identity", "name", chain[1], "exists", exists) if !exists { return fmt.Errorf("%w: identity %q not found", errUtils.ErrInvalidAuthConfig, chain[1]) } var roleArn string var ok bool if roleArn, ok = identity.Principal["assume_role"].(string); !ok || roleArn == "" { return fmt.Errorf("%w: assume_role is required in principal", errUtils.ErrInvalidIdentityConfig) } p.RoleToAssumeFromAssertion = roleArn log.Debug("SAML pre-auth: recorded role to assume from assertion", logFieldRole, p.RoleToAssumeFromAssertion) } return nil } // Authenticate performs SAML authentication using saml2aws. func (p *samlProvider) Authenticate(ctx context.Context) (types.ICredentials, error) { if err := p.validateDriver(); err != nil { return nil, err } samlDriver := p.getDriver() p.logAuthenticationStart(samlDriver) if p.RoleToAssumeFromAssertion == "" { return nil, fmt.Errorf("%w: no role to assume for assertion, SAML provider must be part of a chain", errUtils.ErrInvalidAuthConfig) } if err := p.prepareBrowserDriver(samlDriver); err != nil { return nil, err } // Configure logrus to forward to Atmos logger instead of stdout. // saml2aws uses the global logrus logger which outputs messages like "INFO[0037] opening browser". // We forward these to Atmos's charmbracelet/log for consistent formatting. log.ConfigureLogrusForAtmos() // Create config and client + login details. samlConfig := p.createSAMLConfig() loginDetails := p.createLoginDetails() // Create the SAML client. samlClient, err := saml2aws.NewSAMLClient(samlConfig) if err != nil { return nil, fmt.Errorf("%w: failed to create SAML client: %w", errUtils.ErrInvalidProviderConfig, err) } // Authenticate and get assertion. assertionB64, err := p.authenticateAndGetAssertion(samlClient, loginDetails) if err != nil { return nil, err } roles, err := rolesFromAssertion(assertionB64) if err != nil { return nil, err } selectedRole := p.selectRole(roles) if selectedRole == nil { return nil, fmt.Errorf("%w: no role selected", errUtils.ErrAuthenticationFailed) } // Assume role. awsCreds, err := p.assumeRoleWithSAML(ctx, assertionB64, selectedRole) if err != nil { return nil, fmt.Errorf("%w: failed to assume role with SAML: %w", errUtils.ErrAuthenticationFailed, err) } log.Info("SAML authentication successful", "provider", p.name, logFieldRole, selectedRole.RoleARN) return awsCreds, nil } // logAuthenticationStart logs the start of a SAML login and the effective driver settings. func (p *samlProvider) logAuthenticationStart(samlDriver string) { log.Info("Starting SAML authentication", "provider", p.name, "url", p.url, logFieldDriver, samlDriver) log.Debug("SAML configuration", logFieldDriver, samlDriver, "download_browser", p.shouldDownloadBrowser(), "requires_drivers", samlDriver == "Browser") } // prepareBrowserDriver sets up browser automation, but only for the Browser driver. // Other drivers (GoogleApps, Okta, ADFS) use API/HTTP flows and don't need // Playwright, XDG storage directories, or symlinks. func (p *samlProvider) prepareBrowserDriver(samlDriver string) error { if samlDriver != "Browser" { return nil } if err := p.setupBrowserAutomation(); err != nil { return err } // Pre-seed the Playwright driver from official registries: the download // built into playwright-go/saml2aws points at a retired CDN and 404s. // Best-effort — an already-installed driver keeps working offline. if err := ensurePlaywrightDriver(); err != nil { log.Warn("Could not pre-seed the Playwright driver; browser authentication may fail to download it", "error", err) } else if err := patchPlaywrightDriver(); err != nil { log.Debug("Could not patch the Playwright driver", "error", err) } return nil } // rolesFromAssertion decodes a base64 SAML assertion and returns the AWS roles it grants. func rolesFromAssertion(assertionB64 string) ([]*saml2aws.AWSRole, error) { decodedXML, err := base64.StdEncoding.DecodeString(assertionB64) if err != nil { return nil, fmt.Errorf("%w: failed to decode assertion: %w", errUtils.ErrAwsSAMLDecodeFailed, err) } rolesStr, err := saml2aws.ExtractAwsRoles(decodedXML) if err != nil { return nil, fmt.Errorf("%w: extract AWS roles: %w", errUtils.ErrAwsSAMLDecodeFailed, err) } roles, err := saml2aws.ParseAWSRoles(rolesStr) if err != nil { return nil, fmt.Errorf("%w: parse AWS roles: %w", errUtils.ErrAwsSAMLDecodeFailed, err) } return roles, nil } // createSAMLConfig creates the saml2aws configuration. func (p *samlProvider) createSAMLConfig() *cfg.IDPAccount { return &cfg.IDPAccount{ URL: p.url, Username: p.config.Username, Provider: p.getDriver(), MFA: "Auto", SkipVerify: false, Timeout: samlTimeoutSeconds, // 30 second timeout. AmazonWebservicesURN: "urn:amazon:webservices", SessionDuration: samlDefaultSessionSec, // 1 hour default. Profile: p.name, Region: p.region, BrowserType: p.config.BrowserType, BrowserExecutablePath: p.config.BrowserExecutablePath, Headless: false, // Force non-headless for interactive auth. } } // createLoginDetails creates the login details for saml2aws. func (p *samlProvider) createLoginDetails() *creds.LoginDetails { loginDetails := &creds.LoginDetails{ URL: p.url, Username: p.config.Username, DownloadBrowser: p.shouldDownloadBrowser(), // Enable automatic driver installation. } // If password is provided in config, use it; otherwise prompt. if p.config.Password != "" { loginDetails.Password = p.config.Password } return loginDetails } // authenticateAndGetAssertion authenticates and gets the SAML assertion. // // Upstream saml2aws v2.36.19 panicked here when the browser flow timed out // (nil request dereference in its browser provider). Atmos's vendored copy in // pkg/auth/providers/aws/saml2aws returns an error instead. func (p *samlProvider) authenticateAndGetAssertion(samlClient saml2aws.SAMLClient, loginDetails *creds.LoginDetails) (string, error) { samlAssertion, err := samlClient.Authenticate(loginDetails) if err != nil { return "", fmt.Errorf("%w: SAML authentication failed: %w", errUtils.ErrAuthenticationFailed, err) } if samlAssertion == "" { return "", fmt.Errorf("%w: empty SAML assertion received", errUtils.ErrAuthenticationFailed) } log.Debug("SAML assertion received.", "length", len(samlAssertion)) return samlAssertion, nil } // selectRole selects the AWS role (first for now, with logging). func (p *samlProvider) selectRole(awsRoles []*saml2aws.AWSRole) *saml2aws.AWSRole { // Try preferred hint first, then fall back to the first role. hint := strings.ToLower(p.RoleToAssumeFromAssertion) for _, r := range awsRoles { if strings.Contains(strings.ToLower(r.RoleARN), hint) || strings.Contains(strings.ToLower(r.PrincipalARN), hint) { log.Debug("Selecting role matching preferred hint", logFieldRole, r.RoleARN, "hint", p.RoleToAssumeFromAssertion) return r } } if len(awsRoles) > 0 { log.Debug("No role matched hint; falling back to first role.", logFieldRole, awsRoles[0].RoleARN) return awsRoles[0] } return nil } // assumeRoleWithSAML assumes an AWS role using SAML assertion. func (p *samlProvider) assumeRoleWithSAML(ctx context.Context, samlAssertion string, role *saml2aws.AWSRole) (*types.AWSCredentials, error) { // Use LoadIsolatedAWSConfig to avoid conflicts with external AWS env vars. return p.assumeRoleWithSAMLWithDeps(ctx, samlAssertion, role, awsCloud.LoadIsolatedAWSConfig, func(cfg aws.Config) assumeRoleWithSAMLClient { return sts.NewFromConfig(cfg) }) } func (p *samlProvider) assumeRoleWithSAMLWithDeps( ctx context.Context, samlAssertion string, role *saml2aws.AWSRole, loader func(context.Context, ...func(*config.LoadOptions) error) (aws.Config, error), factory func(aws.Config) assumeRoleWithSAMLClient, ) (*types.AWSCredentials, error) { // Build config options configOpts := []func(*config.LoadOptions) error{ config.WithRegion(p.region), } // Add custom endpoint if configured. if resolverOpt := awsCloud.GetBaseEndpointConfigOption(nil, p.config); resolverOpt != nil { configOpts = append(configOpts, resolverOpt) } // Load AWS configuration (v2). cfg, err := loader(ctx, configOpts...) if err != nil { return nil, fmt.Errorf("%w: failed to create AWS config: %w", errUtils.ErrAuthenticationFailed, err) } stsClient := factory(cfg) // Assume role with SAML. input := &sts.AssumeRoleWithSAMLInput{ RoleArn: aws.String(role.RoleARN), PrincipalArn: aws.String(role.PrincipalARN), SAMLAssertion: aws.String(samlAssertion), DurationSeconds: aws.Int32(p.requestedSessionSeconds()), } result, err := stsClient.AssumeRoleWithSAML(ctx, input) if err != nil { return nil, fmt.Errorf("%w: failed to assume role with SAML: %w", errUtils.ErrAuthenticationFailed, err) } // Convert to AWSCredentials. creds := &types.AWSCredentials{ AccessKeyID: aws.ToString(result.Credentials.AccessKeyId), SecretAccessKey: aws.ToString(result.Credentials.SecretAccessKey), SessionToken: aws.ToString(result.Credentials.SessionToken), Region: p.region, Expiration: result.Credentials.Expiration.Format(time.RFC3339), } return creds, nil } // requestedSessionSeconds returns the desired session duration within STS/account limits. func (p *samlProvider) requestedSessionSeconds() int32 { // Defaults. var sec int32 = samlDefaultSessionSec if p.config == nil || p.config.Session == nil || p.config.Session.Duration == "" { return sec } if parsed, err := duration.ParseDuration(p.config.Session.Duration); err == nil { sec = int32(parsed.Seconds()) if sec < minSTSSeconds { sec = minSTSSeconds } if sec > maxSTSSeconds { sec = maxSTSSeconds } } return sec } // getDriver returns the SAML driver type based on configuration or URL detection. // Priority: Browser (if drivers available) > provider-specific fallbacks (GoogleApps/Okta/ADFS). func (p *samlProvider) getDriver() string { // If user explicitly set driver, always respect their choice. if p.config.Driver != "" { log.Debug("Using explicitly configured SAML driver", logFieldDriver, p.config.Driver) return p.config.Driver } // Check if Playwright drivers are available or can be auto-downloaded. if p.hasPlaywrightDriversOrCanDownload() { log.Debug("Playwright drivers available, using Browser provider for best compatibility") return "Browser" } // Fallback to provider-specific types (use API/HTTP calls without browser automation). // These are less reliable but don't require browser drivers. if strings.Contains(p.url, "accounts.google.com") { log.Debug("Falling back to GoogleApps provider (no drivers available)") return "GoogleApps" } if strings.Contains(p.url, "okta.com") { log.Debug("Falling back to Okta provider (no drivers available)") return "Okta" } if strings.Contains(p.url, "adfs") { log.Debug("Falling back to ADFS provider (no drivers available)") return "ADFS" } // If no drivers and no known provider type, try Browser anyway with auto-download. log.Debug("Unknown provider, defaulting to Browser with auto-download") return "Browser" } // validateDriver rejects an explicit driver that the vendored saml2aws copy does not support. // It runs when this provider authenticates, not in Validate: the auth manager validates every // configured provider up front, so a stale driver on one unused SAML provider must not break // authentication for every other identity. func (p *samlProvider) validateDriver() error { if p.config.Driver == "" { return nil } if _, ok := saml2aws.MFAsByProvider[p.config.Driver]; ok { return nil } return fmt.Errorf("%w: provider %q: unsupported SAML driver %q, supported drivers are %s", errUtils.ErrInvalidProviderConfig, p.name, p.config.Driver, strings.Join(saml2aws.MFAsByProvider.Names(), ", ")) } // Validate validates the provider configuration. func (p *samlProvider) Validate() error { defer perf.Track(nil, "aws.samlProvider.Validate")() if p.url == "" { return fmt.Errorf("%w: URL is required for SAML provider", errUtils.ErrInvalidProviderConfig) } if p.region == "" { return fmt.Errorf("%w: region is required for SAML provider", errUtils.ErrInvalidProviderConfig) } // Validate URL format strictly. u, err := url.ParseRequestURI(p.url) if err != nil || u.Scheme == "" || u.Host == "" { return fmt.Errorf("%w: invalid URL format: %w", errUtils.ErrInvalidProviderConfig, err) } // Validate spec.files.base_path if provided. if err := awsCloud.ValidateFilesBasePath(p.config); err != nil { return err } return nil } // Environment returns environment variables for this provider. func (p *samlProvider) Environment() (map[string]string, error) { env := make(map[string]string) // Set AWS region. env["AWS_DEFAULT_REGION"] = p.region env["AWS_REGION"] = p.region // SAML2AWS_AUTO_BROWSER_DOWNLOAD is not exported: only the saml2aws CLI read it, and the vendored // library installs browsers from LoginDetails.DownloadBrowser (see createLoginDetails). return env, nil } // Paths returns the credential and config file paths used by this SAML provider. // It returns provider-namespaced paths using AWSFileManager to support multiple // AWS provider instances. The credentials path is required, and the config path // is optional. Both paths are marked read-only for container mounting security. // //nolint:dupl // SSO and SAML providers have identical path logic but are separate implementations func (p *samlProvider) Paths() ([]types.Path, error) { basePath := awsCloud.GetFilesBasePath(p.config) // Use AWSFileManager to get correct provider-namespaced paths with realm isolation. fileManager, err := awsCloud.NewAWSFileManager(basePath, p.realm) if err != nil { return nil, err } paths := []types.Path{ { Location: fileManager.GetCredentialsPath(p.name), Type: types.PathTypeFile, Required: true, Purpose: fmt.Sprintf("AWS credentials file for provider %s", p.name), Metadata: map[string]string{ "read_only": "true", }, }, { Location: fileManager.GetConfigPath(p.name), Type: types.PathTypeFile, Required: false, // Config file is optional. Purpose: fmt.Sprintf("AWS config file for provider %s", p.name), Metadata: map[string]string{ "read_only": "true", }, }, } // Add AWS cache directory if it can be determined (contains SSO and CLI cache). // This directory should be writable so the AWS SDK can update cache. awsCacheDir := fileManager.GetCachePath() if awsCacheDir != "" { paths = append(paths, types.Path{ Location: awsCacheDir, Type: types.PathTypeDirectory, Required: false, // Cache is optional - AWS SDK will create if needed. Purpose: "AWS SDK cache directory (SSO tokens, CLI cache)", Metadata: map[string]string{ "read_only": "false", // Cache must be writable. }, }) } return paths, nil } // PrepareEnvironment prepares environment variables for external processes. // For SAML providers, this method is typically not called directly since SAML providers // authenticate to get identity credentials, which then have their own PrepareEnvironment. // However, we implement it for interface compliance. func (p *samlProvider) PrepareEnvironment(_ context.Context, environ map[string]string) (map[string]string, error) { defer perf.Track(nil, "aws.samlProvider.PrepareEnvironment")() // SAML provider doesn't write credential files itself - that's done by identities. // Just return the environment unchanged. return environ, nil } // playwrightDriversInstalled checks if valid Playwright drivers are installed in standard locations. // Returns true if drivers are found, false if not found or home directory cannot be determined. func (p *samlProvider) playwrightDriversInstalled() bool { playwrightPaths := p.playwrightBrowserPaths() for _, path := range playwrightPaths { if p.hasValidPlaywrightDrivers(path) { log.Debug("Found valid Playwright drivers", "path", path) return true } } log.Debug("No valid Playwright drivers found", "checked_paths", playwrightPaths) return false } // playwrightBrowserPaths returns the directories where Playwright browsers may be installed. func (p *samlProvider) playwrightBrowserPaths() []string { var playwrightPaths []string // Check the directory the Playwright driver itself uses first (honors // PLAYWRIGHT_BROWSERS_PATH, and XDG_CACHE_HOME on Linux). if registryDir, err := playwrightRegistryDir(); err == nil { playwrightPaths = append(playwrightPaths, registryDir) } // Check Atmos XDG cache directory (allows users to consolidate all Atmos data). if xdgCacheDir, err := xdg.GetXDGCacheDir(playwrightCacheDir, playwrightCacheDirPermissions); err == nil { playwrightPaths = append(playwrightPaths, xdgCacheDir) } // Check the home-based default browser locations of every OS. // Note: these ignore XDG_CACHE_HOME; the registry directory above covers it on Linux. homeDir, err := homedir.Dir() if err == nil { playwrightPaths = append( playwrightPaths, filepath.Join(homeDir, ".cache", playwrightCacheDir), // Linux (playwright-go default). filepath.Join(homeDir, "Library", "Caches", playwrightCacheDir), // macOS (playwright-go default). filepath.Join(homeDir, "AppData", "Local", playwrightCacheDir), // Windows (playwright-go default). ) } else { log.Debug("Cannot determine home directory for driver detection", "error", err) } // On Windows, also check LOCALAPPDATA if it's set (for test environments or custom configs). // playwright-go uses os.UserCacheDir() which returns LOCALAPPDATA directly on Windows. if runtime.GOOS == "windows" { v := viper.New() if err := v.BindEnv("LOCALAPPDATA"); err == nil { if localAppData := v.GetString("LOCALAPPDATA"); localAppData != "" { playwrightPaths = append(playwrightPaths, filepath.Join(localAppData, playwrightCacheDir)) } } } return playwrightPaths } // hasPlaywrightDriversOrCanDownload checks if Playwright drivers are available or can be downloaded. // Returns true if drivers exist or auto-download is enabled. func (p *samlProvider) hasPlaywrightDriversOrCanDownload() bool { // If user explicitly enabled download, drivers will be available. if p.config.DownloadBrowserDriver { log.Debug("Browser driver download explicitly enabled, drivers will be available") return true } return p.playwrightDriversInstalled() } // hasValidPlaywrightDrivers checks if a path contains actual browser binaries, not just empty directories. func (p *samlProvider) hasValidPlaywrightDrivers(path string) bool { // Check if directory exists. info, err := os.Stat(path) if err != nil { return false } if !info.IsDir() { return false } // Read directory contents to check if it has subdirectories with browsers. entries, err := os.ReadDir(path) if err != nil { log.Debug("Cannot read Playwright directory", "path", path, "error", err) return false } // Check if there are any version subdirectories with content. for _, entry := range entries { if !entry.IsDir() { continue } versionPath := filepath.Join(path, entry.Name()) versionEntries, err := os.ReadDir(versionPath) if err != nil { continue } // If version directory has any files/subdirectories, consider it valid. if len(versionEntries) > 0 { log.Debug("Found browser binaries in version directory", "version", entry.Name(), "files", len(versionEntries)) return true } } log.Debug("Playwright directory exists but contains no browser binaries", "path", path) return false } // shouldDownloadBrowser determines if browser drivers should be auto-downloaded. // It checks if the user explicitly configured download_browser_driver, otherwise // it enables auto-download for the "Browser" driver when the Playwright-managed browser // that will be launched (Chromium by default, or the configured chromium, firefox or webkit // browser_type) is not installed. A system browser channel (chrome*, msedge*) or a // browser_executable_path is the user's own browser and is never downloaded. func (p *samlProvider) shouldDownloadBrowser() bool { // If user explicitly set download_browser_driver, respect their choice. if p.config.DownloadBrowserDriver { log.Debug("Browser driver download explicitly enabled in config") return true } samlDriver := p.getDriver() // Only auto-download for "Browser" driver (others like GoogleApps, Okta don't need drivers). if samlDriver != "Browser" { log.Debug("SAML driver does not require browser drivers", logFieldDriver, samlDriver) return false } // A custom executable path is the user's own browser installation. if p.config.BrowserExecutablePath != "" { log.Debug("Custom browser executable configured, skipping auto-download", "browser_executable_path", p.config.BrowserExecutablePath) return false } // Only Chromium, Firefox and WebKit are installed by Playwright. System channels // (chrome*, msedge*) use the browser installed on the system. browserName, managed := playwrightManagedBrowser(p.config.BrowserType) if !managed { log.Debug("Browser type is not installed by Playwright, skipping auto-download", "browser_type", p.config.BrowserType) return false } // Check if the revision of the launched browser required by the bundled Playwright // driver is installed. Any installed browser is not enough: after a Playwright upgrade // the previous revision stays on disk but cannot be launched by the new driver, and // an installed Chromium does not satisfy Firefox or WebKit. if p.requiredBrowserInstalled(browserName) { log.Debug("Required browser revision is installed, auto-download disabled", "browser", browserName) return false } log.Debug("Required browser revision not found, enabling auto-download for Browser driver", "browser", browserName) return true } // setupBrowserAutomation sets up browser automation for SAML authentication. // Returns an error if a custom browser executable is configured but invalid // (does not exist or is not a file), so the user gets a clear failure instead // of a confusing Playwright crash later. func (p *samlProvider) setupBrowserAutomation() error { // Log browser configuration for diagnostics. if p.config.BrowserType != "" { log.Info("Custom browser type configured", "browser_type", p.config.BrowserType) } if p.config.BrowserExecutablePath != "" { log.Info("Custom browser executable path configured", "browser_executable_path", p.config.BrowserExecutablePath) // Fail fast if the configured browser executable is invalid. if err := p.validateBrowserExecutable(); err != nil { return err } } // Browser auto-download is passed to the vendored saml2aws library through // LoginDetails.DownloadBrowser (see createLoginDetails). The process environment is // not touched: SAML2AWS_AUTO_BROWSER_DOWNLOAD was only read by the saml2aws CLI. // Ensure the storage directory that saml2aws expects exists. // saml2aws hardcodes ~/.aws/saml2aws/storageState.json for browser state. if err := p.setupBrowserStorageDir(); err != nil { log.Warn("Failed to setup browser storage directory", "error", err) } return nil } // validateBrowserExecutable checks if the configured browser executable exists and is executable. func (p *samlProvider) validateBrowserExecutable() error { const ( // executablePermissionBits represents the execute permission bits (owner, group, other). // Used to check if a file has any execute permissions set. executablePermissionBits = 0o111 ) if p.config.BrowserExecutablePath == "" { return nil } // Check if file exists. info, err := os.Stat(p.config.BrowserExecutablePath) if err != nil { return fmt.Errorf("%w: browser executable not found: %w", errUtils.ErrInvalidBrowserExecutable, err) } // Check if it's a file (not directory). if info.IsDir() { return fmt.Errorf("%w: browser executable path is a directory, not a file", errUtils.ErrInvalidBrowserExecutable) } // Check if file is executable (Unix permissions check). // On Windows, this check is less reliable but os.Stat still validates existence. if info.Mode().Perm()&executablePermissionBits == 0 { log.Warn("Browser executable may not have execute permissions", "path", p.config.BrowserExecutablePath, "permissions", info.Mode().Perm().String()) } log.Debug("Browser executable validated successfully", "path", p.config.BrowserExecutablePath, "size", info.Size(), "permissions", info.Mode().Perm().String()) return nil } // setupBrowserStorageDir ensures the directory that saml2aws uses for browser // storage state exists. The path is `~/.aws/saml2aws/storageState.json` // (see storageStatePath in the vendored saml2aws browser provider, which now // builds it with filepath.Join). It is kept at the upstream location so existing // browser sessions keep working after the move to the vendored copy. // // The fix: create `~/.aws/saml2aws/` as a plain directory using filepath.Join // (correct separators on all platforms) and os.MkdirAll (no privilege // requirements). This replaces the previous symlink strategy which broke on // Windows due to symlink privilege requirements and mixed path separators. // // See docs/fixes/2026-04-10-auth-windows-path-issues.md for the full analysis. func (p *samlProvider) setupBrowserStorageDir() error { const ( samlStorageDirPerms = 0o700 awsDir = ".aws" saml2awsSubdir = "saml2aws" ) homeDir, err := homedir.Dir() if err != nil { return fmt.Errorf("%w: user home directory: %w", errUtils.ErrCreateDirectory, err) } // Create ~/.aws/saml2aws/ as a real directory (not a symlink). // The vendored saml2aws browser provider reads and writes storage state here. saml2awsDir := filepath.Join(homeDir, awsDir, saml2awsSubdir) // Migrate legacy symlink left by previous Atmos versions. os.MkdirAll // would leave a stale symlink in place, so upgraded users would never // receive the plain-directory migration. p.migrateLegacySymlink(saml2awsDir) if err := os.MkdirAll(saml2awsDir, samlStorageDirPerms); err != nil { return fmt.Errorf("%w: %s: %w", errUtils.ErrCreateDirectory, saml2awsDir, err) } log.Debug("Browser storage directory ready", "path", saml2awsDir) return nil } // migrateLegacySymlink removes a legacy symlink at path and preserves any // existing storageState.json from the symlink target. This handles upgrades // from Atmos versions that used a symlink-based storage strategy. func (p *samlProvider) migrateLegacySymlink(path string) { const ( storageStateFile = "storageState.json" migrationDirPerms = 0o700 migrationFilePerms = 0o600 ) info, lstatErr := os.Lstat(path) if lstatErr != nil || info.Mode()&os.ModeSymlink == 0 { return // Not a symlink — nothing to migrate. } // Read the symlink target to check for existing state before removing. target, readErr := os.Readlink(path) if readErr != nil { log.Debug("Cannot read legacy symlink target, removing anyway", "path", path, "error", readErr) } // Check for existing storageState.json in the symlink target. var stateData []byte if target != "" { statePath := filepath.Join(target, storageStateFile) if data, readFileErr := os.ReadFile(statePath); readFileErr == nil { stateData = data log.Debug("Preserving browser state from legacy symlink target", "source", statePath) } } // Remove the symlink. log.Debug("Removing legacy saml2aws symlink", "path", path) if removeErr := os.Remove(path); removeErr != nil { log.Warn("Failed to remove legacy saml2aws symlink", "path", path, "error", removeErr) return } // Restore storageState.json into the new real directory. if len(stateData) > 0 { if mkdirErr := os.MkdirAll(path, migrationDirPerms); mkdirErr != nil { log.Warn("Failed to create directory for state migration", "path", path, "error", mkdirErr) return } destPath := filepath.Join(path, storageStateFile) if writeErr := os.WriteFile(destPath, stateData, migrationFilePerms); writeErr != nil { log.Warn("Failed to migrate storageState.json", "dest", destPath, "error", writeErr) } else { log.Debug("Migrated storageState.json from legacy symlink", "dest", destPath) } } } // Logout removes provider-specific credential storage. func (p *samlProvider) Logout(ctx context.Context) error { defer perf.Track(nil, "aws.samlProvider.Logout")() // Get base_path from provider spec if configured. basePath := awsCloud.GetFilesBasePath(p.config) // Use realm for credential isolation between different repositories. fileManager, err := awsCloud.NewAWSFileManager(basePath, p.realm) if err != nil { return errors.Join(errUtils.ErrProviderLogout, errUtils.ErrLogoutFailed, err) } if err := fileManager.Cleanup(p.name); err != nil { log.Debug("Failed to cleanup AWS files for SAML provider", "provider", p.name, "error", err) return errors.Join(errUtils.ErrProviderLogout, errUtils.ErrLogoutFailed, err) } log.Debug("Cleaned up AWS files for SAML provider", "provider", p.name) return nil } // GetFilesDisplayPath returns the display path for AWS credential files. func (p *samlProvider) GetFilesDisplayPath() string { defer perf.Track(nil, "aws.samlProvider.GetFilesDisplayPath")() basePath := awsCloud.GetFilesBasePath(p.config) // Use realm for credential isolation between different repositories. fileManager, err := awsCloud.NewAWSFileManager(basePath, p.realm) if err != nil { homeDir, homeErr := homedir.Dir() if homeErr != nil { return filepath.Join("~", ".aws", "atmos") } return filepath.Join(homeDir, ".aws", "atmos") } return fileManager.GetDisplayPath() }