oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1//go:build hostedlive
2
3package main
4
5import (
6 "context"
7 "net"
8 "net/http"
9 "net/http/httptest"
10 "os"
11 "path/filepath"
12 "regexp"
13 "strings"
14 "sync/atomic"
15 "testing"
16
17 "github.com/aws/aws-sdk-go-v2/aws"
18 "github.com/aws/aws-sdk-go-v2/service/lambdacore"
19 "github.com/aws/aws-sdk-go-v2/service/sts"
20)
21
22// credEnv gives the test its own config and credentials files and profile
23// t17, clears every credential setting of the environment, and points
24// every credential service the SDK knows at a counting server, so a test
25// sees any attempt to reach one.
26func credEnv(t *testing.T, configBody, credsBody string) (dir string, hits *atomic.Int64) {
27 t.Helper()
28 dir = t.TempDir()
29 hits = &atomic.Int64{}
30 srv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
31 hits.Add(1)
32 http.Error(w, "no", http.StatusTeapot)
33 }))
34 ln, err := netListen()
35 if err != nil {
36 t.Fatal(err)
37 }
38 srv.Listener = ln
39 srv.Start()
40 t.Cleanup(srv.Close)
41 cfgFile, credFile := filepath.Join(dir, "config"), filepath.Join(dir, "credentials")
42 for p, b := range map[string]string{cfgFile: configBody, credFile: credsBody} {
43 if err := os.WriteFile(p, []byte(b), 0o600); err != nil {
44 t.Fatal(err)
45 }
46 }
47 for k, v := range map[string]string{
48 "AWS_CONFIG_FILE": cfgFile, "AWS_SHARED_CREDENTIALS_FILE": credFile, "AWS_PROFILE": "t17", "AWS_DEFAULT_PROFILE": "",
49 "AWS_ACCESS_KEY_ID": "", "AWS_SECRET_ACCESS_KEY": "", "AWS_SESSION_TOKEN": "", "AWS_ACCESS_KEY": "", "AWS_SECRET_KEY": "",
50 "AWS_WEB_IDENTITY_TOKEN_FILE": "", "AWS_ROLE_ARN": "", "AWS_ROLE_SESSION_NAME": "",
51 "AWS_CONTAINER_CREDENTIALS_FULL_URI": "", "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI": "", "AWS_REGION": "", "AWS_DEFAULT_REGION": "",
52 "AWS_EC2_METADATA_SERVICE_ENDPOINT": srv.URL, "AWS_ENDPOINT_URL_STS": srv.URL, "AWS_ENDPOINT_URL_SSO": srv.URL,
53 "AWS_ENDPOINT_URL_SSO_OIDC": srv.URL, "AWS_ENDPOINT_URL": srv.URL,
54 } {
55 t.Setenv(k, v)
56 }
57 return dir, hits
58}
59
60const t17Keys = "[t17]\naws_access_key_id = AKIDPROFILE\naws_secret_access_key = profile-secret\n"
61
62// TestCredentialKindsRefused: every provider but static keys is refused
63// with exit 4 and its kind named, without reaching any credential service
64// or running any credential process (R41).
65func TestCredentialKindsRefused(t *testing.T) {
66 for _, c := range []struct {
67 name, config, creds string
68 env map[string]string
69 kind string
70 }{
71 {"assume role", "[profile t17]\nrole_arn = arn:aws:iam::640012953448:role/x\nsource_profile = base\n[profile base]\nregion = eu-west-1\n",
72 t17Keys + "[base]\naws_access_key_id = AKIDBASE\naws_secret_access_key = b\n", nil, "assume role"},
73 {"web identity in the profile", "[profile t17]\nrole_arn = arn:aws:iam::640012953448:role/x\nweb_identity_token_file = /nonexistent/token\n",
74 t17Keys, nil, "web identity"},
75 {"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",
76 t17Keys, nil, "SSO"},
77 {"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",
78 t17Keys, nil, "SSO"},
79 {"credential_process", "[profile t17]\ncredential_process = /bin/sh -c 'touch MARKER'\n", t17Keys, nil, "credential_process"},
80 {"credential_source instance metadata", "[profile t17]\nrole_arn = arn:aws:iam::640012953448:role/x\ncredential_source = Ec2InstanceMetadata\n",
81 "", nil, "instance metadata"},
82 {"credential_source container", "[profile t17]\nrole_arn = arn:aws:iam::640012953448:role/x\ncredential_source = EcsContainer\n",
83 "", nil, "container credentials"},
84 {"web identity in the environment", "[profile t17]\nregion = eu-west-1\n", "",
85 map[string]string{"AWS_WEB_IDENTITY_TOKEN_FILE": "/nonexistent/token", "AWS_ROLE_ARN": "arn:aws:iam::640012953448:role/x"}, "web identity"},
86 {"container in the environment", "[profile t17]\nregion = eu-west-1\n", "",
87 map[string]string{"AWS_CONTAINER_CREDENTIALS_FULL_URI": "http://127.0.0.1:1/creds"}, "container credentials"},
88 {"nothing static (instance metadata)", "[profile t17]\nregion = eu-west-1\n", "", nil, "instance metadata"},
89 {"no such profile", "[profile other]\nregion = eu-west-1\n", "", nil, "instance metadata"},
90 } {
91 t.Run(c.name, func(t *testing.T) {
92 dir, hits := credEnv(t, c.config, c.creds)
93 t.Chdir(dir) // a credential_process would create MARKER here
94 for k, v := range c.env {
95 t.Setenv(k, v)
96 }
97 _, _, f := resolveCredentials(context.Background())
98 if f == nil || f.exit != exitGuard || f.Kind != "guard" || !strings.Contains(f.Message, "credentials from "+c.kind+" are refused") {
99 t.Fatalf("resolveCredentials = %+v, want a guard refusal naming %q", f, c.kind)
100 }
101 if n := hits.Load(); n != 0 {
102 t.Fatalf("%d requests reached a credential service during resolution", n)
103 }
104 if _, err := os.Stat(filepath.Join(dir, "MARKER")); err == nil {
105 t.Fatal("the credential process ran")
106 }
107 })
108 }
109}
110
111func TestStaticCredentialsAccepted(t *testing.T) {
112 t.Run("profile keys", func(t *testing.T) {
113 _, hits := credEnv(t, "[profile t17]\nregion = eu-west-1\n", t17Keys)
114 region, c, f := resolveCredentials(context.Background())
115 if f != nil || region != "eu-west-1" || c.AccessKeyID != "AKIDPROFILE" || c.SecretAccessKey != "profile-secret" {
116 t.Fatalf("resolveCredentials = %q, %+v, %v", region, c, f)
117 }
118 if hits.Load() != 0 {
119 t.Fatal("resolution reached a credential service")
120 }
121 })
122 t.Run("environment keys win over the profile", func(t *testing.T) {
123 credEnv(t, "[profile t17]\nrole_arn = arn:aws:iam::640012953448:role/x\nsource_profile = base\n[profile base]\nregion = eu-west-1\n",
124 "[base]\naws_access_key_id = AKIDBASE\naws_secret_access_key = b\n")
125 t.Setenv("AWS_ACCESS_KEY_ID", "AKIDENV")
126 t.Setenv("AWS_SECRET_ACCESS_KEY", "env-secret")
127 t.Setenv("AWS_SESSION_TOKEN", "env-token")
128 t.Setenv("AWS_REGION", "eu-west-1")
129 _, c, f := resolveCredentials(context.Background())
130 if f != nil || c.AccessKeyID != "AKIDENV" || c.SessionToken != "env-token" {
131 t.Fatalf("resolveCredentials = %+v, %v", c, f)
132 }
133 })
134}
135
136var credentialKey = regexp.MustCompile(`Credential=([A-Z0-9]+)/`)
137
138// TestCredentialsNeverRefresh: the keys are read once; changing the
139// environment afterwards changes nothing, and every request is signed with
140// the identity the account check used.
141func TestCredentialsNeverRefresh(t *testing.T) {
142 credEnv(t, "[profile t17]\nregion = eu-west-1\n", "")
143 t.Setenv("AWS_ACCESS_KEY_ID", "AKIDFIRST")
144 t.Setenv("AWS_SECRET_ACCESS_KEY", "first")
145 region, c, f := resolveCredentials(context.Background())
146 if f != nil {
147 t.Fatal(f)
148 }
149 cfg := staticConfig(region, c)
150 var keys []string
151 rec := &recorder{answer: func(req *http.Request) (*http.Response, error) {
152 if m := credentialKey.FindStringSubmatch(req.Header.Get("Authorization")); m != nil {
153 keys = append(keys, m[1])
154 }
155 return normal(req)
156 }}
157 cfg.HTTPClient = rec
158 core, _, st := newClients(cfg)
159 if _, err := st.GetCallerIdentity(context.Background(), &sts.GetCallerIdentityInput{}); err != nil {
160 t.Fatal(err)
161 }
162 t.Setenv("AWS_ACCESS_KEY_ID", "AKIDSECOND")
163 t.Setenv("AWS_SECRET_ACCESS_KEY", "second")
164 if _, err := core.GetNetworkConnector(context.Background(), &lambdacore.GetNetworkConnectorInput{Identifier: aws.String("nc-1")}); err != nil {
165 t.Fatal(err)
166 }
167 if strings.Join(keys, " ") != "AKIDFIRST AKIDFIRST" {
168 t.Fatalf("requests signed with %v, want the first keys twice", keys)
169 }
170 got, err := cfg.Credentials.Retrieve(context.Background())
171 if err != nil || got.CanExpire || got.AccessKeyID != "AKIDFIRST" {
172 t.Fatalf("Retrieve after the change = %+v, %v; want the first keys, never expiring", got, err)
173 }
174}
175
176// netListen binds the counting server to 127.0.0.1 only.
177func netListen() (net.Listener, error) { return net.Listen("tcp", "127.0.0.1:0") }
178