aws

package
v1.199.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 18, 2025 License: Apache-2.0 Imports: 25 Imported by: 0

README

AWS Cloud Package

This package provides AWS-specific functionality for the Atmos authentication system.

Session Duration Configuration

Session duration can be configured for both providers (SSO, SAML) and identities (IAM users):

auth:
  providers:
    company-sso:
      kind: aws/iam-identity-center
      session:
        duration: "8h"

  identities:
    emergency-admin:
      kind: aws/user
      session:
        duration: "12h"  # Formats: integers (seconds), Go durations ("1h"), or days ("1d")

AWS IAM user limits: 15m-12h (no MFA) or 15m-36h (with MFA). Default: 12h

Custom Endpoint Resolver

The AWS cloud package supports custom endpoint resolvers, which is useful for testing with LocalStack or other AWS-compatible services.

Configuration

You can configure a custom endpoint resolver at either the identity or provider level:

Identity-Level Configuration

For identities, add the aws configuration to the credentials map:

auth:
  identities:
    localstack-superuser:
      kind: aws/user
      credentials:
        access_key_id: test
        secret_access_key: test
        region: us-east-1
        aws:
          resolver:
            url: "http://localhost:4566"
Provider-Level Configuration

For providers, add the aws configuration to the spec map:

auth:
  providers:
    localstack-sso:
      kind: aws/iam-identity-center
      start_url: https://localstack.awsapps.com/start/
      region: us-east-1
      spec:
        aws:
          resolver:
            url: "http://localhost:4566"
Precedence

When both identity and provider have resolver configurations, the identity resolver takes precedence.

Usage

The custom endpoint resolver is automatically applied when:

  • AWS identities authenticate (user, assume-role, permission-set)
  • AWS providers authenticate (SSO, SAML)

All AWS SDK calls will be directed to the configured endpoint URL.

LocalStack Example

For a complete LocalStack example, see:

  • /examples/demo-localstack/atmos.yaml
Implementation Details

The resolver is implemented using AWS SDK v2's config.WithBaseEndpoint:

return config.WithBaseEndpoint(url)

This ensures all AWS services (STS, SSO, etc.) use the custom endpoint. The base endpoint approach is the recommended method in AWS SDK v2 for setting custom endpoints.

Documentation

Index

Constants

View Source
const (
	// AWSFederationEndpoint is the AWS console federation endpoint.
	AWSFederationEndpoint = "https://signin.aws.amazon.com/federation"

	// AWSConsoleDestination is the default AWS console destination.
	AWSConsoleDestination = "https://console.aws.amazon.com/"

	// AWSMaxSessionDuration is the maximum session duration for AWS console (12 hours).
	AWSMaxSessionDuration = 12 * time.Hour

	// AWSDefaultSessionDuration is the default session duration (1 hour).
	AWSDefaultSessionDuration = 1 * time.Hour

	// AWSMinSessionDuration is the minimum session duration for AWS console (15 minutes).
	AWSMinSessionDuration = 15 * time.Minute

	// AWSDefaultSigninTokenExpiration is the signin token expiration enforced by AWS (15 minutes, not configurable).
	// This is the time you have to click the generated URL before it expires.
	// To control how long you stay logged into the console, configure provider.console.session_duration.
	AWSDefaultSigninTokenExpiration = 15 * time.Minute
)
View Source
const (
	PermissionRWX = 0o700
	PermissionRW  = 0o600
)

Variables

View Source
var (
	ErrGetHomeDir                    = errors.New("failed to get home directory")
	ErrCreateCredentialsFile         = errors.New("failed to create credentials file")
	ErrCreateConfigFile              = errors.New("failed to create config file")
	ErrLoadCredentialsFile           = errors.New("failed to load credentials file")
	ErrLoadConfigFile                = errors.New("failed to load config file")
	ErrWriteCredentialsFile          = errors.New("failed to write credentials file")
	ErrWriteConfigFile               = errors.New("failed to write config file")
	ErrSetCredentialsFilePermissions = errors.New("failed to set credentials file permissions")
	ErrSetConfigFilePermissions      = errors.New("failed to set config file permissions")
	ErrProfileSection                = errors.New("failed to get profile section")
	ErrCleanupAWSFiles               = errors.New("failed to cleanup AWS files")
	ErrFileLockTimeout               = errors.New("failed to acquire file lock within timeout")
	ErrRemoveProfile                 = errors.New("failed to remove profile")
)
View Source
var ServiceDestinations = map[string]string{}/* 117 elements not displayed */

ServiceDestinations maps common AWS service aliases to their console URLs. This allows users to use shorthand like "s3" instead of full URLs.

Functions

func GetAliasByCategory added in v1.196.0

func GetAliasByCategory() map[string][]string

GetAliasByCategory returns aliases grouped by service category.

func GetAvailableAliases added in v1.196.0

func GetAvailableAliases() []string

GetAvailableAliases returns a sorted list of all available service aliases.

func GetFilesBasePath added in v1.196.0

func GetFilesBasePath(provider *schema.Provider) string

GetFilesBasePath extracts files.base_path from provider spec. Returns empty string if not configured.

func GetResolverConfigOption added in v1.195.0

func GetResolverConfigOption(identity *schema.Identity, provider *schema.Provider) config.LoadOptionsFunc

GetResolverConfigOption extracts the AWS resolver configuration from identity or provider and returns an AWS config option. Returns nil if no resolver is configured. Identity resolver takes precedence over provider resolver. AWS config is extracted from the Credentials map for identities and Spec map for providers.

func LoadAtmosManagedAWSConfig added in v1.196.0

func LoadAtmosManagedAWSConfig(ctx context.Context, optFns ...func(*config.LoadOptions) error) (aws.Config, error)

LoadAtmosManagedAWSConfig loads AWS configuration while clearing external AWS environment variables but ALLOWING Atmos-managed credential files to be loaded.

This function should be used when you want to use credentials that Atmos has already written to ~/.aws/atmos/<provider>/ directories. Unlike LoadIsolatedAWSConfig, this function ALLOWS the AWS SDK to load from shared config files and respects AWS_PROFILE, AWS_SHARED_CREDENTIALS_FILE, and AWS_CONFIG_FILE environment variables.

It only clears credentials-related variables (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN) to prevent conflicts with file-based credentials.

Use this when: - Validating Atmos-managed credentials - Using credentials from the credential store - Any operation that needs to access previously authenticated credentials

Use LoadIsolatedAWSConfig for initial authentication (SSO device flow, etc.)

func LoadINIFile added in v1.196.0

func LoadINIFile(path string) (*ini.File, error)

LoadINIFile loads an INI file with options that preserve section comments. This is critical for maintaining expiration metadata in credentials files.

func LoadIsolatedAWSConfig added in v1.195.0

func LoadIsolatedAWSConfig(ctx context.Context, optFns ...func(*config.LoadOptions) error) (aws.Config, error)

LoadIsolatedAWSConfig loads AWS configuration with problematic environment variables temporarily cleared to avoid conflicts with Atmos authentication.

This function wraps config.LoadDefaultConfig and ensures that external AWS environment variables AND shared config files don't interfere with the configuration loading process.

The AWS SDK by default loads from ~/.aws/config and ~/.aws/credentials even when AWS_PROFILE is not set. We disable shared config loading to prevent profile-based configuration from interfering with Atmos auth.

Use this for initial authentication (SSO device flow, etc.) when you want complete isolation. Use LoadAtmosManagedAWSConfig when you want to use Atmos-managed credential files.

func PrepareEnvironment added in v1.196.0

func PrepareEnvironment(environ map[string]string, profile, credentialsFile, configFile, region string) map[string]string

PrepareEnvironment configures environment variables for AWS SDK when using Atmos auth.

This function:

  1. Clears direct credential env vars to prevent conflicts with profile-based auth
  2. Sets AWS_SHARED_CREDENTIALS_FILE and AWS_CONFIG_FILE to Atmos-managed paths
  3. Sets AWS_PROFILE to the authenticated identity
  4. Configures region if provided
  5. Disables IMDS fallback to prevent accidental instance credential usage

Returns a NEW map with modifications - does not mutate the input.

Parameters:

  • environ: Current environment variables (map[string]string)
  • profile: AWS profile name (identity name)
  • credentialsFile: Path to AWS credentials file
  • configFile: Path to AWS config file
  • region: AWS region (optional)

func ResolveDestination added in v1.196.0

func ResolveDestination(destination string) (string, error)

ResolveDestination converts a destination alias to a full console URL. If the input is already a URL (starts with http:// or https://), it returns it unchanged. Otherwise, it looks up the alias in the ServiceDestinations map.

func SetAuthContext added in v1.196.0

func SetAuthContext(params *SetAuthContextParams) error

SetAuthContext populates the AWS auth context with Atmos-managed credential paths. This enables in-process AWS SDK calls to use Atmos-managed credentials.

func SetEnvironmentVariables

func SetEnvironmentVariables(authContext *schema.AuthContext, stackInfo *schema.ConfigAndStacksInfo) error

SetEnvironmentVariables derives AWS 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, sets AWS files/profile/region, and disables IMDS.

Parameters:

  • authContext: Runtime auth context containing AWS credentials
  • stackInfo: Stack configuration to populate with environment variables

func SetupFiles

func SetupFiles(providerName, identityName string, creds types.ICredentials, basePath string) error

SetupFiles sets up AWS credentials and config files for the given identity. BasePath specifies the base directory for AWS files (from provider's files.base_path). If empty, uses the default ~/.aws/atmos path.

func ValidateFilesBasePath added in v1.196.0

func ValidateFilesBasePath(provider *schema.Provider) error

ValidateFilesBasePath validates spec.files.base_path if provided.

func WithIsolatedAWSEnv added in v1.195.0

func WithIsolatedAWSEnv(fn func() error) error

WithIsolatedAWSEnv temporarily clears problematic AWS environment variables, executes the provided function, then restores the original values.

This is used to prevent external AWS environment variables from interfering with Atmos's authentication flow. The AWS SDK reads these environment variables automatically, which can cause conflicts with Atmos-managed credentials.

Usage:

err := WithIsolatedAWSEnv(func() error {
    cfg, err := config.LoadDefaultConfig(ctx)
    return err
})

Types

type AWSConfig added in v1.195.0

type AWSConfig struct {
	Resolver *ResolverConfig `yaml:"resolver,omitempty" json:"resolver,omitempty" mapstructure:"resolver"`
}

AWSConfig defines AWS-specific configuration for providers and identities.

type AWSFileManager

type AWSFileManager struct {
	// contains filtered or unexported fields
}

AWSFileManager provides helpers to manage AWS credentials/config files.

func NewAWSFileManager

func NewAWSFileManager(basePath string) (*AWSFileManager, error)

NewAWSFileManager creates a new AWS file manager instance. BasePath is optional and can be empty to use defaults. Precedence: 1) basePath parameter from provider spec, 2) XDG config directory.

Default path follows XDG Base Directory Specification:

  • Linux: $XDG_CONFIG_HOME/atmos/aws (default: ~/.config/atmos/aws)
  • macOS: ~/Library/Application Support/atmos/aws
  • Windows: %APPDATA%\atmos\aws

Respects ATMOS_XDG_CONFIG_HOME and XDG_CONFIG_HOME environment variables.

func (*AWSFileManager) Cleanup

func (m *AWSFileManager) Cleanup(providerName string) error

Cleanup removes AWS files for the provider.

func (*AWSFileManager) CleanupAll added in v1.196.0

func (m *AWSFileManager) CleanupAll() error

CleanupAll removes entire base directory (all providers).

func (*AWSFileManager) DeleteIdentity added in v1.196.0

func (m *AWSFileManager) DeleteIdentity(ctx context.Context, providerName, identityName string) error

DeleteIdentity removes only the specified identity's sections from AWS INI files. This preserves other identities using the same provider. Uses file locking to prevent concurrent modification conflicts.

func (*AWSFileManager) GetBaseDir added in v1.196.0

func (m *AWSFileManager) GetBaseDir() string

GetBaseDir returns the base directory path.

func (*AWSFileManager) GetConfigPath

func (m *AWSFileManager) GetConfigPath(providerName string) string

GetConfigPath returns the path to the config file for the provider.

func (*AWSFileManager) GetCredentialsPath

func (m *AWSFileManager) GetCredentialsPath(providerName string) string

GetCredentialsPath returns the path to the credentials file for the provider.

func (*AWSFileManager) GetDisplayPath added in v1.196.0

func (m *AWSFileManager) GetDisplayPath() string

GetDisplayPath returns a user-friendly display path (with ~ if under home directory).

func (*AWSFileManager) GetEnvironmentVariables

func (m *AWSFileManager) GetEnvironmentVariables(providerName, identityName string) []schema.EnvironmentVariable

GetEnvironmentVariables returns the AWS file environment variables as EnvironmentVariable slice.

func (*AWSFileManager) RemoveConfigProfile added in v1.196.0

func (m *AWSFileManager) RemoveConfigProfile(providerName, identityName string) error

RemoveConfigProfile removes an identity profile from the provider's config file. Uses file locking to prevent concurrent modification conflicts. If this is the last profile, the config file is removed entirely.

func (*AWSFileManager) RemoveCredentialsProfile added in v1.196.0

func (m *AWSFileManager) RemoveCredentialsProfile(providerName, identityName string) error

RemoveCredentialsProfile removes an identity profile from the provider's credentials file. Uses file locking to prevent concurrent modification conflicts. If this is the last profile, the credentials file is removed entirely.

func (*AWSFileManager) WriteConfig

func (m *AWSFileManager) WriteConfig(providerName, identityName, region, outputFormat string) error

WriteConfig writes AWS config to the provider-specific file with identity profile. Uses file locking to prevent concurrent modification conflicts.

func (*AWSFileManager) WriteCredentials

func (m *AWSFileManager) WriteCredentials(providerName, identityName string, creds *types.AWSCredentials) error

WriteCredentials writes AWS credentials to the provider-specific file with identity profile. Uses file locking to prevent concurrent modification conflicts.

type ConsoleURLGenerator added in v1.196.0

type ConsoleURLGenerator struct {
	// contains filtered or unexported fields
}

ConsoleURLGenerator generates AWS console federation URLs.

func NewConsoleURLGenerator added in v1.196.0

func NewConsoleURLGenerator(httpClient http.Client) *ConsoleURLGenerator

NewConsoleURLGenerator creates a new ConsoleURLGenerator with the specified HTTP client.

func (*ConsoleURLGenerator) GetConsoleURL added in v1.196.0

GetConsoleURL generates an AWS console sign-in URL using temporary credentials.

IMPORTANT: There is NO AWS SDK method for console federation. The AWS federation endpoint (https://signin.aws.amazon.com/federation) is a web service separate from the AWS API and must be called directly via HTTP.

AWS Federation Endpoint Limitations:

  • SessionDuration parameter is ONLY valid with direct AssumeRole* operations
  • SessionDuration is NOT valid with GetFederationToken
  • SessionDuration is NOT valid with role chaining (role → role → role)
  • Including SessionDuration with role-chained credentials returns 400 Bad Request

Since Atmos uses role chaining (SSO → PermissionSet → AssumeRole), we MUST omit the SessionDuration parameter. AWS automatically uses the remaining validity of the source credentials (typically 1 hour for role chaining).

References:

func (*ConsoleURLGenerator) SupportsConsoleAccess added in v1.196.0

func (g *ConsoleURLGenerator) SupportsConsoleAccess() bool

SupportsConsoleAccess returns true for AWS.

type ResolverConfig added in v1.195.0

type ResolverConfig struct {
	URL string `yaml:"url" json:"url" mapstructure:"url"`
}

ResolverConfig defines custom endpoint resolver configuration for AWS services.

type SetAuthContextParams added in v1.196.0

type SetAuthContextParams struct {
	AuthContext  *schema.AuthContext
	StackInfo    *schema.ConfigAndStacksInfo
	ProviderName string
	IdentityName string
	Credentials  types.ICredentials
	BasePath     string
}

SetAuthContextParams contains parameters for SetAuthContext.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL