| 1 | //go:build hostedlive |
| 2 | |
| 3 | package main |
| 4 | |
| 5 | import ( |
| 6 | "bytes" |
| 7 | "context" |
| 8 | "errors" |
| 9 | "io" |
| 10 | "net/http" |
| 11 | "os" |
| 12 | "path/filepath" |
| 13 | "strings" |
| 14 | "sync" |
| 15 | "testing" |
| 16 | "time" |
| 17 | |
| 18 | "github.com/aws/aws-sdk-go-v2/aws" |
| 19 | "github.com/aws/aws-sdk-go-v2/config" |
| 20 | "github.com/aws/aws-sdk-go-v2/service/lambdacore" |
| 21 | vms "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms" |
| 22 | "github.com/aws/aws-sdk-go-v2/service/sts" |
| 23 | ) |
| 24 | |
| 25 | var offlineKeys = fixedCredentials{aws.Credentials{AccessKeyID: "AKIDOFFLINE", SecretAccessKey: "offline"}} |
| 26 | |
| 27 | // recorder is an offline HTTP client: it records each request's host and |
| 28 | // answers from answer, so no request leaves the process. |
| 29 | type recorder struct { |
| 30 | mu sync.Mutex |
| 31 | hosts []string |
| 32 | answer func(*http.Request) (*http.Response, error) |
| 33 | } |
| 34 | |
| 35 | func (r *recorder) Do(req *http.Request) (*http.Response, error) { |
| 36 | r.mu.Lock() |
| 37 | r.hosts = append(r.hosts, req.URL.Host) |
| 38 | r.mu.Unlock() |
| 39 | return r.answer(req) |
| 40 | } |
| 41 | |
| 42 | func (r *recorder) seen() []string { |
| 43 | r.mu.Lock() |
| 44 | defer r.mu.Unlock() |
| 45 | return append([]string(nil), r.hosts...) |
| 46 | } |
| 47 | |
| 48 | var serverDate = time.Date(2026, 11, 28, 15, 4, 5, 0, time.UTC) |
| 49 | |
| 50 | func reply(req *http.Request, status int, body string) *http.Response { |
| 51 | h := http.Header{"Date": {serverDate.Format(http.TimeFormat)}, "X-Amzn-Requestid": {"req-9"}} |
| 52 | if strings.Contains(req.URL.Host, "sts") { |
| 53 | h.Set("Content-Type", "text/xml") |
| 54 | } else { |
| 55 | h.Set("Content-Type", "application/json") |
| 56 | } |
| 57 | return &http.Response{StatusCode: status, Header: h, Body: io.NopCloser(strings.NewReader(body)), Request: req} |
| 58 | } |
| 59 | |
| 60 | const stsOK = `<GetCallerIdentityResponse xmlns="https://sts.amazonaws.com/doc/2011-06-15/"><GetCallerIdentityResult>` + |
| 61 | `<Arn>arn:aws:iam::640012953448:user/agent</Arn><UserId>AID</UserId><Account>640012953448</Account>` + |
| 62 | `</GetCallerIdentityResult><ResponseMetadata><RequestId>req-9</RequestId></ResponseMetadata></GetCallerIdentityResponse>` |
| 63 | |
| 64 | // normal answers every call as a healthy service would. |
| 65 | func normal(req *http.Request) (*http.Response, error) { |
| 66 | switch { |
| 67 | case strings.Contains(req.URL.Host, "sts"): |
| 68 | return reply(req, 200, stsOK), nil |
| 69 | case strings.Contains(req.URL.Path, "microvms/"): |
| 70 | return reply(req, 200, `{"microvmId":"vm-1","state":"RUNNING","startedAt":1795878000}`), nil |
| 71 | } |
| 72 | return reply(req, 200, `{}`), nil |
| 73 | } |
| 74 | |
| 75 | // hostileEnv points every endpoint and retry setting the SDK reads from the |
| 76 | // environment or a profile somewhere else. |
| 77 | func hostileEnv(t *testing.T) { |
| 78 | dir := t.TempDir() |
| 79 | cfgFile := filepath.Join(dir, "config") |
| 80 | body := `[profile t17] |
| 81 | region = eu-west-1 |
| 82 | endpoint_url = https://evil-profile.invalid |
| 83 | max_attempts = 7 |
| 84 | retry_mode = adaptive |
| 85 | use_fips_endpoint = true |
| 86 | use_dualstack_endpoint = true |
| 87 | services = evil |
| 88 | |
| 89 | [services evil] |
| 90 | sts = |
| 91 | endpoint_url = https://evil-svc-sts.invalid |
| 92 | lambda_microvms = |
| 93 | endpoint_url = https://evil-svc-microvms.invalid |
| 94 | lambda_core = |
| 95 | endpoint_url = https://evil-svc-core.invalid |
| 96 | ` |
| 97 | if err := os.WriteFile(cfgFile, []byte(body), 0o600); err != nil { |
| 98 | t.Fatal(err) |
| 99 | } |
| 100 | for k, v := range map[string]string{ |
| 101 | "AWS_CONFIG_FILE": cfgFile, "AWS_SHARED_CREDENTIALS_FILE": filepath.Join(dir, "none"), "AWS_PROFILE": "t17", |
| 102 | "AWS_ACCESS_KEY_ID": "AKIDOFFLINE", "AWS_SECRET_ACCESS_KEY": "offline", "AWS_SESSION_TOKEN": "", |
| 103 | "AWS_EC2_METADATA_DISABLED": "true", "AWS_REGION": "eu-west-1", |
| 104 | "AWS_ENDPOINT_URL": "https://evil-global.invalid", "AWS_ENDPOINT_URL_STS": "https://evil-sts.invalid", |
| 105 | "AWS_ENDPOINT_URL_LAMBDA_MICROVMS": "https://evil-microvms.invalid", "AWS_ENDPOINT_URL_LAMBDA_CORE": "https://evil-core.invalid", |
| 106 | "AWS_IGNORE_CONFIGURED_ENDPOINT_URLS": "false", "AWS_MAX_ATTEMPTS": "5", "AWS_RETRY_MODE": "standard", |
| 107 | "AWS_USE_FIPS_ENDPOINT": "true", "AWS_USE_DUALSTACK_ENDPOINT": "true", |
| 108 | } { |
| 109 | t.Setenv(k, v) |
| 110 | } |
| 111 | } |
| 112 | |
| 113 | // callAll makes one call on each client. |
| 114 | func callAll(core *lambdacore.Client, vm *vms.Client, st *sts.Client) []error { |
| 115 | ctx := context.Background() |
| 116 | _, e1 := st.GetCallerIdentity(ctx, &sts.GetCallerIdentityInput{}) |
| 117 | _, e2 := vm.GetMicrovm(ctx, &vms.GetMicrovmInput{MicrovmIdentifier: aws.String("vm-1")}) |
| 118 | _, e3 := core.GetNetworkConnector(ctx, &lambdacore.GetNetworkConnectorInput{Identifier: aws.String("nc-1")}) |
| 119 | return []error{e1, e2, e3} |
| 120 | } |
| 121 | |
| 122 | // TestClientsIgnoreEndpointOverrides (review round 1, Critical): with every |
| 123 | // endpoint override set in the environment and the profile, the three |
| 124 | // clients still call the standard eu-west-1 endpoints, the same hosts a |
| 125 | // clean config gives. |
| 126 | func TestClientsIgnoreEndpointOverrides(t *testing.T) { |
| 127 | clean := &recorder{answer: normal} |
| 128 | cleanCfg := aws.Config{Region: wantRegion, HTTPClient: clean, |
| 129 | Credentials: offlineKeys} |
| 130 | for i, err := range callAll(newClients(cleanCfg)) { |
| 131 | if err != nil { |
| 132 | t.Fatalf("clean call %d: %v", i, err) |
| 133 | } |
| 134 | } |
| 135 | want := clean.seen() |
| 136 | t.Logf("standard hosts %v", want) |
| 137 | for _, h := range want { |
| 138 | if !strings.HasSuffix(h, ".eu-west-1.amazonaws.com") || strings.Contains(h, "fips") || strings.Contains(h, "dualstack") { |
| 139 | t.Fatalf("standard host %q is not a plain eu-west-1 endpoint", h) |
| 140 | } |
| 141 | } |
| 142 | |
| 143 | hostileEnv(t) |
| 144 | rec := &recorder{answer: normal} |
| 145 | cfg, err := config.LoadDefaultConfig(context.Background(), config.WithHTTPClient(rec)) |
| 146 | if err != nil { |
| 147 | t.Fatal(err) |
| 148 | } |
| 149 | if aws.ToString(cfg.BaseEndpoint) == "" { |
| 150 | t.Fatal("the hostile environment set no base endpoint; the test checks nothing") |
| 151 | } |
| 152 | for i, err := range callAll(newClients(cfg)) { |
| 153 | if err != nil { |
| 154 | t.Fatalf("call %d under overrides: %v", i, err) |
| 155 | } |
| 156 | } |
| 157 | got := rec.seen() |
| 158 | if strings.Join(got, " ") != strings.Join(want, " ") { |
| 159 | t.Fatalf("hosts under overrides = %v, want the standard %v", got, want) |
| 160 | } |
| 161 | |
| 162 | // The production path (R41): the config main builds from the resolved |
| 163 | // static keys, under the same environment. |
| 164 | region, creds, f := resolveCredentials(context.Background()) |
| 165 | if f != nil { |
| 166 | t.Fatalf("resolveCredentials under the hostile environment = %v", f) |
| 167 | } |
| 168 | prod := staticConfig(region, creds) |
| 169 | prodRec := &recorder{answer: normal} |
| 170 | prod.HTTPClient = prodRec |
| 171 | for i, err := range callAll(newClients(prod)) { |
| 172 | if err != nil { |
| 173 | t.Fatalf("production call %d: %v", i, err) |
| 174 | } |
| 175 | } |
| 176 | if got := prodRec.seen(); strings.Join(got, " ") != strings.Join(want, " ") { |
| 177 | t.Fatalf("production hosts = %v, want the standard %v", got, want) |
| 178 | } |
| 179 | } |
| 180 | |
| 181 | // TestClientsOneAttempt (review round 1, Important 3): a retryable error is |
| 182 | // one request, whatever AWS_MAX_ATTEMPTS and the profile say. |
| 183 | func TestClientsOneAttempt(t *testing.T) { |
| 184 | hostileEnv(t) |
| 185 | for _, c := range []struct { |
| 186 | status int |
| 187 | body string |
| 188 | }{ |
| 189 | {500, `{"__type":"InternalServerException","message":"boom"}`}, |
| 190 | {429, `{"__type":"ThrottlingException","message":"slow"}`}, |
| 191 | } { |
| 192 | rec := &recorder{answer: func(req *http.Request) (*http.Response, error) { return reply(req, c.status, c.body), nil }} |
| 193 | cfg, err := config.LoadDefaultConfig(context.Background(), config.WithHTTPClient(rec)) |
| 194 | if err != nil { |
| 195 | t.Fatal(err) |
| 196 | } |
| 197 | core, vm, _ := newClients(cfg) |
| 198 | _, err = core.GetNetworkConnector(context.Background(), &lambdacore.GetNetworkConnectorInput{Identifier: aws.String("nc-1")}) |
| 199 | f := apiFailure("GetNetworkConnector", err) |
| 200 | if err == nil || f.Status != c.status { |
| 201 | t.Fatalf("status %d: GetNetworkConnector = %v (failure %+v)", c.status, err, f) |
| 202 | } |
| 203 | _, _ = vm.RunMicrovm(context.Background(), &vms.RunMicrovmInput{ImageIdentifier: aws.String("i"), ClientToken: aws.String("t")}) |
| 204 | if n := len(rec.seen()); n != 2 { |
| 205 | t.Fatalf("status %d: %d requests for two calls, want one each (no retries)", c.status, n) |
| 206 | } |
| 207 | } |
| 208 | } |
| 209 | |
| 210 | // TestClientsBoundEachCall (review round 1, Important 2): a request that |
| 211 | // never answers ends at callTimeout. |
| 212 | func TestClientsBoundEachCall(t *testing.T) { |
| 213 | old := callTimeout |
| 214 | callTimeout = 200 * time.Millisecond |
| 215 | t.Cleanup(func() { callTimeout = old }) |
| 216 | rec := &recorder{answer: func(req *http.Request) (*http.Response, error) { |
| 217 | select { |
| 218 | case <-req.Context().Done(): |
| 219 | return nil, req.Context().Err() |
| 220 | case <-time.After(5 * time.Second): |
| 221 | return nil, errors.New("the request had no deadline") |
| 222 | } |
| 223 | }} |
| 224 | core, vm, st := newClients(aws.Config{Region: wantRegion, HTTPClient: rec, |
| 225 | Credentials: offlineKeys}) |
| 226 | start := time.Now() |
| 227 | for i, err := range callAll(core, vm, st) { |
| 228 | if !errors.Is(err, context.DeadlineExceeded) { |
| 229 | t.Errorf("stalled call %d = %v, want the per-call deadline", i, err) |
| 230 | } |
| 231 | } |
| 232 | if d := time.Since(start); d > 3*time.Second { |
| 233 | t.Fatalf("three stalled calls took %v, want about 3 x %v", d, callTimeout) |
| 234 | } |
| 235 | } |
| 236 | |
| 237 | // TestServerTimePrinted: a real client's output shows the response's Date |
| 238 | // as ResultMetadata.ServerTime. |
| 239 | func TestServerTimePrinted(t *testing.T) { |
| 240 | rec := &recorder{answer: normal} |
| 241 | _, vm, _ := newClients(aws.Config{Region: wantRegion, HTTPClient: rec, |
| 242 | Credentials: offlineKeys}) |
| 243 | out, err := vm.GetMicrovm(context.Background(), &vms.GetMicrovmInput{MicrovmIdentifier: aws.String("vm-1")}) |
| 244 | if err != nil { |
| 245 | t.Fatal(err) |
| 246 | } |
| 247 | var buf bytes.Buffer |
| 248 | if err := printJSON(&buf, out); err != nil { |
| 249 | t.Fatal(err) |
| 250 | } |
| 251 | for _, want := range []string{`"ServerTime":"2026-11-28T15:04:05Z"`, `"StartedAt":"2026-11-28T15:00:00Z"`, `"MicrovmId":"vm-1"`} { |
| 252 | if !strings.Contains(buf.String(), want) { |
| 253 | t.Errorf("GetMicrovm printed %s, want %s", buf.String(), want) |
| 254 | } |
| 255 | } |
| 256 | } |
| 257 | |