//go:build hostedlive package main import ( "context" "net" "net/http" "net/http/httptest" "os" "path/filepath" "regexp" "strings" "sync/atomic" "testing" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/lambdacore" "github.com/aws/aws-sdk-go-v2/service/sts" ) // credEnv gives the test its own config and credentials files and profile // t17, clears every credential setting of the environment, and points // every credential service the SDK knows at a counting server, so a test // sees any attempt to reach one. func credEnv(t *testing.T, configBody, credsBody string) (dir string, hits *atomic.Int64) { t.Helper() dir = t.TempDir() hits = &atomic.Int64{} srv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { hits.Add(1) http.Error(w, "no", http.StatusTeapot) })) ln, err := netListen() if err != nil { t.Fatal(err) } srv.Listener = ln srv.Start() t.Cleanup(srv.Close) cfgFile, credFile := filepath.Join(dir, "config"), filepath.Join(dir, "credentials") for p, b := range map[string]string{cfgFile: configBody, credFile: credsBody} { if err := os.WriteFile(p, []byte(b), 0o600); err != nil { t.Fatal(err) } } for k, v := range map[string]string{ "AWS_CONFIG_FILE": cfgFile, "AWS_SHARED_CREDENTIALS_FILE": credFile, "AWS_PROFILE": "t17", "AWS_DEFAULT_PROFILE": "", "AWS_ACCESS_KEY_ID": "", "AWS_SECRET_ACCESS_KEY": "", "AWS_SESSION_TOKEN": "", "AWS_ACCESS_KEY": "", "AWS_SECRET_KEY": "", "AWS_WEB_IDENTITY_TOKEN_FILE": "", "AWS_ROLE_ARN": "", "AWS_ROLE_SESSION_NAME": "", "AWS_CONTAINER_CREDENTIALS_FULL_URI": "", "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI": "", "AWS_REGION": "", "AWS_DEFAULT_REGION": "", "AWS_EC2_METADATA_SERVICE_ENDPOINT": srv.URL, "AWS_ENDPOINT_URL_STS": srv.URL, "AWS_ENDPOINT_URL_SSO": srv.URL, "AWS_ENDPOINT_URL_SSO_OIDC": srv.URL, "AWS_ENDPOINT_URL": srv.URL, } { t.Setenv(k, v) } return dir, hits } const t17Keys = "[t17]\naws_access_key_id = AKIDPROFILE\naws_secret_access_key = profile-secret\n" // TestCredentialKindsRefused: every provider but static keys is refused // with exit 4 and its kind named, without reaching any credential service // or running any credential process (R41). func TestCredentialKindsRefused(t *testing.T) { for _, c := range []struct { name, config, creds string env map[string]string kind string }{ {"assume role", "[profile t17]\nrole_arn = arn:aws:iam::640012953448:role/x\nsource_profile = base\n[profile base]\nregion = eu-west-1\n", t17Keys + "[base]\naws_access_key_id = AKIDBASE\naws_secret_access_key = b\n", nil, "assume role"}, {"web identity in the profile", "[profile t17]\nrole_arn = arn:aws:iam::640012953448:role/x\nweb_identity_token_file = /nonexistent/token\n", t17Keys, nil, "web identity"}, {"SSO session", "[profile t17]\nsso_session = s\nsso_account_id = 640012953448\nsso_role_name = r\n[sso-session s]\nsso_start_url = https://example.invalid/start\nsso_region = eu-west-1\n", t17Keys, nil, "SSO"}, {"legacy SSO", "[profile t17]\nsso_start_url = https://example.invalid/start\nsso_region = eu-west-1\nsso_account_id = 640012953448\nsso_role_name = r\n", t17Keys, nil, "SSO"}, {"credential_process", "[profile t17]\ncredential_process = /bin/sh -c 'touch MARKER'\n", t17Keys, nil, "credential_process"}, {"credential_source instance metadata", "[profile t17]\nrole_arn = arn:aws:iam::640012953448:role/x\ncredential_source = Ec2InstanceMetadata\n", "", nil, "instance metadata"}, {"credential_source container", "[profile t17]\nrole_arn = arn:aws:iam::640012953448:role/x\ncredential_source = EcsContainer\n", "", nil, "container credentials"}, {"web identity in the environment", "[profile t17]\nregion = eu-west-1\n", "", map[string]string{"AWS_WEB_IDENTITY_TOKEN_FILE": "/nonexistent/token", "AWS_ROLE_ARN": "arn:aws:iam::640012953448:role/x"}, "web identity"}, {"container in the environment", "[profile t17]\nregion = eu-west-1\n", "", map[string]string{"AWS_CONTAINER_CREDENTIALS_FULL_URI": "http://127.0.0.1:1/creds"}, "container credentials"}, {"nothing static (instance metadata)", "[profile t17]\nregion = eu-west-1\n", "", nil, "instance metadata"}, {"no such profile", "[profile other]\nregion = eu-west-1\n", "", nil, "instance metadata"}, } { t.Run(c.name, func(t *testing.T) { dir, hits := credEnv(t, c.config, c.creds) t.Chdir(dir) // a credential_process would create MARKER here for k, v := range c.env { t.Setenv(k, v) } _, _, f := resolveCredentials(context.Background()) if f == nil || f.exit != exitGuard || f.Kind != "guard" || !strings.Contains(f.Message, "credentials from "+c.kind+" are refused") { t.Fatalf("resolveCredentials = %+v, want a guard refusal naming %q", f, c.kind) } if n := hits.Load(); n != 0 { t.Fatalf("%d requests reached a credential service during resolution", n) } if _, err := os.Stat(filepath.Join(dir, "MARKER")); err == nil { t.Fatal("the credential process ran") } }) } } func TestStaticCredentialsAccepted(t *testing.T) { t.Run("profile keys", func(t *testing.T) { _, hits := credEnv(t, "[profile t17]\nregion = eu-west-1\n", t17Keys) region, c, f := resolveCredentials(context.Background()) if f != nil || region != "eu-west-1" || c.AccessKeyID != "AKIDPROFILE" || c.SecretAccessKey != "profile-secret" { t.Fatalf("resolveCredentials = %q, %+v, %v", region, c, f) } if hits.Load() != 0 { t.Fatal("resolution reached a credential service") } }) t.Run("environment keys win over the profile", func(t *testing.T) { credEnv(t, "[profile t17]\nrole_arn = arn:aws:iam::640012953448:role/x\nsource_profile = base\n[profile base]\nregion = eu-west-1\n", "[base]\naws_access_key_id = AKIDBASE\naws_secret_access_key = b\n") t.Setenv("AWS_ACCESS_KEY_ID", "AKIDENV") t.Setenv("AWS_SECRET_ACCESS_KEY", "env-secret") t.Setenv("AWS_SESSION_TOKEN", "env-token") t.Setenv("AWS_REGION", "eu-west-1") _, c, f := resolveCredentials(context.Background()) if f != nil || c.AccessKeyID != "AKIDENV" || c.SessionToken != "env-token" { t.Fatalf("resolveCredentials = %+v, %v", c, f) } }) } var credentialKey = regexp.MustCompile(`Credential=([A-Z0-9]+)/`) // TestCredentialsNeverRefresh: the keys are read once; changing the // environment afterwards changes nothing, and every request is signed with // the identity the account check used. func TestCredentialsNeverRefresh(t *testing.T) { credEnv(t, "[profile t17]\nregion = eu-west-1\n", "") t.Setenv("AWS_ACCESS_KEY_ID", "AKIDFIRST") t.Setenv("AWS_SECRET_ACCESS_KEY", "first") region, c, f := resolveCredentials(context.Background()) if f != nil { t.Fatal(f) } cfg := staticConfig(region, c) var keys []string rec := &recorder{answer: func(req *http.Request) (*http.Response, error) { if m := credentialKey.FindStringSubmatch(req.Header.Get("Authorization")); m != nil { keys = append(keys, m[1]) } return normal(req) }} cfg.HTTPClient = rec core, _, st := newClients(cfg) if _, err := st.GetCallerIdentity(context.Background(), &sts.GetCallerIdentityInput{}); err != nil { t.Fatal(err) } t.Setenv("AWS_ACCESS_KEY_ID", "AKIDSECOND") t.Setenv("AWS_SECRET_ACCESS_KEY", "second") if _, err := core.GetNetworkConnector(context.Background(), &lambdacore.GetNetworkConnectorInput{Identifier: aws.String("nc-1")}); err != nil { t.Fatal(err) } if strings.Join(keys, " ") != "AKIDFIRST AKIDFIRST" { t.Fatalf("requests signed with %v, want the first keys twice", keys) } got, err := cfg.Credentials.Retrieve(context.Background()) if err != nil || got.CanExpire || got.AccessKeyID != "AKIDFIRST" { t.Fatalf("Retrieve after the change = %+v, %v; want the first keys, never expiring", got, err) } } // netListen binds the counting server to 127.0.0.1 only. func netListen() (net.Listener, error) { return net.Listen("tcp", "127.0.0.1:0") }