oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package awsjob
2
3import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "errors"
8 "fmt"
9 "io"
10 "net/http"
11 "net/netip"
12 "os"
13 "reflect"
14 "slices"
15 "strings"
16 "sync"
17 "testing"
18 "time"
19
20 "amadan.net/oficina/equipo/internal/isolatedjob"
21 "amadan.net/rastrillo/rastrillo/budget"
22 "github.com/aws/aws-sdk-go-v2/aws"
23 awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware"
24 "github.com/aws/aws-sdk-go-v2/service/ec2"
25 "github.com/aws/aws-sdk-go-v2/service/lambdacore"
26 vms "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms"
27 "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms/types"
28 "github.com/aws/aws-sdk-go-v2/service/sns"
29 "github.com/aws/smithy-go"
30 "github.com/aws/smithy-go/middleware"
31)
32
33func TestMain(m *testing.M) { os.Exit(budget.Main(m)) }
34
35const (
36 testDigest = isolatedjob.ImageDigest("sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef")
37 otherDigest = isolatedjob.ImageDigest("sha256:fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210")
38 testImageARN = "arn:aws:lambda:eu-west-1:123456789012:microvm-image:runner"
39 testConnector = "arn:aws:lambda:eu-west-1:123456789012:network-connector:nc-1:3"
40 smallVersion = "3"
41 largeVersion = "4"
42)
43
44func testConfig() Config {
45 return Config{
46 Region: "eu-west-1",
47 ConnectorID: testConnector,
48 VPCID: "vpc-1",
49 VMSubnetID: "subnet-1",
50 VMSecurityGroupID: "sg-1",
51 Images: map[isolatedjob.ImageDigest]Image{
52 testDigest: {ARN: testImageARN, Versions: map[isolatedjob.Size]string{
53 isolatedjob.SizeSmall: smallVersion,
54 isolatedjob.SizeLarge: largeVersion,
55 }},
56 },
57 Egress: []netip.AddrPort{netip.MustParseAddrPort("10.0.1.10:3128"), netip.MustParseAddrPort("10.0.1.11:443")},
58 }
59}
60
61func testSpec() isolatedjob.LaunchSpec {
62 return isolatedjob.LaunchSpec{
63 AttemptID: "attempt-7",
64 Image: testDigest,
65 Size: isolatedjob.SizeSmall,
66 MaxLifetime: 2*time.Hour + 30*time.Minute + 900*time.Millisecond,
67 Bootstrap: []byte(`{"code":"one-time"}` + "\n\t~ end"),
68 }
69}
70
71// goodVersion is an image version that passes the image check for the
72// memory given.
73func goodVersion(memMiB int32) *vms.GetMicrovmImageVersionOutput {
74 return &vms.GetMicrovmImageVersionOutput{
75 AdditionalOsCapabilities: []types.Capability{types.CapabilityAll},
76 CpuConfigurations: []types.CpuConfiguration{{Architecture: types.ArchitectureX8664}},
77 Resources: []types.Resources{{MinimumMemoryInMiB: aws.Int32(memMiB)}},
78 }
79}
80
81// stub is the API with every call recorded. A nil func field gives a
82// default: image versions pass for the configured sizes, run returns
83// "vm-1", and the rest succeed with empty outputs.
84type stub struct {
85 mu sync.Mutex
86 calls []string
87 runIn []*vms.RunMicrovmInput
88 verIn []*vms.GetMicrovmImageVersionInput
89
90 run func(*vms.RunMicrovmInput) (*vms.RunMicrovmOutput, error)
91 get func(*vms.GetMicrovmInput) (*vms.GetMicrovmOutput, error)
92 suspend func(*vms.SuspendMicrovmInput) (*vms.SuspendMicrovmOutput, error)
93 resume func(*vms.ResumeMicrovmInput) (*vms.ResumeMicrovmOutput, error)
94 terminate func(*vms.TerminateMicrovmInput) (*vms.TerminateMicrovmOutput, error)
95 list func(*vms.ListMicrovmsInput) (*vms.ListMicrovmsOutput, error)
96 version func(*vms.GetMicrovmImageVersionInput) (*vms.GetMicrovmImageVersionOutput, error)
97
98 vpcAttr func(*ec2.DescribeVpcAttributeInput) (*ec2.DescribeVpcAttributeOutput, error)
99 subnets func(*ec2.DescribeSubnetsInput) (*ec2.DescribeSubnetsOutput, error)
100 routeTables func(*ec2.DescribeRouteTablesInput) (*ec2.DescribeRouteTablesOutput, error)
101 securityGroups func(*ec2.DescribeSecurityGroupsInput) (*ec2.DescribeSecurityGroupsOutput, error)
102 connector func(*lambdacore.GetNetworkConnectorInput) (*lambdacore.GetNetworkConnectorOutput, error)
103}
104
105func (s *stub) record(op string) {
106 s.mu.Lock()
107 defer s.mu.Unlock()
108 s.calls = append(s.calls, op)
109}
110
111func (s *stub) count(op string) int {
112 s.mu.Lock()
113 defer s.mu.Unlock()
114 n := 0
115 for _, c := range s.calls {
116 if c == op {
117 n++
118 }
119 }
120 return n
121}
122
123func (s *stub) RunMicrovm(_ context.Context, in *vms.RunMicrovmInput, _ ...func(*vms.Options)) (*vms.RunMicrovmOutput, error) {
124 s.record("RunMicrovm")
125 s.mu.Lock()
126 s.runIn = append(s.runIn, in)
127 s.mu.Unlock()
128 if s.run != nil {
129 return s.run(in)
130 }
131 return &vms.RunMicrovmOutput{MicrovmId: aws.String("vm-1"), State: types.MicrovmStatePending}, nil
132}
133
134func (s *stub) GetMicrovm(_ context.Context, in *vms.GetMicrovmInput, _ ...func(*vms.Options)) (*vms.GetMicrovmOutput, error) {
135 s.record("GetMicrovm")
136 if s.get != nil {
137 return s.get(in)
138 }
139 return &vms.GetMicrovmOutput{MicrovmId: in.MicrovmIdentifier, State: types.MicrovmStateRunning}, nil
140}
141
142func (s *stub) SuspendMicrovm(_ context.Context, in *vms.SuspendMicrovmInput, _ ...func(*vms.Options)) (*vms.SuspendMicrovmOutput, error) {
143 s.record("SuspendMicrovm")
144 if s.suspend != nil {
145 return s.suspend(in)
146 }
147 return &vms.SuspendMicrovmOutput{}, nil
148}
149
150func (s *stub) ResumeMicrovm(_ context.Context, in *vms.ResumeMicrovmInput, _ ...func(*vms.Options)) (*vms.ResumeMicrovmOutput, error) {
151 s.record("ResumeMicrovm")
152 if s.resume != nil {
153 return s.resume(in)
154 }
155 return &vms.ResumeMicrovmOutput{}, nil
156}
157
158func (s *stub) TerminateMicrovm(_ context.Context, in *vms.TerminateMicrovmInput, _ ...func(*vms.Options)) (*vms.TerminateMicrovmOutput, error) {
159 s.record("TerminateMicrovm")
160 if s.terminate != nil {
161 return s.terminate(in)
162 }
163 return &vms.TerminateMicrovmOutput{}, nil
164}
165
166func (s *stub) ListMicrovms(_ context.Context, in *vms.ListMicrovmsInput, _ ...func(*vms.Options)) (*vms.ListMicrovmsOutput, error) {
167 s.record("ListMicrovms")
168 if s.list != nil {
169 return s.list(in)
170 }
171 return &vms.ListMicrovmsOutput{}, nil
172}
173
174func (s *stub) GetMicrovmImageVersion(_ context.Context, in *vms.GetMicrovmImageVersionInput, _ ...func(*vms.Options)) (*vms.GetMicrovmImageVersionOutput, error) {
175 s.record("GetMicrovmImageVersion")
176 s.mu.Lock()
177 s.verIn = append(s.verIn, in)
178 s.mu.Unlock()
179 if s.version != nil {
180 return s.version(in)
181 }
182 switch aws.ToString(in.ImageVersion) {
183 case smallVersion:
184 return goodVersion(2048), nil
185 case largeVersion:
186 return goodVersion(4096), nil
187 }
188 return nil, &types.ResourceNotFoundException{Message: aws.String("no such version")}
189}
190
191func newTestRunner(t *testing.T, s *stub) *Runner {
192 t.Helper()
193 r, err := New(testConfig(), s)
194 if err != nil {
195 t.Fatalf("New = %v", err)
196 }
197 return r
198}
199
200func TestNew(t *testing.T) {
201 if _, err := New(testConfig(), &stub{}); err != nil {
202 t.Fatalf("New(good config) = %v", err)
203 }
204 if _, err := New(testConfig(), nil); !errors.Is(err, isolatedjob.ErrInvalid) {
205 t.Errorf("New(nil api) = %v, want ErrInvalid", err)
206 }
207 none := testConfig()
208 none.Egress = nil // slice 1a: no egress at all
209 if _, err := New(none, &stub{}); err != nil {
210 t.Errorf("New(no egress) = %v, want nil", err)
211 }
212 for name, change := range map[string]func(*Config){
213 "no region": func(c *Config) { c.Region = "" },
214 "no connector": func(c *Config) { c.ConnectorID = "" },
215 "connector not an ARN": func(c *Config) { c.ConnectorID = "egress" },
216 "connector unqualified": func(c *Config) {
217 c.ConnectorID = "arn:aws:lambda:eu-west-1:123456789012:network-connector:nc-1"
218 },
219 "connector version not a number": func(c *Config) {
220 c.ConnectorID = "arn:aws:lambda:eu-west-1:123456789012:network-connector:nc-1:latest"
221 },
222 "connector in another region": func(c *Config) {
223 c.ConnectorID = "arn:aws:lambda:us-east-1:123456789012:network-connector:nc-1:3"
224 },
225 "connector of another service": func(c *Config) {
226 c.ConnectorID = "arn:aws:ec2:eu-west-1:123456789012:network-connector:nc-1:3"
227 },
228 "no vpc": func(c *Config) { c.VPCID = "" },
229 "no subnet": func(c *Config) { c.VMSubnetID = "" },
230 "no security group": func(c *Config) { c.VMSecurityGroupID = "" },
231 "no images": func(c *Config) { c.Images = nil },
232 "image without ARN": func(c *Config) {
233 c.Images[testDigest] = Image{Versions: map[isolatedjob.Size]string{isolatedjob.SizeSmall: "1"}}
234 },
235 "image without versions": func(c *Config) {
236 c.Images[testDigest] = Image{ARN: testImageARN}
237 },
238 "unknown size": func(c *Config) { c.Images[testDigest].Versions["medium"] = "9" },
239 "empty version": func(c *Config) { c.Images[testDigest].Versions[isolatedjob.SizeSmall] = "" },
240 "egress port 0": func(c *Config) { c.Egress = []netip.AddrPort{netip.MustParseAddrPort("10.0.1.10:0")} },
241 "egress zero": func(c *Config) { c.Egress = []netip.AddrPort{{}} },
242 } {
243 t.Run(name, func(t *testing.T) {
244 c := testConfig()
245 change(&c)
246 if _, err := New(c, &stub{}); !errors.Is(err, isolatedjob.ErrInvalid) {
247 t.Errorf("New = %v, want ErrInvalid", err)
248 }
249 })
250 }
251}
252
253// TestFingerprint: every setting a launch sends beyond the spec changes the
254// fingerprint of the image and size it applies to; nothing else does.
255func TestFingerprint(t *testing.T) {
256 base := testConfig().Fingerprint(testDigest, isolatedjob.SizeSmall)
257 if base == testConfig().Fingerprint(testDigest, isolatedjob.SizeLarge) {
258 t.Fatal("small and large share a fingerprint, though their versions differ")
259 }
260 for name, c := range map[string]struct {
261 change func(*Config)
262 same bool
263 }{
264 "region": {func(c *Config) { c.Region = "us-east-1" }, false},
265 "connector": {func(c *Config) { c.ConnectorID = strings.Replace(testConnector, ":3", ":4", 1) }, false},
266 "image ARN": {func(c *Config) {
267 c.Images[testDigest] = Image{ARN: testImageARN + "-2", Versions: c.Images[testDigest].Versions}
268 }, false},
269 "small version": {func(c *Config) { c.Images[testDigest].Versions[isolatedjob.SizeSmall] = "5" }, false},
270 "image dropped": {func(c *Config) { delete(c.Images, testDigest) }, false},
271 "large version": {func(c *Config) { c.Images[testDigest].Versions[isolatedjob.SizeLarge] = "5" }, true},
272 "egress": {func(c *Config) { c.Egress = nil }, true},
273 "security group": {func(c *Config) { c.VMSecurityGroupID = "sg-2" }, true},
274 "another digest": {func(c *Config) {
275 c.Images[otherDigest] = Image{ARN: "x", Versions: map[isolatedjob.Size]string{isolatedjob.SizeSmall: "1"}}
276 }, true},
277 } {
278 cfg := testConfig()
279 c.change(&cfg)
280 if got := cfg.Fingerprint(testDigest, isolatedjob.SizeSmall); (got == base) != c.same {
281 t.Errorf("%s changed: fingerprint %q (was %q), want same %v", name, got, base, c.same)
282 }
283 }
284}
285
286func TestLimits(t *testing.T) {
287 want := isolatedjob.Limits{MaxLifetime: 28800 * time.Second, MaxBootstrapBytes: 4096, SuspendUsesLifetime: true, ConnectionsSurvive: false}
288 if got := newTestRunner(t, &stub{}).Limits(); got != want {
289 t.Fatalf("Limits() = %+v, want %+v", got, want)
290 }
291}
292
293func TestRunRequestShape(t *testing.T) {
294 s := &stub{}
295 r := newTestRunner(t, s)
296 spec := testSpec()
297 ref, err := r.Launch(context.Background(), spec)
298 if err != nil {
299 t.Fatalf("Launch = %v", err)
300 }
301 if ref != "vm-1" {
302 t.Fatalf("Launch = %q, want vm-1", ref)
303 }
304 if len(s.runIn) != 1 {
305 t.Fatalf("RunMicrovm called %d times, want 1", len(s.runIn))
306 }
307 in := s.runIn[0]
308 if got := aws.ToString(in.ImageIdentifier); got != testImageARN {
309 t.Errorf("imageIdentifier = %q, want the image ARN %q", got, testImageARN)
310 }
311 if got := aws.ToString(in.ImageVersion); got != smallVersion {
312 t.Errorf("imageVersion = %q, want the small version %q", got, smallVersion)
313 }
314 if want := []string{NoIngressConnectorARN("eu-west-1")}; !reflect.DeepEqual(in.IngressNetworkConnectors, want) {
315 t.Errorf("ingressNetworkConnectors = %q, want only NO_INGRESS %q", in.IngressNetworkConnectors, want)
316 }
317 if want := []string{testConnector}; !reflect.DeepEqual(in.EgressNetworkConnectors, want) {
318 t.Errorf("egressNetworkConnectors = %q, want only the configured connector %q", in.EgressNetworkConnectors, want)
319 }
320 if in.ExecutionRoleArn != nil {
321 t.Errorf("executionRoleArn = %q, want none", *in.ExecutionRoleArn)
322 }
323 if in.IdlePolicy != nil {
324 t.Errorf("idlePolicy = %+v, want none", *in.IdlePolicy)
325 }
326 if got := aws.ToInt32(in.MaximumDurationInSeconds); in.MaximumDurationInSeconds == nil || got != 9000 {
327 t.Errorf("maximumDurationInSeconds = %d (set %v), want 9000 (2h30m0.9s in whole seconds)", got, in.MaximumDurationInSeconds != nil)
328 }
329 if in.ClientToken == nil || *in.ClientToken != spec.AttemptID {
330 t.Errorf("clientToken = %v, want the attempt id %q", in.ClientToken, spec.AttemptID)
331 }
332 if in.RunHookPayload == nil || !bytes.Equal([]byte(*in.RunHookPayload), spec.Bootstrap) {
333 t.Errorf("runHookPayload = %q, want the bootstrap %q byte for byte", aws.ToString(in.RunHookPayload), spec.Bootstrap)
334 }
335 if in.KmsKeyIdentifier != nil || !reflect.DeepEqual(in.Logging, types.Logging(nil)) {
336 t.Errorf("kmsKeyIdentifier = %v, logging = %v, want neither", in.KmsKeyIdentifier, in.Logging)
337 }
338 want := vms.RunMicrovmInput{
339 ImageIdentifier: aws.String(testImageARN),
340 ImageVersion: aws.String(smallVersion),
341 ClientToken: aws.String(spec.AttemptID),
342 IngressNetworkConnectors: []string{NoIngressConnectorARN("eu-west-1")},
343 EgressNetworkConnectors: []string{testConnector},
344 MaximumDurationInSeconds: aws.Int32(9000),
345 RunHookPayload: aws.String(string(spec.Bootstrap)),
346 }
347 if !reflect.DeepEqual(*in, want) {
348 t.Errorf("RunMicrovmInput = %+v, want exactly %+v", *in, want)
349 }
350
351 t.Run("large uses the large version", func(t *testing.T) {
352 s := &stub{}
353 r := newTestRunner(t, s)
354 spec := testSpec()
355 spec.Size = isolatedjob.SizeLarge
356 spec.MaxLifetime = isolatedjob.HardMaxLifetime
357 if _, err := r.Launch(context.Background(), spec); err != nil {
358 t.Fatalf("Launch = %v", err)
359 }
360 if got := aws.ToString(s.runIn[0].ImageVersion); got != largeVersion {
361 t.Errorf("imageVersion = %q, want %q", got, largeVersion)
362 }
363 if got := aws.ToInt32(s.runIn[0].MaximumDurationInSeconds); got != 28800 {
364 t.Errorf("maximumDurationInSeconds = %d, want 28800", got)
365 }
366 })
367
368 t.Run("same attempt sends the same request", func(t *testing.T) {
369 s := &stub{}
370 r := newTestRunner(t, s)
371 for range 2 {
372 if _, err := r.Launch(context.Background(), testSpec()); err != nil {
373 t.Fatalf("Launch = %v", err)
374 }
375 }
376 if !reflect.DeepEqual(*s.runIn[0], *s.runIn[1]) {
377 t.Errorf("second request %+v differs from first %+v", *s.runIn[1], *s.runIn[0])
378 }
379 })
380
381 for name, change := range map[string]func(*isolatedjob.LaunchSpec, *Config){
382 "unmapped digest": func(s *isolatedjob.LaunchSpec, _ *Config) { s.Image = otherDigest },
383 "size with no version": func(_ *isolatedjob.LaunchSpec, c *Config) {
384 delete(c.Images[testDigest].Versions, isolatedjob.SizeLarge)
385 },
386 "spec invalid": func(s *isolatedjob.LaunchSpec, _ *Config) { s.AttemptID = "" },
387 "bootstrap with invalid UTF-8": func(s *isolatedjob.LaunchSpec, _ *Config) {
388 s.Bootstrap = []byte("code-\xff-end")
389 },
390 "bootstrap with valid non-ASCII UTF-8": func(s *isolatedjob.LaunchSpec, _ *Config) {
391 s.Bootstrap = []byte("code-é")
392 },
393 } {
394 t.Run(name, func(t *testing.T) {
395 s := &stub{}
396 c := testConfig()
397 spec := testSpec()
398 spec.Size = isolatedjob.SizeLarge
399 change(&spec, &c)
400 r, err := New(c, s)
401 if err != nil {
402 t.Fatalf("New = %v", err)
403 }
404 ref, err := r.Launch(context.Background(), spec)
405 if !errors.Is(err, isolatedjob.ErrInvalid) {
406 t.Errorf("Launch = (%q, %v), want ErrInvalid", ref, err)
407 }
408 if len(s.calls) != 0 {
409 t.Errorf("API calls %v, want none before the refusal", s.calls)
410 }
411 })
412 }
413
414 t.Run("oversize bootstrap", func(t *testing.T) {
415 s := &stub{}
416 spec := testSpec()
417 spec.Bootstrap = bytes.Repeat([]byte("x"), 4097)
418 if _, err := newTestRunner(t, s).Launch(context.Background(), spec); !errors.Is(err, isolatedjob.ErrBootstrapTooLarge) {
419 t.Errorf("Launch = %v, want ErrBootstrapTooLarge", err)
420 }
421 if len(s.calls) != 0 {
422 t.Errorf("API calls %v, want none", s.calls)
423 }
424 })
425
426 t.Run("no microvm id in the reply", func(t *testing.T) {
427 s := &stub{run: func(*vms.RunMicrovmInput) (*vms.RunMicrovmOutput, error) { return &vms.RunMicrovmOutput{}, nil }}
428 if ref, err := newTestRunner(t, s).Launch(context.Background(), testSpec()); err == nil {
429 t.Errorf("Launch = %q, nil; want an error for a reply with no id", ref)
430 }
431 })
432}
433
434// TestPayloadThroughSDK sends a bootstrap holding every ASCII byte through
435// the real lambdamicrovms serializer, over a transport that never leaves
436// the process, and checks the JSON body AWS would receive carries it byte
437// for byte, with the attempt as client token.
438func TestPayloadThroughSDK(t *testing.T) {
439 var body []byte
440 client := vms.New(vms.Options{
441 Region: "eu-west-1",
442 Credentials: aws.AnonymousCredentials{},
443 HTTPClient: doFunc(func(r *http.Request) (*http.Response, error) {
444 reply := `{"additionalOsCapabilities":["ALL"],"cpuConfigurations":[{"architecture":"X86_64"}],"resources":[{"minimumMemoryInMiB":2048}]}`
445 if r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/microvms") {
446 b, err := io.ReadAll(r.Body)
447 if err != nil {
448 return nil, err
449 }
450 body = b
451 reply = `{"microvmId":"vm-sdk","state":"PENDING"}`
452 }
453 h := http.Header{}
454 h.Set("Content-Type", "application/json")
455 return &http.Response{StatusCode: 200, Header: h, Body: io.NopCloser(strings.NewReader(reply)), Request: r}, nil
456 }),
457 })
458 r, err := New(testConfig(), NewAPI(client, &stub{}, &stub{}))
459 if err != nil {
460 t.Fatalf("New = %v", err)
461 }
462 spec := testSpec()
463 spec.Bootstrap = make([]byte, 0x80)
464 for i := range spec.Bootstrap {
465 spec.Bootstrap[i] = byte(i)
466 }
467 ref, err := r.Launch(context.Background(), spec)
468 if err != nil || ref != "vm-sdk" {
469 t.Fatalf("Launch = %q, %v; want vm-sdk", ref, err)
470 }
471 var sent struct {
472 ClientToken string `json:"clientToken"`
473 RunHookPayload string `json:"runHookPayload"`
474 }
475 if err := json.Unmarshal(body, &sent); err != nil {
476 t.Fatalf("run request body %q: %v", body, err)
477 }
478 if !bytes.Equal([]byte(sent.RunHookPayload), spec.Bootstrap) {
479 t.Errorf("runHookPayload on the wire = %q, want %q byte for byte", sent.RunHookPayload, spec.Bootstrap)
480 }
481 if sent.ClientToken != spec.AttemptID {
482 t.Errorf("clientToken on the wire = %q, want %q", sent.ClientToken, spec.AttemptID)
483 }
484}
485
486type doFunc func(*http.Request) (*http.Response, error)
487
488func (f doFunc) Do(r *http.Request) (*http.Response, error) { return f(r) }
489
490func TestImageVersionChecked(t *testing.T) {
491 rows := []struct {
492 name string
493 change func(*vms.GetMicrovmImageVersionOutput)
494 pass bool
495 }{
496 {"passing", func(*vms.GetMicrovmImageVersionOutput) {}, true},
497 {"capabilities missing", func(o *vms.GetMicrovmImageVersionOutput) { o.AdditionalOsCapabilities = nil }, false},
498 {"capabilities twice", func(o *vms.GetMicrovmImageVersionOutput) {
499 o.AdditionalOsCapabilities = []types.Capability{types.CapabilityAll, types.CapabilityAll}
500 }, false},
501 {"capability unknown", func(o *vms.GetMicrovmImageVersionOutput) {
502 o.AdditionalOsCapabilities = []types.Capability{"NET_ADMIN"}
503 }, false},
504 {"cpu ARM_64", func(o *vms.GetMicrovmImageVersionOutput) {
505 o.CpuConfigurations = []types.CpuConfiguration{{Architecture: types.ArchitectureArm64}}
506 }, false},
507 {"cpu missing", func(o *vms.GetMicrovmImageVersionOutput) { o.CpuConfigurations = nil }, false},
508 {"cpu both", func(o *vms.GetMicrovmImageVersionOutput) {
509 o.CpuConfigurations = []types.CpuConfiguration{{Architecture: types.ArchitectureX8664}, {Architecture: types.ArchitectureArm64}}
510 }, false},
511 {"memory of the other size", func(o *vms.GetMicrovmImageVersionOutput) { o.Resources[0].MinimumMemoryInMiB = aws.Int32(4096) }, false},
512 {"memory missing", func(o *vms.GetMicrovmImageVersionOutput) { o.Resources = nil }, false},
513 {"memory unset", func(o *vms.GetMicrovmImageVersionOutput) { o.Resources[0].MinimumMemoryInMiB = nil }, false},
514 }
515 for _, row := range rows {
516 t.Run(row.name, func(t *testing.T) {
517 s := &stub{version: func(*vms.GetMicrovmImageVersionInput) (*vms.GetMicrovmImageVersionOutput, error) {
518 o := goodVersion(2048)
519 row.change(o)
520 return o, nil
521 }}
522 r := newTestRunner(t, s)
523 _, err := r.Launch(context.Background(), testSpec())
524 if row.pass {
525 if err != nil {
526 t.Fatalf("Launch = %v, want nil", err)
527 }
528 in := s.verIn[0]
529 if aws.ToString(in.ImageIdentifier) != testImageARN || aws.ToString(in.ImageVersion) != smallVersion {
530 t.Errorf("image version read %q/%q, want %q/%q", aws.ToString(in.ImageIdentifier), aws.ToString(in.ImageVersion), testImageARN, smallVersion)
531 }
532 return
533 }
534 if !errors.Is(err, isolatedjob.ErrInvalid) {
535 t.Errorf("Launch = %v, want ErrInvalid", err)
536 }
537 if n := s.count("RunMicrovm"); n != 0 {
538 t.Errorf("RunMicrovm called %d times after a failed image check, want 0", n)
539 }
540 })
541 }
542
543 t.Run("a pass is cached per version", func(t *testing.T) {
544 s := &stub{}
545 r := newTestRunner(t, s)
546 for range 3 {
547 if _, err := r.Launch(context.Background(), testSpec()); err != nil {
548 t.Fatalf("Launch = %v", err)
549 }
550 }
551 if n := s.count("GetMicrovmImageVersion"); n != 1 {
552 t.Errorf("GetMicrovmImageVersion called %d times for one version, want 1", n)
553 }
554 large := testSpec()
555 large.Size = isolatedjob.SizeLarge
556 if _, err := r.Launch(context.Background(), large); err != nil {
557 t.Fatalf("Launch(large) = %v", err)
558 }
559 if n := s.count("GetMicrovmImageVersion"); n != 2 {
560 t.Errorf("GetMicrovmImageVersion called %d times for two versions, want 2", n)
561 }
562 })
563
564 t.Run("a failure is not cached", func(t *testing.T) {
565 bad := true
566 s := &stub{version: func(*vms.GetMicrovmImageVersionInput) (*vms.GetMicrovmImageVersionOutput, error) {
567 if bad {
568 return goodVersion(4096), nil
569 }
570 return goodVersion(2048), nil
571 }}
572 r := newTestRunner(t, s)
573 if _, err := r.Launch(context.Background(), testSpec()); !errors.Is(err, isolatedjob.ErrInvalid) {
574 t.Fatalf("first Launch = %v, want ErrInvalid", err)
575 }
576 bad = false
577 if _, err := r.Launch(context.Background(), testSpec()); err != nil {
578 t.Fatalf("second Launch after the version was fixed = %v, want nil", err)
579 }
580 })
581
582 t.Run("one version mapped to both sizes", func(t *testing.T) {
583 s := &stub{}
584 c := testConfig()
585 c.Images[testDigest].Versions[isolatedjob.SizeLarge] = smallVersion
586 r, err := New(c, s)
587 if err != nil {
588 t.Fatalf("New = %v", err)
589 }
590 if _, err := r.Launch(context.Background(), testSpec()); err != nil {
591 t.Fatalf("Launch(small) = %v", err)
592 }
593 large := testSpec()
594 large.Size = isolatedjob.SizeLarge
595 if _, err := r.Launch(context.Background(), large); !errors.Is(err, isolatedjob.ErrInvalid) {
596 t.Errorf("Launch(large) on the cached 2048 MiB version = %v, want ErrInvalid", err)
597 }
598 })
599
600 t.Run("version read fails", func(t *testing.T) {
601 s := &stub{version: func(*vms.GetMicrovmImageVersionInput) (*vms.GetMicrovmImageVersionOutput, error) {
602 return nil, &types.ThrottlingException{Message: aws.String("slow down")}
603 }}
604 if _, err := newTestRunner(t, s).Launch(context.Background(), testSpec()); !errors.Is(err, isolatedjob.ErrThrottled) {
605 t.Errorf("Launch = %v, want ErrThrottled", err)
606 }
607 if n := s.count("RunMicrovm"); n != 0 {
608 t.Errorf("RunMicrovm called %d times, want 0", n)
609 }
610 })
611}
612
613func TestStateMapping(t *testing.T) {
614 rows := []struct {
615 raw types.MicrovmState
616 reason *string
617 want isolatedjob.State
618 inWhy string
619 }{
620 {types.MicrovmStatePending, nil, isolatedjob.StateStarting, ""},
621 {types.MicrovmStateRunning, nil, isolatedjob.StateRunning, ""},
622 {types.MicrovmStateSuspending, nil, isolatedjob.StateSuspending, ""},
623 {types.MicrovmStateSuspended, nil, isolatedjob.StateSuspended, ""},
624 {types.MicrovmStateTerminating, nil, isolatedjob.StateStopping, ""},
625 {types.MicrovmStateTerminated, aws.String("run hook timed out"), isolatedjob.StateStopped, "run hook timed out"},
626 {"HIBERNATING", nil, isolatedjob.StateUnknown, "HIBERNATING"},
627 {"FAILED", aws.String("host lost"), isolatedjob.StateUnknown, "FAILED"},
628 {"", nil, isolatedjob.StateUnknown, `""`},
629 }
630 for _, row := range rows {
631 t.Run(string(row.raw), func(t *testing.T) {
632 s := &stub{get: func(in *vms.GetMicrovmInput) (*vms.GetMicrovmOutput, error) {
633 return &vms.GetMicrovmOutput{MicrovmId: in.MicrovmIdentifier, State: row.raw, StateReason: row.reason}, nil
634 }}
635 job, err := newTestRunner(t, s).Get(context.Background(), "vm-1")
636 if err != nil {
637 t.Fatalf("Get = %v", err)
638 }
639 if job.State != row.want {
640 t.Errorf("Get(%s).State = %s, want %s", row.raw, job.State, row.want)
641 }
642 if job.Ref != "vm-1" {
643 t.Errorf("Get.Ref = %q, want vm-1", job.Ref)
644 }
645 if !strings.Contains(job.Reason, row.inWhy) {
646 t.Errorf("Get(%s).Reason = %q, want it to hold %q", row.raw, job.Reason, row.inWhy)
647 }
648 })
649 }
650}
651
652// serverMeta returns response metadata carrying the server time at, as the
653// SDK's own middleware records it from a Date header. The metadata key is
654// unexported, so a real client answers one canned response through a
655// transport that never leaves the process.
656func serverMeta(t *testing.T, at time.Time) middleware.Metadata {
657 t.Helper()
658 client := vms.New(vms.Options{
659 Region: "eu-west-1",
660 Credentials: aws.AnonymousCredentials{},
661 HTTPClient: dateTransport{at},
662 })
663 out, err := client.GetMicrovm(context.Background(), &vms.GetMicrovmInput{MicrovmIdentifier: aws.String("vm-meta")})
664 if err != nil {
665 t.Fatalf("canned GetMicrovm: %v", err)
666 }
667 if got, ok := awsmiddleware.GetServerTime(out.ResultMetadata); !ok || !got.Equal(at) {
668 t.Fatalf("canned metadata server time = %v, %v; want %v", got, ok, at)
669 }
670 return out.ResultMetadata
671}
672
673type dateTransport struct{ at time.Time }
674
675func (d dateTransport) Do(r *http.Request) (*http.Response, error) {
676 h := http.Header{}
677 h.Set("Content-Type", "application/json")
678 h.Set("Date", d.at.UTC().Format(http.TimeFormat))
679 return &http.Response{StatusCode: 200, Header: h, Body: io.NopCloser(strings.NewReader("{}")), Request: r}, nil
680}
681
682func TestProviderAge(t *testing.T) {
683 started := time.Date(2026, 1, 2, 10, 0, 0, 0, time.UTC)
684 server := started.Add(90 * time.Second)
685 meta := serverMeta(t, server)
686
687 rows := []struct {
688 name string
689 started *time.Time
690 meta middleware.Metadata
691 age time.Duration
692 known bool
693 }{
694 {"both present", &started, meta, 90 * time.Second, true},
695 {"no server time", &started, middleware.Metadata{}, 0, false},
696 {"no start time", nil, meta, 0, false},
697 {"start after server time", aws.Time(server.Add(time.Minute)), meta, 0, false},
698 }
699 for _, row := range rows {
700 t.Run("get "+row.name, func(t *testing.T) {
701 s := &stub{get: func(in *vms.GetMicrovmInput) (*vms.GetMicrovmOutput, error) {
702 return &vms.GetMicrovmOutput{MicrovmId: in.MicrovmIdentifier, State: types.MicrovmStateRunning, StartedAt: row.started, ResultMetadata: row.meta}, nil
703 }}
704 job, err := newTestRunner(t, s).Get(context.Background(), "vm-1")
705 if err != nil {
706 t.Fatalf("Get = %v", err)
707 }
708 if job.ProviderAge != row.age || job.AgeKnown != row.known {
709 t.Errorf("Get = age %v known %v, want age %v known %v", job.ProviderAge, job.AgeKnown, row.age, row.known)
710 }
711 if row.started != nil && !job.StartedAt.Equal(*row.started) {
712 t.Errorf("Get.StartedAt = %v, want %v", job.StartedAt, *row.started)
713 }
714 })
715 t.Run("list "+row.name, func(t *testing.T) {
716 s := &stub{list: func(*vms.ListMicrovmsInput) (*vms.ListMicrovmsOutput, error) {
717 return &vms.ListMicrovmsOutput{
718 Items: []types.MicrovmItem{{MicrovmId: aws.String("vm-1"), ImageArn: aws.String(testImageARN),
719 State: types.MicrovmStateRunning, StartedAt: row.started}},
720 ResultMetadata: row.meta,
721 }, nil
722 }}
723 jobs, err := newTestRunner(t, s).List(context.Background())
724 if err != nil || len(jobs) != 1 {
725 t.Fatalf("List = %v, %v; want one job", jobs, err)
726 }
727 if jobs[0].ProviderAge != row.age || jobs[0].AgeKnown != row.known {
728 t.Errorf("List = age %v known %v, want age %v known %v", jobs[0].ProviderAge, jobs[0].AgeKnown, row.age, row.known)
729 }
730 })
731 }
732}
733
734var sentinels = []error{isolatedjob.ErrNotFound, isolatedjob.ErrInvalid, isolatedjob.ErrConflict,
735 isolatedjob.ErrThrottled, isolatedjob.ErrIncomplete, isolatedjob.ErrBootstrapTooLarge}
736
737func TestErrorMapping(t *testing.T) {
738 notFound := &types.ResourceNotFoundException{Message: aws.String("gone")}
739 conflict := &types.ConflictException{Message: aws.String("state")}
740 throttle := &types.ThrottlingException{Message: aws.String("slow")}
741 tooMany := &types.TooManyRequestsException{Message: aws.String("slow")}
742 quota := &types.ServiceQuotaExceededException{Message: aws.String("quota")}
743 validation := &types.ValidationException{Message: aws.String("bad")}
744 denied := &types.AccessDeniedException{Message: aws.String("no")}
745 internal := &types.InternalServerException{Message: aws.String("oops")}
746 capacity := &types.InsufficientCapacityException{Message: aws.String("full")}
747 generic := &smithy.GenericAPIError{Code: "SomethingNew", Message: "new"}
748 params := &smithy.InvalidParamsError{Context: "GetMicrovmInput"}
749
750 ops := map[string]func(*Runner, error) error{
751 "launch": func(r *Runner, e error) error {
752 r.api.(*stub).run = func(*vms.RunMicrovmInput) (*vms.RunMicrovmOutput, error) { return nil, e }
753 _, err := r.Launch(context.Background(), testSpec())
754 return err
755 },
756 "get": func(r *Runner, e error) error {
757 r.api.(*stub).get = func(*vms.GetMicrovmInput) (*vms.GetMicrovmOutput, error) { return nil, e }
758 _, err := r.Get(context.Background(), "vm-1")
759 return err
760 },
761 "suspend": func(r *Runner, e error) error {
762 r.api.(*stub).suspend = func(*vms.SuspendMicrovmInput) (*vms.SuspendMicrovmOutput, error) { return nil, e }
763 return r.Suspend(context.Background(), "vm-1")
764 },
765 "resume": func(r *Runner, e error) error {
766 r.api.(*stub).resume = func(*vms.ResumeMicrovmInput) (*vms.ResumeMicrovmOutput, error) { return nil, e }
767 return r.Resume(context.Background(), "vm-1")
768 },
769 "stop": func(r *Runner, e error) error {
770 r.api.(*stub).terminate = func(*vms.TerminateMicrovmInput) (*vms.TerminateMicrovmOutput, error) { return nil, e }
771 return r.Stop(context.Background(), "vm-1", "test")
772 },
773 }
774 rows := []struct {
775 op string
776 err error
777 want error // nil with none: no sentinel; errNone: the call succeeds
778 }{
779 {"get", notFound, isolatedjob.ErrNotFound},
780 {"suspend", notFound, isolatedjob.ErrNotFound},
781 {"resume", notFound, isolatedjob.ErrNotFound},
782 {"stop", notFound, errNone},
783 {"launch", throttle, isolatedjob.ErrThrottled},
784 {"launch", tooMany, isolatedjob.ErrThrottled},
785 {"launch", quota, isolatedjob.ErrThrottled},
786 {"get", throttle, isolatedjob.ErrThrottled},
787 {"stop", throttle, isolatedjob.ErrThrottled},
788 {"launch", validation, isolatedjob.ErrInvalid},
789 {"get", validation, isolatedjob.ErrInvalid},
790 {"get", params, isolatedjob.ErrInvalid},
791 {"launch", conflict, isolatedjob.ErrConflict},
792 {"suspend", conflict, isolatedjob.ErrConflict},
793 {"stop", conflict, isolatedjob.ErrConflict},
794 {"launch", denied, nil},
795 {"launch", internal, nil},
796 {"launch", capacity, nil},
797 {"get", generic, nil},
798 {"stop", denied, nil},
799 }
800 for _, row := range rows {
801 t.Run(row.op+" "+errorName(row.err), func(t *testing.T) {
802 r := newTestRunner(t, &stub{})
803 err := ops[row.op](r, row.err)
804 switch {
805 case row.want == errNone:
806 if err != nil {
807 t.Fatalf("%s = %v, want nil", row.op, err)
808 }
809 case row.want == nil:
810 if err == nil {
811 t.Fatalf("%s = nil, want an error", row.op)
812 }
813 for _, s := range sentinels {
814 if errors.Is(err, s) {
815 t.Errorf("%s = %v, matches %v; want no sentinel", row.op, err, s)
816 }
817 }
818 default:
819 if !errors.Is(err, row.want) {
820 t.Errorf("%s = %v, want %v", row.op, err, row.want)
821 }
822 }
823 if err != nil && !errors.Is(err, row.err) {
824 t.Errorf("%s = %v, lost the provider error %v", row.op, err, row.err)
825 }
826 })
827 }
828}
829
830// TestClientTokenReuseConflicts pins the one ValidationException that
831// means ErrConflict: RunMicrovm's answer to a client token reused with
832// different request parameters (Task 17 attempt 4, live). Every other
833// ValidationException, the payload limit included, stays ErrInvalid, and
834// the same text on another operation is not reinterpreted.
835func TestClientTokenReuseConflicts(t *testing.T) {
836 const live = "The provided clientToken was used with different request parameters."
837 rows := []struct {
838 name string
839 op string
840 msg string
841 nilMsg bool
842 wrapped bool
843 want error
844 }{
845 {name: "launch token reuse", op: "launch", msg: live, want: isolatedjob.ErrConflict},
846 {name: "launch token reuse wrapped", op: "launch", msg: live, wrapped: true, want: isolatedjob.ErrConflict},
847 {name: "launch payload limit", op: "launch", msg: "Payload size exceeds the maximum allowed size of 4096 bytes.", want: isolatedjob.ErrInvalid},
848 {name: "launch other validation", op: "launch", msg: "1 validation error detected: Value at 'maxDurationInSeconds' failed to satisfy constraint", want: isolatedjob.ErrInvalid},
849 {name: "launch empty message", op: "launch", msg: "", want: isolatedjob.ErrInvalid},
850 {name: "launch nil message", op: "launch", nilMsg: true, want: isolatedjob.ErrInvalid},
851 {name: "get same text", op: "get", msg: live, want: isolatedjob.ErrInvalid},
852 }
853 for _, row := range rows {
854 t.Run(row.name, func(t *testing.T) {
855 e := &types.ValidationException{Message: aws.String(row.msg)}
856 if row.nilMsg {
857 e.Message = nil
858 }
859 var sent error = e
860 if row.wrapped {
861 sent = &smithy.OperationError{ServiceID: "Lambda Microvms", OperationName: "RunMicrovm", Err: fmt.Errorf("https response error: %w", e)}
862 }
863 stub := &stub{}
864 r := newTestRunner(t, stub)
865 var err error
866 switch row.op {
867 case "launch":
868 stub.run = func(*vms.RunMicrovmInput) (*vms.RunMicrovmOutput, error) { return nil, sent }
869 _, err = r.Launch(context.Background(), testSpec())
870 case "get":
871 stub.get = func(*vms.GetMicrovmInput) (*vms.GetMicrovmOutput, error) { return nil, sent }
872 _, err = r.Get(context.Background(), "vm-1")
873 }
874 if !errors.Is(err, row.want) {
875 t.Fatalf("%s with %q = %v, want %v", row.op, row.msg, err, row.want)
876 }
877 for _, s := range sentinels {
878 if s != row.want && errors.Is(err, s) {
879 t.Errorf("%s with %q = %v, also matches %v", row.op, row.msg, err, s)
880 }
881 }
882 if !errors.Is(err, e) {
883 t.Errorf("%s = %v, lost the provider error", row.op, err)
884 }
885 })
886 }
887}
888
889var errNone = errors.New("no error")
890
891func errorName(err error) string {
892 var api smithy.APIError
893 if errors.As(err, &api) {
894 return api.ErrorCode()
895 }
896 return reflect.TypeOf(err).Elem().Name()
897}
898
899func TestResumeConflict(t *testing.T) {
900 conflict := &types.ConflictException{Message: aws.String("not suspended")}
901 rows := []struct {
902 name string
903 get func(*vms.GetMicrovmInput) (*vms.GetMicrovmOutput, error)
904 ok bool
905 }{
906 {"running is a no-op", func(in *vms.GetMicrovmInput) (*vms.GetMicrovmOutput, error) {
907 return &vms.GetMicrovmOutput{MicrovmId: in.MicrovmIdentifier, State: types.MicrovmStateRunning}, nil
908 }, true},
909 {"suspended conflicts", func(in *vms.GetMicrovmInput) (*vms.GetMicrovmOutput, error) {
910 return &vms.GetMicrovmOutput{MicrovmId: in.MicrovmIdentifier, State: types.MicrovmStateSuspended}, nil
911 }, false},
912 {"terminating conflicts", func(in *vms.GetMicrovmInput) (*vms.GetMicrovmOutput, error) {
913 return &vms.GetMicrovmOutput{MicrovmId: in.MicrovmIdentifier, State: types.MicrovmStateTerminating}, nil
914 }, false},
915 {"unreadable conflicts", func(*vms.GetMicrovmInput) (*vms.GetMicrovmOutput, error) {
916 return nil, &types.ThrottlingException{Message: aws.String("slow")}
917 }, false},
918 }
919 for _, row := range rows {
920 t.Run(row.name, func(t *testing.T) {
921 s := &stub{
922 resume: func(*vms.ResumeMicrovmInput) (*vms.ResumeMicrovmOutput, error) { return nil, conflict },
923 get: row.get,
924 }
925 err := newTestRunner(t, s).Resume(context.Background(), "vm-1")
926 if row.ok && err != nil {
927 t.Errorf("Resume = %v, want nil", err)
928 }
929 if !row.ok && !errors.Is(err, isolatedjob.ErrConflict) {
930 t.Errorf("Resume = %v, want ErrConflict", err)
931 }
932 if n := s.count("GetMicrovm"); n != 1 {
933 t.Errorf("GetMicrovm called %d times, want exactly 1", n)
934 }
935 })
936 }
937
938 t.Run("success reads nothing", func(t *testing.T) {
939 s := &stub{}
940 if err := newTestRunner(t, s).Resume(context.Background(), "vm-1"); err != nil {
941 t.Fatalf("Resume = %v", err)
942 }
943 if n := s.count("GetMicrovm"); n != 0 {
944 t.Errorf("GetMicrovm called %d times after a clean resume, want 0", n)
945 }
946 })
947}
948
949func TestRequestsNameTheRef(t *testing.T) {
950 var ids []string
951 s := &stub{
952 get: func(in *vms.GetMicrovmInput) (*vms.GetMicrovmOutput, error) {
953 ids = append(ids, aws.ToString(in.MicrovmIdentifier))
954 return &vms.GetMicrovmOutput{MicrovmId: in.MicrovmIdentifier, State: types.MicrovmStateRunning}, nil
955 },
956 suspend: func(in *vms.SuspendMicrovmInput) (*vms.SuspendMicrovmOutput, error) {
957 ids = append(ids, aws.ToString(in.MicrovmIdentifier))
958 return &vms.SuspendMicrovmOutput{}, nil
959 },
960 resume: func(in *vms.ResumeMicrovmInput) (*vms.ResumeMicrovmOutput, error) {
961 ids = append(ids, aws.ToString(in.MicrovmIdentifier))
962 return &vms.ResumeMicrovmOutput{}, nil
963 },
964 terminate: func(in *vms.TerminateMicrovmInput) (*vms.TerminateMicrovmOutput, error) {
965 ids = append(ids, aws.ToString(in.MicrovmIdentifier))
966 return &vms.TerminateMicrovmOutput{}, nil
967 },
968 }
969 r := newTestRunner(t, s)
970 ctx := context.Background()
971 if _, err := r.Get(ctx, "vm-a"); err != nil {
972 t.Fatal(err)
973 }
974 if err := r.Suspend(ctx, "vm-b"); err != nil {
975 t.Fatal(err)
976 }
977 if err := r.Resume(ctx, "vm-c"); err != nil {
978 t.Fatal(err)
979 }
980 if err := r.Stop(ctx, "vm-d", "done"); err != nil {
981 t.Fatal(err)
982 }
983 if want := []string{"vm-a", "vm-b", "vm-c", "vm-d"}; !reflect.DeepEqual(ids, want) {
984 t.Errorf("identifiers sent = %q, want %q", ids, want)
985 }
986 for _, call := range []func() error{
987 func() error { _, err := r.Get(ctx, ""); return err },
988 func() error { return r.Suspend(ctx, "") },
989 func() error { return r.Resume(ctx, "") },
990 func() error { return r.Stop(ctx, "", "x") },
991 } {
992 if err := call(); !errors.Is(err, isolatedjob.ErrInvalid) {
993 t.Errorf("call with an empty ref = %v, want ErrInvalid", err)
994 }
995 }
996}
997
998func TestListAllPages(t *testing.T) {
999 item := func(id string) types.MicrovmItem {
1000 return types.MicrovmItem{MicrovmId: aws.String(id), ImageArn: aws.String(testImageARN), State: types.MicrovmStateRunning,
1001 StartedAt: aws.Time(time.Unix(1_800_000_000, 0))}
1002 }
1003 t.Run("three pages", func(t *testing.T) {
1004 var tokens []string
1005 pages := map[string]*vms.ListMicrovmsOutput{
1006 "": {Items: []types.MicrovmItem{item("vm-1"), item("vm-2")}, NextToken: aws.String("t2")},
1007 "t2": {Items: []types.MicrovmItem{item("vm-3")}, NextToken: aws.String("t3")},
1008 "t3": {Items: []types.MicrovmItem{{MicrovmId: aws.String("vm-4"), ImageArn: aws.String(testImageARN), State: "NEW"}}},
1009 }
1010 s := &stub{list: func(in *vms.ListMicrovmsInput) (*vms.ListMicrovmsOutput, error) {
1011 tokens = append(tokens, aws.ToString(in.NextToken))
1012 if aws.ToInt32(in.MaxResults) != 50 {
1013 t.Errorf("maxResults = %d, want 50", aws.ToInt32(in.MaxResults))
1014 }
1015 if aws.ToString(in.ImageIdentifier) != testImageARN || in.ImageVersion != nil {
1016 t.Errorf("list filtered by image %v/%v, want the configured image %s and any version", in.ImageIdentifier, in.ImageVersion, testImageARN)
1017 }
1018 return pages[aws.ToString(in.NextToken)], nil
1019 }}
1020 jobs, err := newTestRunner(t, s).List(context.Background())
1021 if err != nil {
1022 t.Fatalf("List = %v", err)
1023 }
1024 var refs []isolatedjob.Ref
1025 for _, j := range jobs {
1026 refs = append(refs, j.Ref)
1027 }
1028 if want := []isolatedjob.Ref{"vm-1", "vm-2", "vm-3", "vm-4"}; !reflect.DeepEqual(refs, want) {
1029 t.Errorf("List refs = %v, want %v", refs, want)
1030 }
1031 if want := []string{"", "t2", "t3"}; !reflect.DeepEqual(tokens, want) {
1032 t.Errorf("tokens sent = %q, want %q", tokens, want)
1033 }
1034 if jobs[3].State != isolatedjob.StateUnknown || !strings.Contains(jobs[3].Reason, "NEW") {
1035 t.Errorf("vm-4 = %s %q, want unknown naming NEW", jobs[3].State, jobs[3].Reason)
1036 }
1037 })
1038
1039 failing := map[string]func(in *vms.ListMicrovmsInput) (*vms.ListMicrovmsOutput, error){
1040 "page two fails": func(in *vms.ListMicrovmsInput) (*vms.ListMicrovmsOutput, error) {
1041 if in.NextToken == nil {
1042 return &vms.ListMicrovmsOutput{Items: []types.MicrovmItem{item("vm-1")}, NextToken: aws.String("t2")}, nil
1043 }
1044 return nil, &types.InternalServerException{Message: aws.String("oops")}
1045 },
1046 "page one fails": func(*vms.ListMicrovmsInput) (*vms.ListMicrovmsOutput, error) {
1047 return nil, &types.ThrottlingException{Message: aws.String("slow")}
1048 },
1049 "token repeats": func(*vms.ListMicrovmsInput) (*vms.ListMicrovmsOutput, error) {
1050 return &vms.ListMicrovmsOutput{Items: []types.MicrovmItem{item("vm-1")}, NextToken: aws.String("same")}, nil
1051 },
1052 "item without an id": func(*vms.ListMicrovmsInput) (*vms.ListMicrovmsOutput, error) {
1053 return &vms.ListMicrovmsOutput{Items: []types.MicrovmItem{item("vm-1"),
1054 {ImageArn: aws.String(testImageARN), State: types.MicrovmStateRunning}}}, nil
1055 },
1056 }
1057 for name, list := range failing {
1058 t.Run(name, func(t *testing.T) {
1059 jobs, err := newTestRunner(t, &stub{list: list}).List(context.Background())
1060 if !errors.Is(err, isolatedjob.ErrIncomplete) {
1061 t.Errorf("List = %v, want ErrIncomplete", err)
1062 }
1063 if jobs != nil {
1064 t.Errorf("List returned %d jobs with an error, want none", len(jobs))
1065 }
1066 })
1067 }
1068}
1069
1070// TestListOnlyConfiguredImages (ruling R32): the account may be shared, and
1071// the reaper stops every listed VM no job owns, so List asks for each
1072// configured image ARN in turn and never returns a VM from another image,
1073// even from a provider that ignores the filter.
1074func TestListOnlyConfiguredImages(t *testing.T) {
1075 const otherARN = "arn:aws:lambda:eu-west-1:123456789012:microvm-image:another-team"
1076 const secondARN = "arn:aws:lambda:eu-west-1:123456789012:microvm-image:zz-second"
1077 secondDigest := isolatedjob.ImageDigest("sha256:" + strings.Repeat("e", 64))
1078 cfg := testConfig()
1079 cfg.Images[secondDigest] = Image{ARN: secondARN, Versions: map[isolatedjob.Size]string{isolatedjob.SizeSmall: "1"}}
1080 item := func(id, arn string) types.MicrovmItem {
1081 return types.MicrovmItem{MicrovmId: aws.String(id), ImageArn: aws.String(arn), State: types.MicrovmStateRunning}
1082 }
1083 // account holds every VM in the account, by image, two pages each.
1084 account := map[string][2][]types.MicrovmItem{
1085 testImageARN: {{item("vm-a1", testImageARN)}, {item("vm-a2", testImageARN)}},
1086 secondARN: {{item("vm-b1", secondARN)}, {item("vm-b2", secondARN)}},
1087 otherARN: {{item("vm-x1", otherARN)}, {item("vm-x2", otherARN)}},
1088 }
1089 // serve answers like ListMicrovms: the image filter when set, every
1090 // image when not. ignoreFilter plays a provider that drops the filter.
1091 serve := func(in *vms.ListMicrovmsInput, ignoreFilter bool) *vms.ListMicrovmsOutput {
1092 page := 0
1093 if aws.ToString(in.NextToken) != "" {
1094 page = 1
1095 }
1096 out := &vms.ListMicrovmsOutput{}
1097 for _, arn := range []string{testImageARN, secondARN, otherARN} {
1098 if ignoreFilter || in.ImageIdentifier == nil || aws.ToString(in.ImageIdentifier) == arn {
1099 out.Items = append(out.Items, account[arn][page]...)
1100 }
1101 }
1102 if page == 0 {
1103 out.NextToken = aws.String("p2")
1104 }
1105 return out
1106 }
1107 refs := func(jobs []isolatedjob.Job) []isolatedjob.Ref {
1108 var out []isolatedjob.Ref
1109 for _, j := range jobs {
1110 out = append(out, j.Ref)
1111 }
1112 slices.Sort(out)
1113 return out
1114 }
1115 want := []isolatedjob.Ref{"vm-a1", "vm-a2", "vm-b1", "vm-b2"}
1116
1117 for _, ignore := range []bool{false, true} {
1118 t.Run(fmt.Sprintf("provider ignores the filter %v", ignore), func(t *testing.T) {
1119 var asked []string
1120 s := &stub{list: func(in *vms.ListMicrovmsInput) (*vms.ListMicrovmsOutput, error) {
1121 asked = append(asked, aws.ToString(in.ImageIdentifier)+" "+aws.ToString(in.NextToken))
1122 return serve(in, ignore), nil
1123 }}
1124 r, err := New(cfg, s)
1125 if err != nil {
1126 t.Fatal(err)
1127 }
1128 jobs, err := r.List(context.Background())
1129 if err != nil {
1130 t.Fatalf("List = %v", err)
1131 }
1132 if got := refs(jobs); !reflect.DeepEqual(got, want) {
1133 t.Errorf("List refs = %v, want %v: only VMs from the configured images", got, want)
1134 }
1135 wantAsked := []string{testImageARN + " ", testImageARN + " p2", secondARN + " ", secondARN + " p2"}
1136 if !reflect.DeepEqual(asked, wantAsked) {
1137 t.Errorf("ListMicrovms calls (image, token) = %q, want %q", asked, wantAsked)
1138 }
1139 })
1140 }
1141
1142 t.Run("page error on the second image", func(t *testing.T) {
1143 s := &stub{list: func(in *vms.ListMicrovmsInput) (*vms.ListMicrovmsOutput, error) {
1144 if aws.ToString(in.ImageIdentifier) == secondARN && aws.ToString(in.NextToken) != "" {
1145 return nil, &types.InternalServerException{Message: aws.String("oops")}
1146 }
1147 return serve(in, false), nil
1148 }}
1149 r, err := New(cfg, s)
1150 if err != nil {
1151 t.Fatal(err)
1152 }
1153 jobs, err := r.List(context.Background())
1154 if !errors.Is(err, isolatedjob.ErrIncomplete) || jobs != nil {
1155 t.Errorf("List = %v, %v; want no jobs and ErrIncomplete", refs(jobs), err)
1156 }
1157 })
1158}
1159
1160type snsStub struct {
1161 in []*sns.PublishInput
1162 err error
1163}
1164
1165func (s *snsStub) Publish(_ context.Context, in *sns.PublishInput, _ ...func(*sns.Options)) (*sns.PublishOutput, error) {
1166 s.in = append(s.in, in)
1167 return &sns.PublishOutput{}, s.err
1168}
1169
1170func TestSNSPublish(t *testing.T) {
1171 const topic = "arn:aws:sns:eu-west-1:123456789012:equipo-hosted"
1172 s := &snsStub{}
1173 p := SNSPublisher{TopicARN: topic, Client: s}
1174 if err := p.Publish(context.Background(), "audit_failed", "route out present\nin subnet-1"); err != nil {
1175 t.Fatalf("Publish = %v", err)
1176 }
1177 in := s.in[0]
1178 if aws.ToString(in.TopicArn) != topic {
1179 t.Errorf("TopicArn = %q, want %q", aws.ToString(in.TopicArn), topic)
1180 }
1181 if subj := aws.ToString(in.Subject); !strings.Contains(subj, "audit_failed") || len(subj) > 100 || strings.ContainsAny(subj, "\r\n") {
1182 t.Errorf("Subject = %q, want the kind on one line of at most 100 characters", subj)
1183 }
1184 if msg := aws.ToString(in.Message); !strings.Contains(msg, "audit_failed") || !strings.Contains(msg, "route out present\nin subnet-1") {
1185 t.Errorf("Message = %q, want the kind and the detail", msg)
1186 }
1187
1188 long := SNSPublisher{TopicARN: topic, Client: s}
1189 if err := long.Publish(context.Background(), strings.Repeat("k", 200)+"\x00é", "d"); err != nil {
1190 t.Fatalf("Publish(long kind) = %v", err)
1191 }
1192 if subj := aws.ToString(s.in[1].Subject); len(subj) > 100 || strings.ContainsFunc(subj, func(r rune) bool { return r < 0x20 || r > 0x7e }) {
1193 t.Errorf("Subject = %q, want printable ASCII of at most 100 characters", subj)
1194 }
1195
1196 failing := &snsStub{err: errors.New("denied")}
1197 if err := (SNSPublisher{TopicARN: topic, Client: failing}).Publish(context.Background(), "k", "d"); err == nil || !strings.Contains(err.Error(), "denied") {
1198 t.Errorf("Publish with a failing client = %v, want the client's error", err)
1199 }
1200 for name, p := range map[string]SNSPublisher{"no topic": {Client: s}, "no client": {TopicARN: topic}} {
1201 before := len(s.in)
1202 if err := p.Publish(context.Background(), "k", "d"); err == nil {
1203 t.Errorf("%s: Publish = nil, want an error", name)
1204 }
1205 if len(s.in) != before {
1206 t.Errorf("%s: Publish called the client", name)
1207 }
1208 }
1209}
1210