|
| 1 | +package eks |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "encoding/json" |
| 6 | + "fmt" |
| 7 | + "os" |
| 8 | + "time" |
| 9 | + |
| 10 | + "github.com/spf13/cobra" |
| 11 | + |
| 12 | + errUtils "github.com/cloudposse/atmos/errors" |
| 13 | + "github.com/cloudposse/atmos/pkg/auth" |
| 14 | + awsCloud "github.com/cloudposse/atmos/pkg/auth/cloud/aws" |
| 15 | + "github.com/cloudposse/atmos/pkg/auth/credentials" |
| 16 | + "github.com/cloudposse/atmos/pkg/auth/types" |
| 17 | + "github.com/cloudposse/atmos/pkg/auth/validation" |
| 18 | + cfg "github.com/cloudposse/atmos/pkg/config" |
| 19 | + "github.com/cloudposse/atmos/pkg/data" |
| 20 | + log "github.com/cloudposse/atmos/pkg/logger" |
| 21 | + "github.com/cloudposse/atmos/pkg/perf" |
| 22 | + "github.com/cloudposse/atmos/pkg/schema" |
| 23 | +) |
| 24 | + |
| 25 | +// execCredentialAPIVersion is the Kubernetes exec credential plugin API version. |
| 26 | +const execCredentialAPIVersion = "client.authentication.k8s.io/v1beta1" |
| 27 | + |
| 28 | +// initCliConfigFn loads Atmos CLI configuration. Overridable in tests. |
| 29 | +var initCliConfigFn = func(info schema.ConfigAndStacksInfo, processStacks bool) (schema.AtmosConfiguration, error) { |
| 30 | + return cfg.InitCliConfig(info, processStacks) |
| 31 | +} |
| 32 | + |
| 33 | +// authenticateForTokenFn authenticates an identity and returns credentials. Overridable in tests. |
| 34 | +var authenticateForTokenFn = authenticateForToken |
| 35 | + |
| 36 | +// getEKSTokenFn generates an EKS bearer token. Overridable in tests. |
| 37 | +var getEKSTokenFn = awsCloud.GetToken |
| 38 | + |
| 39 | +// tokenCmd generates a short-lived EKS bearer token for kubectl. |
| 40 | +var tokenCmd = &cobra.Command{ |
| 41 | + Use: "token", |
| 42 | + Short: "Generate an EKS bearer token for kubectl", |
| 43 | + Long: `Generate a short-lived EKS bearer token using STS pre-signed GetCallerIdentity URL. |
| 44 | +
|
| 45 | +This command is designed to be used as a kubectl exec credential plugin. |
| 46 | +It authenticates using the specified identity and outputs an ExecCredential |
| 47 | +JSON object to stdout. |
| 48 | +
|
| 49 | +The kubeconfig generated by 'atmos auth login' automatically configures |
| 50 | +kubectl to call this command for token generation. |
| 51 | +
|
| 52 | +Examples: |
| 53 | + # Generate token for a cluster (typically called by kubectl) |
| 54 | + atmos aws eks token --cluster-name my-cluster --region us-east-2 |
| 55 | +
|
| 56 | + # Generate token using a specific identity |
| 57 | + atmos aws eks token --cluster-name my-cluster --region us-east-2 --identity dev-admin`, |
| 58 | + |
| 59 | + FParseErrWhitelist: struct{ UnknownFlags bool }{UnknownFlags: false}, |
| 60 | + Args: cobra.NoArgs, |
| 61 | + RunE: executeTokenCommand, |
| 62 | + // Suppress usage on errors since kubectl invokes this automatically. |
| 63 | + SilenceUsage: true, |
| 64 | +} |
| 65 | + |
| 66 | +// execCredential represents the Kubernetes ExecCredential response. |
| 67 | +type execCredential struct { |
| 68 | + APIVersion string `json:"apiVersion"` |
| 69 | + Kind string `json:"kind"` |
| 70 | + Status execCredentialStatus `json:"status"` |
| 71 | +} |
| 72 | + |
| 73 | +// execCredentialStatus contains the token and expiration. |
| 74 | +type execCredentialStatus struct { |
| 75 | + ExpirationTimestamp string `json:"expirationTimestamp"` |
| 76 | + Token string `json:"token"` |
| 77 | +} |
| 78 | + |
| 79 | +func executeTokenCommand(cmd *cobra.Command, args []string) error { |
| 80 | + // Load atmos config. |
| 81 | + atmosConfig, err := initCliConfigFn(schema.ConfigAndStacksInfo{}, false) |
| 82 | + if err != nil { |
| 83 | + return fmt.Errorf(errUtils.ErrWrapFormat, errUtils.ErrFailedToInitConfig, err) |
| 84 | + } |
| 85 | + defer perf.Track(&atmosConfig, "eks.executeTokenCommand")() |
| 86 | + |
| 87 | + ctx := context.Background() |
| 88 | + |
| 89 | + // Get flag values. |
| 90 | + clusterName, _ := cmd.Flags().GetString("cluster-name") |
| 91 | + region, _ := cmd.Flags().GetString("region") |
| 92 | + |
| 93 | + if clusterName == "" { |
| 94 | + return fmt.Errorf("%w: --cluster-name is required", errUtils.ErrEKSTokenGeneration) |
| 95 | + } |
| 96 | + |
| 97 | + if region == "" { |
| 98 | + return fmt.Errorf("%w: --region is required", errUtils.ErrEKSTokenGeneration) |
| 99 | + } |
| 100 | + |
| 101 | + // Resolve identity: flag > env var > default. |
| 102 | + identityName := resolveIdentity(cmd) |
| 103 | + |
| 104 | + log.Debug("Generating EKS token", "cluster", clusterName, "region", region, "identity", identityName) |
| 105 | + |
| 106 | + // Authenticate to get credentials. |
| 107 | + // Skip integrations to avoid rewriting the kubeconfig during token generation. |
| 108 | + ctx = auth.ContextWithSkipIntegrations(ctx) |
| 109 | + creds, err := authenticateForTokenFn(ctx, &atmosConfig.Auth, atmosConfig.CliConfigPath, identityName) |
| 110 | + if err != nil { |
| 111 | + return fmt.Errorf("%w: %w", errUtils.ErrEKSTokenGeneration, err) |
| 112 | + } |
| 113 | + |
| 114 | + // Export AWS credentials to process environment so the AWS SDK can use them |
| 115 | + // for the STS presign call. This ensures credentials are available regardless |
| 116 | + // of how the exec plugin is invoked (e.g., by kubectl). |
| 117 | + if err := exportAWSCredsToEnv(creds); err != nil { |
| 118 | + log.Warn("eks token: failed to export AWS credentials to environment", "error", err) |
| 119 | + } |
| 120 | + |
| 121 | + // Generate token. |
| 122 | + token, expiresAt, err := getEKSTokenFn(ctx, creds, clusterName, region) |
| 123 | + if err != nil { |
| 124 | + return fmt.Errorf("%w: %w", errUtils.ErrEKSTokenGeneration, err) |
| 125 | + } |
| 126 | + |
| 127 | + // Output ExecCredential JSON to stdout. |
| 128 | + credential := execCredential{ |
| 129 | + APIVersion: execCredentialAPIVersion, |
| 130 | + Kind: "ExecCredential", |
| 131 | + Status: execCredentialStatus{ |
| 132 | + ExpirationTimestamp: expiresAt.UTC().Format(time.RFC3339), |
| 133 | + Token: token, |
| 134 | + }, |
| 135 | + } |
| 136 | + |
| 137 | + output, err := json.Marshal(credential) |
| 138 | + if err != nil { |
| 139 | + return fmt.Errorf("%w: failed to marshal ExecCredential: %w", errUtils.ErrEKSTokenGeneration, err) |
| 140 | + } |
| 141 | + |
| 142 | + return data.Write(string(output)) |
| 143 | +} |
| 144 | + |
| 145 | +// resolveIdentity resolves the identity name from flag, env var, or returns empty. |
| 146 | +func resolveIdentity(cmd *cobra.Command) string { |
| 147 | + // Check flag first. |
| 148 | + identity, _ := cmd.Flags().GetString("identity") |
| 149 | + if identity != "" { |
| 150 | + return identity |
| 151 | + } |
| 152 | + |
| 153 | + // Fall back to environment variable. |
| 154 | + if envIdentity := os.Getenv("ATMOS_IDENTITY"); envIdentity != "" { |
| 155 | + return envIdentity |
| 156 | + } |
| 157 | + |
| 158 | + return "" |
| 159 | +} |
| 160 | + |
| 161 | +// authenticateForToken authenticates an identity and returns credentials. |
| 162 | +func authenticateForToken(ctx context.Context, authConfig *schema.AuthConfig, cliConfigPath, identityName string) (types.ICredentials, error) { |
| 163 | + defer perf.Track(nil, "eks.authenticateForToken")() |
| 164 | + |
| 165 | + authStackInfo := &schema.ConfigAndStacksInfo{ |
| 166 | + AuthContext: &schema.AuthContext{}, |
| 167 | + } |
| 168 | + |
| 169 | + credStore := credentials.NewCredentialStore() |
| 170 | + validator := validation.NewValidator() |
| 171 | + |
| 172 | + mgr, err := auth.NewAuthManager(authConfig, credStore, validator, authStackInfo, cliConfigPath) |
| 173 | + if err != nil { |
| 174 | + return nil, fmt.Errorf(errUtils.ErrWrapFormat, errUtils.ErrFailedToInitializeAuthManager, err) |
| 175 | + } |
| 176 | + |
| 177 | + // If no identity specified, try to resolve default. |
| 178 | + if identityName == "" { |
| 179 | + identityName = resolveDefaultIdentity(authConfig) |
| 180 | + if identityName == "" { |
| 181 | + return nil, fmt.Errorf("%w: no identity specified and no default identity found", errUtils.ErrEKSTokenGeneration) |
| 182 | + } |
| 183 | + } |
| 184 | + |
| 185 | + whoami, err := mgr.Authenticate(ctx, identityName) |
| 186 | + if err != nil { |
| 187 | + return nil, fmt.Errorf(errUtils.ErrWrapWithNameAndCauseFormat, errUtils.ErrIdentityAuthFailed, identityName, err) |
| 188 | + } |
| 189 | + |
| 190 | + if whoami.Credentials == nil { |
| 191 | + return nil, fmt.Errorf(errUtils.ErrWrapWithNameAndCauseFormat, errUtils.ErrIdentityAuthFailed, identityName, errUtils.ErrIdentityCredentialsNone) |
| 192 | + } |
| 193 | + |
| 194 | + return whoami.Credentials, nil |
| 195 | +} |
| 196 | + |
| 197 | +// resolveDefaultIdentity finds a default identity from the auth config. |
| 198 | +func resolveDefaultIdentity(authConfig *schema.AuthConfig) string { |
| 199 | + if authConfig == nil || len(authConfig.Identities) == 0 { |
| 200 | + return "" |
| 201 | + } |
| 202 | + |
| 203 | + // If there's only one identity, use it. |
| 204 | + if len(authConfig.Identities) == 1 { |
| 205 | + for name := range authConfig.Identities { |
| 206 | + return name |
| 207 | + } |
| 208 | + } |
| 209 | + |
| 210 | + return "" |
| 211 | +} |
| 212 | + |
| 213 | +// exportAWSCredsToEnv sets AWS credential environment variables in the current process. |
| 214 | +// This ensures the AWS SDK can authenticate for the STS presign call used in token generation. |
| 215 | +func exportAWSCredsToEnv(creds types.ICredentials) error { |
| 216 | + defer perf.Track(nil, "eks.exportAWSCredsToEnv")() |
| 217 | + |
| 218 | + awsCreds, ok := creds.(*types.AWSCredentials) |
| 219 | + if !ok { |
| 220 | + return fmt.Errorf("%w: expected AWS credentials for environment export", errUtils.ErrEKSTokenGeneration) |
| 221 | + } |
| 222 | + |
| 223 | + if awsCreds.AccessKeyID != "" { |
| 224 | + os.Setenv("AWS_ACCESS_KEY_ID", awsCreds.AccessKeyID) |
| 225 | + } |
| 226 | + if awsCreds.SecretAccessKey != "" { |
| 227 | + os.Setenv("AWS_SECRET_ACCESS_KEY", awsCreds.SecretAccessKey) |
| 228 | + } |
| 229 | + if awsCreds.SessionToken != "" { |
| 230 | + os.Setenv("AWS_SESSION_TOKEN", awsCreds.SessionToken) |
| 231 | + } |
| 232 | + if awsCreds.Region != "" { |
| 233 | + os.Setenv("AWS_REGION", awsCreds.Region) |
| 234 | + os.Setenv("AWS_DEFAULT_REGION", awsCreds.Region) |
| 235 | + } |
| 236 | + |
| 237 | + // Clear AWS_PROFILE to prevent the SDK from using a named profile |
| 238 | + // that might conflict with the explicit credentials. |
| 239 | + os.Unsetenv("AWS_PROFILE") |
| 240 | + |
| 241 | + log.Debug("Exported AWS credentials to environment", |
| 242 | + "hasAccessKey", awsCreds.AccessKeyID != "", |
| 243 | + "hasSecretKey", awsCreds.SecretAccessKey != "", |
| 244 | + "hasSessionToken", awsCreds.SessionToken != "", |
| 245 | + "region", awsCreds.Region, |
| 246 | + ) |
| 247 | + |
| 248 | + return nil |
| 249 | +} |
| 250 | + |
| 251 | +func init() { |
| 252 | + tokenCmd.Flags().String("cluster-name", "", "EKS cluster name (required)") |
| 253 | + tokenCmd.Flags().String("region", "", "AWS region (required)") |
| 254 | + tokenCmd.Flags().StringP("identity", "i", "", "Atmos identity to authenticate with") |
| 255 | + EksCmd.AddCommand(tokenCmd) |
| 256 | +} |
0 commit comments