oficina / equipo Public

isolatedjob: AWS MicroVM adapter and provider guard

awsjob.Runner implements Runner and NetworkAuditor over the
lambdamicrovms SDK (v1.13.0) and EC2, through a narrow API interface the
tests stub. Launch checks each image version once (ALL capabilities,
x86_64, the size's memory) and sends NO_INGRESS, the connector as the
only egress, no role, no idle policy and the attempt as client token.
SNSPublisher sends operator alerts. TestProviderTypesStayInAdapter keeps
the SDK and awsjob out of every package but awsjob and cmd/ composition
points; guardfixture is its mutation target.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 55294d3ab308b035037515713a9a8eccbb8746dc parent 9da7743
12 files changed, +2,284 −0
  • docs/superpowers/plans/HOSTED-SLICE1-PROGRESS.md +25 −0
  • go.mod +17 −0
  • go.sum +34 −0
  • internal/isolatedjob/awsjob/errors.go +50 −0
  • internal/isolatedjob/awsjob/live_test.go +111 −0
  • internal/isolatedjob/awsjob/network.go +198 −0
  • internal/isolatedjob/awsjob/network_test.go +343 −0
  • internal/isolatedjob/awsjob/publish.go +60 −0
  • internal/isolatedjob/awsjob/runner.go +388 −0
  • internal/isolatedjob/awsjob/runner_test.go +941 −0
  • internal/isolatedjob/guardfixture/doc.go +5 −0
  • internal/isolatedjob/providerguard_test.go +112 −0
diff --git a/docs/superpowers/plans/HOSTED-SLICE1-PROGRESS.md b/docs/superpowers/plans/HOSTED-SLICE1-PROGRESS.md
index c89c7c18..bda0a2b6 100644
--- a/docs/superpowers/plans/HOSTED-SLICE1-PROGRESS.md
+++ b/docs/superpowers/plans/HOSTED-SLICE1-PROGRESS.md
@@ -136,3 +136,28 @@ Fix round 1 (review r1). `Vanish(ref)` makes the fake provider forget a VM: Get,
| backstop switch ignored (`if (f.backstop \|\| true) && ...`) | same | `fake_test.go:463: Get(vm-0001).State = stopping, want running` | yes, passes |
| Inject takes any pair (`if false && !ok {`) | same | `fake_test.go:531: Inject(OpGet, FaultIncompleteList) did not panic` | yes, passes |
| lost-reply Stop skips the effect (`fl != FaultLostReply &&` in Stop) | `go test ./internal/isolatedjob -run 'TestFakeFaults' -count=1` | `fake_test.go:144: Get(vm-0001).State = starting, want stopping` | yes, passes |
+
+## Task 7
+
+`awsjob.Runner` (Runner and NetworkAuditor over `lambdamicrovms` v1.13.0 and EC2, through the narrow `API` interface), `SNSPublisher`, and `TestProviderTypesStayInAdapter` in `isolatedjob` with the empty `guardfixture` as its target. Rows applied by a scratch script that replaced one exact string, ran the command, kept the first assertion line, wrote the original back and ran the command again. No row failed by a build error (a first try at the throttle row did, and was redone so the code still compiles).
+
+| Mutation | Command | Observed failure | Restored |
+| --- | --- | --- | --- |
+| role set (`ExecutionRoleArn: aws.String(...)` on the run request) | `go test ./internal/isolatedjob/awsjob -run '^TestRunRequestShape$' -count=1` | `runner_test.go:267: executionRoleArn = "arn:aws:iam::1:role/r", want none` | yes, passes |
+| idle policy set (`IdlePolicy: &types.IdlePolicy{AutoResumeEnabled: aws.Bool(true)}`) | same | `runner_test.go:270: idlePolicy = {AutoResumeEnabled:0x... ...}, want none` | yes, passes |
+| extra: client token dropped (line deleted) | same | `runner_test.go:276: clientToken = <nil>, want the attempt id "attempt-7"` | yes, passes |
+| capabilities check dropped (`if false && !slices.Equal(out.AdditionalOsCapabilities, ...)`) | `go test ./internal/isolatedjob/awsjob -run '^TestImageVersionChecked$' -count=1` | `runner_test.go:419: Launch = <nil>, want ErrInvalid` in `capabilities_missing`, `capabilities_twice`, `capability_unknown` | yes, passes |
+| cpu check dropped (`if false && (len(out.CpuConfigurations) != 1 \|\| ...)`) | same | `runner_test.go:419: Launch = <nil>, want ErrInvalid` in `cpu_ARM_64`, `cpu_missing`, `cpu_both` | yes, passes |
+| memory check dropped (`if false && (len(out.Resources) != 1 \|\| ...)`) | same | `runner_test.go:419: Launch = <nil>, want ErrInvalid` in `memory_of_the_other_size`, `memory_missing`, `memory_unset`, `a_failure_is_not_cached` | yes, passes |
+| unfamiliar state maps to failed (`return isolatedjob.StateFailed, why`) | `go test ./internal/isolatedjob/awsjob -run '^TestStateMapping$' -count=1` | `runner_test.go:524: Get(HIBERNATING).State = failed, want unknown` (also `FAILED` and `""`) | yes, passes |
+| age from the local clock (`time.Since(*started)`) | `go test ./internal/isolatedjob/awsjob -run '^TestProviderAge$' -count=1` | `runner_test.go:593: Get = age 7782h22m36.49s known true, want age 1m30s known true` | yes, passes |
+| partial pages returned (`return jobs, nil` on a page error) | `go test ./internal/isolatedjob/awsjob -run '^TestListAllPages$' -count=1` | `runner_test.go:883: List = <nil>, want ErrIncomplete` in `page_two_fails`, `page_one_fails` | yes, passes |
+| extra: resume conflict always a no-op (`if true \|\| j.State == isolatedjob.StateRunning {`) | `go test ./internal/isolatedjob/awsjob -run '^TestResumeConflict$' -count=1` | `runner_test.go:754: Resume = <nil>, want ErrConflict` | yes, passes |
+| extra: terminate not-found not swallowed (`false && errors.Is(err, isolatedjob.ErrNotFound)`) | `go test ./internal/isolatedjob/awsjob -run '^TestErrorMapping$' -count=1` | `runner_test.go:690: stop = awsjob: terminate: isolatedjob: not found: ResourceNotFoundException: gone, want nil` | yes, passes |
+| extra: throttling not mapped (`case false && errors.As(err, &throttle), ...`) | same | `runner_test.go:703: launch = awsjob: run: ThrottlingException: slow, want isolatedjob: throttled` | yes, passes |
+| extra: audit ignores ingress rules (`a.IngressClosed = true`) | `go test ./internal/isolatedjob/awsjob -run '^TestAuditNetwork$' -count=1` | `network_test.go:208: AuditNetwork = {... IngressClosed:true ...}, want {... IngressClosed:false ...}` | yes, passes |
+| extra: audit ignores non-local routes (`if false && (aws.ToString(rt.GatewayId) != "local" \|\| other) {`) | same | `network_test.go:208: AuditNetwork = {... RouteOutAbsent:true ...}, want {... RouteOutAbsent:false ...}` | yes, passes |
+| extra: audit takes a network as a host (`if err != nil {` without `IsSingleIP`) | same | `network_test.go:336: AuditNetwork = {... EgressOnly:[... 0.0.0.0:443]}, nil; want an error` | yes, passes |
+| guard: `import _ "github.com/aws/aws-sdk-go-v2/aws"` in `guardfixture/doc.go` (`go build ./internal/isolatedjob/guardfixture` succeeds) | `go test ./internal/isolatedjob -run '^TestProviderTypesStayInAdapter$' -count=1` | `providerguard_test.go:84: packages outside amadan.net/oficina/equipo/internal/isolatedjob/awsjob depend on the AWS SDK or the adapter: amadan.net/oficina/equipo/internal/isolatedjob/guardfixture (via github.com/aws/aws-sdk-go-v2/aws)` | yes, passes |
+| guard: `guardModule + "/internal/isolatedjob/guardfixture"` added to `providerAllowed` | same | `providerguard_test.go:35: providerAllowed holds amadan.net/oficina/equipo/internal/isolatedjob/guardfixture; only cmd/ composition points may depend on the AWS SDK or awsjob` | yes, passes |
+| extra: guard sees test-only imports (scratch `guardfixture/leak_test.go` importing `github.com/aws/smithy-go`, then removed) | same | `providerguard_test.go:84: ... guardfixture (via github.com/aws/smithy-go)` | yes, file removed, passes |
diff --git a/go.mod b/go.mod
index 68fe9f87..19bc1a43 100644
--- a/go.mod
+++ b/go.mod
@@ -19,6 +19,12 @@ require (
amadan.net/oficina/agent-access.git v0.0.0-20261024232549-8ed8ba826000
amadan.net/oficina/home/connect v0.0.0-20261114000742-e9829fda431e
amadan.net/oficina/home/handoff v0.0.0-20261114110939-e03a01a1881c
+ github.com/aws/aws-sdk-go-v2 v1.48.0
+ github.com/aws/aws-sdk-go-v2/config v1.33.21
+ github.com/aws/aws-sdk-go-v2/service/ec2 v1.350.0
+ github.com/aws/aws-sdk-go-v2/service/lambdamicrovms v1.13.0
+ github.com/aws/aws-sdk-go-v2/service/sns v1.48.0
+ github.com/aws/smithy-go v1.28.9
github.com/sqids/sqids-go v0.4.1
golang.org/x/crypto v0.53.0
)
@@ -32,6 +38,17 @@ require (
github.com/Masterminds/sprig/v3 v3.3.0 // indirect
github.com/STARRY-S/zip v0.2.1 // indirect
github.com/andybalholm/brotli v1.1.2-0.20250424173009-453214e765f3 // indirect
+ github.com/aws/aws-sdk-go-v2/credentials v1.21.3 // indirect
+ github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.9 // indirect
+ github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.12 // indirect
+ github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.12 // indirect
+ github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.12 // indirect
+ github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.25 // indirect
+ github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.12 // indirect
+ github.com/aws/aws-sdk-go-v2/service/signin v1.14.0 // indirect
+ github.com/aws/aws-sdk-go-v2/service/sso v1.39.5 // indirect
+ github.com/aws/aws-sdk-go-v2/service/ssooidc v1.44.5 // indirect
+ github.com/aws/aws-sdk-go-v2/service/sts v1.53.0 // indirect
github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect
github.com/bodgit/plumbing v1.3.0 // indirect
github.com/bodgit/sevenzip v1.6.0 // indirect
diff --git a/go.sum b/go.sum
index 5aed7780..a6f14dbe 100644
--- a/go.sum
+++ b/go.sum
@@ -45,6 +45,40 @@ github.com/STARRY-S/zip v0.2.1 h1:pWBd4tuSGm3wtpoqRZZ2EAwOmcHK6XFf7bU9qcJXyFg=
github.com/STARRY-S/zip v0.2.1/go.mod h1:xNvshLODWtC4EJ702g7cTYn13G53o1+X9BWnPFpcWV4=
github.com/andybalholm/brotli v1.1.2-0.20250424173009-453214e765f3 h1:8PmGpDEZl9yDpcdEr6Odf23feCxK3LNUNMxjXg41pZQ=
github.com/andybalholm/brotli v1.1.2-0.20250424173009-453214e765f3/go.mod h1:05ib4cKhjx3OQYUY22hTVd34Bc8upXjOLL2rKwwZBoA=
+github.com/aws/aws-sdk-go-v2 v1.48.0 h1:tFU7EJVm7MfyaXLsXdYTZ0Vd6vwt9OljCyqq0gqk0Mc=
+github.com/aws/aws-sdk-go-v2 v1.48.0/go.mod h1:oeKU5p+TQBnpeLmU42WZLWvzv+ORLn+74n4QVLnm/Z0=
+github.com/aws/aws-sdk-go-v2/config v1.33.21 h1:NY1d3yXmplUSYnUAue0sR88svD+SJiaI+YJGp8TxSNg=
+github.com/aws/aws-sdk-go-v2/config v1.33.21/go.mod h1:pVJNXUXaCLu9a/4/liTklg9zR3yO0xm/XBEQhgg5nzc=
+github.com/aws/aws-sdk-go-v2/credentials v1.21.3 h1:bh+9VoJ4eDzJVEY6jfdNTBa0Dx7tdr+lWSPNovU1vXc=
+github.com/aws/aws-sdk-go-v2/credentials v1.21.3/go.mod h1:4CNs0EBvjDEpyaXSYCdNeNRhFjHFX2Y373tFUaeTYXA=
+github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.9 h1:oH1E0tjN0g+ZRusbX1dsuat4FJ0z05l8hWaycSbDuNc=
+github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.9/go.mod h1:3ZaQGigIoaS45x9HgnLZ4sP475Fs7QoxU3IsZX/J3h4=
+github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.12 h1:W0yUUzKBA8SofGQ0yZafEUuZq9UxfvijRgdc6vcRQPA=
+github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.12/go.mod h1:xwKv6vwBNdpPFOxEm/ld4IODZK2s/1ksHvdBqLfH6Gs=
+github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.12 h1:lqSi8qvAnKC1vfosImdmOsuiJLr/jdybZX5299beB6Q=
+github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.12/go.mod h1:rqPQE2vqkW9YHx5+Gp55sx1wsTM4xtGQLl+TKMjxxrs=
+github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.12 h1:uvX2yaL+aMjkmnrLPPlR/zwjoKFRMoNhhJfeGjfk6qc=
+github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.12/go.mod h1:dicT+2eNhHHqGkxHO7LoXw3QghIUGuzgdmFqaSTopgI=
+github.com/aws/aws-sdk-go-v2/service/ec2 v1.350.0 h1:EjAV+HmAnHedN+iYZF+b4SQYtMGlMdjURLbZc3q32fs=
+github.com/aws/aws-sdk-go-v2/service/ec2 v1.350.0/go.mod h1:uMJiOkxaT3pV+LAeAvEaXToZ2x3nEnN53HnPdj+pcNo=
+github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.25 h1:rKwkY3Z+fvt2W0msjdNs6uNewPmXzPayQ961oyuWhes=
+github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.25/go.mod h1:dBuAadQKd1F4Q4ZOg8gnFmuSHMRE40Pe3IfFwbtC4lE=
+github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.12 h1:wzAqMZ2O4+ij9HQqIrk+P9PBGacE0wOTuWB7Mo97//I=
+github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.12/go.mod h1:/0TfyruByHsOlphzP26xDTRe2DKD0J1I1Uyy2TyP8EI=
+github.com/aws/aws-sdk-go-v2/service/lambdamicrovms v1.13.0 h1:fDJjTeLNm1xh1Nwq+pPO/D9RbMbO1F+Kp1q8KJdPmqA=
+github.com/aws/aws-sdk-go-v2/service/lambdamicrovms v1.13.0/go.mod h1:GEnG9FBOraRH3j7GPz/wQmuBLI7d+yjDje4IriTgQ7o=
+github.com/aws/aws-sdk-go-v2/service/signin v1.14.0 h1:bIEk1HfTd3MGzvDa5YOQUodGr96D9+UTnmBLBB8ZJ10=
+github.com/aws/aws-sdk-go-v2/service/signin v1.14.0/go.mod h1:LdwHjKqPE9VCC7sTlWcOAizZx3ZJYjmfwC/EW2tIIAE=
+github.com/aws/aws-sdk-go-v2/service/sns v1.48.0 h1:Y19AwHx+iYmAeiWrqmm3vQ0UwLfBuV5DNuAis5mYZ0A=
+github.com/aws/aws-sdk-go-v2/service/sns v1.48.0/go.mod h1:+/n+Y7rTBcnpCXKo1IQoEvbxJsumASEQQfgj1RldXm8=
+github.com/aws/aws-sdk-go-v2/service/sso v1.39.5 h1:ANAoa+qt3/9kXnvQVgUyxcTzhzZf4DqaBS+M2DQrELU=
+github.com/aws/aws-sdk-go-v2/service/sso v1.39.5/go.mod h1:vsMi+SSR7xGQXtV430LVi49qbv/R+U+upHHSp1W/+QI=
+github.com/aws/aws-sdk-go-v2/service/ssooidc v1.44.5 h1:uIOBLMhef4N16WguadoHKuBy9etdz+RKTeqzchXErAI=
+github.com/aws/aws-sdk-go-v2/service/ssooidc v1.44.5/go.mod h1:NwWmkFLtsTVyXQpbzPOlYLwEoANkdCFjJRtrNcbg/vY=
+github.com/aws/aws-sdk-go-v2/service/sts v1.53.0 h1:my9Y6lxcqvPV5k4OTqnxr8XbiTDDRos1leEh050Z93U=
+github.com/aws/aws-sdk-go-v2/service/sts v1.53.0/go.mod h1:MG6N8U9+lY4LqchrlHPqCOSr7hyxw70XU0Et2YR3eNA=
+github.com/aws/smithy-go v1.28.9 h1:zkZ058OpNX0iGTK24b+ZUEQSMc11CBA6oO7xtKZfzkY=
+github.com/aws/smithy-go v1.28.9/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k=
github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8=
github.com/bodgit/plumbing v1.3.0 h1:pf9Itz1JOQgn7vEOE7v7nlEfBykYqvUYioC61TwWCFU=
diff --git a/internal/isolatedjob/awsjob/errors.go b/internal/isolatedjob/awsjob/errors.go
new file mode 100644
index 00000000..38f59503
--- /dev/null
+++ b/internal/isolatedjob/awsjob/errors.go
@@ -0,0 +1,50 @@
+package awsjob
+
+import (
+ "errors"
+ "fmt"
+
+ "amadan.net/oficina/equipo/internal/isolatedjob"
+ "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms/types"
+ "github.com/aws/smithy-go"
+)
+
+// mapErr wraps an error from operation op in the isolatedjob sentinel it
+// means, keeping the provider error too:
+//
+// - ResourceNotFoundException: ErrNotFound (Stop turns it into success)
+// - ThrottlingException, TooManyRequestsException,
+// ServiceQuotaExceededException: ErrThrottled
+// - ValidationException, or a request the SDK refused before sending:
+// ErrInvalid
+// - ConflictException: ErrConflict (Resume reads the VM first)
+//
+// Anything else is wrapped with no sentinel.
+func mapErr(op string, err error) error {
+ if err == nil {
+ return nil
+ }
+ var (
+ notFound *types.ResourceNotFoundException
+ throttle *types.ThrottlingException
+ tooMany *types.TooManyRequestsException
+ quota *types.ServiceQuotaExceededException
+ validation *types.ValidationException
+ params *smithy.InvalidParamsError
+ conflict *types.ConflictException
+ )
+ var sentinel error
+ switch {
+ case errors.As(err, &notFound):
+ sentinel = isolatedjob.ErrNotFound
+ case errors.As(err, &throttle), errors.As(err, &tooMany), errors.As(err, &quota):
+ sentinel = isolatedjob.ErrThrottled
+ case errors.As(err, &validation), errors.As(err, &params):
+ sentinel = isolatedjob.ErrInvalid
+ case errors.As(err, &conflict):
+ sentinel = isolatedjob.ErrConflict
+ default:
+ return fmt.Errorf("awsjob: %s: %w", op, err)
+ }
+ return fmt.Errorf("awsjob: %s: %w: %w", op, sentinel, err)
+}
diff --git a/internal/isolatedjob/awsjob/live_test.go b/internal/isolatedjob/awsjob/live_test.go
new file mode 100644
index 00000000..1d118506
--- /dev/null
+++ b/internal/isolatedjob/awsjob/live_test.go
@@ -0,0 +1,111 @@
+//go:build hostedlive
+
+package awsjob
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net/netip"
+ "os"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/isolatedjob"
+ "amadan.net/oficina/equipo/internal/isolatedjob/isolatedjobtest"
+ "github.com/aws/aws-sdk-go-v2/config"
+ "github.com/aws/aws-sdk-go-v2/service/ec2"
+ vms "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms"
+)
+
+// liveConfig is the JSON file EQUIPO_HOSTED_LIVE_CONFIG names. Credentials
+// come from the usual AWS environment (AWS_PROFILE and the rest).
+type liveConfig struct {
+ Region string `json:"region"`
+ ConnectorID string `json:"connector_id"`
+ VPCID string `json:"vpc_id"`
+ VMSubnetID string `json:"vm_subnet_id"`
+ VMSecurityGroupID string `json:"vm_security_group_id"`
+ Image isolatedjob.ImageDigest `json:"image"` // the digest the contract launches
+ ImageARN string `json:"image_arn"`
+ Versions map[isolatedjob.Size]string `json:"versions"` // size to image version
+ Egress []string `json:"egress"` // "host:port"
+}
+
+// TestLiveContract runs the Runner contract against real AWS Lambda
+// MicroVMs. It launches and stops real VMs, so it runs only by hand, with
+// -tags hostedlive and EQUIPO_HOSTED_LIVE_CONFIG set (Task 17).
+func TestLiveContract(t *testing.T) {
+ path := os.Getenv("EQUIPO_HOSTED_LIVE_CONFIG")
+ if path == "" {
+ t.Skip("EQUIPO_HOSTED_LIVE_CONFIG is not set")
+ }
+ raw, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatalf("live config: %v", err)
+ }
+ var lc liveConfig
+ if err := json.Unmarshal(raw, &lc); err != nil {
+ t.Fatalf("live config %s: %v", path, err)
+ }
+ cfg := Config{
+ Region: lc.Region,
+ ConnectorID: lc.ConnectorID,
+ VPCID: lc.VPCID,
+ VMSubnetID: lc.VMSubnetID,
+ VMSecurityGroupID: lc.VMSecurityGroupID,
+ Images: map[isolatedjob.ImageDigest]Image{lc.Image: {ARN: lc.ImageARN, Versions: lc.Versions}},
+ }
+ for _, e := range lc.Egress {
+ ap, err := netip.ParseAddrPort(e)
+ if err != nil {
+ t.Fatalf("live config egress %q: %v", e, err)
+ }
+ cfg.Egress = append(cfg.Egress, ap)
+ }
+
+ ctx := context.Background()
+ awsCfg, err := config.LoadDefaultConfig(ctx, config.WithRegion(lc.Region))
+ if err != nil {
+ t.Fatalf("AWS config: %v", err)
+ }
+ r, err := New(cfg, NewAPI(vms.NewFromConfig(awsCfg), ec2.NewFromConfig(awsCfg)))
+ if err != nil {
+ t.Fatalf("New: %v", err)
+ }
+
+ isolatedjobtest.Contract(t, isolatedjobtest.Harness{
+ Runner: r,
+ Image: lc.Image,
+ Settle: func(ctx context.Context, ref isolatedjob.Ref, want func(isolatedjob.State) bool) (isolatedjob.Job, error) {
+ return settle(ctx, r, ref, want, 5*time.Minute)
+ },
+ // GetMicrovm's state is eventually consistent (doc.go, States), and
+ // ListMicrovms is a separate read that can trail it. 30 s is a
+ // guess for Task 17 to replace with what it measures.
+ ListLag: 30 * time.Second,
+ })
+}
+
+// settle polls Get every 5 s until want holds or bound passes.
+func settle(ctx context.Context, r *Runner, ref isolatedjob.Ref, want func(isolatedjob.State) bool, bound time.Duration) (isolatedjob.Job, error) {
+ deadline := time.Now().Add(bound)
+ for {
+ job, err := r.Get(ctx, ref)
+ if err != nil && !errors.Is(err, isolatedjob.ErrThrottled) {
+ return job, err
+ }
+ if err == nil && want(job.State) {
+ return job, nil
+ }
+ if time.Now().After(deadline) {
+ return job, fmt.Errorf("%s still %s after %v (last error %v)", ref, job.State, bound, err)
+ }
+ select {
+ case <-ctx.Done():
+ return job, ctx.Err()
+ case <-time.After(5 * time.Second):
+ }
+ }
+}
diff --git a/internal/isolatedjob/awsjob/network.go b/internal/isolatedjob/awsjob/network.go
new file mode 100644
index 00000000..bc35c80f
--- /dev/null
+++ b/internal/isolatedjob/awsjob/network.go
@@ -0,0 +1,198 @@
+package awsjob
+
+import (
+ "context"
+ "fmt"
+ "net/netip"
+ "slices"
+
+ "amadan.net/oficina/equipo/internal/isolatedjob"
+ "github.com/aws/aws-sdk-go-v2/aws"
+ "github.com/aws/aws-sdk-go-v2/service/ec2"
+ ec2types "github.com/aws/aws-sdk-go-v2/service/ec2/types"
+)
+
+// AuditNetwork reads the configured VPC, subnet and security group as they
+// are now:
+//
+// - ResolverDisabled: the VPC has both enableDnsSupport and
+// enableDnsHostnames read as false.
+// - IngressClosed: the security group has no inbound rules.
+// - RouteOutAbsent: the subnet's route table (its own, or the VPC's main
+// table when it has none) has only "local" routes. Any other target,
+// gateway endpoints included, counts as a route out.
+// - EgressOnly: every host and port the security group's outbound rules
+// allow. It equals Config.Egress when the group is right.
+//
+// It returns an error, and the zero audit in which every property has
+// failed, when a read fails, an ID is missing or outside the VPC, or an
+// outbound rule allows more than single TCP hosts and ports (a network, a
+// port range, another protocol, a prefix list or a group): what it cannot
+// establish is never assumed.
+func (r *Runner) AuditNetwork(ctx context.Context) (isolatedjob.NetworkAudit, error) {
+ a, err := r.audit(ctx)
+ if err != nil {
+ return isolatedjob.NetworkAudit{}, fmt.Errorf("awsjob: network audit: %w", err)
+ }
+ return a, nil
+}
+
+func (r *Runner) audit(ctx context.Context) (isolatedjob.NetworkAudit, error) {
+ var a isolatedjob.NetworkAudit
+ support, err := r.vpcAttribute(ctx, ec2types.VpcAttributeNameEnableDnsSupport)
+ if err != nil {
+ return a, err
+ }
+ hostnames, err := r.vpcAttribute(ctx, ec2types.VpcAttributeNameEnableDnsHostnames)
+ if err != nil {
+ return a, err
+ }
+ a.ResolverDisabled = support != nil && !*support && hostnames != nil && !*hostnames
+
+ table, err := r.subnetRouteTable(ctx)
+ if err != nil {
+ return a, err
+ }
+ a.RouteOutAbsent = table != nil && onlyLocal(table.Routes)
+
+ sgs, err := r.api.DescribeSecurityGroups(ctx, &ec2.DescribeSecurityGroupsInput{GroupIds: []string{r.cfg.VMSecurityGroupID}})
+ if err != nil {
+ return a, fmt.Errorf("describe security group %s: %w", r.cfg.VMSecurityGroupID, err)
+ }
+ if len(sgs.SecurityGroups) != 1 || aws.ToString(sgs.SecurityGroups[0].VpcId) != r.cfg.VPCID {
+ return a, fmt.Errorf("security group %s is not one group in %s", r.cfg.VMSecurityGroupID, r.cfg.VPCID)
+ }
+ sg := sgs.SecurityGroups[0]
+ a.IngressClosed = len(sg.IpPermissions) == 0
+ for _, p := range sg.IpPermissionsEgress {
+ dests, err := hostPorts(p)
+ if err != nil {
+ return a, fmt.Errorf("security group %s: %w", r.cfg.VMSecurityGroupID, err)
+ }
+ for _, d := range dests {
+ if !slices.Contains(a.EgressOnly, d) {
+ a.EgressOnly = append(a.EgressOnly, d)
+ }
+ }
+ }
+ return a, nil
+}
+
+// vpcAttribute reads one boolean VPC attribute; nil means AWS gave no value.
+func (r *Runner) vpcAttribute(ctx context.Context, name ec2types.VpcAttributeName) (*bool, error) {
+ out, err := r.api.DescribeVpcAttribute(ctx, &ec2.DescribeVpcAttributeInput{VpcId: aws.String(r.cfg.VPCID), Attribute: name})
+ if err != nil {
+ return nil, fmt.Errorf("describe %s of %s: %w", name, r.cfg.VPCID, err)
+ }
+ var v *ec2types.AttributeBooleanValue
+ switch name {
+ case ec2types.VpcAttributeNameEnableDnsSupport:
+ v = out.EnableDnsSupport
+ case ec2types.VpcAttributeNameEnableDnsHostnames:
+ v = out.EnableDnsHostnames
+ }
+ if v == nil {
+ return nil, nil
+ }
+ return v.Value, nil
+}
+
+// subnetRouteTable returns the route table the VM subnet uses: the one
+// associated with it, or else the VPC's main table. nil means none was
+// found.
+func (r *Runner) subnetRouteTable(ctx context.Context) (*ec2types.RouteTable, error) {
+ subnets, err := r.api.DescribeSubnets(ctx, &ec2.DescribeSubnetsInput{SubnetIds: []string{r.cfg.VMSubnetID}})
+ if err != nil {
+ return nil, fmt.Errorf("describe subnet %s: %w", r.cfg.VMSubnetID, err)
+ }
+ if len(subnets.Subnets) != 1 || aws.ToString(subnets.Subnets[0].VpcId) != r.cfg.VPCID {
+ return nil, fmt.Errorf("subnet %s is not one subnet in %s", r.cfg.VMSubnetID, r.cfg.VPCID)
+ }
+ tables, err := r.routeTables(ctx, filter("association.subnet-id", r.cfg.VMSubnetID))
+ if err != nil {
+ return nil, err
+ }
+ if len(tables) == 0 {
+ if tables, err = r.routeTables(ctx, filter("vpc-id", r.cfg.VPCID), filter("association.main", "true")); err != nil {
+ return nil, err
+ }
+ }
+ switch len(tables) {
+ case 0:
+ return nil, nil
+ case 1:
+ return &tables[0], nil
+ }
+ return nil, fmt.Errorf("subnet %s matches %d route tables", r.cfg.VMSubnetID, len(tables))
+}
+
+func (r *Runner) routeTables(ctx context.Context, filters ...ec2types.Filter) ([]ec2types.RouteTable, error) {
+ var tables []ec2types.RouteTable
+ var token *string
+ seen := map[string]bool{}
+ for {
+ out, err := r.api.DescribeRouteTables(ctx, &ec2.DescribeRouteTablesInput{Filters: filters, NextToken: token})
+ if err != nil {
+ return nil, fmt.Errorf("describe route tables: %w", err)
+ }
+ tables = append(tables, out.RouteTables...)
+ next := aws.ToString(out.NextToken)
+ if next == "" {
+ return tables, nil
+ }
+ if seen[next] {
+ return nil, fmt.Errorf("describe route tables repeats a page token")
+ }
+ seen[next] = true
+ token = aws.String(next)
+ }
+}
+
+func filter(name, value string) ec2types.Filter {
+ return ec2types.Filter{Name: aws.String(name), Values: []string{value}}
+}
+
+// onlyLocal reports whether every route stays inside the VPC: target
+// "local" and nothing else.
+func onlyLocal(routes []ec2types.Route) bool {
+ for _, rt := range routes {
+ other := rt.CarrierGatewayId != nil || rt.CoreNetworkArn != nil || rt.EgressOnlyInternetGatewayId != nil ||
+ rt.InstanceId != nil || rt.LocalGatewayId != nil || rt.NatGatewayId != nil || rt.NetworkInterfaceId != nil ||
+ rt.OdbNetworkArn != nil || rt.TransitGatewayId != nil || rt.VpcPeeringConnectionId != nil || rt.IgwFirewall != nil
+ if aws.ToString(rt.GatewayId) != "local" || other {
+ return false
+ }
+ }
+ return true
+}
+
+// hostPorts turns one outbound rule into the hosts and port it allows, or
+// an error when it allows more than single hosts on one TCP port.
+func hostPorts(p ec2types.IpPermission) ([]netip.AddrPort, error) {
+ proto := aws.ToString(p.IpProtocol)
+ if proto != "tcp" && proto != "6" {
+ return nil, fmt.Errorf("outbound rule for protocol %q, want tcp only", proto)
+ }
+ if p.FromPort == nil || p.ToPort == nil || *p.FromPort != *p.ToPort || *p.FromPort < 1 || *p.FromPort > 65535 {
+ return nil, fmt.Errorf("outbound rule for ports %d to %d, want one port", aws.ToInt32(p.FromPort), aws.ToInt32(p.ToPort))
+ }
+ if len(p.PrefixListIds) > 0 || len(p.UserIdGroupPairs) > 0 {
+ return nil, fmt.Errorf("outbound rule to a prefix list or group on port %d, want single hosts", *p.FromPort)
+ }
+ var cidrs []string
+ for _, r := range p.IpRanges {
+ cidrs = append(cidrs, aws.ToString(r.CidrIp))
+ }
+ for _, r := range p.Ipv6Ranges {
+ cidrs = append(cidrs, aws.ToString(r.CidrIpv6))
+ }
+ var out []netip.AddrPort
+ for _, c := range cidrs {
+ prefix, err := netip.ParsePrefix(c)
+ if err != nil || !prefix.IsSingleIP() {
+ return nil, fmt.Errorf("outbound rule to %q on port %d, want a single host", c, *p.FromPort)
+ }
+ out = append(out, netip.AddrPortFrom(prefix.Addr(), uint16(*p.FromPort)))
+ }
+ return out, nil
+}
diff --git a/internal/isolatedjob/awsjob/network_test.go b/internal/isolatedjob/awsjob/network_test.go
new file mode 100644
index 00000000..ab08f829
--- /dev/null
+++ b/internal/isolatedjob/awsjob/network_test.go
@@ -0,0 +1,343 @@
+package awsjob
+
+import (
+ "context"
+ "errors"
+ "net/netip"
+ "reflect"
+ "slices"
+ "testing"
+
+ "amadan.net/oficina/equipo/internal/isolatedjob"
+ "github.com/aws/aws-sdk-go-v2/aws"
+ "github.com/aws/aws-sdk-go-v2/service/ec2"
+ ec2types "github.com/aws/aws-sdk-go-v2/service/ec2/types"
+)
+
+// The EC2 half of stub. A nil func field answers with the network
+// testConfig describes, set up correctly.
+
+func (s *stub) DescribeVpcAttribute(_ context.Context, in *ec2.DescribeVpcAttributeInput, _ ...func(*ec2.Options)) (*ec2.DescribeVpcAttributeOutput, error) {
+ s.record("DescribeVpcAttribute")
+ if s.vpcAttr != nil {
+ return s.vpcAttr(in)
+ }
+ return vpcAttr(in, false, false), nil
+}
+
+func (s *stub) DescribeSubnets(_ context.Context, in *ec2.DescribeSubnetsInput, _ ...func(*ec2.Options)) (*ec2.DescribeSubnetsOutput, error) {
+ s.record("DescribeSubnets")
+ if s.subnets != nil {
+ return s.subnets(in)
+ }
+ return &ec2.DescribeSubnetsOutput{Subnets: []ec2types.Subnet{{SubnetId: aws.String("subnet-1"), VpcId: aws.String("vpc-1")}}}, nil
+}
+
+func (s *stub) DescribeRouteTables(_ context.Context, in *ec2.DescribeRouteTablesInput, _ ...func(*ec2.Options)) (*ec2.DescribeRouteTablesOutput, error) {
+ s.record("DescribeRouteTables")
+ if s.routeTables != nil {
+ return s.routeTables(in)
+ }
+ if filterValue(in.Filters, "association.subnet-id") != "subnet-1" {
+ return &ec2.DescribeRouteTablesOutput{}, nil
+ }
+ return &ec2.DescribeRouteTablesOutput{RouteTables: []ec2types.RouteTable{localTable()}}, nil
+}
+
+func (s *stub) DescribeSecurityGroups(_ context.Context, in *ec2.DescribeSecurityGroupsInput, _ ...func(*ec2.Options)) (*ec2.DescribeSecurityGroupsOutput, error) {
+ s.record("DescribeSecurityGroups")
+ if s.securityGroups != nil {
+ return s.securityGroups(in)
+ }
+ return &ec2.DescribeSecurityGroupsOutput{SecurityGroups: []ec2types.SecurityGroup{goodGroup()}}, nil
+}
+
+func vpcAttr(in *ec2.DescribeVpcAttributeInput, support, hostnames bool) *ec2.DescribeVpcAttributeOutput {
+ out := &ec2.DescribeVpcAttributeOutput{VpcId: in.VpcId}
+ switch in.Attribute {
+ case ec2types.VpcAttributeNameEnableDnsSupport:
+ out.EnableDnsSupport = &ec2types.AttributeBooleanValue{Value: aws.Bool(support)}
+ case ec2types.VpcAttributeNameEnableDnsHostnames:
+ out.EnableDnsHostnames = &ec2types.AttributeBooleanValue{Value: aws.Bool(hostnames)}
+ }
+ return out
+}
+
+func filterValue(filters []ec2types.Filter, name string) string {
+ for _, f := range filters {
+ if aws.ToString(f.Name) == name && len(f.Values) == 1 {
+ return f.Values[0]
+ }
+ }
+ return ""
+}
+
+func localTable() ec2types.RouteTable {
+ return ec2types.RouteTable{
+ RouteTableId: aws.String("rtb-1"),
+ VpcId: aws.String("vpc-1"),
+ Routes: []ec2types.Route{
+ {DestinationCidrBlock: aws.String("10.0.0.0/16"), GatewayId: aws.String("local")},
+ {DestinationIpv6CidrBlock: aws.String("2001:db8::/56"), GatewayId: aws.String("local")},
+ },
+ }
+}
+
+func hostRule(port int32, cidrs ...string) ec2types.IpPermission {
+ p := ec2types.IpPermission{IpProtocol: aws.String("tcp"), FromPort: aws.Int32(port), ToPort: aws.Int32(port)}
+ for _, c := range cidrs {
+ p.IpRanges = append(p.IpRanges, ec2types.IpRange{CidrIp: aws.String(c)})
+ }
+ return p
+}
+
+func goodGroup() ec2types.SecurityGroup {
+ return ec2types.SecurityGroup{
+ GroupId: aws.String("sg-1"),
+ VpcId: aws.String("vpc-1"),
+ IpPermissionsEgress: []ec2types.IpPermission{
+ hostRule(3128, "10.0.1.10/32"),
+ hostRule(443, "10.0.1.11/32"),
+ },
+ }
+}
+
+func TestAuditNetwork(t *testing.T) {
+ want := testConfig().Egress
+ withGroup := func(change func(*ec2types.SecurityGroup)) func(*ec2.DescribeSecurityGroupsInput) (*ec2.DescribeSecurityGroupsOutput, error) {
+ return func(*ec2.DescribeSecurityGroupsInput) (*ec2.DescribeSecurityGroupsOutput, error) {
+ g := goodGroup()
+ change(&g)
+ return &ec2.DescribeSecurityGroupsOutput{SecurityGroups: []ec2types.SecurityGroup{g}}, nil
+ }
+ }
+ withRoutes := func(routes ...ec2types.Route) func(*ec2.DescribeRouteTablesInput) (*ec2.DescribeRouteTablesOutput, error) {
+ return func(*ec2.DescribeRouteTablesInput) (*ec2.DescribeRouteTablesOutput, error) {
+ rt := localTable()
+ rt.Routes = append(rt.Routes, routes...)
+ return &ec2.DescribeRouteTablesOutput{RouteTables: []ec2types.RouteTable{rt}}, nil
+ }
+ }
+ good := isolatedjob.NetworkAudit{ResolverDisabled: true, IngressClosed: true, RouteOutAbsent: true, EgressOnly: want}
+
+ rows := []struct {
+ name string
+ setup func(*stub)
+ want isolatedjob.NetworkAudit
+ }{
+ {"all good", func(*stub) {}, good},
+ {"dns support on", func(s *stub) {
+ s.vpcAttr = func(in *ec2.DescribeVpcAttributeInput) (*ec2.DescribeVpcAttributeOutput, error) {
+ return vpcAttr(in, true, false), nil
+ }
+ }, isolatedjob.NetworkAudit{IngressClosed: true, RouteOutAbsent: true, EgressOnly: want}},
+ {"dns hostnames on", func(s *stub) {
+ s.vpcAttr = func(in *ec2.DescribeVpcAttributeInput) (*ec2.DescribeVpcAttributeOutput, error) {
+ return vpcAttr(in, false, true), nil
+ }
+ }, isolatedjob.NetworkAudit{IngressClosed: true, RouteOutAbsent: true, EgressOnly: want}},
+ {"dns value missing", func(s *stub) {
+ s.vpcAttr = func(in *ec2.DescribeVpcAttributeInput) (*ec2.DescribeVpcAttributeOutput, error) {
+ return &ec2.DescribeVpcAttributeOutput{VpcId: in.VpcId}, nil
+ }
+ }, isolatedjob.NetworkAudit{IngressClosed: true, RouteOutAbsent: true, EgressOnly: want}},
+ {"ingress rule", func(s *stub) {
+ s.securityGroups = withGroup(func(g *ec2types.SecurityGroup) {
+ g.IpPermissions = []ec2types.IpPermission{hostRule(22, "10.0.0.0/16")}
+ })
+ }, isolatedjob.NetworkAudit{ResolverDisabled: true, RouteOutAbsent: true, EgressOnly: want}},
+ {"internet gateway route", func(s *stub) {
+ s.routeTables = withRoutes(ec2types.Route{DestinationCidrBlock: aws.String("0.0.0.0/0"), GatewayId: aws.String("igw-1")})
+ }, isolatedjob.NetworkAudit{ResolverDisabled: true, IngressClosed: true, EgressOnly: want}},
+ {"nat route", func(s *stub) {
+ s.routeTables = withRoutes(ec2types.Route{DestinationCidrBlock: aws.String("0.0.0.0/0"), NatGatewayId: aws.String("nat-1")})
+ }, isolatedjob.NetworkAudit{ResolverDisabled: true, IngressClosed: true, EgressOnly: want}},
+ {"egress-only gateway route", func(s *stub) {
+ s.routeTables = withRoutes(ec2types.Route{DestinationIpv6CidrBlock: aws.String("::/0"), EgressOnlyInternetGatewayId: aws.String("eigw-1")})
+ }, isolatedjob.NetworkAudit{ResolverDisabled: true, IngressClosed: true, EgressOnly: want}},
+ {"local route with a second target", func(s *stub) {
+ s.routeTables = withRoutes(ec2types.Route{DestinationCidrBlock: aws.String("10.9.0.0/16"), GatewayId: aws.String("local"), TransitGatewayId: aws.String("tgw-1")})
+ }, isolatedjob.NetworkAudit{ResolverDisabled: true, IngressClosed: true, EgressOnly: want}},
+ {"main table when no explicit association", func(s *stub) {
+ s.routeTables = func(in *ec2.DescribeRouteTablesInput) (*ec2.DescribeRouteTablesOutput, error) {
+ if filterValue(in.Filters, "association.main") == "true" && filterValue(in.Filters, "vpc-id") == "vpc-1" {
+ return &ec2.DescribeRouteTablesOutput{RouteTables: []ec2types.RouteTable{localTable()}}, nil
+ }
+ return &ec2.DescribeRouteTablesOutput{}, nil
+ }
+ }, good},
+ {"route tables over two pages", func(s *stub) {
+ s.routeTables = func(in *ec2.DescribeRouteTablesInput) (*ec2.DescribeRouteTablesOutput, error) {
+ if in.NextToken == nil {
+ return &ec2.DescribeRouteTablesOutput{NextToken: aws.String("p2")}, nil
+ }
+ return withRoutes(ec2types.Route{DestinationCidrBlock: aws.String("0.0.0.0/0"), GatewayId: aws.String("igw-1")})(in)
+ }
+ }, isolatedjob.NetworkAudit{ResolverDisabled: true, IngressClosed: true, EgressOnly: want}},
+ {"no route table found", func(s *stub) {
+ s.routeTables = func(*ec2.DescribeRouteTablesInput) (*ec2.DescribeRouteTablesOutput, error) {
+ return &ec2.DescribeRouteTablesOutput{}, nil
+ }
+ }, isolatedjob.NetworkAudit{ResolverDisabled: true, IngressClosed: true, EgressOnly: want}},
+ {"extra egress host", func(s *stub) {
+ s.securityGroups = withGroup(func(g *ec2types.SecurityGroup) {
+ g.IpPermissionsEgress = append(g.IpPermissionsEgress, hostRule(443, "10.0.1.12/32"))
+ })
+ }, isolatedjob.NetworkAudit{ResolverDisabled: true, IngressClosed: true, RouteOutAbsent: true,
+ EgressOnly: append(slices.Clone(want), netip.MustParseAddrPort("10.0.1.12:443"))}},
+ {"one egress host missing", func(s *stub) {
+ s.securityGroups = withGroup(func(g *ec2types.SecurityGroup) { g.IpPermissionsEgress = g.IpPermissionsEgress[:1] })
+ }, isolatedjob.NetworkAudit{ResolverDisabled: true, IngressClosed: true, RouteOutAbsent: true, EgressOnly: want[:1]}},
+ {"ipv6 host and protocol 6", func(s *stub) {
+ s.securityGroups = withGroup(func(g *ec2types.SecurityGroup) {
+ g.IpPermissionsEgress = append(g.IpPermissionsEgress, ec2types.IpPermission{IpProtocol: aws.String("6"),
+ FromPort: aws.Int32(443), ToPort: aws.Int32(443), Ipv6Ranges: []ec2types.Ipv6Range{{CidrIpv6: aws.String("2001:db8::5/128")}}})
+ })
+ }, isolatedjob.NetworkAudit{ResolverDisabled: true, IngressClosed: true, RouteOutAbsent: true,
+ EgressOnly: append(slices.Clone(want), netip.MustParseAddrPort("[2001:db8::5]:443"))}},
+ }
+ for _, row := range rows {
+ t.Run(row.name, func(t *testing.T) {
+ s := &stub{}
+ row.setup(s)
+ got, err := newTestRunner(t, s).AuditNetwork(context.Background())
+ if err != nil {
+ t.Fatalf("AuditNetwork = %v", err)
+ }
+ if !reflect.DeepEqual(got, row.want) {
+ t.Errorf("AuditNetwork = %+v, want %+v", got, row.want)
+ }
+ if passes := got.OK(want) == nil; passes != (row.name == "all good" || row.name == "main table when no explicit association") {
+ t.Errorf("OK(want) passes = %v for %s", passes, row.name)
+ }
+ })
+ }
+
+ t.Run("reads the configured ids", func(t *testing.T) {
+ var attrs []ec2types.VpcAttributeName
+ s := &stub{
+ vpcAttr: func(in *ec2.DescribeVpcAttributeInput) (*ec2.DescribeVpcAttributeOutput, error) {
+ if aws.ToString(in.VpcId) != "vpc-1" {
+ t.Errorf("DescribeVpcAttribute vpc = %q, want vpc-1", aws.ToString(in.VpcId))
+ }
+ attrs = append(attrs, in.Attribute)
+ return vpcAttr(in, false, false), nil
+ },
+ subnets: func(in *ec2.DescribeSubnetsInput) (*ec2.DescribeSubnetsOutput, error) {
+ if !reflect.DeepEqual(in.SubnetIds, []string{"subnet-1"}) {
+ t.Errorf("DescribeSubnets ids = %q, want [subnet-1]", in.SubnetIds)
+ }
+ return &ec2.DescribeSubnetsOutput{Subnets: []ec2types.Subnet{{SubnetId: aws.String("subnet-1"), VpcId: aws.String("vpc-1")}}}, nil
+ },
+ securityGroups: func(in *ec2.DescribeSecurityGroupsInput) (*ec2.DescribeSecurityGroupsOutput, error) {
+ if !reflect.DeepEqual(in.GroupIds, []string{"sg-1"}) {
+ t.Errorf("DescribeSecurityGroups ids = %q, want [sg-1]", in.GroupIds)
+ }
+ return &ec2.DescribeSecurityGroupsOutput{SecurityGroups: []ec2types.SecurityGroup{goodGroup()}}, nil
+ },
+ }
+ if _, err := newTestRunner(t, s).AuditNetwork(context.Background()); err != nil {
+ t.Fatalf("AuditNetwork = %v", err)
+ }
+ slices.Sort(attrs)
+ if want := []ec2types.VpcAttributeName{ec2types.VpcAttributeNameEnableDnsHostnames, ec2types.VpcAttributeNameEnableDnsSupport}; !reflect.DeepEqual(attrs, want) {
+ t.Errorf("VPC attributes read = %v, want %v", attrs, want)
+ }
+ })
+
+ refusals := map[string]func(*stub){
+ "vpc attribute read fails": func(s *stub) {
+ s.vpcAttr = func(*ec2.DescribeVpcAttributeInput) (*ec2.DescribeVpcAttributeOutput, error) {
+ return nil, errors.New("denied")
+ }
+ },
+ "subnet read fails": func(s *stub) {
+ s.subnets = func(*ec2.DescribeSubnetsInput) (*ec2.DescribeSubnetsOutput, error) { return nil, errors.New("denied") }
+ },
+ "route table read fails": func(s *stub) {
+ s.routeTables = func(*ec2.DescribeRouteTablesInput) (*ec2.DescribeRouteTablesOutput, error) {
+ return nil, errors.New("denied")
+ }
+ },
+ "security group read fails": func(s *stub) {
+ s.securityGroups = func(*ec2.DescribeSecurityGroupsInput) (*ec2.DescribeSecurityGroupsOutput, error) {
+ return nil, errors.New("denied")
+ }
+ },
+ "subnet in another vpc": func(s *stub) {
+ s.subnets = func(*ec2.DescribeSubnetsInput) (*ec2.DescribeSubnetsOutput, error) {
+ return &ec2.DescribeSubnetsOutput{Subnets: []ec2types.Subnet{{SubnetId: aws.String("subnet-1"), VpcId: aws.String("vpc-2")}}}, nil
+ }
+ },
+ "subnet not found": func(s *stub) {
+ s.subnets = func(*ec2.DescribeSubnetsInput) (*ec2.DescribeSubnetsOutput, error) {
+ return &ec2.DescribeSubnetsOutput{}, nil
+ }
+ },
+ "group in another vpc": func(s *stub) {
+ s.securityGroups = withGroup(func(g *ec2types.SecurityGroup) { g.VpcId = aws.String("vpc-2") })
+ },
+ "group not found": func(s *stub) {
+ s.securityGroups = func(*ec2.DescribeSecurityGroupsInput) (*ec2.DescribeSecurityGroupsOutput, error) {
+ return &ec2.DescribeSecurityGroupsOutput{}, nil
+ }
+ },
+ "two explicit route tables": func(s *stub) {
+ s.routeTables = func(*ec2.DescribeRouteTablesInput) (*ec2.DescribeRouteTablesOutput, error) {
+ return &ec2.DescribeRouteTablesOutput{RouteTables: []ec2types.RouteTable{localTable(), localTable()}}, nil
+ }
+ },
+ "egress to a network": func(s *stub) {
+ s.securityGroups = withGroup(func(g *ec2types.SecurityGroup) {
+ g.IpPermissionsEgress = append(g.IpPermissionsEgress, hostRule(443, "0.0.0.0/0"))
+ })
+ },
+ "egress to every protocol": func(s *stub) {
+ s.securityGroups = withGroup(func(g *ec2types.SecurityGroup) {
+ g.IpPermissionsEgress = append(g.IpPermissionsEgress, ec2types.IpPermission{IpProtocol: aws.String("-1"),
+ IpRanges: []ec2types.IpRange{{CidrIp: aws.String("10.0.1.10/32")}}})
+ })
+ },
+ "egress over a port range": func(s *stub) {
+ s.securityGroups = withGroup(func(g *ec2types.SecurityGroup) {
+ r := hostRule(443, "10.0.1.10/32")
+ r.ToPort = aws.Int32(444)
+ g.IpPermissionsEgress = append(g.IpPermissionsEgress, r)
+ })
+ },
+ "egress over udp": func(s *stub) {
+ s.securityGroups = withGroup(func(g *ec2types.SecurityGroup) {
+ r := hostRule(53, "10.0.1.10/32")
+ r.IpProtocol = aws.String("udp")
+ g.IpPermissionsEgress = append(g.IpPermissionsEgress, r)
+ })
+ },
+ "egress to a prefix list": func(s *stub) {
+ s.securityGroups = withGroup(func(g *ec2types.SecurityGroup) {
+ r := hostRule(443)
+ r.PrefixListIds = []ec2types.PrefixListId{{PrefixListId: aws.String("pl-1")}}
+ g.IpPermissionsEgress = append(g.IpPermissionsEgress, r)
+ })
+ },
+ "egress to a group": func(s *stub) {
+ s.securityGroups = withGroup(func(g *ec2types.SecurityGroup) {
+ r := hostRule(443)
+ r.UserIdGroupPairs = []ec2types.UserIdGroupPair{{GroupId: aws.String("sg-2")}}
+ g.IpPermissionsEgress = append(g.IpPermissionsEgress, r)
+ })
+ },
+ }
+ for name, setup := range refusals {
+ t.Run(name, func(t *testing.T) {
+ s := &stub{}
+ setup(s)
+ got, err := newTestRunner(t, s).AuditNetwork(context.Background())
+ if err == nil {
+ t.Fatalf("AuditNetwork = %+v, nil; want an error", got)
+ }
+ if !reflect.DeepEqual(got, isolatedjob.NetworkAudit{}) {
+ t.Errorf("AuditNetwork with an error = %+v, want the zero audit (every property failed)", got)
+ }
+ })
+ }
+}
diff --git a/internal/isolatedjob/awsjob/publish.go b/internal/isolatedjob/awsjob/publish.go
new file mode 100644
index 00000000..6e9e0dde
--- /dev/null
+++ b/internal/isolatedjob/awsjob/publish.go
@@ -0,0 +1,60 @@
+package awsjob
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "strings"
+
+ "github.com/aws/aws-sdk-go-v2/aws"
+ "github.com/aws/aws-sdk-go-v2/service/sns"
+)
+
+// SNSAPI is the part of the SNS client SNSPublisher calls. *sns.Client
+// satisfies it.
+type SNSAPI interface {
+ Publish(context.Context, *sns.PublishInput, ...func(*sns.Options)) (*sns.PublishOutput, error)
+}
+
+// SNSPublisher sends operator alerts to an SNS topic. It knows nothing of
+// the controller; the controller's command wraps it as its alerter.
+type SNSPublisher struct {
+ TopicARN string
+ Client SNSAPI
+}
+
+// maxSubject is the longest subject SNS takes for email endpoints.
+const maxSubject = 100
+
+// Publish sends one alert: kind in the subject and the message, detail in
+// the message.
+func (p SNSPublisher) Publish(ctx context.Context, kind, detail string) error {
+ if p.TopicARN == "" || p.Client == nil {
+ return errors.New("awsjob: SNS publisher needs a topic and a client")
+ }
+ _, err := p.Client.Publish(ctx, &sns.PublishInput{
+ TopicArn: aws.String(p.TopicARN),
+ Subject: aws.String(subject("Equipo hosted alert: " + kind)),
+ Message: aws.String(kind + "\n\n" + detail),
+ })
+ if err != nil {
+ return fmt.Errorf("awsjob: publish %s alert: %w", kind, err)
+ }
+ return nil
+}
+
+// subject keeps s to what SNS takes in a subject: printable ASCII on one
+// line, at most 100 characters. Anything else becomes '?'.
+func subject(s string) string {
+ var b strings.Builder
+ for _, r := range s {
+ if b.Len() == maxSubject {
+ break
+ }
+ if r < 0x20 || r > 0x7e {
+ r = '?'
+ }
+ b.WriteRune(r)
+ }
+ return b.String()
+}
diff --git a/internal/isolatedjob/awsjob/runner.go b/internal/isolatedjob/awsjob/runner.go
new file mode 100644
index 00000000..9c3a350d
--- /dev/null
+++ b/internal/isolatedjob/awsjob/runner.go
@@ -0,0 +1,388 @@
+package awsjob
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "net/netip"
+ "slices"
+ "strings"
+ "sync"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/isolatedjob"
+ "github.com/aws/aws-sdk-go-v2/aws"
+ awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware"
+ "github.com/aws/aws-sdk-go-v2/service/ec2"
+ vms "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms"
+ "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms/types"
+ "github.com/aws/smithy-go/middleware"
+)
+
+// MicroVMAPI is the part of the Lambda MicroVMs client the runner calls.
+// *lambdamicrovms.Client satisfies it.
+type MicroVMAPI interface {
+ RunMicrovm(context.Context, *vms.RunMicrovmInput, ...func(*vms.Options)) (*vms.RunMicrovmOutput, error)
+ GetMicrovm(context.Context, *vms.GetMicrovmInput, ...func(*vms.Options)) (*vms.GetMicrovmOutput, error)
+ SuspendMicrovm(context.Context, *vms.SuspendMicrovmInput, ...func(*vms.Options)) (*vms.SuspendMicrovmOutput, error)
+ ResumeMicrovm(context.Context, *vms.ResumeMicrovmInput, ...func(*vms.Options)) (*vms.ResumeMicrovmOutput, error)
+ TerminateMicrovm(context.Context, *vms.TerminateMicrovmInput, ...func(*vms.Options)) (*vms.TerminateMicrovmOutput, error)
+ ListMicrovms(context.Context, *vms.ListMicrovmsInput, ...func(*vms.Options)) (*vms.ListMicrovmsOutput, error)
+ GetMicrovmImageVersion(context.Context, *vms.GetMicrovmImageVersionInput, ...func(*vms.Options)) (*vms.GetMicrovmImageVersionOutput, error)
+}
+
+// EC2API is the part of the EC2 client the network audit calls.
+// *ec2.Client satisfies it.
+type EC2API interface {
+ DescribeVpcAttribute(context.Context, *ec2.DescribeVpcAttributeInput, ...func(*ec2.Options)) (*ec2.DescribeVpcAttributeOutput, error)
+ DescribeSubnets(context.Context, *ec2.DescribeSubnetsInput, ...func(*ec2.Options)) (*ec2.DescribeSubnetsOutput, error)
+ DescribeRouteTables(context.Context, *ec2.DescribeRouteTablesInput, ...func(*ec2.Options)) (*ec2.DescribeRouteTablesOutput, error)
+ DescribeSecurityGroups(context.Context, *ec2.DescribeSecurityGroupsInput, ...func(*ec2.Options)) (*ec2.DescribeSecurityGroupsOutput, error)
+}
+
+// API is every provider call the runner makes.
+type API interface {
+ MicroVMAPI
+ EC2API
+}
+
+// NewAPI joins the two clients into an API, for example
+// NewAPI(lambdamicrovms.NewFromConfig(cfg), ec2.NewFromConfig(cfg)).
+func NewAPI(m MicroVMAPI, e EC2API) API {
+ return clients{m, e}
+}
+
+type clients struct {
+ MicroVMAPI
+ EC2API
+}
+
+// Image is one certified base image: its MicroVM image ARN and the image
+// version to run for each size. Memory, CPU and OS capabilities are set on
+// an image version, and one version has one memory size, so each size needs
+// a version of its own.
+type Image struct {
+ ARN string
+ Versions map[isolatedjob.Size]string
+}
+
+// Config is where hosted VMs launch and what they may reach.
+type Config struct {
+ Region string
+ ConnectorID string // ARN of the VPC_EGRESS network connector, the VMs' only egress
+ VPCID string // the VPC the connector's subnet is in
+ VMSubnetID string // the subnet the connector places VMs' traffic in
+ VMSecurityGroupID string // the security group on that traffic
+ Images map[isolatedjob.ImageDigest]Image
+ // Egress is every destination the security group should let VMs
+ // reach: the shared proxies.
+ Egress []netip.AddrPort
+}
+
+// Runner is the isolatedjob.Runner and isolatedjob.NetworkAuditor for AWS
+// Lambda MicroVMs. It is safe for concurrent use.
+type Runner struct {
+ cfg Config
+ api API
+
+ mu sync.Mutex
+ verified map[imageVersion]int // memory in MiB of each version that passed the image check
+}
+
+type imageVersion struct{ arn, version string }
+
+var (
+ _ isolatedjob.Runner = (*Runner)(nil)
+ _ isolatedjob.NetworkAuditor = (*Runner)(nil)
+)
+
+// New checks cfg and returns a Runner that calls api. Every config error
+// wraps isolatedjob.ErrInvalid.
+func New(cfg Config, api API) (*Runner, error) {
+ if err := cfg.check(); err != nil {
+ return nil, fmt.Errorf("%w: awsjob config: %v", isolatedjob.ErrInvalid, err)
+ }
+ if api == nil {
+ return nil, fmt.Errorf("%w: awsjob: no API", isolatedjob.ErrInvalid)
+ }
+ return &Runner{cfg: cfg, api: api, verified: map[imageVersion]int{}}, nil
+}
+
+func (c Config) check() error {
+ for name, v := range map[string]string{"region": c.Region, "connector": c.ConnectorID, "vpc": c.VPCID,
+ "subnet": c.VMSubnetID, "security group": c.VMSecurityGroupID} {
+ if v == "" {
+ return fmt.Errorf("%s is empty", name)
+ }
+ }
+ if !strings.HasPrefix(c.ConnectorID, "arn:") {
+ return fmt.Errorf("connector %q is not an ARN", c.ConnectorID)
+ }
+ if len(c.Images) == 0 {
+ return errors.New("no images")
+ }
+ for d, img := range c.Images {
+ if img.ARN == "" || len(img.Versions) == 0 {
+ return fmt.Errorf("image %s needs an ARN and at least one version", d)
+ }
+ for size, v := range img.Versions {
+ if size.MemoryMiB() == 0 || v == "" {
+ return fmt.Errorf("image %s: size %q, version %q", d, size, v)
+ }
+ }
+ }
+ if len(c.Egress) == 0 {
+ return errors.New("no egress destinations")
+ }
+ for _, e := range c.Egress {
+ if !e.IsValid() || e.Port() == 0 {
+ return fmt.Errorf("egress %v is not an address and port", e)
+ }
+ }
+ return nil
+}
+
+// NoIngressConnectorARN is the Lambda-provided NO_INGRESS connector in
+// region, in the form the developer guide prints for the managed ingress
+// connectors (doc.go, Connectors). The guide does not print this one; the
+// live check confirms it.
+func NoIngressConnectorARN(region string) string {
+ return "arn:aws:lambda:" + region + ":aws:network-connector:aws-network-connector:NO_INGRESS"
+}
+
+// Limits are the spike's findings and doc.go's: 8 hours including suspended
+// time, a 4096-byte run hook payload, and connections dropped by suspend.
+func (r *Runner) Limits() isolatedjob.Limits {
+ return isolatedjob.Limits{
+ MaxLifetime: 28800 * time.Second,
+ MaxBootstrapBytes: 4096,
+ SuspendUsesLifetime: true,
+ ConnectionsSurvive: false,
+ }
+}
+
+// Launch runs one VM with NO_INGRESS, the configured connector as its only
+// egress, no execution role, no idle policy, the spec's lifetime as the
+// maximum duration and the attempt ID as the client token. It refuses with
+// isolatedjob.ErrInvalid, before any run call, a spec that fails Validate,
+// an image or size with no configured version, and an image version that is
+// not x86_64 with all OS capabilities and the size's memory.
+func (r *Runner) Launch(ctx context.Context, s isolatedjob.LaunchSpec) (isolatedjob.Ref, error) {
+ if err := s.Validate(r.Limits()); err != nil {
+ return "", err
+ }
+ img, ok := r.cfg.Images[s.Image]
+ if !ok {
+ return "", fmt.Errorf("%w: image %s is not configured", isolatedjob.ErrInvalid, s.Image)
+ }
+ version, ok := img.Versions[s.Size]
+ if !ok {
+ return "", fmt.Errorf("%w: image %s has no version for size %s", isolatedjob.ErrInvalid, s.Image, s.Size)
+ }
+ seconds := int64(s.MaxLifetime / time.Second)
+ if seconds < 1 || seconds > 28800 {
+ return "", fmt.Errorf("%w: lifetime %v is not 1 to 28800 whole seconds", isolatedjob.ErrInvalid, s.MaxLifetime)
+ }
+ if err := r.checkImageVersion(ctx, img.ARN, version, s.Size); err != nil {
+ return "", err
+ }
+ out, err := r.api.RunMicrovm(ctx, &vms.RunMicrovmInput{
+ ImageIdentifier: aws.String(img.ARN),
+ ImageVersion: aws.String(version),
+ ClientToken: aws.String(s.AttemptID), // always set: the SDK invents one when it is nil
+ IngressNetworkConnectors: []string{NoIngressConnectorARN(r.cfg.Region)},
+ EgressNetworkConnectors: []string{r.cfg.ConnectorID},
+ MaximumDurationInSeconds: aws.Int32(int32(seconds)),
+ RunHookPayload: aws.String(string(s.Bootstrap)),
+ })
+ if err != nil {
+ return "", mapErr("run", err)
+ }
+ id := aws.ToString(out.MicrovmId)
+ if id == "" {
+ return "", fmt.Errorf("awsjob: run %s: the reply has no microvm id", s.AttemptID)
+ }
+ return isolatedjob.Ref(id), nil
+}
+
+// checkImageVersion reads the image version once and refuses it unless it
+// has exactly the "ALL" OS capability, one x86_64 CPU configuration and
+// one memory setting equal to the size's. A pass is kept for the life of
+// the Runner; a failure is not, so a fixed version passes on the next try.
+func (r *Runner) checkImageVersion(ctx context.Context, arn, version string, size isolatedjob.Size) error {
+ key := imageVersion{arn, version}
+ want := size.MemoryMiB()
+ r.mu.Lock()
+ mem, seen := r.verified[key]
+ r.mu.Unlock()
+ if seen {
+ if mem != want {
+ return fmt.Errorf("%w: image version %s:%s has %d MiB, size %s needs %d", isolatedjob.ErrInvalid, arn, version, mem, size, want)
+ }
+ return nil
+ }
+ out, err := r.api.GetMicrovmImageVersion(ctx, &vms.GetMicrovmImageVersionInput{
+ ImageIdentifier: aws.String(arn),
+ ImageVersion: aws.String(version),
+ })
+ if err != nil {
+ err = mapErr("get image version", err)
+ if errors.Is(err, isolatedjob.ErrNotFound) {
+ return fmt.Errorf("%w: image version %s:%s: %w", isolatedjob.ErrInvalid, arn, version, err)
+ }
+ return err
+ }
+ if !slices.Equal(out.AdditionalOsCapabilities, []types.Capability{types.CapabilityAll}) {
+ return fmt.Errorf("%w: image version %s:%s has OS capabilities %v, want [ALL]", isolatedjob.ErrInvalid, arn, version, out.AdditionalOsCapabilities)
+ }
+ if len(out.CpuConfigurations) != 1 || out.CpuConfigurations[0].Architecture != types.ArchitectureX8664 {
+ return fmt.Errorf("%w: image version %s:%s has CPU configurations %v, want one X86_64", isolatedjob.ErrInvalid, arn, version, out.CpuConfigurations)
+ }
+ if len(out.Resources) != 1 || out.Resources[0].MinimumMemoryInMiB == nil || int(*out.Resources[0].MinimumMemoryInMiB) != want {
+ return fmt.Errorf("%w: image version %s:%s has memory %v, size %s needs one setting of %d MiB", isolatedjob.ErrInvalid, arn, version, memories(out.Resources), size, want)
+ }
+ r.mu.Lock()
+ r.verified[key] = want
+ r.mu.Unlock()
+ return nil
+}
+
+func memories(rs []types.Resources) []int32 {
+ var out []int32
+ for _, r := range rs {
+ out = append(out, aws.ToInt32(r.MinimumMemoryInMiB))
+ }
+ return out
+}
+
+// Get reads one VM.
+func (r *Runner) Get(ctx context.Context, ref isolatedjob.Ref) (isolatedjob.Job, error) {
+ if ref == "" {
+ return isolatedjob.Job{}, fmt.Errorf("%w: empty ref", isolatedjob.ErrInvalid)
+ }
+ out, err := r.api.GetMicrovm(ctx, &vms.GetMicrovmInput{MicrovmIdentifier: aws.String(string(ref))})
+ if err != nil {
+ return isolatedjob.Job{}, mapErr("get", err)
+ }
+ if id := aws.ToString(out.MicrovmId); id != "" {
+ ref = isolatedjob.Ref(id)
+ }
+ return job(ref, out.State, out.StateReason, out.StartedAt, out.ResultMetadata), nil
+}
+
+// Suspend asks AWS to suspend the VM.
+func (r *Runner) Suspend(ctx context.Context, ref isolatedjob.Ref) error {
+ if ref == "" {
+ return fmt.Errorf("%w: empty ref", isolatedjob.ErrInvalid)
+ }
+ _, err := r.api.SuspendMicrovm(ctx, &vms.SuspendMicrovmInput{MicrovmIdentifier: aws.String(string(ref))})
+ return mapErr("suspend", err)
+}
+
+// Resume asks AWS to resume the VM. AWS refuses to resume a VM that is not
+// suspended with a ConflictException; Resume then reads the VM once and
+// returns nil only if it is running, so resuming a running VM is a no-op.
+func (r *Runner) Resume(ctx context.Context, ref isolatedjob.Ref) error {
+ if ref == "" {
+ return fmt.Errorf("%w: empty ref", isolatedjob.ErrInvalid)
+ }
+ _, err := r.api.ResumeMicrovm(ctx, &vms.ResumeMicrovmInput{MicrovmIdentifier: aws.String(string(ref))})
+ var conflict *types.ConflictException
+ if !errors.As(err, &conflict) {
+ return mapErr("resume", err)
+ }
+ j, getErr := r.Get(ctx, ref)
+ if getErr != nil {
+ return fmt.Errorf("%w: resume %s refused (%v) and its state is unreadable: %v", isolatedjob.ErrConflict, ref, err, getErr)
+ }
+ if j.State == isolatedjob.StateRunning {
+ return nil
+ }
+ return fmt.Errorf("%w: resume %s refused in state %s: %w", isolatedjob.ErrConflict, ref, j.State, err)
+}
+
+// Stop terminates the VM. AWS has no field for the reason, so it is not
+// sent. A VM AWS no longer knows is already gone, which is success.
+func (r *Runner) Stop(ctx context.Context, ref isolatedjob.Ref, reason string) error {
+ if ref == "" {
+ return fmt.Errorf("%w: empty ref", isolatedjob.ErrInvalid)
+ }
+ _, err := r.api.TerminateMicrovm(ctx, &vms.TerminateMicrovmInput{MicrovmIdentifier: aws.String(string(ref))})
+ if err = mapErr("terminate", err); errors.Is(err, isolatedjob.ErrNotFound) {
+ return nil
+ }
+ return err
+}
+
+// listPageSize is the most ListMicrovms returns in one page.
+const listPageSize = 50
+
+// List reads every VM in the account and region, page by page. If any page
+// fails, repeats a token or holds a VM with no ID, it returns no jobs and
+// an error wrapping isolatedjob.ErrIncomplete.
+func (r *Runner) List(ctx context.Context) ([]isolatedjob.Job, error) {
+ var jobs []isolatedjob.Job
+ var token *string
+ seen := map[string]bool{}
+ for page := 1; ; page++ {
+ out, err := r.api.ListMicrovms(ctx, &vms.ListMicrovmsInput{MaxResults: aws.Int32(listPageSize), NextToken: token})
+ if err != nil {
+ return nil, fmt.Errorf("%w: list page %d: %w", isolatedjob.ErrIncomplete, page, mapErr("list", err))
+ }
+ for _, it := range out.Items {
+ id := aws.ToString(it.MicrovmId)
+ if id == "" {
+ return nil, fmt.Errorf("%w: list page %d holds a VM with no id", isolatedjob.ErrIncomplete, page)
+ }
+ jobs = append(jobs, job(isolatedjob.Ref(id), it.State, nil, it.StartedAt, out.ResultMetadata))
+ }
+ next := aws.ToString(out.NextToken)
+ if next == "" {
+ return jobs, nil
+ }
+ if seen[next] {
+ return nil, fmt.Errorf("%w: list page %d repeats a page token", isolatedjob.ErrIncomplete, page)
+ }
+ seen[next] = true
+ token = aws.String(next)
+ }
+}
+
+// job builds a Job from one response. ProviderAge is the response's server
+// time minus the VM's start time, both from AWS; with either missing, or a
+// start after the server time, AgeKnown is false.
+func job(ref isolatedjob.Ref, raw types.MicrovmState, reason *string, started *time.Time, meta middleware.Metadata) isolatedjob.Job {
+ j := isolatedjob.Job{Ref: ref}
+ j.State, j.Reason = state(raw, aws.ToString(reason))
+ if started != nil {
+ j.StartedAt = *started
+ }
+ if server, ok := awsmiddleware.GetServerTime(meta); ok && started != nil && !server.Before(*started) {
+ j.ProviderAge, j.AgeKnown = server.Sub(*started), true
+ }
+ return j
+}
+
+// state maps an AWS MicroVM state. A state this package does not know is
+// unknown, with the raw value in the reason; AWS says the set can grow.
+func state(raw types.MicrovmState, reason string) (isolatedjob.State, string) {
+ switch raw {
+ case types.MicrovmStatePending:
+ return isolatedjob.StateStarting, reason
+ case types.MicrovmStateRunning:
+ return isolatedjob.StateRunning, reason
+ case types.MicrovmStateSuspending:
+ return isolatedjob.StateSuspending, reason
+ case types.MicrovmStateSuspended:
+ return isolatedjob.StateSuspended, reason
+ case types.MicrovmStateTerminating:
+ return isolatedjob.StateStopping, reason
+ case types.MicrovmStateTerminated:
+ return isolatedjob.StateStopped, reason
+ }
+ why := fmt.Sprintf("provider state %q", string(raw))
+ if reason != "" {
+ why += ": " + reason
+ }
+ return isolatedjob.StateUnknown, why
+}
diff --git a/internal/isolatedjob/awsjob/runner_test.go b/internal/isolatedjob/awsjob/runner_test.go
new file mode 100644
index 00000000..66cc9639
--- /dev/null
+++ b/internal/isolatedjob/awsjob/runner_test.go
@@ -0,0 +1,941 @@
+package awsjob
+
+import (
+ "bytes"
+ "context"
+ "errors"
+ "io"
+ "net/http"
+ "net/netip"
+ "os"
+ "reflect"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/isolatedjob"
+ "amadan.net/rastrillo/rastrillo/budget"
+ "github.com/aws/aws-sdk-go-v2/aws"
+ awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware"
+ "github.com/aws/aws-sdk-go-v2/service/ec2"
+ vms "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms"
+ "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms/types"
+ "github.com/aws/aws-sdk-go-v2/service/sns"
+ "github.com/aws/smithy-go"
+ "github.com/aws/smithy-go/middleware"
+)
+
+func TestMain(m *testing.M) { os.Exit(budget.Main(m)) }
+
+const (
+ testDigest = isolatedjob.ImageDigest("sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef")
+ otherDigest = isolatedjob.ImageDigest("sha256:fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210")
+ testImageARN = "arn:aws:lambda:eu-west-1:123456789012:microvm-image:runner"
+ testConnector = "arn:aws:lambda:eu-west-1:123456789012:network-connector:egress"
+ smallVersion = "3"
+ largeVersion = "4"
+)
+
+func testConfig() Config {
+ return Config{
+ Region: "eu-west-1",
+ ConnectorID: testConnector,
+ VPCID: "vpc-1",
+ VMSubnetID: "subnet-1",
+ VMSecurityGroupID: "sg-1",
+ Images: map[isolatedjob.ImageDigest]Image{
+ testDigest: {ARN: testImageARN, Versions: map[isolatedjob.Size]string{
+ isolatedjob.SizeSmall: smallVersion,
+ isolatedjob.SizeLarge: largeVersion,
+ }},
+ },
+ Egress: []netip.AddrPort{netip.MustParseAddrPort("10.0.1.10:3128"), netip.MustParseAddrPort("10.0.1.11:443")},
+ }
+}
+
+func testSpec() isolatedjob.LaunchSpec {
+ return isolatedjob.LaunchSpec{
+ AttemptID: "attempt-7",
+ Image: testDigest,
+ Size: isolatedjob.SizeSmall,
+ MaxLifetime: 2*time.Hour + 30*time.Minute + 900*time.Millisecond,
+ Bootstrap: []byte(`{"code":"one-time"}` + "\n\t~ end"),
+ }
+}
+
+// goodVersion is an image version that passes the image check for the
+// memory given.
+func goodVersion(memMiB int32) *vms.GetMicrovmImageVersionOutput {
+ return &vms.GetMicrovmImageVersionOutput{
+ AdditionalOsCapabilities: []types.Capability{types.CapabilityAll},
+ CpuConfigurations: []types.CpuConfiguration{{Architecture: types.ArchitectureX8664}},
+ Resources: []types.Resources{{MinimumMemoryInMiB: aws.Int32(memMiB)}},
+ }
+}
+
+// stub is the API with every call recorded. A nil func field gives a
+// default: image versions pass for the configured sizes, run returns
+// "vm-1", and the rest succeed with empty outputs.
+type stub struct {
+ mu sync.Mutex
+ calls []string
+ runIn []*vms.RunMicrovmInput
+ verIn []*vms.GetMicrovmImageVersionInput
+
+ run func(*vms.RunMicrovmInput) (*vms.RunMicrovmOutput, error)
+ get func(*vms.GetMicrovmInput) (*vms.GetMicrovmOutput, error)
+ suspend func(*vms.SuspendMicrovmInput) (*vms.SuspendMicrovmOutput, error)
+ resume func(*vms.ResumeMicrovmInput) (*vms.ResumeMicrovmOutput, error)
+ terminate func(*vms.TerminateMicrovmInput) (*vms.TerminateMicrovmOutput, error)
+ list func(*vms.ListMicrovmsInput) (*vms.ListMicrovmsOutput, error)
+ version func(*vms.GetMicrovmImageVersionInput) (*vms.GetMicrovmImageVersionOutput, error)
+
+ vpcAttr func(*ec2.DescribeVpcAttributeInput) (*ec2.DescribeVpcAttributeOutput, error)
+ subnets func(*ec2.DescribeSubnetsInput) (*ec2.DescribeSubnetsOutput, error)
+ routeTables func(*ec2.DescribeRouteTablesInput) (*ec2.DescribeRouteTablesOutput, error)
+ securityGroups func(*ec2.DescribeSecurityGroupsInput) (*ec2.DescribeSecurityGroupsOutput, error)
+}
+
+func (s *stub) record(op string) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ s.calls = append(s.calls, op)
+}
+
+func (s *stub) count(op string) int {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ n := 0
+ for _, c := range s.calls {
+ if c == op {
+ n++
+ }
+ }
+ return n
+}
+
+func (s *stub) RunMicrovm(_ context.Context, in *vms.RunMicrovmInput, _ ...func(*vms.Options)) (*vms.RunMicrovmOutput, error) {
+ s.record("RunMicrovm")
+ s.mu.Lock()
+ s.runIn = append(s.runIn, in)
+ s.mu.Unlock()
+ if s.run != nil {
+ return s.run(in)
+ }
+ return &vms.RunMicrovmOutput{MicrovmId: aws.String("vm-1"), State: types.MicrovmStatePending}, nil
+}
+
+func (s *stub) GetMicrovm(_ context.Context, in *vms.GetMicrovmInput, _ ...func(*vms.Options)) (*vms.GetMicrovmOutput, error) {
+ s.record("GetMicrovm")
+ if s.get != nil {
+ return s.get(in)
+ }
+ return &vms.GetMicrovmOutput{MicrovmId: in.MicrovmIdentifier, State: types.MicrovmStateRunning}, nil
+}
+
+func (s *stub) SuspendMicrovm(_ context.Context, in *vms.SuspendMicrovmInput, _ ...func(*vms.Options)) (*vms.SuspendMicrovmOutput, error) {
+ s.record("SuspendMicrovm")
+ if s.suspend != nil {
+ return s.suspend(in)
+ }
+ return &vms.SuspendMicrovmOutput{}, nil
+}
+
+func (s *stub) ResumeMicrovm(_ context.Context, in *vms.ResumeMicrovmInput, _ ...func(*vms.Options)) (*vms.ResumeMicrovmOutput, error) {
+ s.record("ResumeMicrovm")
+ if s.resume != nil {
+ return s.resume(in)
+ }
+ return &vms.ResumeMicrovmOutput{}, nil
+}
+
+func (s *stub) TerminateMicrovm(_ context.Context, in *vms.TerminateMicrovmInput, _ ...func(*vms.Options)) (*vms.TerminateMicrovmOutput, error) {
+ s.record("TerminateMicrovm")
+ if s.terminate != nil {
+ return s.terminate(in)
+ }
+ return &vms.TerminateMicrovmOutput{}, nil
+}
+
+func (s *stub) ListMicrovms(_ context.Context, in *vms.ListMicrovmsInput, _ ...func(*vms.Options)) (*vms.ListMicrovmsOutput, error) {
+ s.record("ListMicrovms")
+ if s.list != nil {
+ return s.list(in)
+ }
+ return &vms.ListMicrovmsOutput{}, nil
+}
+
+func (s *stub) GetMicrovmImageVersion(_ context.Context, in *vms.GetMicrovmImageVersionInput, _ ...func(*vms.Options)) (*vms.GetMicrovmImageVersionOutput, error) {
+ s.record("GetMicrovmImageVersion")
+ s.mu.Lock()
+ s.verIn = append(s.verIn, in)
+ s.mu.Unlock()
+ if s.version != nil {
+ return s.version(in)
+ }
+ switch aws.ToString(in.ImageVersion) {
+ case smallVersion:
+ return goodVersion(2048), nil
+ case largeVersion:
+ return goodVersion(4096), nil
+ }
+ return nil, &types.ResourceNotFoundException{Message: aws.String("no such version")}
+}
+
+func newTestRunner(t *testing.T, s *stub) *Runner {
+ t.Helper()
+ r, err := New(testConfig(), s)
+ if err != nil {
+ t.Fatalf("New = %v", err)
+ }
+ return r
+}
+
+func TestNew(t *testing.T) {
+ if _, err := New(testConfig(), &stub{}); err != nil {
+ t.Fatalf("New(good config) = %v", err)
+ }
+ if _, err := New(testConfig(), nil); !errors.Is(err, isolatedjob.ErrInvalid) {
+ t.Errorf("New(nil api) = %v, want ErrInvalid", err)
+ }
+ for name, change := range map[string]func(*Config){
+ "no region": func(c *Config) { c.Region = "" },
+ "no connector": func(c *Config) { c.ConnectorID = "" },
+ "connector not an ARN": func(c *Config) { c.ConnectorID = "egress" },
+ "no vpc": func(c *Config) { c.VPCID = "" },
+ "no subnet": func(c *Config) { c.VMSubnetID = "" },
+ "no security group": func(c *Config) { c.VMSecurityGroupID = "" },
+ "no images": func(c *Config) { c.Images = nil },
+ "image without ARN": func(c *Config) {
+ c.Images[testDigest] = Image{Versions: map[isolatedjob.Size]string{isolatedjob.SizeSmall: "1"}}
+ },
+ "image without versions": func(c *Config) {
+ c.Images[testDigest] = Image{ARN: testImageARN}
+ },
+ "unknown size": func(c *Config) { c.Images[testDigest].Versions["medium"] = "9" },
+ "empty version": func(c *Config) { c.Images[testDigest].Versions[isolatedjob.SizeSmall] = "" },
+ "no egress": func(c *Config) { c.Egress = nil },
+ "egress port 0": func(c *Config) { c.Egress = []netip.AddrPort{netip.MustParseAddrPort("10.0.1.10:0")} },
+ "egress zero": func(c *Config) { c.Egress = []netip.AddrPort{{}} },
+ } {
+ t.Run(name, func(t *testing.T) {
+ c := testConfig()
+ change(&c)
+ if _, err := New(c, &stub{}); !errors.Is(err, isolatedjob.ErrInvalid) {
+ t.Errorf("New = %v, want ErrInvalid", err)
+ }
+ })
+ }
+}
+
+func TestLimits(t *testing.T) {
+ want := isolatedjob.Limits{MaxLifetime: 28800 * time.Second, MaxBootstrapBytes: 4096, SuspendUsesLifetime: true, ConnectionsSurvive: false}
+ if got := newTestRunner(t, &stub{}).Limits(); got != want {
+ t.Fatalf("Limits() = %+v, want %+v", got, want)
+ }
+}
+
+func TestRunRequestShape(t *testing.T) {
+ s := &stub{}
+ r := newTestRunner(t, s)
+ spec := testSpec()
+ ref, err := r.Launch(context.Background(), spec)
+ if err != nil {
+ t.Fatalf("Launch = %v", err)
+ }
+ if ref != "vm-1" {
+ t.Fatalf("Launch = %q, want vm-1", ref)
+ }
+ if len(s.runIn) != 1 {
+ t.Fatalf("RunMicrovm called %d times, want 1", len(s.runIn))
+ }
+ in := s.runIn[0]
+ if got := aws.ToString(in.ImageIdentifier); got != testImageARN {
+ t.Errorf("imageIdentifier = %q, want the image ARN %q", got, testImageARN)
+ }
+ if got := aws.ToString(in.ImageVersion); got != smallVersion {
+ t.Errorf("imageVersion = %q, want the small version %q", got, smallVersion)
+ }
+ if want := []string{NoIngressConnectorARN("eu-west-1")}; !reflect.DeepEqual(in.IngressNetworkConnectors, want) {
+ t.Errorf("ingressNetworkConnectors = %q, want only NO_INGRESS %q", in.IngressNetworkConnectors, want)
+ }
+ if want := []string{testConnector}; !reflect.DeepEqual(in.EgressNetworkConnectors, want) {
+ t.Errorf("egressNetworkConnectors = %q, want only the configured connector %q", in.EgressNetworkConnectors, want)
+ }
+ if in.ExecutionRoleArn != nil {
+ t.Errorf("executionRoleArn = %q, want none", *in.ExecutionRoleArn)
+ }
+ if in.IdlePolicy != nil {
+ t.Errorf("idlePolicy = %+v, want none", *in.IdlePolicy)
+ }
+ if got := aws.ToInt32(in.MaximumDurationInSeconds); in.MaximumDurationInSeconds == nil || got != 9000 {
+ t.Errorf("maximumDurationInSeconds = %d (set %v), want 9000 (2h30m0.9s in whole seconds)", got, in.MaximumDurationInSeconds != nil)
+ }
+ if in.ClientToken == nil || *in.ClientToken != spec.AttemptID {
+ t.Errorf("clientToken = %v, want the attempt id %q", in.ClientToken, spec.AttemptID)
+ }
+ if in.RunHookPayload == nil || !bytes.Equal([]byte(*in.RunHookPayload), spec.Bootstrap) {
+ t.Errorf("runHookPayload = %q, want the bootstrap %q byte for byte", aws.ToString(in.RunHookPayload), spec.Bootstrap)
+ }
+ if in.KmsKeyIdentifier != nil || !reflect.DeepEqual(in.Logging, types.Logging(nil)) {
+ t.Errorf("kmsKeyIdentifier = %v, logging = %v, want neither", in.KmsKeyIdentifier, in.Logging)
+ }
+ want := vms.RunMicrovmInput{
+ ImageIdentifier: aws.String(testImageARN),
+ ImageVersion: aws.String(smallVersion),
+ ClientToken: aws.String(spec.AttemptID),
+ IngressNetworkConnectors: []string{NoIngressConnectorARN("eu-west-1")},
+ EgressNetworkConnectors: []string{testConnector},
+ MaximumDurationInSeconds: aws.Int32(9000),
+ RunHookPayload: aws.String(string(spec.Bootstrap)),
+ }
+ if !reflect.DeepEqual(*in, want) {
+ t.Errorf("RunMicrovmInput = %+v, want exactly %+v", *in, want)
+ }
+
+ t.Run("large uses the large version", func(t *testing.T) {
+ s := &stub{}
+ r := newTestRunner(t, s)
+ spec := testSpec()
+ spec.Size = isolatedjob.SizeLarge
+ spec.MaxLifetime = isolatedjob.HardMaxLifetime
+ if _, err := r.Launch(context.Background(), spec); err != nil {
+ t.Fatalf("Launch = %v", err)
+ }
+ if got := aws.ToString(s.runIn[0].ImageVersion); got != largeVersion {
+ t.Errorf("imageVersion = %q, want %q", got, largeVersion)
+ }
+ if got := aws.ToInt32(s.runIn[0].MaximumDurationInSeconds); got != 28800 {
+ t.Errorf("maximumDurationInSeconds = %d, want 28800", got)
+ }
+ })
+
+ t.Run("same attempt sends the same request", func(t *testing.T) {
+ s := &stub{}
+ r := newTestRunner(t, s)
+ for range 2 {
+ if _, err := r.Launch(context.Background(), testSpec()); err != nil {
+ t.Fatalf("Launch = %v", err)
+ }
+ }
+ if !reflect.DeepEqual(*s.runIn[0], *s.runIn[1]) {
+ t.Errorf("second request %+v differs from first %+v", *s.runIn[1], *s.runIn[0])
+ }
+ })
+
+ for name, change := range map[string]func(*isolatedjob.LaunchSpec, *Config){
+ "unmapped digest": func(s *isolatedjob.LaunchSpec, _ *Config) { s.Image = otherDigest },
+ "size with no version": func(_ *isolatedjob.LaunchSpec, c *Config) {
+ delete(c.Images[testDigest].Versions, isolatedjob.SizeLarge)
+ },
+ "spec invalid": func(s *isolatedjob.LaunchSpec, _ *Config) { s.AttemptID = "" },
+ } {
+ t.Run(name, func(t *testing.T) {
+ s := &stub{}
+ c := testConfig()
+ spec := testSpec()
+ spec.Size = isolatedjob.SizeLarge
+ change(&spec, &c)
+ r, err := New(c, s)
+ if err != nil {
+ t.Fatalf("New = %v", err)
+ }
+ ref, err := r.Launch(context.Background(), spec)
+ if !errors.Is(err, isolatedjob.ErrInvalid) {
+ t.Errorf("Launch = (%q, %v), want ErrInvalid", ref, err)
+ }
+ if len(s.calls) != 0 {
+ t.Errorf("API calls %v, want none before the refusal", s.calls)
+ }
+ })
+ }
+
+ t.Run("oversize bootstrap", func(t *testing.T) {
+ s := &stub{}
+ spec := testSpec()
+ spec.Bootstrap = bytes.Repeat([]byte("x"), 4097)
+ if _, err := newTestRunner(t, s).Launch(context.Background(), spec); !errors.Is(err, isolatedjob.ErrBootstrapTooLarge) {
+ t.Errorf("Launch = %v, want ErrBootstrapTooLarge", err)
+ }
+ if len(s.calls) != 0 {
+ t.Errorf("API calls %v, want none", s.calls)
+ }
+ })
+
+ t.Run("no microvm id in the reply", func(t *testing.T) {
+ s := &stub{run: func(*vms.RunMicrovmInput) (*vms.RunMicrovmOutput, error) { return &vms.RunMicrovmOutput{}, nil }}
+ if ref, err := newTestRunner(t, s).Launch(context.Background(), testSpec()); err == nil {
+ t.Errorf("Launch = %q, nil; want an error for a reply with no id", ref)
+ }
+ })
+}
+
+func TestImageVersionChecked(t *testing.T) {
+ rows := []struct {
+ name string
+ change func(*vms.GetMicrovmImageVersionOutput)
+ pass bool
+ }{
+ {"passing", func(*vms.GetMicrovmImageVersionOutput) {}, true},
+ {"capabilities missing", func(o *vms.GetMicrovmImageVersionOutput) { o.AdditionalOsCapabilities = nil }, false},
+ {"capabilities twice", func(o *vms.GetMicrovmImageVersionOutput) {
+ o.AdditionalOsCapabilities = []types.Capability{types.CapabilityAll, types.CapabilityAll}
+ }, false},
+ {"capability unknown", func(o *vms.GetMicrovmImageVersionOutput) {
+ o.AdditionalOsCapabilities = []types.Capability{"NET_ADMIN"}
+ }, false},
+ {"cpu ARM_64", func(o *vms.GetMicrovmImageVersionOutput) {
+ o.CpuConfigurations = []types.CpuConfiguration{{Architecture: types.ArchitectureArm64}}
+ }, false},
+ {"cpu missing", func(o *vms.GetMicrovmImageVersionOutput) { o.CpuConfigurations = nil }, false},
+ {"cpu both", func(o *vms.GetMicrovmImageVersionOutput) {
+ o.CpuConfigurations = []types.CpuConfiguration{{Architecture: types.ArchitectureX8664}, {Architecture: types.ArchitectureArm64}}
+ }, false},
+ {"memory of the other size", func(o *vms.GetMicrovmImageVersionOutput) { o.Resources[0].MinimumMemoryInMiB = aws.Int32(4096) }, false},
+ {"memory missing", func(o *vms.GetMicrovmImageVersionOutput) { o.Resources = nil }, false},
+ {"memory unset", func(o *vms.GetMicrovmImageVersionOutput) { o.Resources[0].MinimumMemoryInMiB = nil }, false},
+ }
+ for _, row := range rows {
+ t.Run(row.name, func(t *testing.T) {
+ s := &stub{version: func(*vms.GetMicrovmImageVersionInput) (*vms.GetMicrovmImageVersionOutput, error) {
+ o := goodVersion(2048)
+ row.change(o)
+ return o, nil
+ }}
+ r := newTestRunner(t, s)
+ _, err := r.Launch(context.Background(), testSpec())
+ if row.pass {
+ if err != nil {
+ t.Fatalf("Launch = %v, want nil", err)
+ }
+ in := s.verIn[0]
+ if aws.ToString(in.ImageIdentifier) != testImageARN || aws.ToString(in.ImageVersion) != smallVersion {
+ t.Errorf("image version read %q/%q, want %q/%q", aws.ToString(in.ImageIdentifier), aws.ToString(in.ImageVersion), testImageARN, smallVersion)
+ }
+ return
+ }
+ if !errors.Is(err, isolatedjob.ErrInvalid) {
+ t.Errorf("Launch = %v, want ErrInvalid", err)
+ }
+ if n := s.count("RunMicrovm"); n != 0 {
+ t.Errorf("RunMicrovm called %d times after a failed image check, want 0", n)
+ }
+ })
+ }
+
+ t.Run("a pass is cached per version", func(t *testing.T) {
+ s := &stub{}
+ r := newTestRunner(t, s)
+ for range 3 {
+ if _, err := r.Launch(context.Background(), testSpec()); err != nil {
+ t.Fatalf("Launch = %v", err)
+ }
+ }
+ if n := s.count("GetMicrovmImageVersion"); n != 1 {
+ t.Errorf("GetMicrovmImageVersion called %d times for one version, want 1", n)
+ }
+ large := testSpec()
+ large.Size = isolatedjob.SizeLarge
+ if _, err := r.Launch(context.Background(), large); err != nil {
+ t.Fatalf("Launch(large) = %v", err)
+ }
+ if n := s.count("GetMicrovmImageVersion"); n != 2 {
+ t.Errorf("GetMicrovmImageVersion called %d times for two versions, want 2", n)
+ }
+ })
+
+ t.Run("a failure is not cached", func(t *testing.T) {
+ bad := true
+ s := &stub{version: func(*vms.GetMicrovmImageVersionInput) (*vms.GetMicrovmImageVersionOutput, error) {
+ if bad {
+ return goodVersion(4096), nil
+ }
+ return goodVersion(2048), nil
+ }}
+ r := newTestRunner(t, s)
+ if _, err := r.Launch(context.Background(), testSpec()); !errors.Is(err, isolatedjob.ErrInvalid) {
+ t.Fatalf("first Launch = %v, want ErrInvalid", err)
+ }
+ bad = false
+ if _, err := r.Launch(context.Background(), testSpec()); err != nil {
+ t.Fatalf("second Launch after the version was fixed = %v, want nil", err)
+ }
+ })
+
+ t.Run("one version mapped to both sizes", func(t *testing.T) {
+ s := &stub{}
+ c := testConfig()
+ c.Images[testDigest].Versions[isolatedjob.SizeLarge] = smallVersion
+ r, err := New(c, s)
+ if err != nil {
+ t.Fatalf("New = %v", err)
+ }
+ if _, err := r.Launch(context.Background(), testSpec()); err != nil {
+ t.Fatalf("Launch(small) = %v", err)
+ }
+ large := testSpec()
+ large.Size = isolatedjob.SizeLarge
+ if _, err := r.Launch(context.Background(), large); !errors.Is(err, isolatedjob.ErrInvalid) {
+ t.Errorf("Launch(large) on the cached 2048 MiB version = %v, want ErrInvalid", err)
+ }
+ })
+
+ t.Run("version read fails", func(t *testing.T) {
+ s := &stub{version: func(*vms.GetMicrovmImageVersionInput) (*vms.GetMicrovmImageVersionOutput, error) {
+ return nil, &types.ThrottlingException{Message: aws.String("slow down")}
+ }}
+ if _, err := newTestRunner(t, s).Launch(context.Background(), testSpec()); !errors.Is(err, isolatedjob.ErrThrottled) {
+ t.Errorf("Launch = %v, want ErrThrottled", err)
+ }
+ if n := s.count("RunMicrovm"); n != 0 {
+ t.Errorf("RunMicrovm called %d times, want 0", n)
+ }
+ })
+}
+
+func TestStateMapping(t *testing.T) {
+ rows := []struct {
+ raw types.MicrovmState
+ reason *string
+ want isolatedjob.State
+ inWhy string
+ }{
+ {types.MicrovmStatePending, nil, isolatedjob.StateStarting, ""},
+ {types.MicrovmStateRunning, nil, isolatedjob.StateRunning, ""},
+ {types.MicrovmStateSuspending, nil, isolatedjob.StateSuspending, ""},
+ {types.MicrovmStateSuspended, nil, isolatedjob.StateSuspended, ""},
+ {types.MicrovmStateTerminating, nil, isolatedjob.StateStopping, ""},
+ {types.MicrovmStateTerminated, aws.String("run hook timed out"), isolatedjob.StateStopped, "run hook timed out"},
+ {"HIBERNATING", nil, isolatedjob.StateUnknown, "HIBERNATING"},
+ {"FAILED", aws.String("host lost"), isolatedjob.StateUnknown, "FAILED"},
+ {"", nil, isolatedjob.StateUnknown, `""`},
+ }
+ for _, row := range rows {
+ t.Run(string(row.raw), func(t *testing.T) {
+ s := &stub{get: func(in *vms.GetMicrovmInput) (*vms.GetMicrovmOutput, error) {
+ return &vms.GetMicrovmOutput{MicrovmId: in.MicrovmIdentifier, State: row.raw, StateReason: row.reason}, nil
+ }}
+ job, err := newTestRunner(t, s).Get(context.Background(), "vm-1")
+ if err != nil {
+ t.Fatalf("Get = %v", err)
+ }
+ if job.State != row.want {
+ t.Errorf("Get(%s).State = %s, want %s", row.raw, job.State, row.want)
+ }
+ if job.Ref != "vm-1" {
+ t.Errorf("Get.Ref = %q, want vm-1", job.Ref)
+ }
+ if !strings.Contains(job.Reason, row.inWhy) {
+ t.Errorf("Get(%s).Reason = %q, want it to hold %q", row.raw, job.Reason, row.inWhy)
+ }
+ })
+ }
+}
+
+// serverMeta returns response metadata carrying the server time at, as the
+// SDK's own middleware records it from a Date header. The metadata key is
+// unexported, so a real client answers one canned response through a
+// transport that never leaves the process.
+func serverMeta(t *testing.T, at time.Time) middleware.Metadata {
+ t.Helper()
+ client := vms.New(vms.Options{
+ Region: "eu-west-1",
+ Credentials: aws.AnonymousCredentials{},
+ HTTPClient: dateTransport{at},
+ })
+ out, err := client.GetMicrovm(context.Background(), &vms.GetMicrovmInput{MicrovmIdentifier: aws.String("vm-meta")})
+ if err != nil {
+ t.Fatalf("canned GetMicrovm: %v", err)
+ }
+ if got, ok := awsmiddleware.GetServerTime(out.ResultMetadata); !ok || !got.Equal(at) {
+ t.Fatalf("canned metadata server time = %v, %v; want %v", got, ok, at)
+ }
+ return out.ResultMetadata
+}
+
+type dateTransport struct{ at time.Time }
+
+func (d dateTransport) Do(r *http.Request) (*http.Response, error) {
+ h := http.Header{}
+ h.Set("Content-Type", "application/json")
+ h.Set("Date", d.at.UTC().Format(http.TimeFormat))
+ return &http.Response{StatusCode: 200, Header: h, Body: io.NopCloser(strings.NewReader("{}")), Request: r}, nil
+}
+
+func TestProviderAge(t *testing.T) {
+ started := time.Date(2026, 1, 2, 10, 0, 0, 0, time.UTC)
+ server := started.Add(90 * time.Second)
+ meta := serverMeta(t, server)
+
+ rows := []struct {
+ name string
+ started *time.Time
+ meta middleware.Metadata
+ age time.Duration
+ known bool
+ }{
+ {"both present", &started, meta, 90 * time.Second, true},
+ {"no server time", &started, middleware.Metadata{}, 0, false},
+ {"no start time", nil, meta, 0, false},
+ {"start after server time", aws.Time(server.Add(time.Minute)), meta, 0, false},
+ }
+ for _, row := range rows {
+ t.Run("get "+row.name, func(t *testing.T) {
+ s := &stub{get: func(in *vms.GetMicrovmInput) (*vms.GetMicrovmOutput, error) {
+ return &vms.GetMicrovmOutput{MicrovmId: in.MicrovmIdentifier, State: types.MicrovmStateRunning, StartedAt: row.started, ResultMetadata: row.meta}, nil
+ }}
+ job, err := newTestRunner(t, s).Get(context.Background(), "vm-1")
+ if err != nil {
+ t.Fatalf("Get = %v", err)
+ }
+ if job.ProviderAge != row.age || job.AgeKnown != row.known {
+ t.Errorf("Get = age %v known %v, want age %v known %v", job.ProviderAge, job.AgeKnown, row.age, row.known)
+ }
+ if row.started != nil && !job.StartedAt.Equal(*row.started) {
+ t.Errorf("Get.StartedAt = %v, want %v", job.StartedAt, *row.started)
+ }
+ })
+ t.Run("list "+row.name, func(t *testing.T) {
+ s := &stub{list: func(*vms.ListMicrovmsInput) (*vms.ListMicrovmsOutput, error) {
+ return &vms.ListMicrovmsOutput{
+ Items: []types.MicrovmItem{{MicrovmId: aws.String("vm-1"), State: types.MicrovmStateRunning, StartedAt: row.started}},
+ ResultMetadata: row.meta,
+ }, nil
+ }}
+ jobs, err := newTestRunner(t, s).List(context.Background())
+ if err != nil || len(jobs) != 1 {
+ t.Fatalf("List = %v, %v; want one job", jobs, err)
+ }
+ if jobs[0].ProviderAge != row.age || jobs[0].AgeKnown != row.known {
+ t.Errorf("List = age %v known %v, want age %v known %v", jobs[0].ProviderAge, jobs[0].AgeKnown, row.age, row.known)
+ }
+ })
+ }
+}
+
+var sentinels = []error{isolatedjob.ErrNotFound, isolatedjob.ErrInvalid, isolatedjob.ErrConflict,
+ isolatedjob.ErrThrottled, isolatedjob.ErrIncomplete, isolatedjob.ErrBootstrapTooLarge}
+
+func TestErrorMapping(t *testing.T) {
+ notFound := &types.ResourceNotFoundException{Message: aws.String("gone")}
+ conflict := &types.ConflictException{Message: aws.String("state")}
+ throttle := &types.ThrottlingException{Message: aws.String("slow")}
+ tooMany := &types.TooManyRequestsException{Message: aws.String("slow")}
+ quota := &types.ServiceQuotaExceededException{Message: aws.String("quota")}
+ validation := &types.ValidationException{Message: aws.String("bad")}
+ denied := &types.AccessDeniedException{Message: aws.String("no")}
+ internal := &types.InternalServerException{Message: aws.String("oops")}
+ capacity := &types.InsufficientCapacityException{Message: aws.String("full")}
+ generic := &smithy.GenericAPIError{Code: "SomethingNew", Message: "new"}
+ params := &smithy.InvalidParamsError{Context: "GetMicrovmInput"}
+
+ ops := map[string]func(*Runner, error) error{
+ "launch": func(r *Runner, e error) error {
+ r.api.(*stub).run = func(*vms.RunMicrovmInput) (*vms.RunMicrovmOutput, error) { return nil, e }
+ _, err := r.Launch(context.Background(), testSpec())
+ return err
+ },
+ "get": func(r *Runner, e error) error {
+ r.api.(*stub).get = func(*vms.GetMicrovmInput) (*vms.GetMicrovmOutput, error) { return nil, e }
+ _, err := r.Get(context.Background(), "vm-1")
+ return err
+ },
+ "suspend": func(r *Runner, e error) error {
+ r.api.(*stub).suspend = func(*vms.SuspendMicrovmInput) (*vms.SuspendMicrovmOutput, error) { return nil, e }
+ return r.Suspend(context.Background(), "vm-1")
+ },
+ "resume": func(r *Runner, e error) error {
+ r.api.(*stub).resume = func(*vms.ResumeMicrovmInput) (*vms.ResumeMicrovmOutput, error) { return nil, e }
+ return r.Resume(context.Background(), "vm-1")
+ },
+ "stop": func(r *Runner, e error) error {
+ r.api.(*stub).terminate = func(*vms.TerminateMicrovmInput) (*vms.TerminateMicrovmOutput, error) { return nil, e }
+ return r.Stop(context.Background(), "vm-1", "test")
+ },
+ }
+ rows := []struct {
+ op string
+ err error
+ want error // nil with none: no sentinel; errNone: the call succeeds
+ }{
+ {"get", notFound, isolatedjob.ErrNotFound},
+ {"suspend", notFound, isolatedjob.ErrNotFound},
+ {"resume", notFound, isolatedjob.ErrNotFound},
+ {"stop", notFound, errNone},
+ {"launch", throttle, isolatedjob.ErrThrottled},
+ {"launch", tooMany, isolatedjob.ErrThrottled},
+ {"launch", quota, isolatedjob.ErrThrottled},
+ {"get", throttle, isolatedjob.ErrThrottled},
+ {"stop", throttle, isolatedjob.ErrThrottled},
+ {"launch", validation, isolatedjob.ErrInvalid},
+ {"get", validation, isolatedjob.ErrInvalid},
+ {"get", params, isolatedjob.ErrInvalid},
+ {"launch", conflict, isolatedjob.ErrConflict},
+ {"suspend", conflict, isolatedjob.ErrConflict},
+ {"stop", conflict, isolatedjob.ErrConflict},
+ {"launch", denied, nil},
+ {"launch", internal, nil},
+ {"launch", capacity, nil},
+ {"get", generic, nil},
+ {"stop", denied, nil},
+ }
+ for _, row := range rows {
+ t.Run(row.op+" "+errorName(row.err), func(t *testing.T) {
+ r := newTestRunner(t, &stub{})
+ err := ops[row.op](r, row.err)
+ switch {
+ case row.want == errNone:
+ if err != nil {
+ t.Fatalf("%s = %v, want nil", row.op, err)
+ }
+ case row.want == nil:
+ if err == nil {
+ t.Fatalf("%s = nil, want an error", row.op)
+ }
+ for _, s := range sentinels {
+ if errors.Is(err, s) {
+ t.Errorf("%s = %v, matches %v; want no sentinel", row.op, err, s)
+ }
+ }
+ default:
+ if !errors.Is(err, row.want) {
+ t.Errorf("%s = %v, want %v", row.op, err, row.want)
+ }
+ }
+ if err != nil && !errors.Is(err, row.err) {
+ t.Errorf("%s = %v, lost the provider error %v", row.op, err, row.err)
+ }
+ })
+ }
+}
+
+var errNone = errors.New("no error")
+
+func errorName(err error) string {
+ var api smithy.APIError
+ if errors.As(err, &api) {
+ return api.ErrorCode()
+ }
+ return reflect.TypeOf(err).Elem().Name()
+}
+
+func TestResumeConflict(t *testing.T) {
+ conflict := &types.ConflictException{Message: aws.String("not suspended")}
+ rows := []struct {
+ name string
+ get func(*vms.GetMicrovmInput) (*vms.GetMicrovmOutput, error)
+ ok bool
+ }{
+ {"running is a no-op", func(in *vms.GetMicrovmInput) (*vms.GetMicrovmOutput, error) {
+ return &vms.GetMicrovmOutput{MicrovmId: in.MicrovmIdentifier, State: types.MicrovmStateRunning}, nil
+ }, true},
+ {"suspended conflicts", func(in *vms.GetMicrovmInput) (*vms.GetMicrovmOutput, error) {
+ return &vms.GetMicrovmOutput{MicrovmId: in.MicrovmIdentifier, State: types.MicrovmStateSuspended}, nil
+ }, false},
+ {"terminating conflicts", func(in *vms.GetMicrovmInput) (*vms.GetMicrovmOutput, error) {
+ return &vms.GetMicrovmOutput{MicrovmId: in.MicrovmIdentifier, State: types.MicrovmStateTerminating}, nil
+ }, false},
+ {"unreadable conflicts", func(*vms.GetMicrovmInput) (*vms.GetMicrovmOutput, error) {
+ return nil, &types.ThrottlingException{Message: aws.String("slow")}
+ }, false},
+ }
+ for _, row := range rows {
+ t.Run(row.name, func(t *testing.T) {
+ s := &stub{
+ resume: func(*vms.ResumeMicrovmInput) (*vms.ResumeMicrovmOutput, error) { return nil, conflict },
+ get: row.get,
+ }
+ err := newTestRunner(t, s).Resume(context.Background(), "vm-1")
+ if row.ok && err != nil {
+ t.Errorf("Resume = %v, want nil", err)
+ }
+ if !row.ok && !errors.Is(err, isolatedjob.ErrConflict) {
+ t.Errorf("Resume = %v, want ErrConflict", err)
+ }
+ if n := s.count("GetMicrovm"); n != 1 {
+ t.Errorf("GetMicrovm called %d times, want exactly 1", n)
+ }
+ })
+ }
+
+ t.Run("success reads nothing", func(t *testing.T) {
+ s := &stub{}
+ if err := newTestRunner(t, s).Resume(context.Background(), "vm-1"); err != nil {
+ t.Fatalf("Resume = %v", err)
+ }
+ if n := s.count("GetMicrovm"); n != 0 {
+ t.Errorf("GetMicrovm called %d times after a clean resume, want 0", n)
+ }
+ })
+}
+
+func TestRequestsNameTheRef(t *testing.T) {
+ var ids []string
+ s := &stub{
+ get: func(in *vms.GetMicrovmInput) (*vms.GetMicrovmOutput, error) {
+ ids = append(ids, aws.ToString(in.MicrovmIdentifier))
+ return &vms.GetMicrovmOutput{MicrovmId: in.MicrovmIdentifier, State: types.MicrovmStateRunning}, nil
+ },
+ suspend: func(in *vms.SuspendMicrovmInput) (*vms.SuspendMicrovmOutput, error) {
+ ids = append(ids, aws.ToString(in.MicrovmIdentifier))
+ return &vms.SuspendMicrovmOutput{}, nil
+ },
+ resume: func(in *vms.ResumeMicrovmInput) (*vms.ResumeMicrovmOutput, error) {
+ ids = append(ids, aws.ToString(in.MicrovmIdentifier))
+ return &vms.ResumeMicrovmOutput{}, nil
+ },
+ terminate: func(in *vms.TerminateMicrovmInput) (*vms.TerminateMicrovmOutput, error) {
+ ids = append(ids, aws.ToString(in.MicrovmIdentifier))
+ return &vms.TerminateMicrovmOutput{}, nil
+ },
+ }
+ r := newTestRunner(t, s)
+ ctx := context.Background()
+ if _, err := r.Get(ctx, "vm-a"); err != nil {
+ t.Fatal(err)
+ }
+ if err := r.Suspend(ctx, "vm-b"); err != nil {
+ t.Fatal(err)
+ }
+ if err := r.Resume(ctx, "vm-c"); err != nil {
+ t.Fatal(err)
+ }
+ if err := r.Stop(ctx, "vm-d", "done"); err != nil {
+ t.Fatal(err)
+ }
+ if want := []string{"vm-a", "vm-b", "vm-c", "vm-d"}; !reflect.DeepEqual(ids, want) {
+ t.Errorf("identifiers sent = %q, want %q", ids, want)
+ }
+ for _, call := range []func() error{
+ func() error { _, err := r.Get(ctx, ""); return err },
+ func() error { return r.Suspend(ctx, "") },
+ func() error { return r.Resume(ctx, "") },
+ func() error { return r.Stop(ctx, "", "x") },
+ } {
+ if err := call(); !errors.Is(err, isolatedjob.ErrInvalid) {
+ t.Errorf("call with an empty ref = %v, want ErrInvalid", err)
+ }
+ }
+}
+
+func TestListAllPages(t *testing.T) {
+ item := func(id string) types.MicrovmItem {
+ return types.MicrovmItem{MicrovmId: aws.String(id), State: types.MicrovmStateRunning, StartedAt: aws.Time(time.Unix(1_800_000_000, 0))}
+ }
+ t.Run("three pages", func(t *testing.T) {
+ var tokens []string
+ pages := map[string]*vms.ListMicrovmsOutput{
+ "": {Items: []types.MicrovmItem{item("vm-1"), item("vm-2")}, NextToken: aws.String("t2")},
+ "t2": {Items: []types.MicrovmItem{item("vm-3")}, NextToken: aws.String("t3")},
+ "t3": {Items: []types.MicrovmItem{{MicrovmId: aws.String("vm-4"), State: "NEW"}}},
+ }
+ s := &stub{list: func(in *vms.ListMicrovmsInput) (*vms.ListMicrovmsOutput, error) {
+ tokens = append(tokens, aws.ToString(in.NextToken))
+ if aws.ToInt32(in.MaxResults) != 50 {
+ t.Errorf("maxResults = %d, want 50", aws.ToInt32(in.MaxResults))
+ }
+ if in.ImageIdentifier != nil || in.ImageVersion != nil {
+ t.Errorf("list filtered by image %v/%v, want every VM", in.ImageIdentifier, in.ImageVersion)
+ }
+ return pages[aws.ToString(in.NextToken)], nil
+ }}
+ jobs, err := newTestRunner(t, s).List(context.Background())
+ if err != nil {
+ t.Fatalf("List = %v", err)
+ }
+ var refs []isolatedjob.Ref
+ for _, j := range jobs {
+ refs = append(refs, j.Ref)
+ }
+ if want := []isolatedjob.Ref{"vm-1", "vm-2", "vm-3", "vm-4"}; !reflect.DeepEqual(refs, want) {
+ t.Errorf("List refs = %v, want %v", refs, want)
+ }
+ if want := []string{"", "t2", "t3"}; !reflect.DeepEqual(tokens, want) {
+ t.Errorf("tokens sent = %q, want %q", tokens, want)
+ }
+ if jobs[3].State != isolatedjob.StateUnknown || !strings.Contains(jobs[3].Reason, "NEW") {
+ t.Errorf("vm-4 = %s %q, want unknown naming NEW", jobs[3].State, jobs[3].Reason)
+ }
+ })
+
+ failing := map[string]func(in *vms.ListMicrovmsInput) (*vms.ListMicrovmsOutput, error){
+ "page two fails": func(in *vms.ListMicrovmsInput) (*vms.ListMicrovmsOutput, error) {
+ if in.NextToken == nil {
+ return &vms.ListMicrovmsOutput{Items: []types.MicrovmItem{item("vm-1")}, NextToken: aws.String("t2")}, nil
+ }
+ return nil, &types.InternalServerException{Message: aws.String("oops")}
+ },
+ "page one fails": func(*vms.ListMicrovmsInput) (*vms.ListMicrovmsOutput, error) {
+ return nil, &types.ThrottlingException{Message: aws.String("slow")}
+ },
+ "token repeats": func(*vms.ListMicrovmsInput) (*vms.ListMicrovmsOutput, error) {
+ return &vms.ListMicrovmsOutput{Items: []types.MicrovmItem{item("vm-1")}, NextToken: aws.String("same")}, nil
+ },
+ "item without an id": func(*vms.ListMicrovmsInput) (*vms.ListMicrovmsOutput, error) {
+ return &vms.ListMicrovmsOutput{Items: []types.MicrovmItem{item("vm-1"), {State: types.MicrovmStateRunning}}}, nil
+ },
+ }
+ for name, list := range failing {
+ t.Run(name, func(t *testing.T) {
+ jobs, err := newTestRunner(t, &stub{list: list}).List(context.Background())
+ if !errors.Is(err, isolatedjob.ErrIncomplete) {
+ t.Errorf("List = %v, want ErrIncomplete", err)
+ }
+ if jobs != nil {
+ t.Errorf("List returned %d jobs with an error, want none", len(jobs))
+ }
+ })
+ }
+}
+
+type snsStub struct {
+ in []*sns.PublishInput
+ err error
+}
+
+func (s *snsStub) Publish(_ context.Context, in *sns.PublishInput, _ ...func(*sns.Options)) (*sns.PublishOutput, error) {
+ s.in = append(s.in, in)
+ return &sns.PublishOutput{}, s.err
+}
+
+func TestSNSPublish(t *testing.T) {
+ const topic = "arn:aws:sns:eu-west-1:123456789012:equipo-hosted"
+ s := &snsStub{}
+ p := SNSPublisher{TopicARN: topic, Client: s}
+ if err := p.Publish(context.Background(), "audit_failed", "route out present\nin subnet-1"); err != nil {
+ t.Fatalf("Publish = %v", err)
+ }
+ in := s.in[0]
+ if aws.ToString(in.TopicArn) != topic {
+ t.Errorf("TopicArn = %q, want %q", aws.ToString(in.TopicArn), topic)
+ }
+ if subj := aws.ToString(in.Subject); !strings.Contains(subj, "audit_failed") || len(subj) > 100 || strings.ContainsAny(subj, "\r\n") {
+ t.Errorf("Subject = %q, want the kind on one line of at most 100 characters", subj)
+ }
+ if msg := aws.ToString(in.Message); !strings.Contains(msg, "audit_failed") || !strings.Contains(msg, "route out present\nin subnet-1") {
+ t.Errorf("Message = %q, want the kind and the detail", msg)
+ }
+
+ long := SNSPublisher{TopicARN: topic, Client: s}
+ if err := long.Publish(context.Background(), strings.Repeat("k", 200)+"\x00é", "d"); err != nil {
+ t.Fatalf("Publish(long kind) = %v", err)
+ }
+ if subj := aws.ToString(s.in[1].Subject); len(subj) > 100 || strings.ContainsFunc(subj, func(r rune) bool { return r < 0x20 || r > 0x7e }) {
+ t.Errorf("Subject = %q, want printable ASCII of at most 100 characters", subj)
+ }
+
+ failing := &snsStub{err: errors.New("denied")}
+ if err := (SNSPublisher{TopicARN: topic, Client: failing}).Publish(context.Background(), "k", "d"); err == nil || !strings.Contains(err.Error(), "denied") {
+ t.Errorf("Publish with a failing client = %v, want the client's error", err)
+ }
+ for name, p := range map[string]SNSPublisher{"no topic": {Client: s}, "no client": {TopicARN: topic}} {
+ before := len(s.in)
+ if err := p.Publish(context.Background(), "k", "d"); err == nil {
+ t.Errorf("%s: Publish = nil, want an error", name)
+ }
+ if len(s.in) != before {
+ t.Errorf("%s: Publish called the client", name)
+ }
+ }
+}
diff --git a/internal/isolatedjob/guardfixture/doc.go b/internal/isolatedjob/guardfixture/doc.go
new file mode 100644
index 00000000..16d0959d
--- /dev/null
+++ b/internal/isolatedjob/guardfixture/doc.go
@@ -0,0 +1,5 @@
+// Package guardfixture is an empty package with no imports. It exists only
+// so the provider guard in isolatedjob (TestProviderTypesStayInAdapter) can be
+// shown to fail: give this package an AWS SDK import and the guard must name
+// it. Nothing imports it.
+package guardfixture
diff --git a/internal/isolatedjob/providerguard_test.go b/internal/isolatedjob/providerguard_test.go
new file mode 100644
index 00000000..c9bedfa4
--- /dev/null
+++ b/internal/isolatedjob/providerguard_test.go
@@ -0,0 +1,112 @@
+package isolatedjob
+
+import (
+ "encoding/json"
+ "errors"
+ "io"
+ "os/exec"
+ "slices"
+ "strings"
+ "testing"
+
+ "amadan.net/oficina/equipo/internal/testci"
+)
+
+const guardModule = "amadan.net/oficina/equipo"
+
+// providerAdapter is the one package tree that may hold AWS SDK types.
+const providerAdapter = guardModule + "/internal/isolatedjob/awsjob"
+
+// providerAllowed are the composition points that wire the adapter in. Only
+// commands belong here: a library package that needs AWS is a leak. Slice
+// 1b adds cmd/equipo-vm-init and cmd/equipo-hosted-image.
+var providerAllowed = []string{
+ guardModule + "/cmd/equipo-hosted-controller",
+}
+
+// TestProviderTypesStayInAdapter keeps the AWS SDK and the adapter out of
+// every package of this module except the adapter itself and the commands
+// in providerAllowed. Test files count: a test that imports the SDK is a
+// package that depends on it.
+func TestProviderTypesStayInAdapter(t *testing.T) {
+ for _, p := range providerAllowed {
+ if !strings.HasPrefix(p, guardModule+"/cmd/") {
+ t.Errorf("providerAllowed holds %s; only cmd/ composition points may depend on the AWS SDK or awsjob", p)
+ }
+ }
+
+ // go list reads every package in the tree, which go test cannot see,
+ // so declare the whole tree: a new or edited package reruns the guard.
+ testci.RepoFiles(t)
+ out, err := exec.Command("go", "list", "-test", "-json=ImportPath,Deps,Module", guardModule+"/...").Output()
+ if err != nil {
+ var exit *exec.ExitError
+ if errors.As(err, &exit) {
+ t.Fatalf("go list: %v\n%s", err, exit.Stderr)
+ }
+ t.Fatalf("go list: %v", err)
+ }
+
+ var offenders []string
+ adapterSeen := false
+ dec := json.NewDecoder(strings.NewReader(string(out)))
+ for {
+ var p struct {
+ ImportPath string
+ Deps []string
+ Module *struct{ Path string }
+ }
+ if err := dec.Decode(&p); err == io.EOF {
+ break
+ } else if err != nil {
+ t.Fatalf("go list output: %v", err)
+ }
+ if p.Module == nil || p.Module.Path != guardModule {
+ continue
+ }
+ base := basePackage(p.ImportPath)
+ pulled := providerDep(p.Deps)
+ if inAdapter(base) {
+ if pulled != "" {
+ adapterSeen = true
+ }
+ continue
+ }
+ if pulled == "" || slices.Contains(providerAllowed, base) {
+ continue
+ }
+ line := base + " (via " + pulled + ")"
+ if !slices.Contains(offenders, line) {
+ offenders = append(offenders, line)
+ }
+ }
+ if len(offenders) > 0 {
+ t.Errorf("packages outside %s depend on the AWS SDK or the adapter:\n %s", providerAdapter, strings.Join(offenders, "\n "))
+ }
+ if !adapterSeen {
+ t.Errorf("go list showed no %s package depending on github.com/aws/; the guard is not seeing the adapter", providerAdapter)
+ }
+}
+
+// basePackage strips the test decorations go list -test adds: "p [p.test]",
+// "p.test" and an external test package "p_test".
+func basePackage(path string) string {
+ path, _, _ = strings.Cut(path, " ")
+ path = strings.TrimSuffix(path, ".test")
+ return strings.TrimSuffix(path, "_test")
+}
+
+func inAdapter(path string) bool {
+ return path == providerAdapter || strings.HasPrefix(path, providerAdapter+"/")
+}
+
+// providerDep returns the first dependency that is the AWS SDK or the
+// adapter, or "" when there is none.
+func providerDep(deps []string) string {
+ for _, d := range deps {
+ if strings.HasPrefix(d, "github.com/aws/") || inAdapter(d) {
+ return d
+ }
+ }
+ return ""
+}