//go:build hostedlive package main import ( "bytes" "context" "errors" "io" "net/http" "os" "path/filepath" "strings" "sync" "testing" "time" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/lambdacore" vms "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms" "github.com/aws/aws-sdk-go-v2/service/sts" ) var offlineKeys = fixedCredentials{aws.Credentials{AccessKeyID: "AKIDOFFLINE", SecretAccessKey: "offline"}} // recorder is an offline HTTP client: it records each request's host and // answers from answer, so no request leaves the process. type recorder struct { mu sync.Mutex hosts []string answer func(*http.Request) (*http.Response, error) } func (r *recorder) Do(req *http.Request) (*http.Response, error) { r.mu.Lock() r.hosts = append(r.hosts, req.URL.Host) r.mu.Unlock() return r.answer(req) } func (r *recorder) seen() []string { r.mu.Lock() defer r.mu.Unlock() return append([]string(nil), r.hosts...) } var serverDate = time.Date(2026, 11, 28, 15, 4, 5, 0, time.UTC) func reply(req *http.Request, status int, body string) *http.Response { h := http.Header{"Date": {serverDate.Format(http.TimeFormat)}, "X-Amzn-Requestid": {"req-9"}} if strings.Contains(req.URL.Host, "sts") { h.Set("Content-Type", "text/xml") } else { h.Set("Content-Type", "application/json") } return &http.Response{StatusCode: status, Header: h, Body: io.NopCloser(strings.NewReader(body)), Request: req} } const stsOK = `` + `arn:aws:iam::640012953448:user/agentAID640012953448` + `req-9` // normal answers every call as a healthy service would. func normal(req *http.Request) (*http.Response, error) { switch { case strings.Contains(req.URL.Host, "sts"): return reply(req, 200, stsOK), nil case strings.Contains(req.URL.Path, "microvms/"): return reply(req, 200, `{"microvmId":"vm-1","state":"RUNNING","startedAt":1795878000}`), nil } return reply(req, 200, `{}`), nil } // hostileEnv points every endpoint and retry setting the SDK reads from the // environment or a profile somewhere else. func hostileEnv(t *testing.T) { dir := t.TempDir() cfgFile := filepath.Join(dir, "config") body := `[profile t17] region = eu-west-1 endpoint_url = https://evil-profile.invalid max_attempts = 7 retry_mode = adaptive use_fips_endpoint = true use_dualstack_endpoint = true services = evil [services evil] sts = endpoint_url = https://evil-svc-sts.invalid lambda_microvms = endpoint_url = https://evil-svc-microvms.invalid lambda_core = endpoint_url = https://evil-svc-core.invalid ` if err := os.WriteFile(cfgFile, []byte(body), 0o600); err != nil { t.Fatal(err) } for k, v := range map[string]string{ "AWS_CONFIG_FILE": cfgFile, "AWS_SHARED_CREDENTIALS_FILE": filepath.Join(dir, "none"), "AWS_PROFILE": "t17", "AWS_ACCESS_KEY_ID": "AKIDOFFLINE", "AWS_SECRET_ACCESS_KEY": "offline", "AWS_SESSION_TOKEN": "", "AWS_EC2_METADATA_DISABLED": "true", "AWS_REGION": "eu-west-1", "AWS_ENDPOINT_URL": "https://evil-global.invalid", "AWS_ENDPOINT_URL_STS": "https://evil-sts.invalid", "AWS_ENDPOINT_URL_LAMBDA_MICROVMS": "https://evil-microvms.invalid", "AWS_ENDPOINT_URL_LAMBDA_CORE": "https://evil-core.invalid", "AWS_IGNORE_CONFIGURED_ENDPOINT_URLS": "false", "AWS_MAX_ATTEMPTS": "5", "AWS_RETRY_MODE": "standard", "AWS_USE_FIPS_ENDPOINT": "true", "AWS_USE_DUALSTACK_ENDPOINT": "true", } { t.Setenv(k, v) } } // callAll makes one call on each client. func callAll(core *lambdacore.Client, vm *vms.Client, st *sts.Client) []error { ctx := context.Background() _, e1 := st.GetCallerIdentity(ctx, &sts.GetCallerIdentityInput{}) _, e2 := vm.GetMicrovm(ctx, &vms.GetMicrovmInput{MicrovmIdentifier: aws.String("vm-1")}) _, e3 := core.GetNetworkConnector(ctx, &lambdacore.GetNetworkConnectorInput{Identifier: aws.String("nc-1")}) return []error{e1, e2, e3} } // TestClientsIgnoreEndpointOverrides (review round 1, Critical): with every // endpoint override set in the environment and the profile, the three // clients still call the standard eu-west-1 endpoints, the same hosts a // clean config gives. func TestClientsIgnoreEndpointOverrides(t *testing.T) { clean := &recorder{answer: normal} cleanCfg := aws.Config{Region: wantRegion, HTTPClient: clean, Credentials: offlineKeys} for i, err := range callAll(newClients(cleanCfg)) { if err != nil { t.Fatalf("clean call %d: %v", i, err) } } want := clean.seen() t.Logf("standard hosts %v", want) for _, h := range want { if !strings.HasSuffix(h, ".eu-west-1.amazonaws.com") || strings.Contains(h, "fips") || strings.Contains(h, "dualstack") { t.Fatalf("standard host %q is not a plain eu-west-1 endpoint", h) } } hostileEnv(t) rec := &recorder{answer: normal} cfg, err := config.LoadDefaultConfig(context.Background(), config.WithHTTPClient(rec)) if err != nil { t.Fatal(err) } if aws.ToString(cfg.BaseEndpoint) == "" { t.Fatal("the hostile environment set no base endpoint; the test checks nothing") } for i, err := range callAll(newClients(cfg)) { if err != nil { t.Fatalf("call %d under overrides: %v", i, err) } } got := rec.seen() if strings.Join(got, " ") != strings.Join(want, " ") { t.Fatalf("hosts under overrides = %v, want the standard %v", got, want) } // The production path (R41): the config main builds from the resolved // static keys, under the same environment. region, creds, f := resolveCredentials(context.Background()) if f != nil { t.Fatalf("resolveCredentials under the hostile environment = %v", f) } prod := staticConfig(region, creds) prodRec := &recorder{answer: normal} prod.HTTPClient = prodRec for i, err := range callAll(newClients(prod)) { if err != nil { t.Fatalf("production call %d: %v", i, err) } } if got := prodRec.seen(); strings.Join(got, " ") != strings.Join(want, " ") { t.Fatalf("production hosts = %v, want the standard %v", got, want) } } // TestClientsOneAttempt (review round 1, Important 3): a retryable error is // one request, whatever AWS_MAX_ATTEMPTS and the profile say. func TestClientsOneAttempt(t *testing.T) { hostileEnv(t) for _, c := range []struct { status int body string }{ {500, `{"__type":"InternalServerException","message":"boom"}`}, {429, `{"__type":"ThrottlingException","message":"slow"}`}, } { rec := &recorder{answer: func(req *http.Request) (*http.Response, error) { return reply(req, c.status, c.body), nil }} cfg, err := config.LoadDefaultConfig(context.Background(), config.WithHTTPClient(rec)) if err != nil { t.Fatal(err) } core, vm, _ := newClients(cfg) _, err = core.GetNetworkConnector(context.Background(), &lambdacore.GetNetworkConnectorInput{Identifier: aws.String("nc-1")}) f := apiFailure("GetNetworkConnector", err) if err == nil || f.Status != c.status { t.Fatalf("status %d: GetNetworkConnector = %v (failure %+v)", c.status, err, f) } _, _ = vm.RunMicrovm(context.Background(), &vms.RunMicrovmInput{ImageIdentifier: aws.String("i"), ClientToken: aws.String("t")}) if n := len(rec.seen()); n != 2 { t.Fatalf("status %d: %d requests for two calls, want one each (no retries)", c.status, n) } } } // TestClientsBoundEachCall (review round 1, Important 2): a request that // never answers ends at callTimeout. func TestClientsBoundEachCall(t *testing.T) { old := callTimeout callTimeout = 200 * time.Millisecond t.Cleanup(func() { callTimeout = old }) rec := &recorder{answer: func(req *http.Request) (*http.Response, error) { select { case <-req.Context().Done(): return nil, req.Context().Err() case <-time.After(5 * time.Second): return nil, errors.New("the request had no deadline") } }} core, vm, st := newClients(aws.Config{Region: wantRegion, HTTPClient: rec, Credentials: offlineKeys}) start := time.Now() for i, err := range callAll(core, vm, st) { if !errors.Is(err, context.DeadlineExceeded) { t.Errorf("stalled call %d = %v, want the per-call deadline", i, err) } } if d := time.Since(start); d > 3*time.Second { t.Fatalf("three stalled calls took %v, want about 3 x %v", d, callTimeout) } } // TestServerTimePrinted: a real client's output shows the response's Date // as ResultMetadata.ServerTime. func TestServerTimePrinted(t *testing.T) { rec := &recorder{answer: normal} _, vm, _ := newClients(aws.Config{Region: wantRegion, HTTPClient: rec, Credentials: offlineKeys}) out, err := vm.GetMicrovm(context.Background(), &vms.GetMicrovmInput{MicrovmIdentifier: aws.String("vm-1")}) if err != nil { t.Fatal(err) } var buf bytes.Buffer if err := printJSON(&buf, out); err != nil { t.Fatal(err) } for _, want := range []string{`"ServerTime":"2026-11-28T15:04:05Z"`, `"StartedAt":"2026-11-28T15:00:00Z"`, `"MicrovmId":"vm-1"`} { if !strings.Contains(buf.String(), want) { t.Errorf("GetMicrovm printed %s, want %s", buf.String(), want) } } }