hostedimage: reproducible image build and a guarded publish tool
Task 10 of the hosted runners slice 2 plan. internal/hostedimage pins every image input in a manifest and writes a byte-reproducible zip (sorted, stored, fixed times and modes) whose SHA-256 is the image digest; publish, list, delete and connector-wait go through a Provider with the account, region and prefix guards, and journal the create's intent and records in the run's ledger. awsjob/awsctl holds the guarded SDK plumbing livectl and the new command share; awsjob/imageaws is the SDK side, tested with SDK middleware stubs. make hosted-image-check and CI step 15 scan the image inputs for secrets.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
25 files changed,
+4,057
−205
.amadan/ci.d/15-hosted-image+6 −0Makefile+12 −2cmd/equipo-hosted-image/main.go+261 −0cmd/equipo-hosted-image/main_test.go+220 −0docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md+44 −0infra/hosted/image/Dockerfile.tmpl+35 −0infra/hosted/image/manifest.json+15 −0internal/hostedimage/build.go+307 −0internal/hostedimage/build_test.go+327 −0internal/hostedimage/manifest.go+276 −0internal/hostedimage/manifest_test.go+152 −0internal/hostedimage/publish.go+679 −0internal/hostedimage/publish_test.go+443 −0internal/isolatedjob/awsjob/awsctl/awsctl_test.go+404 −0internal/isolatedjob/awsjob/awsctl/clients.go+134 −0internal/isolatedjob/awsjob/awsctl/creds.go+137 −0internal/isolatedjob/awsjob/imageaws/imageaws.go+249 −0internal/isolatedjob/awsjob/imageaws/imageaws_test.go+274 −0internal/isolatedjob/awsjob/livectl/clients.go+6 −50internal/isolatedjob/awsjob/livectl/creds.go+21 −77internal/isolatedjob/awsjob/livectl/image.go+4 −27internal/isolatedjob/awsjob/livectl/main.go+12 −24internal/isolatedjob/providerguard_test.go+5 −2internal/vminit/measure.go+0 −23internal/vminit/measured.go+34 −0
diff --git a/.amadan/ci.d/15-hosted-image b/.amadan/ci.d/15-hosted-image| new file mode 100755 |
| index 00000000..9526968e |
| --- /dev/null |
| +++ b/.amadan/ci.d/15-hosted-image |
| @@ -0,0 +1,6 @@ |
| +#!/bin/sh |
| +# The hosted runner image's inputs (infra/hosted/image) scanned for |
| +# secrets, then the image's own checks: every input pinned, the zip |
| +# byte-reproducible, nothing secret-shaped in what it carries (spec §4). |
| +# Seconds, after the compile step; no AWS call and no credentials. |
| +exec "$(dirname "$0")/../../scripts/ci-box.py" run make hosted-image-check |
diff --git a/Makefile b/Makefile| index 7ea6de8a..ffb4c59c 100644 |
| --- a/Makefile |
| +++ b/Makefile |
| @@ -27,7 +27,7 @@ RUNNER_RELEASE_DIR = releases/equipo-runner-linux-amd64-$(RELEASE_VERSION) |
| # and a suite running beside it would be measured too. |
| .NOTPARALLEL: |
| -.PHONY: build release test test-lane ci-shard ci-compile lanes-check test-quarantine vet fmt-check staticcheck govulncheck gitleaks budget perf migration-check runner-adapter-test runner-namespace-test runner-host runner-dead-references ci |
| +.PHONY: build release test test-lane ci-shard ci-compile lanes-check test-quarantine vet fmt-check staticcheck govulncheck gitleaks budget perf migration-check runner-adapter-test runner-namespace-test runner-host runner-dead-references hosted-image-check ci |
| RASTRILLO := go run amadan.net/rastrillo/rastrillo/cmd/rastrillo |
| @@ -217,6 +217,16 @@ gitleaks: |
| echo "gitleaks: this directory is not the root of a git repository, so there is nothing committed to scan"; \ |
| fi |
| +# hosted-image-check is spec §4's "CI scans the image inputs for |
| +# secrets": gitleaks over infra/hosted/image (every file the hosted |
| +# runner image is built from that lives in this repository), then the |
| +# image's own checks: every input pinned, the zip byte-reproducible, and |
| +# nothing secret-shaped, no credential path and no repository in what it |
| +# carries. No AWS call. .amadan/ci.d/15-hosted-image runs it on CI. |
| +hosted-image-check: |
| + go run $(GITLEAKS) dir --no-banner --redact --config .gitleaks.toml infra/hosted/image |
| + CGO_ENABLED=0 go test ./internal/hostedimage -run '^(TestManifestPinsEverything|TestBuildReproducible|TestBuildChecksPins|TestImageInputsHaveNoSecrets)$$' -count=1 |
| + |
| # Rastrillo v0.30.0's CLI assumes a single internal app directory. The |
| # runner protocol is a second package, so call the same dump.Compute API |
| # from the app test instead of using CLI package discovery. |
| @@ -253,7 +263,7 @@ runner-host: runner-adapter-test runner-namespace-test |
| # fails the build the moment models.go and migrations/ disagree, |
| # instead of at boot on whatever machine notices next. If the app |
| # declares manifest resources, also add: rastrillo generate --check |
| -ci: copy-release-check runner-dead-references lanes-check build vet fmt-check spacing staticcheck govulncheck gitleaks budget test test-quarantine runner-host migration-check perf |
| +ci: copy-release-check runner-dead-references lanes-check build vet fmt-check spacing staticcheck govulncheck gitleaks hosted-image-check budget test test-quarantine runner-host migration-check perf |
| .PHONY: copy-release-check direct-release-check release-runner runner-prerequisites |
| copy-release-check: |
diff --git a/cmd/equipo-hosted-image/main.go b/cmd/equipo-hosted-image/main.go| new file mode 100644 |
| index 00000000..b6320bdf |
| --- /dev/null |
| +++ b/cmd/equipo-hosted-image/main.go |
| @@ -0,0 +1,261 @@ |
| +// Command equipo-hosted-image builds the hosted runner's image input and |
| +// publishes it as a Lambda MicroVM image (spec §4; plan Task 10): |
| +// |
| +// equipo-hosted-image [-profile P] -account A -region R -prefix X COMMAND [flags] |
| +// |
| +// build -manifest FILE -inputs DIR -out FILE |
| +// writes the byte-reproducible zip and prints its digest, its |
| +// inventory and the digests vm-init will measure. No AWS call, no |
| +// credentials read; the global flags are not needed. |
| +// publish -ledger DIR -name NAME -bucket B -key K -base-version V |
| +// [-allow-step-down] -build-role-arn ARN -log-group G -size small|large |
| +// -capabilities ALL [-timeout 45m] [-interval 15s] [-tag k=v ...] -out FILE |
| +// creates the image from s3://B/K and its one version, journals the |
| +// intent and the records in DIR/journal.tsv, waits for the build and |
| +// writes ImageArn and VersionArn ("<image ARN>:<version>") to FILE. |
| +// list |
| +// the prefix's images. |
| +// delete -arn ARN [-timeout 15m] [-interval 15s] |
| +// deletes an image of the prefix and waits until it is gone. |
| +// connector-wait -arn ARN [-timeout 20m] [-interval 15s] |
| +// waits for a network connector of the prefix to be ACTIVE. |
| +// |
| +// The AWS commands carry livectl's guards, with the account, region and |
| +// prefix as flags: static credentials only, resolved once before any |
| +// call (-profile, else AWS_PROFILE, else default; awsctl.ResolveStatic); |
| +// clients pinned to the region's standard endpoints, one attempt per |
| +// call, 60 s per call; STS must name -account before any other call; |
| +// waits bounded (at most 60 minutes); every name the tool creates, |
| +// deletes or waits on carries -prefix. The SDK half is |
| +// internal/isolatedjob/awsjob/imageaws; the guards are hostedimage's. |
| +// |
| +// Each success prints one JSON object on stdout. Each failure prints one |
| +// JSON line on stderr and exits 2 (an AWS call failed), 3 (usage), 4 (a |
| +// guard refused), 5 (a wait ran out), 6 (a failed state, or a built |
| +// version that differs from the request) or 1 (anything else). |
| +package main |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "flag" |
| + "fmt" |
| + "io" |
| + "os" |
| + "strings" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/hostedimage" |
| + "amadan.net/oficina/equipo/internal/isolatedjob" |
| + "amadan.net/oficina/equipo/internal/isolatedjob/awsjob/awsctl" |
| + "amadan.net/oficina/equipo/internal/isolatedjob/awsjob/imageaws" |
| +) |
| + |
| +// callTimeout bounds each SDK call, the STS check included. |
| +const callTimeout = 60 * time.Second |
| + |
| +func main() { |
| + os.Exit(run(context.Background(), os.Args[1:], os.Stdout, os.Stderr, connect)) |
| +} |
| + |
| +// connectFunc gives the provider for an AWS command; tests replace it. |
| +type connectFunc func(ctx context.Context, profile, region string) (hostedimage.Provider, error) |
| + |
| +// connect resolves static credentials once and builds the pinned clients. |
| +// The region is the flag's; a region in the environment or the profile |
| +// steers nothing. |
| +func connect(ctx context.Context, profile, region string) (hostedimage.Provider, error) { |
| + _, creds, err := awsctl.ResolveStatic(ctx, profile) |
| + var refused *awsctl.RefusedError |
| + var bad *awsctl.ConfigError |
| + switch { |
| + case errors.As(err, &refused): |
| + return nil, &hostedimage.Failure{Exit: hostedimage.ExitGuard, Kind: "guard", |
| + Message: refused.Error() + "; equipo-hosted-image takes only static keys"} |
| + case errors.As(err, &bad): |
| + return nil, &hostedimage.Failure{Exit: hostedimage.ExitOther, Kind: "other", Message: bad.Message} |
| + case err != nil: |
| + return nil, err |
| + } |
| + return imageaws.New(awsctl.NewClients(awsctl.StaticConfig(region, region, creds), region, callTimeout)), nil |
| +} |
| + |
| +type realClock struct{} |
| + |
| +func (realClock) Now() time.Time { return time.Now() } |
| +func (realClock) Sleep(d time.Duration) { time.Sleep(d) } |
| + |
| +// tagsFlag collects repeated -tag k=v flags. |
| +type tagsFlag map[string]string |
| + |
| +func (t tagsFlag) String() string { return fmt.Sprint(map[string]string(t)) } |
| +func (t tagsFlag) Set(s string) error { |
| + k, v, ok := strings.Cut(s, "=") |
| + if !ok || k == "" { |
| + return fmt.Errorf("tag %q is not key=value", s) |
| + } |
| + t[k] = v |
| + return nil |
| +} |
| + |
| +func usage(format string, a ...any) *hostedimage.Failure { |
| + return &hostedimage.Failure{Exit: hostedimage.ExitUsage, Kind: "usage", Message: fmt.Sprintf(format, a...)} |
| +} |
| + |
| +// report writes err as one JSON line on stderr and returns its exit code. |
| +func report(w io.Writer, err error) int { |
| + var f *hostedimage.Failure |
| + if !errors.As(err, &f) { |
| + f = &hostedimage.Failure{Exit: hostedimage.ExitOther, Kind: "other", Message: err.Error()} |
| + } |
| + b, merr := json.Marshal(f) |
| + if merr != nil { |
| + b = []byte(`{"error":"other","message":"error did not encode"}`) |
| + } |
| + fmt.Fprintf(w, "%s\n", b) |
| + return f.Exit |
| +} |
| + |
| +// waitFlags declares a wait's -timeout and -interval. |
| +func waitFlags(fs *flag.FlagSet, def time.Duration) func() hostedimage.Wait { |
| + timeout := fs.Duration("timeout", def, "give up after this long (at most 60m)") |
| + interval := fs.Duration("interval", 15*time.Second, "time between reads (at least 1s)") |
| + return func() hostedimage.Wait { |
| + return hostedimage.Wait{Timeout: *timeout, Interval: *interval, Clock: realClock{}} |
| + } |
| +} |
| + |
| +// run parses args and runs one command. It returns the exit code. |
| +func run(ctx context.Context, args []string, stdout, stderr io.Writer, connect connectFunc) int { |
| + top := flag.NewFlagSet("equipo-hosted-image", flag.ContinueOnError) |
| + top.SetOutput(io.Discard) |
| + profile := top.String("profile", "", "the shared-config profile holding static keys (default AWS_PROFILE, then default)") |
| + var t hostedimage.Target |
| + top.StringVar(&t.Account, "account", "", "the one account the tool may act in") |
| + top.StringVar(&t.Region, "region", "", "the one region the tool may act in") |
| + top.StringVar(&t.Prefix, "prefix", "", "every name the tool touches starts with this") |
| + if err := top.Parse(args); err != nil { |
| + return report(stderr, usage("%v", err)) |
| + } |
| + rest := top.Args() |
| + if len(rest) == 0 { |
| + return report(stderr, usage("want a command: build, publish, list, delete or connector-wait")) |
| + } |
| + fs := flag.NewFlagSet(rest[0], flag.ContinueOnError) |
| + fs.SetOutput(io.Discard) |
| + var step func(hostedimage.Provider) (any, error) |
| + switch rest[0] { |
| + case "build": |
| + manifest := fs.String("manifest", "", "the image manifest (infra/hosted/image/manifest.json)") |
| + inputs := fs.String("inputs", "", "the directory holding the pinned files") |
| + out := fs.String("out", "", "the zip to write") |
| + if err := parse(fs, rest[1:]); err != nil { |
| + return report(stderr, err) |
| + } |
| + if *manifest == "" || *inputs == "" || *out == "" { |
| + return report(stderr, usage("build needs -manifest, -inputs and -out")) |
| + } |
| + res, err := build(*manifest, *inputs, *out) |
| + return finish(stdout, stderr, res, err) |
| + case "publish": |
| + var r hostedimage.PublishRequest |
| + fs.StringVar(&r.Ledger, "ledger", "", "the run's ledger directory; the intent and records go to journal.tsv there") |
| + fs.StringVar(&r.Name, "name", "", "the image name (the prefix, or the prefix, '-' and more)") |
| + fs.StringVar(&r.Bucket, "bucket", "", "the bucket holding the image zip") |
| + fs.StringVar(&r.Key, "key", "", "the image zip's key") |
| + fs.StringVar(&r.BaseVersion, "base-version", "", "the managed base image version the release pins") |
| + fs.BoolVar(&r.AllowStepDown, "allow-step-down", false, "build on the base version listed directly below -base-version") |
| + fs.StringVar(&r.BuildRoleARN, "build-role-arn", "", "the build role, in -account") |
| + fs.StringVar(&r.LogGroup, "log-group", "", "the build's log group") |
| + size := fs.String("size", "", "small or large") |
| + fs.StringVar(&r.Capabilities, "capabilities", "", "the OS capabilities: ALL") |
| + fs.StringVar(&r.Out, "out", "", "the JSON result file (ImageArn, VersionArn)") |
| + tags := tagsFlag{} |
| + fs.Var(tags, "tag", "key=value tag (repeatable)") |
| + wait := waitFlags(fs, 45*time.Minute) |
| + if err := parse(fs, rest[1:]); err != nil { |
| + return report(stderr, err) |
| + } |
| + r.Size, r.Tags, r.Wait = isolatedjob.Size(*size), tags, wait() |
| + step = func(p hostedimage.Provider) (any, error) { return hostedimage.Publish(ctx, p, t, r) } |
| + case "list": |
| + if err := parse(fs, rest[1:]); err != nil { |
| + return report(stderr, err) |
| + } |
| + step = func(p hostedimage.Provider) (any, error) { |
| + imgs, err := hostedimage.List(ctx, p, t) |
| + return map[string]any{"Items": imgs}, err |
| + } |
| + case "delete": |
| + arn := fs.String("arn", "", "the image ARN") |
| + wait := waitFlags(fs, 15*time.Minute) |
| + if err := parse(fs, rest[1:]); err != nil { |
| + return report(stderr, err) |
| + } |
| + step = func(p hostedimage.Provider) (any, error) { return hostedimage.Delete(ctx, p, t, *arn, wait()) } |
| + case "connector-wait": |
| + arn := fs.String("arn", "", "the network connector ARN") |
| + wait := waitFlags(fs, 20*time.Minute) |
| + if err := parse(fs, rest[1:]); err != nil { |
| + return report(stderr, err) |
| + } |
| + step = func(p hostedimage.Provider) (any, error) { return hostedimage.ConnectorWait(ctx, p, t, *arn, wait()) } |
| + default: |
| + return report(stderr, usage("unknown command %q", rest[0])) |
| + } |
| + // The flags are checked before any credential is read. |
| + if err := t.Check(); err != nil { |
| + return report(stderr, err) |
| + } |
| + p, err := connect(ctx, *profile, t.Region) |
| + if err != nil { |
| + return report(stderr, err) |
| + } |
| + res, err := step(p) |
| + return finish(stdout, stderr, res, err) |
| +} |
| + |
| +func parse(fs *flag.FlagSet, args []string) error { |
| + if err := fs.Parse(args); err != nil { |
| + return usage("%v", err) |
| + } |
| + if fs.NArg() != 0 { |
| + return usage("unexpected arguments %q", fs.Args()) |
| + } |
| + return nil |
| +} |
| + |
| +// finish prints res on success and reports err otherwise. |
| +func finish(stdout, stderr io.Writer, res any, err error) int { |
| + if err != nil { |
| + return report(stderr, err) |
| + } |
| + b, merr := json.Marshal(res) |
| + if merr != nil { |
| + return report(stderr, merr) |
| + } |
| + fmt.Fprintf(stdout, "%s\n", b) |
| + return hostedimage.ExitOK |
| +} |
| + |
| +// buildResult is what build prints. |
| +type buildResult struct { |
| + Digest isolatedjob.ImageDigest |
| + ZipSHA256 string |
| + Files map[string]string |
| + Measured map[string]string // what vm-init's measured.json must hold |
| +} |
| + |
| +func build(manifest, inputs, out string) (buildResult, error) { |
| + m, err := hostedimage.LoadManifest(manifest) |
| + if err != nil { |
| + return buildResult{}, usage("%v", err) |
| + } |
| + m.Inputs = inputs |
| + inv, err := hostedimage.Build(m, out) |
| + if err != nil { |
| + return buildResult{}, err |
| + } |
| + return buildResult{Digest: inv.Digest(), ZipSHA256: inv.ZipSHA256, Files: inv.Files, Measured: m.Measured()}, nil |
| +} |
diff --git a/cmd/equipo-hosted-image/main_test.go b/cmd/equipo-hosted-image/main_test.go| new file mode 100644 |
| index 00000000..9662724a |
| --- /dev/null |
| +++ b/cmd/equipo-hosted-image/main_test.go |
| @@ -0,0 +1,220 @@ |
| +package main |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "crypto/sha256" |
| + "encoding/hex" |
| + "encoding/json" |
| + "os" |
| + "path/filepath" |
| + "slices" |
| + "strings" |
| + "testing" |
| + |
| + "amadan.net/oficina/equipo/internal/hostedimage" |
| + "amadan.net/rastrillo/rastrillo/budget" |
| +) |
| + |
| +func TestMain(m *testing.M) { os.Exit(budget.Main(m)) } |
| + |
| +const ( |
| + acct = "111122223333" |
| + region = "eu-west-1" |
| + prefix = "equipo-hosted-prod-1201-abcdef" |
| +) |
| + |
| +var global = []string{"-account", acct, "-region", region, "-prefix", prefix} |
| + |
| +// noConnect fails the test if a command reaches for credentials. |
| +func noConnect(t *testing.T) connectFunc { |
| + return func(context.Context, string, string) (hostedimage.Provider, error) { |
| + t.Fatal("the command read credentials") |
| + return nil, nil |
| + } |
| +} |
| + |
| +func runCmd(t *testing.T, connect connectFunc, args ...string) (int, string, string) { |
| + t.Helper() |
| + var out, errw bytes.Buffer |
| + code := run(context.Background(), args, &out, &errw, connect) |
| + return code, out.String(), errw.String() |
| +} |
| + |
| +// credentialTrap points every credential setting at a credential_process |
| +// that leaves a marker, so any credential resolution shows. |
| +func credentialTrap(t *testing.T) (marker string) { |
| + dir := t.TempDir() |
| + marker = filepath.Join(dir, "MARKER") |
| + cfg := filepath.Join(dir, "config") |
| + body := "[profile trap]\ncredential_process = /bin/sh -c 'touch " + marker + "'\nregion = " + region + "\n" |
| + if err := os.WriteFile(cfg, []byte(body), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + for k, v := range map[string]string{"AWS_CONFIG_FILE": cfg, "AWS_SHARED_CREDENTIALS_FILE": filepath.Join(dir, "none"), |
| + "AWS_PROFILE": "trap", "AWS_ACCESS_KEY_ID": "", "AWS_SECRET_ACCESS_KEY": "", "AWS_SESSION_TOKEN": "", |
| + "AWS_EC2_METADATA_DISABLED": "true", "AWS_ENDPOINT_URL": "http://127.0.0.1:1"} { |
| + t.Setenv(k, v) |
| + } |
| + return marker |
| +} |
| + |
| +// TestBuildReadsNoCredentials: build makes no AWS call and reads no |
| +// credentials, even with the global flags given; it prints the digest of |
| +// the zip it wrote. |
| +func TestBuildReadsNoCredentials(t *testing.T) { |
| + marker := credentialTrap(t) |
| + dir := t.TempDir() |
| + in := filepath.Join(dir, "inputs") |
| + sums := map[string]string{} |
| + for _, name := range []string{"equipo-runner", "equipo-vm-init", "bwrap", "codex", "containment.test", "go1.26.11.linux-amd64.tar.gz"} { |
| + body := []byte("fake " + name) |
| + if err := os.MkdirAll(in, 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.WriteFile(filepath.Join(in, name), body, 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + h := sha256.Sum256(body) |
| + sums[name] = hex.EncodeToString(h[:]) |
| + } |
| + tmpl, err := os.ReadFile("../../infra/hosted/image/Dockerfile.tmpl") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.WriteFile(filepath.Join(dir, "Dockerfile.tmpl"), tmpl, 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + m := map[string]any{ |
| + "RunnerRelease": "r1", "RunnerSHA256": sums["equipo-runner"], "VMInitSHA256": sums["equipo-vm-init"], |
| + "BubblewrapSHA256": sums["bwrap"], "GoToolchain": "go1.26.11", "GoToolchainSHA256": sums["go1.26.11.linux-amd64.tar.gz"], |
| + "GitSHA256": strings.Repeat("5", 64), "CodexSHA256": sums["codex"], "ContainmentTestSHA256": sums["containment.test"], |
| + "Packages": []any{}, "Policies": []string{hostedimage.PathBwrap}, "Resolvers": []string{"10.0.0.2"}, |
| + "Metadata": []string{"169.254.169.254:80"}, |
| + } |
| + b, _ := json.Marshal(m) |
| + if err := os.WriteFile(filepath.Join(dir, "manifest.json"), b, 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + out := filepath.Join(dir, "image.zip") |
| + code, stdout, stderr := runCmd(t, noConnect(t), append(global, "build", "-manifest", filepath.Join(dir, "manifest.json"), "-inputs", in, "-out", out)...) |
| + if code != 0 { |
| + t.Fatalf("build = %d: %s", code, stderr) |
| + } |
| + zb, err := os.ReadFile(out) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + h := sha256.Sum256(zb) |
| + var res struct { |
| + Digest string |
| + Measured map[string]string |
| + } |
| + if err := json.Unmarshal([]byte(stdout), &res); err != nil || res.Digest != "sha256:"+hex.EncodeToString(h[:]) { |
| + t.Fatalf("build printed %s (%v), want the zip's digest", stdout, err) |
| + } |
| + if res.Measured["runner"] != sums["equipo-runner"] || res.Measured["vm_init"] != sums["equipo-vm-init"] || len(res.Measured["sandbox_policy"]) != 64 { |
| + t.Fatalf("Measured = %v", res.Measured) |
| + } |
| + if _, err := os.Stat(marker); err == nil { |
| + t.Fatal("build resolved credentials") |
| + } |
| + |
| + // Without the global flags too. |
| + if code, _, stderr := runCmd(t, noConnect(t), "build", "-manifest", filepath.Join(dir, "manifest.json"), "-inputs", in, "-out", out); code != 0 { |
| + t.Fatalf("build without global flags = %d: %s", code, stderr) |
| + } |
| +} |
| + |
| +// TestFlagsCheckedBeforeCredentials: a bad account, region or prefix is a |
| +// usage error before any credential is read. |
| +func TestFlagsCheckedBeforeCredentials(t *testing.T) { |
| + for _, g := range [][]string{ |
| + {"-account", "12345", "-region", region, "-prefix", prefix}, |
| + {"-account", acct, "-region", "Ireland", "-prefix", prefix}, |
| + {"-account", acct, "-region", region, "-prefix", ""}, |
| + {"-account", acct, "-region", region}, |
| + } { |
| + code, _, stderr := runCmd(t, noConnect(t), append(g, "list")...) |
| + if code != hostedimage.ExitUsage || !strings.Contains(stderr, `"error":"usage"`) { |
| + t.Errorf("%v list = %d %s, want a usage error", g, code, stderr) |
| + } |
| + } |
| +} |
| + |
| +// TestCredentialsRefusedBeforeAnyCall: the real connect refuses a profile |
| +// that is not static keys, with the guard's exit, before any call. |
| +func TestCredentialsRefusedBeforeAnyCall(t *testing.T) { |
| + marker := credentialTrap(t) |
| + code, _, stderr := runCmd(t, connect, append(global, "list")...) |
| + if code != hostedimage.ExitGuard || !strings.Contains(stderr, "credential_process are refused") { |
| + t.Fatalf("list = %d %s, want a guard refusal of the credential_process", code, stderr) |
| + } |
| + if _, err := os.Stat(marker); err == nil { |
| + t.Fatal("the credential process ran") |
| + } |
| +} |
| + |
| +// fake is a provider whose caller is another account. |
| +type fake struct{ calls []string } |
| + |
| +func (f *fake) Region() string { return region } |
| +func (f *fake) CallerAccount(context.Context) (string, error) { |
| + f.calls = append(f.calls, "CallerAccount") |
| + return "444455556666", nil |
| +} |
| +func (f *fake) BaseVersions(context.Context, string) ([]hostedimage.BaseVersion, error) { |
| + f.calls = append(f.calls, "BaseVersions") |
| + return nil, nil |
| +} |
| +func (f *fake) CreateImage(context.Context, hostedimage.CreateImage) (hostedimage.Created, error) { |
| + f.calls = append(f.calls, "CreateImage") |
| + return hostedimage.Created{}, nil |
| +} |
| +func (f *fake) GetImage(context.Context, string) (hostedimage.Image, error) { |
| + f.calls = append(f.calls, "GetImage") |
| + return hostedimage.Image{}, nil |
| +} |
| +func (f *fake) GetImageVersion(context.Context, string, string) (hostedimage.Version, error) { |
| + f.calls = append(f.calls, "GetImageVersion") |
| + return hostedimage.Version{}, nil |
| +} |
| +func (f *fake) ListImages(context.Context, string) ([]hostedimage.Image, error) { |
| + f.calls = append(f.calls, "ListImages") |
| + return nil, nil |
| +} |
| +func (f *fake) DeleteImage(context.Context, string) error { |
| + f.calls = append(f.calls, "DeleteImage") |
| + return nil |
| +} |
| +func (f *fake) GetConnector(context.Context, string) (hostedimage.Connector, error) { |
| + f.calls = append(f.calls, "GetConnector") |
| + return hostedimage.Connector{}, nil |
| +} |
| + |
| +// TestPublishFlags: publish's flags reach the guarded publish, which |
| +// stops at the account check with the guard's exit and one JSON line. |
| +func TestPublishFlags(t *testing.T) { |
| + f := &fake{} |
| + conn := func(_ context.Context, profile, r string) (hostedimage.Provider, error) { |
| + if profile != "ops" || r != region { |
| + t.Errorf("connect(%q, %q), want the -profile and -region flags", profile, r) |
| + } |
| + return f, nil |
| + } |
| + args := append([]string{"-profile", "ops"}, global...) |
| + args = append(args, "publish", "-ledger", t.TempDir(), "-name", prefix, "-bucket", "equipo-hosted-image-inputs", |
| + "-key", "images/x.zip", "-base-version", "4", "-allow-step-down", "-build-role-arn", "arn:aws:iam::"+acct+":role/build", |
| + "-log-group", "/equipo-hosted/image-build", "-size", "large", "-capabilities", "ALL", "-timeout", "45m", |
| + "-tag", "purpose=equipo-hosted", "-out", filepath.Join(t.TempDir(), "image.json")) |
| + code, stdout, stderr := runCmd(t, conn, args...) |
| + if code != hostedimage.ExitGuard || stdout != "" || strings.Count(stderr, "\n") != 1 || !strings.Contains(stderr, "caller account") { |
| + t.Fatalf("publish = %d, stdout %q, stderr %q", code, stdout, stderr) |
| + } |
| + if !slices.Equal(f.calls, []string{"CallerAccount"}) { |
| + t.Fatalf("calls %v, want only the account check", f.calls) |
| + } |
| + if code, _, _ := runCmd(t, conn, append(slices.Clone(args[:len(args)-2]), "-size", "huge")...); code != hostedimage.ExitUsage { |
| + t.Fatalf("publish -size huge = %d, want usage", code) |
| + } |
| +} |
diff --git a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md| index 89cbbca6..16041eb7 100644 |
| --- a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md |
| +++ b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md |
| @@ -494,3 +494,47 @@ Mutation checks. Each was applied by script, the named test run with `CGO_ENABLE |
| 41. Repeated subnet page token accepted (its `return` replaced by a no-op). TestAuditSubnetPagesRepeatToken: FAIL, `network_test.go:1075: subnet pages asked for = 3, want 2 (refused at the repeated token)`. This failed on the page-count assertion, not a timeout. Restored. |
| Also run: `CGO_ENABLED=0 go test ./internal/isolatedjob/... ./cmd/equipo-hosted-controller -count=1` ok; `go vet -tags hostedlive ./internal/isolatedjob/...` ok; `make budget build vet` ok (129 directories within budget); staticcheck v0.7.0 clean; gofmt and `git diff --check` clean. |
| + |
| +## Task 10 |
| + |
| +The image build and a guarded publish tool. New: `internal/hostedimage` (manifest, build, publish; no AWS type), `internal/isolatedjob/awsjob/awsctl` (the guarded SDK plumbing livectl and the image tool share: static credentials resolved once, clients pinned to one region's standard endpoints with one attempt and a 60 s deadline per call, the STS caller check, `Describe` for failed calls), `internal/isolatedjob/awsjob/imageaws` (hostedimage.Provider over the SDK), `cmd/equipo-hosted-image` (`build`, `publish`, `list`, `delete`, `connector-wait`), `infra/hosted/image/{manifest.json,Dockerfile.tmpl}`, `.amadan/ci.d/15-hosted-image`, `make hosted-image-check` (gitleaks over `infra/hosted/image`, then the image tests; also in `make ci`). livectl now calls awsctl (its own wrappers keep its kass hard-wiring and its tests unchanged and green) and `hostedimage.CompareVersions`. `vminit.PolicySetDigest` and the `Measured*` names moved, unchanged, into the portable `internal/vminit/measured.go` so the image tool computes the digests vm-init measures. `TestProviderTypesStayInAdapter` allows `cmd/equipo-hosted-image` only. |
| + |
| +The zip carries every byte the image installs (runner, vm-init, bwrap, codex, containment.test, the Go tarball, pinned RPMs) under `files/`, plus the rendered `Dockerfile`, `image.json` (hooks.port 9000, run hook 60 s, X86_64, ALL) and `manifest.json`. Entries sorted, stored, fixed time 2026-01-01 and mode 0644/0755; each input checked against its pin as it is copied. `Inventory.Digest()` is `sha256:` + the zip's SHA-256. Publish journals `INTENT microvm-image <name> <token>` (token derived from the whole request) before the create, then `REC microvm-image <arn>` and `REC microvm-image-version <arn>:<version>`, and writes `-out` with `ImageArn` and `VersionArn` = `<image ARN>:<version>` (the form certificates sign). |
| + |
| +RED: first the build failure (`go test ./internal/hostedimage -run 'TestBuild|TestManifest|TestImageInputs|TestPublish' -count=1`: `publish_test.go:23:14: undefined: Target`, `build_test.go:23:28: undefined: Manifest`, ...). Then, with the types and stub bodies, the same command FAIL on assertions: TestBuildReproducible (`build_test.go:101: ZipSHA256 = and , want the zip's e3b0...`), TestBuildChecksPins (`build_test.go:214: Build = nil, want a refusal` x4, `:224`), TestImageInputsHaveNoSecrets (`build_test.go:275: open .../image.zip: no such file or directory`), TestManifestPinsEverything (`manifest_test.go:107: LoadManifest accepted an unknown key`, a case-variant key encoding/json accepts; with `Validate` stubbed to nil, 47 lines such as `manifest_test.go:67: RunnerSHA256 = "": Validate = <nil>, want a refusal naming RunnerSHA256`), TestPublishRefusesOtherAccount (`publish_test.go:169: error <nil> is not a *Failure`), TestPublishRefusesForeignName (12 x `:213`, `:222`), TestPublishJournalsBeforeCreate (`:241: 0 creates, want 1`), TestPublishBaseVersion (`:331`, `:326` x4), TestPublishWaitBounded (`:347`). TestProviderTypesStayInAdapter with the command written and the list unchanged: FAIL, `providerguard_test.go:65: packages outside .../awsjob depend on the AWS SDK or the adapter: amadan.net/oficina/equipo/cmd/equipo-hosted-image (via .../awsjob/awsctl)` (and no line for internal/hostedimage). |
| + |
| +GREEN: `CGO_ENABLED=0 go test ./internal/hostedimage ./internal/isolatedjob -run 'TestBuild|TestManifest|TestImageInputs|TestPublish|TestProviderTypes' -count=1` ok; `make hosted-image-check` ok (gitleaks: no leaks found). |
| + |
| +Mutation checks (each applied by script, the named test run with `CGO_ENABLED=0 go test <pkg> -run '^<Test>$' -count=1`, every run compiled and failed on its assertion, the file restored and checked by SHA-256): |
| + |
| +1. Zip times from the input files' mtimes (brief). TestBuildReproducible: FAIL, `build_test.go:98: two builds of the same inputs differ (6052 and 6052 bytes)`. Restored. |
| +2. Skip the account check (brief; `if a != t.Account` dropped). TestPublishRefusesOtherAccount: FAIL, `publish_test.go:170: Publish = transport: GetMicrovmImageVersion failed before an answer came back, want a guard refusal`. Restored. |
| +3. Skip the region check. TestPublishRefusesOtherAccount: FAIL, `publish_test.go:186: Publish from another region = ... with calls [CallerAccount BaseVersions CreateImage GetImageVersion], want a guard refusal and no call`. Restored. |
| +4. Entries not sorted. TestBuildReproducible: FAIL, `build_test.go:146: entries [Dockerfile image.json manifest.json files/equipo-runner ...] are not sorted`. Restored. |
| +5. Input file modes copied into the zip. TestBuildReproducible: FAIL, `build_test.go:98: two builds of the same inputs differ`. Restored. |
| +6. Input pins not compared. TestBuildChecksPins: FAIL, `build_test.go:214: Build = nil, want a refusal`. Restored. |
| +7. A link accepted as an input (Lstat replaced by Stat). TestBuildChecksPins: FAIL, `build_test.go:214: Build = nil, want a refusal` (bwrap is a link). Restored. |
| +8. Name outside the prefix accepted. TestPublishRefusesForeignName: FAIL, `publish_test.go:214: Publish = transport: ..., want a guard or usage refusal`. Restored. |
| +9. Prefix matched without the '-'. TestPublishRefusesForeignName: FAIL, `publish_test.go:214` (prefix without a dash). Restored. |
| +10. Intent journalled after the create. TestPublishJournalsBeforeCreate: FAIL, `publish_test.go:246: journal at the create call = [], want [INTENT microvm-image equipo-hosted-prod-1201-abcdef equipo-image-9d99...]`. Restored. |
| +11. Step-down taken without the flag. TestPublishBaseVersion: FAIL, `publish_test.go:331: ... want base 4`. Restored. |
| +12. A recalled base accepted. TestPublishBaseVersion: FAIL, `publish_test.go:326: ... calls [CallerAccount BaseVersions CreateImage GetImageVersion]; want a refusal before the create`. Restored. |
| +13. An unlisted base accepted. TestPublishBaseVersion: FAIL, `publish_test.go:326` (not listed). Restored. |
| +14. Built version not compared. TestPublishWaitBounded: FAIL, `publish_test.go:380: hooks port: a built version that differs was accepted`, `:383: -out written for a refused version`. Restored. |
| +15. A failed build waited on. TestPublishWaitBounded: FAIL, `publish_test.go:361: failed build = timeout: wait for image version built ran out after 45m0s, want exit 6 with FAILED`. Restored. |
| +16. Delete without the name check. TestDeleteRefusesForeignImage: FAIL, `publish_test.go:394: error <nil> is not a *Failure`. Restored. |
| +17. List unfiltered. TestListOnlyPrefix: FAIL, `publish_test.go:417: List = [... abcdefx ... other ...]`. Restored. |
| +18. Connector name unchecked. TestConnectorWait: FAIL, `publish_test.go:435: error <nil> is not a *Failure`. Restored. |
| +19. Digest fields not checked. TestManifestPinsEverything: FAIL, `manifest_test.go:67: RunnerSHA256 = "": Validate = <nil>, want a refusal naming RunnerSHA256`. Restored. |
| +20. Keys matched without case (exactKeys skipped). TestManifestPinsEverything: FAIL, `manifest_test.go:107: LoadManifest accepted an unknown key`. Restored. |
| +21. A policy the image does not install. TestManifestPinsEverything: FAIL, `manifest_test.go:91: policy the image does not own: Validate = nil, want a refusal`. Restored. |
| +22. The Dockerfile copies the whole zip (`COPY . ...` in Dockerfile.tmpl). TestImageInputsHaveNoSecrets: FAIL, `build_test.go:314: Dockerfile copies something other than files/: "COPY . /tmp/equipo-image/"`. Restored. |
| +23. The SDK fills the client token (ClientToken not set in imageaws). TestPublishThroughSDK first PASSED: the SDK's idempotency middleware fills a random token into the same input, so the non-empty check held. The test now requires the token sent to be the journalled one; rerun FAIL, `imageaws_test.go:192: client token "d0843024-..." is not the journalled one`. Restored. |
| +24. Retries allowed (NopRetryer dropped from the core client). TestClientsOneAttempt: FAIL, `awsctl_test.go:204: status 500: 6 requests for two calls, want one each (no retries)`. Restored. |
| +25. STS endpoint override kept. TestClientsIgnoreEndpointOverrides: FAIL, `awsctl_test.go:159: hosts under overrides = [evil-sts.invalid ...], want the standard [sts.eu-central-1.amazonaws.com ...]`. Restored. |
| +26. Environment keys beside a named profile. TestNamedProfile: FAIL, `awsctl_test.go:358: ResolveStatic(q) with keys in the environment = <nil>, want a refusal`. Restored. |
| +27. Assume-role profile not recognised. TestCredentialKindsRefused: FAIL, `awsctl_test.go:333: ResolveStatic = credentials from instance metadata are refused, want a refusal naming "assume role"`. Restored. |
| +28. Flags checked after credentials. TestFlagsCheckedBeforeCredentials: FAIL, `main_test.go:32: the command read credentials`. Restored. |
| +29. hostedimage imports the SDK. TestProviderTypesStayInAdapter: FAIL, `providerguard_test.go:68: packages outside .../awsjob depend on the AWS SDK or the adapter:`. Restored. |
| + |
| +Also run: `CGO_ENABLED=0 go test ./internal/hostedimage ./internal/isolatedjob/... ./internal/vminit ./cmd/equipo-hosted-image -count=1` ok; `CGO_ENABLED=0 go test -tags hostedlive ./internal/isolatedjob/awsjob/livectl -count=1` ok; `go vet -tags hostedlive ./internal/isolatedjob/...` ok; `make budget build vet hosted-image-check` ok (133 directories within budget); `python3 scripts/ci-test.py check` ok; staticcheck v0.7.0 clean on the new and changed packages (livectl with `-tags hostedlive`); gitleaks `dir` clean on every new directory; gofmt and `git diff --check` clean. |
diff --git a/infra/hosted/image/Dockerfile.tmpl b/infra/hosted/image/Dockerfile.tmpl| new file mode 100644 |
| index 00000000..67ac603c |
| --- /dev/null |
| +++ b/infra/hosted/image/Dockerfile.tmpl |
| @@ -0,0 +1,35 @@ |
| +# The hosted runner image (spec §4), rendered by `equipo-hosted-image build` |
| +# from infra/hosted/image/Dockerfile.tmpl and manifest.json. Every file it |
| +# installs is in the zip beside it and pinned by SHA-256 in the manifest; |
| +# the build reaches no network. The image holds no credential, no person's |
| +# configuration and no repository, and the runner's state directory is |
| +# empty (vm-init's /ready hook refuses the build otherwise). |
| +FROM public.ecr.aws/lambda/microvms:al2023-minimal |
| +COPY files/ /tmp/equipo-image/ |
| +RUN set -eu; \ |
| + cd /tmp/equipo-image; \ |
| + printf '%s\n'{{range .Sums}} '{{.}}'{{end}} > SHA256SUMS; \ |
| + sha256sum --check --strict SHA256SUMS; \ |
| +{{- if .Manifest.Packages}} |
| + rpm --install --verbose{{range .Manifest.Packages}} 'pkgs/{{.Name}}'{{end}}; \ |
| +{{- end}} |
| + install -D -m 0755 -o root -g root equipo-runner {{.PathRunner}}; \ |
| + install -D -m 0755 -o root -g root equipo-vm-init {{.PathVMInit}}; \ |
| + install -D -m 0755 -o root -g root bwrap {{.PathBwrap}}; \ |
| + install -D -m 0755 -o root -g root codex {{.PathCodex}}; \ |
| + install -D -m 0755 -o root -g root containment.test {{.PathContainmentTest}}; \ |
| + tar -C /usr/local -xzf go.tar.gz; \ |
| + ln -s /usr/local/go/bin/go /usr/local/bin/go; \ |
| + ln -s /usr/local/go/bin/gofmt /usr/local/bin/gofmt; \ |
| + test "$(/usr/local/go/bin/go version)" = 'go version {{.Manifest.GoToolchain}} linux/amd64'; \ |
| + printf '%s %s\n' '{{.Manifest.GitSHA256}}' /usr/bin/git | sha256sum --check --strict; \ |
| + useradd --system --user-group --no-create-home --home-dir {{.StateDir}} --shell /sbin/nologin {{.RunnerUser}}; \ |
| + install -d -m 0700 -o {{.RunnerUser}} -g {{.RunnerUser}} {{.StateDir}}; \ |
| + install -d -m 0755 -o root -g root {{.ResultsDir}}; \ |
| + mkdir -p {{.EtcParent}}; \ |
| + cp -a /etc {{.EtcSource}}; \ |
| + rm -f {{.EtcSource}}/resolv.conf; \ |
| + install -m 0644 -o root -g root /dev/null {{.EtcSource}}/resolv.conf; \ |
| + cd /; \ |
| + rm -rf /tmp/equipo-image |
| +CMD {{.Cmd}} |
diff --git a/infra/hosted/image/manifest.json b/infra/hosted/image/manifest.json| new file mode 100644 |
| index 00000000..e0f0d72f |
| --- /dev/null |
| +++ b/infra/hosted/image/manifest.json |
| @@ -0,0 +1,15 @@ |
| +{ |
| + "RunnerRelease": "", |
| + "RunnerSHA256": "", |
| + "VMInitSHA256": "", |
| + "BubblewrapSHA256": "0dfa36b98ada69568aaaa741fe210d2150a1441433bd13c428137d6a972a959c", |
| + "GoToolchain": "go1.26.11", |
| + "GoToolchainSHA256": "", |
| + "GitSHA256": "", |
| + "CodexSHA256": "c06a67fd8ac76508dc78bd99ce20c9f317b8d568beda59485f3f4134df9962d5", |
| + "ContainmentTestSHA256": "", |
| + "Packages": [], |
| + "Policies": ["/usr/local/bin/bwrap"], |
| + "Resolvers": [], |
| + "Metadata": ["169.254.169.254:80"] |
| +} |
diff --git a/internal/hostedimage/build.go b/internal/hostedimage/build.go| new file mode 100644 |
| index 00000000..56825c1f |
| --- /dev/null |
| +++ b/internal/hostedimage/build.go |
| @@ -0,0 +1,307 @@ |
| +package hostedimage |
| + |
| +import ( |
| + "archive/zip" |
| + "bytes" |
| + "crypto/sha256" |
| + "encoding/hex" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "os" |
| + "path" |
| + "path/filepath" |
| + "slices" |
| + "strings" |
| + "text/template" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/isolatedjob" |
| +) |
| + |
| +// HooksPort is the image's hooks.port: vm-init's hook listener. |
| +const HooksPort = 9000 |
| + |
| +// zipTime is every entry's modification time. |
| +var zipTime = time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) |
| + |
| +// Hook timeouts, in seconds. The /run hook measures and, for |
| +// certification, runs the root probes before it answers (Task 8: about 2 |
| +// s per resolver query in the worst case), so it gets the API's maximum. |
| +const ( |
| + runHookTimeout = 60 |
| + otherHookTimeout = 10 |
| + readyHookTimeout = 120 |
| +) |
| + |
| +// Settings are the image settings every version gets: the hooks, the CPU |
| +// and the OS capabilities. The API's JSON shape; image.json in the zip |
| +// records them, and publish sends exactly these. |
| +type Settings struct { |
| + Hooks Hooks `json:"hooks"` |
| + CPU []CPUConfig `json:"cpuConfigurations"` |
| + Capabilities []string `json:"additionalOsCapabilities"` |
| +} |
| + |
| +// Hooks is the API's Hooks. |
| +type Hooks struct { |
| + Port int `json:"port"` |
| + Microvm MicrovmHooks `json:"microvmHooks"` |
| + Image ImageHooks `json:"microvmImageHooks"` |
| +} |
| + |
| +// MicrovmHooks is the API's MicrovmHooks: each hook ENABLED or DISABLED, |
| +// with a timeout in seconds. |
| +type MicrovmHooks struct { |
| + Run string `json:"run"` |
| + RunTimeout int `json:"runTimeoutInSeconds"` |
| + Resume string `json:"resume"` |
| + ResumeTimeout int `json:"resumeTimeoutInSeconds"` |
| + Suspend string `json:"suspend"` |
| + SuspendTimeout int `json:"suspendTimeoutInSeconds"` |
| + Terminate string `json:"terminate"` |
| + TerminateTimeout int `json:"terminateTimeoutInSeconds"` |
| +} |
| + |
| +// ImageHooks is the API's MicrovmImageHooks. |
| +type ImageHooks struct { |
| + Ready string `json:"ready"` |
| + ReadyTimeout int `json:"readyTimeoutInSeconds"` |
| + Validate string `json:"validate"` |
| +} |
| + |
| +// CPUConfig is the API's CpuConfiguration. |
| +type CPUConfig struct { |
| + Architecture string `json:"architecture"` |
| +} |
| + |
| +// ImageSettings are the settings of every hosted runner image version: |
| +// hooks on HooksPort, all enabled (vm-init answers /suspend and /resume |
| +// with 409, S2-6) but validate, /ready run at build time; x86_64; and the |
| +// ALL capability bubblewrap needs (spec §15). |
| +func ImageSettings() Settings { |
| + return Settings{ |
| + Hooks: Hooks{ |
| + Port: HooksPort, |
| + Microvm: MicrovmHooks{ |
| + Run: "ENABLED", RunTimeout: runHookTimeout, |
| + Resume: "ENABLED", ResumeTimeout: otherHookTimeout, |
| + Suspend: "ENABLED", SuspendTimeout: otherHookTimeout, |
| + Terminate: "ENABLED", TerminateTimeout: otherHookTimeout, |
| + }, |
| + Image: ImageHooks{Ready: "ENABLED", ReadyTimeout: readyHookTimeout, Validate: "DISABLED"}, |
| + }, |
| + CPU: []CPUConfig{{Architecture: "X86_64"}}, |
| + Capabilities: []string{"ALL"}, |
| + } |
| +} |
| + |
| +// Inventory is what Build wrote: the zip's SHA-256 and each entry's. |
| +type Inventory struct { |
| + ZipSHA256 string |
| + Files map[string]string // entry name -> hex SHA-256 |
| +} |
| + |
| +// Digest is the image digest the controller and certificates name. |
| +func (i Inventory) Digest() isolatedjob.ImageDigest { |
| + return isolatedjob.ImageDigest("sha256:" + i.ZipSHA256) |
| +} |
| + |
| +// entry is one zip entry: either bytes made here or a pinned input file. |
| +type entry struct { |
| + name string |
| + mode os.FileMode |
| + data []byte // made here |
| + input carried // or read from m.Inputs and checked against its pin |
| +} |
| + |
| +// Build writes the image zip for m to out, byte-reproducibly: entries in |
| +// name order, stored (not compressed, so the bytes depend on no |
| +// compressor's version), each with the fixed time zipTime and mode 0644 |
| +// or 0755. Nothing of the input files but their bytes reaches the zip. |
| +// The zip holds: |
| +// |
| +// - Dockerfile, rendered from Dockerfile.tmpl beside the manifest; |
| +// - image.json, the image settings publish sends (ImageSettings); |
| +// - manifest.json, m itself; |
| +// - files/..., every pinned input, each checked against its pin as it |
| +// is copied. |
| +// |
| +// m must pass Validate. An input that is missing, not a regular file, or |
| +// not its pinned bytes stops the build and leaves nothing at out. |
| +func Build(m Manifest, out string) (Inventory, error) { |
| + if err := m.Validate(); err != nil { |
| + return Inventory{}, err |
| + } |
| + if m.Dir == "" || m.Inputs == "" { |
| + return Inventory{}, errors.New("hostedimage: build needs the manifest's directory and the inputs directory") |
| + } |
| + dockerfile, err := renderDockerfile(m) |
| + if err != nil { |
| + return Inventory{}, err |
| + } |
| + settings, err := json.MarshalIndent(ImageSettings(), "", " ") |
| + if err != nil { |
| + return Inventory{}, err |
| + } |
| + manifest, err := json.MarshalIndent(m, "", " ") |
| + if err != nil { |
| + return Inventory{}, err |
| + } |
| + entries := []entry{ |
| + {name: "Dockerfile", mode: 0o644, data: dockerfile}, |
| + {name: "image.json", mode: 0o644, data: append(settings, '\n')}, |
| + {name: "manifest.json", mode: 0o644, data: append(manifest, '\n')}, |
| + } |
| + for _, f := range m.files() { |
| + mode := os.FileMode(0o644) |
| + if strings.HasPrefix(f.dest, "/usr/local/") && f.dest != "/usr/local/go" { |
| + mode = 0o755 |
| + } |
| + entries = append(entries, entry{name: f.entry, mode: mode, input: f}) |
| + } |
| + slices.SortFunc(entries, func(a, b entry) int { return strings.Compare(a.name, b.name) }) |
| + |
| + tmp, err := os.CreateTemp(filepath.Dir(out), ".equipo-image-*.zip") |
| + if err != nil { |
| + return Inventory{}, fmt.Errorf("hostedimage: %w", err) |
| + } |
| + ok := false |
| + defer func() { |
| + if !ok { |
| + tmp.Close() |
| + os.Remove(tmp.Name()) |
| + } |
| + }() |
| + whole := sha256.New() |
| + zw := zip.NewWriter(io.MultiWriter(tmp, whole)) |
| + inv := Inventory{Files: map[string]string{}} |
| + for _, e := range entries { |
| + h := &zip.FileHeader{Name: e.name, Method: zip.Store, Modified: zipTime} |
| + h.SetMode(e.mode) |
| + w, err := zw.CreateHeader(h) |
| + if err != nil { |
| + return Inventory{}, fmt.Errorf("hostedimage: %w", err) |
| + } |
| + sum := sha256.New() |
| + if e.data != nil { |
| + _, err = io.MultiWriter(w, sum).Write(e.data) |
| + } else { |
| + err = copyInput(io.MultiWriter(w, sum), filepath.Join(m.Inputs, filepath.FromSlash(e.input.input))) |
| + } |
| + if err != nil { |
| + return Inventory{}, err |
| + } |
| + got := hex.EncodeToString(sum.Sum(nil)) |
| + if e.data == nil && got != e.input.sha { |
| + return Inventory{}, fmt.Errorf("hostedimage: input %s is %s, the manifest pins %s", e.input.input, got, e.input.sha) |
| + } |
| + inv.Files[e.name] = got |
| + } |
| + if err := zw.Close(); err != nil { |
| + return Inventory{}, fmt.Errorf("hostedimage: %w", err) |
| + } |
| + if err := tmp.Chmod(0o644); err != nil { |
| + return Inventory{}, fmt.Errorf("hostedimage: %w", err) |
| + } |
| + if err := tmp.Sync(); err != nil { |
| + return Inventory{}, fmt.Errorf("hostedimage: %w", err) |
| + } |
| + if err := tmp.Close(); err != nil { |
| + return Inventory{}, fmt.Errorf("hostedimage: %w", err) |
| + } |
| + if err := os.Rename(tmp.Name(), out); err != nil { |
| + return Inventory{}, fmt.Errorf("hostedimage: %w", err) |
| + } |
| + ok = true |
| + inv.ZipSHA256 = hex.EncodeToString(whole.Sum(nil)) |
| + return inv, nil |
| +} |
| + |
| +// copyInput copies the regular file at path to w. A link, a directory or |
| +// a file replaced between the check and the open is refused. |
| +func copyInput(w io.Writer, path string) error { |
| + before, err := os.Lstat(path) |
| + if err != nil { |
| + return fmt.Errorf("hostedimage: input: %w", err) |
| + } |
| + if !before.Mode().IsRegular() { |
| + return fmt.Errorf("hostedimage: input %s is not a regular file", path) |
| + } |
| + f, err := os.Open(path) |
| + if err != nil { |
| + return fmt.Errorf("hostedimage: input: %w", err) |
| + } |
| + defer f.Close() |
| + after, err := f.Stat() |
| + if err != nil || !os.SameFile(before, after) { |
| + return fmt.Errorf("hostedimage: input %s changed while it was opened", path) |
| + } |
| + if _, err := io.Copy(w, f); err != nil { |
| + return fmt.Errorf("hostedimage: input %s: %w", path, err) |
| + } |
| + return nil |
| +} |
| + |
| +// TemplateFile is the Dockerfile template's name beside the manifest. |
| +const TemplateFile = "Dockerfile.tmpl" |
| + |
| +// dockerData is what the template sees. Every value in it is either a |
| +// constant of this package or a manifest value Validate has held to a |
| +// pattern that cannot leave its quotes (hex digests, release and package |
| +// names, addresses). |
| +type dockerData struct { |
| + Manifest Manifest |
| + Sums []string |
| + PathRunner, PathVMInit, PathBwrap, PathCodex, PathContainmentTest string |
| + StateDir, ResultsDir, EtcSource, EtcParent, RunnerUser string |
| + Cmd string |
| +} |
| + |
| +// VMInitArgs is the image's command: vm-init with every path and address |
| +// given explicitly (cmd/equipo-vm-init). The hooks listen on every |
| +// address inside the VM, where Lambda's hook requests arrive. |
| +func VMInitArgs(m Manifest) []string { |
| + args := []string{PathVMInit, |
| + "-hooks", fmt.Sprintf("0.0.0.0:%d", HooksPort), |
| + "-runner-user", RunnerUser, "-runner", PathRunner, |
| + "-state", StateDir, "-results", ResultsDir, "-etc-source", EtcSource} |
| + for _, p := range m.Policies { |
| + args = append(args, "-policy", p) |
| + } |
| + for _, r := range m.Resolvers { |
| + args = append(args, "-resolver", r) |
| + } |
| + for _, a := range m.Metadata { |
| + args = append(args, "-metadata", a) |
| + } |
| + return args |
| +} |
| + |
| +func renderDockerfile(m Manifest) ([]byte, error) { |
| + text, err := os.ReadFile(filepath.Join(m.Dir, TemplateFile)) |
| + if err != nil { |
| + return nil, fmt.Errorf("hostedimage: %w", err) |
| + } |
| + tmpl, err := template.New(TemplateFile).Option("missingkey=error").Parse(string(text)) |
| + if err != nil { |
| + return nil, fmt.Errorf("hostedimage: %s: %w", TemplateFile, err) |
| + } |
| + cmd, err := json.Marshal(VMInitArgs(m)) |
| + if err != nil { |
| + return nil, err |
| + } |
| + d := dockerData{Manifest: m, PathRunner: PathRunner, PathVMInit: PathVMInit, PathBwrap: PathBwrap, PathCodex: PathCodex, |
| + PathContainmentTest: PathContainmentTest, StateDir: StateDir, ResultsDir: ResultsDir, EtcSource: EtcSource, |
| + EtcParent: path.Dir(EtcSource), RunnerUser: RunnerUser, Cmd: string(cmd)} |
| + for _, f := range m.files() { |
| + d.Sums = append(d.Sums, f.sha+" "+strings.TrimPrefix(f.entry, "files/")) |
| + } |
| + slices.Sort(d.Sums) |
| + var b bytes.Buffer |
| + if err := tmpl.Execute(&b, d); err != nil { |
| + return nil, fmt.Errorf("hostedimage: %s: %w", TemplateFile, err) |
| + } |
| + return b.Bytes(), nil |
| +} |
diff --git a/internal/hostedimage/build_test.go b/internal/hostedimage/build_test.go| new file mode 100644 |
| index 00000000..a70aa5e4 |
| --- /dev/null |
| +++ b/internal/hostedimage/build_test.go |
| @@ -0,0 +1,327 @@ |
| +package hostedimage |
| + |
| +import ( |
| + "archive/zip" |
| + "bytes" |
| + "crypto/sha256" |
| + "encoding/hex" |
| + "encoding/json" |
| + "io" |
| + "os" |
| + "path/filepath" |
| + "regexp" |
| + "slices" |
| + "strings" |
| + "testing" |
| + "time" |
| +) |
| + |
| +func sum(b []byte) string { h := sha256.Sum256(b); return hex.EncodeToString(h[:]) } |
| + |
| +// fixture writes made-up input files into a new directory and returns a |
| +// complete manifest pinning them, with the checked-in Dockerfile.tmpl. |
| +func fixture(t *testing.T) Manifest { |
| + t.Helper() |
| + in := t.TempDir() |
| + m := validManifest() |
| + m.Dir = filepath.Join(repoRoot, "infra", "hosted", "image") |
| + m.Inputs = in |
| + files := map[string]*string{ |
| + "equipo-runner": &m.RunnerSHA256, |
| + "equipo-vm-init": &m.VMInitSHA256, |
| + "bwrap": &m.BubblewrapSHA256, |
| + "codex": &m.CodexSHA256, |
| + "containment.test": &m.ContainmentTestSHA256, |
| + m.GoToolchain + ".linux-amd64.tar.gz": &m.GoToolchainSHA256, |
| + } |
| + for name, pin := range files { |
| + body := []byte("fake " + name + "\n") |
| + write(t, filepath.Join(in, name), body, 0o755) |
| + *pin = sum(body) |
| + } |
| + body := []byte("fake rpm\n") |
| + write(t, filepath.Join(in, "pkgs", m.Packages[0].Name), body, 0o644) |
| + m.Packages = []Pinned{{Name: m.Packages[0].Name, SHA256: sum(body)}} |
| + return m |
| +} |
| + |
| +func write(t *testing.T, path string, body []byte, mode os.FileMode) { |
| + t.Helper() |
| + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.WriteFile(path, body, mode); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// TestBuildReproducible: the same manifest and the same bytes give the |
| +// same zip, byte for byte, whatever the input files' times, modes, umask |
| +// or directory order; entries are sorted, with fixed times and modes; the |
| +// inventory is the zip's; and the image settings say hooks.port, X86_64 |
| +// and ALL. |
| +func TestBuildReproducible(t *testing.T) { |
| + m := fixture(t) |
| + out1 := filepath.Join(t.TempDir(), "a.zip") |
| + inv1, err := Build(m, out1) |
| + if err != nil { |
| + t.Fatalf("Build: %v", err) |
| + } |
| + |
| + // Same bytes, everything else different: other times, other modes. |
| + m2 := m |
| + m2.Inputs = t.TempDir() |
| + if err := filepath.WalkDir(m.Inputs, func(p string, d os.DirEntry, err error) error { |
| + if err != nil || d.IsDir() { |
| + return err |
| + } |
| + rel, _ := filepath.Rel(m.Inputs, p) |
| + b, err := os.ReadFile(p) |
| + if err != nil { |
| + return err |
| + } |
| + write(t, filepath.Join(m2.Inputs, rel), b, 0o600) |
| + old := time.Date(2001, 2, 3, 4, 5, 6, 0, time.UTC) |
| + return os.Chtimes(filepath.Join(m2.Inputs, rel), old, old) |
| + }); err != nil { |
| + t.Fatal(err) |
| + } |
| + time.Sleep(10 * time.Millisecond) |
| + out2 := filepath.Join(t.TempDir(), "b.zip") |
| + inv2, err := Build(m2, out2) |
| + if err != nil { |
| + t.Fatalf("second Build: %v", err) |
| + } |
| + b1, _ := os.ReadFile(out1) |
| + b2, _ := os.ReadFile(out2) |
| + if !bytes.Equal(b1, b2) { |
| + t.Fatalf("two builds of the same inputs differ (%d and %d bytes)", len(b1), len(b2)) |
| + } |
| + if inv1.ZipSHA256 != sum(b1) || inv2.ZipSHA256 != inv1.ZipSHA256 { |
| + t.Fatalf("ZipSHA256 = %s and %s, want the zip's %s", inv1.ZipSHA256, inv2.ZipSHA256, sum(b1)) |
| + } |
| + if d := inv1.Digest(); string(d) != "sha256:"+sum(b1) { |
| + t.Fatalf("Digest = %s, want sha256:%s", d, sum(b1)) |
| + } |
| + |
| + zr, err := zip.NewReader(bytes.NewReader(b1), int64(len(b1))) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var names []string |
| + got := map[string]string{} |
| + for _, f := range zr.File { |
| + names = append(names, f.Name) |
| + if !f.Modified.Equal(zipTime) { |
| + t.Errorf("%s: modified %v, want the fixed %v", f.Name, f.Modified, zipTime) |
| + } |
| + if mode := f.Mode(); mode != 0o644 && mode != 0o755 { |
| + t.Errorf("%s: mode %v, want 0644 or 0755", f.Name, mode) |
| + } |
| + if f.Method != zip.Store { |
| + t.Errorf("%s: method %d, want stored", f.Name, f.Method) |
| + } |
| + rc, err := f.Open() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + b, err := io.ReadAll(rc) |
| + rc.Close() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + got[f.Name] = sum(b) |
| + if f.Name == "image.json" { |
| + var s Settings |
| + if err := json.Unmarshal(b, &s); err != nil { |
| + t.Fatalf("image.json: %v", err) |
| + } |
| + if s.Hooks.Port != HooksPort || !slices.Equal(s.Capabilities, []string{"ALL"}) || |
| + len(s.CPU) != 1 || s.CPU[0].Architecture != "X86_64" || s.Hooks.Microvm.RunTimeout != 60 { |
| + t.Errorf("image.json = %s, want port %d, X86_64, ALL and a 60 s run hook", b, HooksPort) |
| + } |
| + } |
| + } |
| + if !slices.IsSorted(names) { |
| + t.Errorf("entries %v are not sorted", names) |
| + } |
| + if !mapsEqual(got, inv1.Files) { |
| + t.Errorf("Files = %v, want the zip's %v", inv1.Files, got) |
| + } |
| + for name, pin := range map[string]string{ |
| + "files/equipo-runner": m.RunnerSHA256, "files/equipo-vm-init": m.VMInitSHA256, "files/bwrap": m.BubblewrapSHA256, |
| + "files/codex": m.CodexSHA256, "files/containment.test": m.ContainmentTestSHA256, "files/go.tar.gz": m.GoToolchainSHA256, |
| + "files/pkgs/" + m.Packages[0].Name: m.Packages[0].SHA256, |
| + } { |
| + if got[name] != pin { |
| + t.Errorf("%s = %s, want the pinned %s", name, got[name], pin) |
| + } |
| + } |
| + for _, name := range []string{"Dockerfile", "image.json", "manifest.json"} { |
| + if got[name] == "" { |
| + t.Errorf("no %s in the zip", name) |
| + } |
| + } |
| + |
| + // A different pin is a different image. |
| + m3 := m |
| + m3.Metadata = []string{"169.254.170.2:80"} |
| + inv3, err := Build(m3, filepath.Join(t.TempDir(), "c.zip")) |
| + if err != nil || inv3.ZipSHA256 == inv1.ZipSHA256 { |
| + t.Errorf("a changed manifest gave %s, %v; want another digest", inv3.ZipSHA256, err) |
| + } |
| +} |
| + |
| +func mapsEqual(a, b map[string]string) bool { |
| + if len(a) != len(b) { |
| + return false |
| + } |
| + for k, v := range a { |
| + if b[k] != v { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
| + |
| +// TestBuildChecksPins: an input whose bytes are not the pinned ones, a |
| +// missing input, or a link in place of one stops the build, and no zip is |
| +// left behind. |
| +func TestBuildChecksPins(t *testing.T) { |
| + for name, edit := range map[string]func(t *testing.T, m Manifest){ |
| + "changed runner": func(t *testing.T, m Manifest) { |
| + write(t, filepath.Join(m.Inputs, "equipo-runner"), []byte("another runner\n"), 0o755) |
| + }, |
| + "missing codex": func(t *testing.T, m Manifest) { os.Remove(filepath.Join(m.Inputs, "codex")) }, |
| + "changed package": func(t *testing.T, m Manifest) { |
| + write(t, filepath.Join(m.Inputs, "pkgs", m.Packages[0].Name), []byte("other\n"), 0o644) |
| + }, |
| + "bwrap is a link": func(t *testing.T, m Manifest) { |
| + p := filepath.Join(m.Inputs, "bwrap") |
| + b, _ := os.ReadFile(p) |
| + write(t, filepath.Join(m.Inputs, "real-bwrap"), b, 0o755) |
| + os.Remove(p) |
| + if err := os.Symlink("real-bwrap", p); err != nil { |
| + t.Fatal(err) |
| + } |
| + }, |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + m := fixture(t) |
| + edit(t, m) |
| + out := filepath.Join(t.TempDir(), "x.zip") |
| + if _, err := Build(m, out); err == nil { |
| + t.Fatal("Build = nil, want a refusal") |
| + } |
| + if entries, _ := os.ReadDir(filepath.Dir(out)); len(entries) != 0 { |
| + t.Fatalf("Build left %v behind", entries) |
| + } |
| + }) |
| + } |
| + m := fixture(t) |
| + m.RunnerSHA256 = "" |
| + if _, err := Build(m, filepath.Join(t.TempDir(), "x.zip")); err == nil { |
| + t.Fatal("Build with an incomplete manifest = nil, want a refusal") |
| + } |
| +} |
| + |
| +// secretPattern matches the shapes of credential the image must never |
| +// hold: private keys, AWS keys, forge and model provider tokens, bearer |
| +// headers, and assignments of secret-named settings. |
| +var secretPattern = regexp.MustCompile(`(?i)(-----BEGIN [A-Z ]*PRIVATE KEY-----|AKIA[0-9A-Z]{16}|ASIA[0-9A-Z]{16}|gh[pousr]_[A-Za-z0-9]{20,}|glpat-|sk-[A-Za-z0-9_-]{16,}|xox[abp]-|authorization:\s*bearer|(secret|token|password|passwd|api_key|apikey|private_key)\s*[=:])`) |
| + |
| +// forbiddenPath matches paths that would put a credential, a person's |
| +// configuration or a repository in the image (spec §4). |
| +var forbiddenPath = regexp.MustCompile(`(?i)(^|/)(\.ssh|\.aws|\.codex|\.claude|\.config|\.git|\.netrc|\.gitconfig|\.npmrc|\.docker|auth\.json|credentials|id_[a-z0-9]+|[^/]*\.(pem|key|p12))(/|$)`) |
| + |
| +// TestImageInputsHaveNoSecrets: the checked-in image inputs, and the zip |
| +// built from them, hold no token, key, OAuth home, forge credential, |
| +// person's configuration or repository (spec §4). Files beside the pinned |
| +// inputs never reach the zip; the Dockerfile copies only named files and |
| +// fetches nothing; and the runner's state directory starts empty. |
| +func TestImageInputsHaveNoSecrets(t *testing.T) { |
| + dir := filepath.Join(repoRoot, "infra", "hosted", "image") |
| + entries, err := os.ReadDir(dir) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var have []string |
| + for _, e := range entries { |
| + have = append(have, e.Name()) |
| + b, err := os.ReadFile(filepath.Join(dir, e.Name())) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if loc := secretPattern.FindIndex(b); loc != nil { |
| + t.Errorf("%s holds a secret-shaped string at byte %d", e.Name(), loc[0]) |
| + } |
| + } |
| + if want := []string{"Dockerfile.tmpl", "manifest.json"}; !slices.Equal(have, want) { |
| + t.Errorf("infra/hosted/image holds %v, want exactly %v (every image input is reviewed here)", have, want) |
| + } |
| + |
| + m := fixture(t) |
| + // Credentials and a repository beside the pinned inputs. |
| + for _, p := range []string{".ssh/id_ed25519", ".codex/auth.json", ".aws/credentials", ".git/config", "home/.gitconfig", "token.txt"} { |
| + write(t, filepath.Join(m.Inputs, p), []byte("aws_secret_access_key = not-in-the-image\n"), 0o600) |
| + } |
| + out := filepath.Join(t.TempDir(), "image.zip") |
| + inv, err := Build(m, out) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + b, err := os.ReadFile(out) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if bytes.Contains(b, []byte("not-in-the-image")) { |
| + t.Error("a file beside the pinned inputs reached the zip") |
| + } |
| + allowed := regexp.MustCompile(`^(Dockerfile|image\.json|manifest\.json|files/(equipo-runner|equipo-vm-init|bwrap|codex|containment\.test|go\.tar\.gz|pkgs/[A-Za-z0-9][A-Za-z0-9._+-]*\.rpm))$`) |
| + for name := range inv.Files { |
| + if !allowed.MatchString(name) || forbiddenPath.MatchString(name) { |
| + t.Errorf("zip entry %q is not one the image may carry", name) |
| + } |
| + } |
| + zr, err := zip.NewReader(bytes.NewReader(b), int64(len(b))) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, f := range zr.File { |
| + if strings.HasPrefix(f.Name, "files/") { |
| + continue // the fake binaries; their bytes are pinned, not read |
| + } |
| + rc, _ := f.Open() |
| + body, _ := io.ReadAll(rc) |
| + rc.Close() |
| + if loc := secretPattern.FindIndex(body); loc != nil { |
| + t.Errorf("%s holds a secret-shaped string: %q", f.Name, body[loc[0]:loc[1]]) |
| + } |
| + if f.Name != "Dockerfile" { |
| + continue |
| + } |
| + df := string(body) |
| + for _, line := range strings.Split(df, "\n") { |
| + fields := strings.Fields(line) |
| + if len(fields) == 0 || strings.HasPrefix(fields[0], "#") { |
| + continue |
| + } |
| + switch strings.ToUpper(fields[0]) { |
| + case "ADD", "ENV", "ARG", "VOLUME", "ONBUILD": |
| + t.Errorf("Dockerfile uses %s: %q", fields[0], line) |
| + case "COPY": |
| + if len(fields) != 3 || fields[1] != "files/" { |
| + t.Errorf("Dockerfile copies something other than files/: %q", line) |
| + } |
| + } |
| + } |
| + for _, bad := range []string{"curl ", "wget ", "git clone", "dnf ", "yum ", "pip ", "go get", "go install", "http://", "https://"} { |
| + if strings.Contains(df, bad) { |
| + t.Errorf("Dockerfile fetches (%q); every input must be in the zip", bad) |
| + } |
| + } |
| + if !regexp.MustCompile(`install -d -m 0700 -o equipo -g equipo ` + regexp.QuoteMeta(StateDir)).MatchString(df) { |
| + t.Errorf("Dockerfile does not create the runner's state directory %s empty", StateDir) |
| + } |
| + } |
| +} |
diff --git a/internal/hostedimage/manifest.go b/internal/hostedimage/manifest.go| new file mode 100644 |
| index 00000000..e84aa876 |
| --- /dev/null |
| +++ b/internal/hostedimage/manifest.go |
| @@ -0,0 +1,276 @@ |
| +// Package hostedimage builds the hosted runner's MicroVM image input and |
| +// publishes it (spec §4; plan Task 10). It holds no AWS type: publishing |
| +// goes through Provider, which the SDK side |
| +// (internal/isolatedjob/awsjob/imageaws) implements and |
| +// cmd/equipo-hosted-image wires in. |
| +// |
| +// The image is built from a zip holding a Dockerfile and every file the |
| +// Dockerfile installs, each pinned by SHA-256 in the manifest. The build |
| +// in AWS fetches nothing: the build role reads the one zip, and the |
| +// Dockerfile copies only the named files. The zip is byte-reproducible, |
| +// so its SHA-256 is the image digest the controller and the certificates |
| +// name (isolatedjob.ImageDigest), and anyone can rebuild it from the |
| +// manifest and the pinned files and get the same digest. |
| +package hostedimage |
| + |
| +import ( |
| + "bytes" |
| + "encoding/json" |
| + "fmt" |
| + "net/netip" |
| + "os" |
| + "path" |
| + "path/filepath" |
| + "reflect" |
| + "regexp" |
| + "slices" |
| + |
| + "amadan.net/oficina/equipo/internal/vminit" |
| +) |
| + |
| +// Pinned is one file the image carries beyond the named ones: its name in |
| +// the inputs directory (under pkgs/) and its SHA-256. |
| +type Pinned struct { |
| + Name string |
| + SHA256 string |
| +} |
| + |
| +// Manifest pins every input of the image (infra/hosted/image/manifest.json). |
| +// Each *SHA256 is the hex SHA-256 of the input file's bytes, except |
| +// GitSHA256, which is /usr/bin/git's once the packages are installed (the |
| +// Dockerfile checks it). |
| +type Manifest struct { |
| + // RunnerRelease names the runner release the binaries come from (the |
| + // release directory or tag that published equipo-runner, equipo-vm-init |
| + // and containment.test). |
| + RunnerRelease string |
| + RunnerSHA256 string |
| + VMInitSHA256 string |
| + BubblewrapSHA256 string |
| + GoToolchain string // "go1.26.11": the input is <GoToolchain>.linux-amd64.tar.gz |
| + GoToolchainSHA256 string |
| + GitSHA256 string |
| + CodexSHA256 string |
| + ContainmentTestSHA256 string |
| + // Packages are RPM files installed, offline, before anything else. |
| + Packages []Pinned |
| + // Policies are the in-image paths of the sandbox policy set vm-init |
| + // measures (its -policy flags). Each must be a file the image installs |
| + // from a pinned input, so its digest is known here. |
| + Policies []string |
| + // Resolvers and Metadata are vm-init's -resolver and -metadata: the |
| + // managed resolver addresses and metadata endpoints the certification |
| + // probes check. Required, with no default (Task 8); Task 34 confirms |
| + // the MicroVM's values live. |
| + Resolvers []string |
| + Metadata []string |
| + |
| + // Dir is the directory holding manifest.json and Dockerfile.tmpl; |
| + // LoadManifest sets it. |
| + Dir string `json:"-"` |
| + // Inputs is the directory holding the pinned files, by their input |
| + // names (InputName). Nothing else in it is read. |
| + Inputs string `json:"-"` |
| +} |
| + |
| +// Where the image installs the pinned files. vm-init's flags (in the |
| +// Dockerfile) and the measured names refer to these paths. |
| +const ( |
| + PathRunner = "/usr/local/bin/equipo-runner" |
| + PathVMInit = "/usr/local/sbin/equipo-vm-init" |
| + PathBwrap = "/usr/local/bin/bwrap" |
| + PathCodex = "/usr/local/bin/codex" |
| + PathContainmentTest = "/usr/local/libexec/equipo/containment.test" |
| + // StateDir is the runner's state directory, empty in the image (spec |
| + // §4; vm-init's /ready refuses otherwise); ResultsDir holds what |
| + // vm-init measures; EtcSource is the image's copy of /etc, with an |
| + // empty resolv.conf, that vm-init binds over /etc. |
| + StateDir = "/var/lib/equipo-runner" |
| + ResultsDir = "/var/lib/equipo-results" |
| + EtcSource = "/opt/equipo/etc" |
| + // RunnerUser is the unprivileged account the runner runs as. |
| + RunnerUser = "equipo" |
| +) |
| + |
| +// carried is one pinned file: its name in the inputs directory, its zip |
| +// entry, where the image installs it, and its pin. |
| +type carried struct { |
| + input, entry, dest string |
| + sha string |
| +} |
| + |
| +// files lists every file the image carries, in no particular order. |
| +func (m Manifest) files() []carried { |
| + fs := []carried{ |
| + {"equipo-runner", "files/equipo-runner", PathRunner, m.RunnerSHA256}, |
| + {"equipo-vm-init", "files/equipo-vm-init", PathVMInit, m.VMInitSHA256}, |
| + {"bwrap", "files/bwrap", PathBwrap, m.BubblewrapSHA256}, |
| + {"codex", "files/codex", PathCodex, m.CodexSHA256}, |
| + {"containment.test", "files/containment.test", PathContainmentTest, m.ContainmentTestSHA256}, |
| + {m.GoToolchain + ".linux-amd64.tar.gz", "files/go.tar.gz", "/usr/local/go", m.GoToolchainSHA256}, |
| + } |
| + for _, p := range m.Packages { |
| + fs = append(fs, carried{"pkgs/" + p.Name, "files/pkgs/" + p.Name, "", p.SHA256}) |
| + } |
| + return fs |
| +} |
| + |
| +var ( |
| + hexDigest = regexp.MustCompile(`^[0-9a-f]{64}$`) |
| + releaseName = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$`) |
| + goRelease = regexp.MustCompile(`^go1\.[0-9]+(\.[0-9]+)?$`) |
| + rpmName = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._+-]*\.rpm$`) |
| +) |
| + |
| +// releaseFilled are the fields a runner release fills in: the checked-in |
| +// manifest leaves them empty until the release commit pins them (Task |
| +// 29), and a build refuses it until then. |
| +var releaseFilled = []string{"RunnerRelease", "RunnerSHA256", "VMInitSHA256", "ContainmentTestSHA256", "GoToolchainSHA256", "GitSHA256", "Packages", "Resolvers"} |
| + |
| +// Validate refuses a manifest that leaves any input unpinned or |
| +// malformed. A build needs it to pass. |
| +func (m Manifest) Validate() error { return m.validate(false) } |
| + |
| +// ValidateStatic is Validate with the release-filled fields allowed to be |
| +// empty (releaseFilled); set ones must still be well formed. The |
| +// checked-in manifest passes it between releases. |
| +func (m Manifest) ValidateStatic() error { return m.validate(true) } |
| + |
| +func (m Manifest) validate(static bool) error { |
| + bad := func(field, format string, a ...any) error { |
| + return fmt.Errorf("hostedimage: manifest %s: "+format, append([]any{field}, a...)...) |
| + } |
| + unset := func(field, v string) bool { return v == "" && static && slices.Contains(releaseFilled, field) } |
| + for _, f := range []struct{ name, v string }{ |
| + {"RunnerSHA256", m.RunnerSHA256}, {"VMInitSHA256", m.VMInitSHA256}, {"BubblewrapSHA256", m.BubblewrapSHA256}, |
| + {"GoToolchainSHA256", m.GoToolchainSHA256}, {"GitSHA256", m.GitSHA256}, {"CodexSHA256", m.CodexSHA256}, |
| + {"ContainmentTestSHA256", m.ContainmentTestSHA256}, |
| + } { |
| + if !unset(f.name, f.v) && !hexDigest.MatchString(f.v) { |
| + return bad(f.name, "%q is not 64 lower-case hex digits", f.v) |
| + } |
| + } |
| + if !unset("RunnerRelease", m.RunnerRelease) && !releaseName.MatchString(m.RunnerRelease) { |
| + return bad("RunnerRelease", "%q is not a release name", m.RunnerRelease) |
| + } |
| + if !goRelease.MatchString(m.GoToolchain) { |
| + return bad("GoToolchain", "%q is not a Go release such as go1.26.11", m.GoToolchain) |
| + } |
| + seen := map[string]bool{} |
| + for _, p := range m.Packages { |
| + if !rpmName.MatchString(p.Name) || seen[p.Name] { |
| + return bad("Packages", "%q is not a distinct .rpm file name", p.Name) |
| + } |
| + seen[p.Name] = true |
| + if !hexDigest.MatchString(p.SHA256) { |
| + return bad("Packages", "%s's digest %q is not 64 lower-case hex digits", p.Name, p.SHA256) |
| + } |
| + } |
| + installed := map[string]bool{} |
| + for _, f := range m.files() { |
| + if f.dest != "" { |
| + installed[f.dest] = true |
| + } |
| + } |
| + if len(m.Policies) == 0 { |
| + return bad("Policies", "the sandbox policy set is empty") |
| + } |
| + seen = map[string]bool{} |
| + for _, p := range m.Policies { |
| + if !installed[p] || path.Clean(p) != p || seen[p] || p == "/usr/local/go" { |
| + return bad("Policies", "%q is not a distinct file the image installs from a pinned input", p) |
| + } |
| + seen[p] = true |
| + } |
| + if len(m.Resolvers) == 0 && !static { |
| + return bad("Resolvers", "vm-init needs at least one managed resolver address to probe") |
| + } |
| + for _, r := range m.Resolvers { |
| + if _, err := netip.ParseAddr(r); err != nil { |
| + return bad("Resolvers", "%q is not an IP address", r) |
| + } |
| + } |
| + if len(m.Metadata) == 0 { |
| + return bad("Metadata", "vm-init needs at least one metadata endpoint to probe") |
| + } |
| + for _, a := range m.Metadata { |
| + if _, err := netip.ParseAddrPort(a); err != nil { |
| + return bad("Metadata", "%q is not ADDR:PORT", a) |
| + } |
| + } |
| + return nil |
| +} |
| + |
| +// Measured is what vm-init's measured.json must hold for an image built |
| +// from m, under the names certification compares (Task 13): the runner, |
| +// vm-init and the sandbox policy set's digest, computed as vm-init |
| +// computes it (vminit.PolicySetDigest over the policy paths). |
| +func (m Manifest) Measured() map[string]string { |
| + sha := map[string]string{} |
| + for _, f := range m.files() { |
| + sha[f.dest] = f.sha |
| + } |
| + policies := map[string]string{} |
| + for _, p := range m.Policies { |
| + policies[p] = sha[p] |
| + } |
| + return map[string]string{ |
| + vminit.MeasuredRunner: m.RunnerSHA256, |
| + vminit.MeasuredVMInit: m.VMInitSHA256, |
| + vminit.MeasuredSandboxPolicy: vminit.PolicySetDigest(policies), |
| + } |
| +} |
| + |
| +// LoadManifest reads path strictly (an unknown key, such as a misspelt |
| +// pin, is refused) and sets Dir to its directory. It does not validate. |
| +func LoadManifest(file string) (Manifest, error) { |
| + b, err := os.ReadFile(file) |
| + if err != nil { |
| + return Manifest{}, fmt.Errorf("hostedimage: %w", err) |
| + } |
| + dec := json.NewDecoder(bytes.NewReader(b)) |
| + dec.DisallowUnknownFields() |
| + var m Manifest |
| + if err := dec.Decode(&m); err != nil { |
| + return Manifest{}, fmt.Errorf("hostedimage: %s: %w", file, err) |
| + } |
| + if dec.More() { |
| + return Manifest{}, fmt.Errorf("hostedimage: %s: more than one JSON value", file) |
| + } |
| + // encoding/json matches keys without regard to case, so a key that |
| + // differs from a field only in case (RunnerSha256) would pass the |
| + // decoder above, and two such keys would silently override each |
| + // other. Every key must be a field's exact name. |
| + if err := exactKeys(b, reflect.TypeOf(Manifest{})); err != nil { |
| + return Manifest{}, fmt.Errorf("hostedimage: %s: %w", file, err) |
| + } |
| + m.Dir = filepath.Dir(file) |
| + return m, nil |
| +} |
| + |
| +// exactKeys checks that every key of the JSON object b, and of the |
| +// objects in its arrays of structs, is the exact name of a field of t. |
| +func exactKeys(b []byte, t reflect.Type) error { |
| + var raw map[string]json.RawMessage |
| + if err := json.Unmarshal(b, &raw); err != nil { |
| + return err |
| + } |
| + for k, v := range raw { |
| + f, ok := t.FieldByName(k) |
| + if !ok || f.Tag.Get("json") == "-" || !f.IsExported() { |
| + return fmt.Errorf("unknown key %q (keys are the exact field names)", k) |
| + } |
| + if f.Type.Kind() == reflect.Slice && f.Type.Elem().Kind() == reflect.Struct { |
| + var items []json.RawMessage |
| + if err := json.Unmarshal(v, &items); err != nil { |
| + return err |
| + } |
| + for _, it := range items { |
| + if err := exactKeys(it, f.Type.Elem()); err != nil { |
| + return fmt.Errorf("%s: %w", k, err) |
| + } |
| + } |
| + } |
| + } |
| + return nil |
| +} |
diff --git a/internal/hostedimage/manifest_test.go b/internal/hostedimage/manifest_test.go| new file mode 100644 |
| index 00000000..680504f6 |
| --- /dev/null |
| +++ b/internal/hostedimage/manifest_test.go |
| @@ -0,0 +1,152 @@ |
| +package hostedimage |
| + |
| +import ( |
| + "encoding/json" |
| + "os" |
| + "path/filepath" |
| + "reflect" |
| + "strings" |
| + "testing" |
| + |
| + "amadan.net/oficina/equipo/internal/vminit" |
| + "amadan.net/rastrillo/rastrillo/budget" |
| +) |
| + |
| +func TestMain(m *testing.M) { os.Exit(budget.Main(m)) } |
| + |
| +func hex64(c byte) string { return strings.Repeat(string(c), 64) } |
| + |
| +// validManifest is a complete manifest with made-up digests. |
| +func validManifest() Manifest { |
| + return Manifest{ |
| + RunnerRelease: "equipo-runner-linux-amd64-abc1234", |
| + RunnerSHA256: hex64('1'), |
| + VMInitSHA256: hex64('2'), |
| + BubblewrapSHA256: hex64('3'), |
| + GoToolchain: "go1.26.11", |
| + GoToolchainSHA256: hex64('4'), |
| + GitSHA256: hex64('5'), |
| + CodexSHA256: hex64('6'), |
| + ContainmentTestSHA256: hex64('7'), |
| + Packages: []Pinned{{Name: "git-core-2.47.1-1.amzn2023.x86_64.rpm", SHA256: hex64('8')}}, |
| + Policies: []string{PathBwrap}, |
| + Resolvers: []string{"10.0.0.2"}, |
| + Metadata: []string{"169.254.169.254:80"}, |
| + } |
| +} |
| + |
| +// repoRoot is the module root; go test runs in the package directory. |
| +const repoRoot = "../.." |
| + |
| +// TestManifestPinsEverything: a manifest passes only when every input is |
| +// pinned: each digest field 64 lower-case hex digits, the release and |
| +// toolchain named, every package with a file name and a digest, a policy |
| +// set the image carries, and the addresses vm-init probes. Unknown keys |
| +// are refused, and the checked-in manifest's static pins agree with the |
| +// release's. |
| +func TestManifestPinsEverything(t *testing.T) { |
| + if err := validManifest().Validate(); err != nil { |
| + t.Fatalf("a complete manifest: %v", err) |
| + } |
| + |
| + // Every string field, blanked or malformed, is refused by name. |
| + mt := reflect.TypeOf(Manifest{}) |
| + for i := range mt.NumField() { |
| + f := mt.Field(i) |
| + if f.Type.Kind() != reflect.String || f.Tag.Get("json") == "-" { |
| + continue |
| + } |
| + for _, bad := range []string{"", "x y", strings.Repeat("A", 64), hex64('1')[:63]} { |
| + m := validManifest() |
| + reflect.ValueOf(&m).Elem().Field(i).SetString(bad) |
| + if f.Name == "RunnerRelease" && (bad == strings.Repeat("A", 64) || bad == hex64('1')[:63]) { |
| + continue // a release name may be any such word |
| + } |
| + err := m.Validate() |
| + if err == nil || !strings.Contains(err.Error(), f.Name) { |
| + t.Errorf("%s = %q: Validate = %v, want a refusal naming %s", f.Name, bad, err, f.Name) |
| + } |
| + } |
| + } |
| + |
| + for name, edit := range map[string]func(*Manifest){ |
| + "package without a digest": func(m *Manifest) { m.Packages[0].SHA256 = "" }, |
| + "package with a bad digest": func(m *Manifest) { m.Packages[0].SHA256 = "zz" }, |
| + "package that is not an rpm": func(m *Manifest) { m.Packages[0].Name = "setup.sh" }, |
| + "package with a path": func(m *Manifest) { m.Packages[0].Name = "../git.rpm" }, |
| + "package listed twice": func(m *Manifest) { m.Packages = append(m.Packages, m.Packages[0]) }, |
| + "no policy": func(m *Manifest) { m.Policies = nil }, |
| + "policy the image does not own": func(m *Manifest) { m.Policies = []string{"/etc/passwd"} }, |
| + "policy twice": func(m *Manifest) { m.Policies = []string{PathBwrap, PathBwrap} }, |
| + "no resolver": func(m *Manifest) { m.Resolvers = nil }, |
| + "resolver not an address": func(m *Manifest) { m.Resolvers = []string{"dns.example"} }, |
| + "no metadata endpoint": func(m *Manifest) { m.Metadata = nil }, |
| + "metadata without a port": func(m *Manifest) { m.Metadata = []string{"169.254.169.254"} }, |
| + "toolchain not a Go release": func(m *Manifest) { m.GoToolchain = "latest" }, |
| + } { |
| + m := validManifest() |
| + m.Packages = append([]Pinned(nil), m.Packages...) |
| + edit(&m) |
| + if err := m.Validate(); err == nil { |
| + t.Errorf("%s: Validate = nil, want a refusal", name) |
| + } |
| + } |
| + |
| + // Strict decoding: an unknown key (a misspelt pin) is refused. |
| + dir := t.TempDir() |
| + b, _ := json.Marshal(validManifest()) |
| + var raw map[string]any |
| + _ = json.Unmarshal(b, &raw) |
| + raw["RunnerSha256"] = hex64('9') |
| + b, _ = json.Marshal(raw) |
| + p := filepath.Join(dir, "manifest.json") |
| + if err := os.WriteFile(p, b, 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := LoadManifest(p); err == nil { |
| + t.Error("LoadManifest accepted an unknown key") |
| + } |
| + |
| + // The measured digests are the manifest's, the policy set's computed |
| + // as vm-init computes it. |
| + m := validManifest() |
| + got := m.Measured() |
| + want := map[string]string{ |
| + vminit.MeasuredRunner: m.RunnerSHA256, |
| + vminit.MeasuredVMInit: m.VMInitSHA256, |
| + vminit.MeasuredSandboxPolicy: vminit.PolicySetDigest(map[string]string{PathBwrap: m.BubblewrapSHA256}), |
| + } |
| + if !reflect.DeepEqual(got, want) { |
| + t.Errorf("Measured = %v, want %v", got, want) |
| + } |
| + |
| + // The checked-in manifest decodes strictly, and its static pins are |
| + // the release's (internal/release/manifest.json). |
| + root := repoRoot |
| + checked, err := LoadManifest(filepath.Join(root, "infra", "hosted", "image", "manifest.json")) |
| + if err != nil { |
| + t.Fatalf("checked-in manifest: %v", err) |
| + } |
| + var rel struct { |
| + Go string `json:"go"` |
| + Binaries []struct{ Name, SHA256 string } |
| + } |
| + rb, err := os.ReadFile(filepath.Join(root, "internal", "release", "manifest.json")) |
| + if err != nil || json.Unmarshal(rb, &rel) != nil { |
| + t.Fatalf("release manifest: %v", err) |
| + } |
| + pins := map[string]string{} |
| + for _, b := range rel.Binaries { |
| + pins[b.Name] = b.SHA256 |
| + } |
| + if checked.GoToolchain != rel.Go || checked.CodexSHA256 != pins["codex"] || checked.BubblewrapSHA256 != pins["bwrap"] { |
| + t.Errorf("checked-in pins go=%s codex=%s bwrap=%s, want the release's go=%s codex=%s bwrap=%s", |
| + checked.GoToolchain, checked.CodexSHA256, checked.BubblewrapSHA256, rel.Go, pins["codex"], pins["bwrap"]) |
| + } |
| + if len(checked.Metadata) == 0 { |
| + t.Error("checked-in manifest has no metadata endpoint for vm-init") |
| + } |
| + if err := checked.ValidateStatic(); err != nil { |
| + t.Errorf("checked-in manifest's static pins: %v", err) |
| + } |
| +} |
diff --git a/internal/hostedimage/publish.go b/internal/hostedimage/publish.go| new file mode 100644 |
| index 00000000..1d34fc66 |
| --- /dev/null |
| +++ b/internal/hostedimage/publish.go |
| @@ -0,0 +1,679 @@ |
| +package hostedimage |
| + |
| +import ( |
| + "context" |
| + "crypto/sha256" |
| + "encoding/hex" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "os" |
| + "path/filepath" |
| + "regexp" |
| + "slices" |
| + "strconv" |
| + "strings" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/isolatedjob" |
| +) |
| + |
| +// Exit codes of equipo-hosted-image, as livectl's. |
| +const ( |
| + ExitOK = 0 |
| + ExitOther = 1 |
| + ExitAPI = 2 |
| + ExitUsage = 3 |
| + ExitGuard = 4 |
| + ExitTimeout = 5 |
| + ExitFailed = 6 |
| +) |
| + |
| +// Failure is how an operation ends other than success. The command prints |
| +// it as one JSON line. |
| +type Failure struct { |
| + Exit int `json:"-"` |
| + Kind string `json:"error"` // api, transport, usage, guard, timeout, failed_state, mismatch, other |
| + Op string `json:"op,omitempty"` |
| + Code string `json:"code,omitempty"` |
| + Status int `json:"http_status,omitempty"` |
| + Message string `json:"message"` |
| + AWSMessage string `json:"aws_message,omitempty"` |
| + RequestID string `json:"request_id,omitempty"` |
| +} |
| + |
| +func (f *Failure) Error() string { return f.Kind + ": " + f.Message } |
| + |
| +// ErrNotFound is wrapped by a CallError for a resource AWS does not know. |
| +var ErrNotFound = errors.New("hostedimage: not found") |
| + |
| +// CallError is a failed provider call. |
| +type CallError struct { |
| + Op string |
| + Answered bool // the service answered; false for a transport failure |
| + Code string |
| + Status int |
| + AWSMessage string |
| + RequestID string |
| + Err error |
| +} |
| + |
| +func (e *CallError) Error() string { return e.Op + " failed" } |
| +func (e *CallError) Unwrap() error { return e.Err } |
| + |
| +// BaseVersion is one version of the managed base image. |
| +type BaseVersion struct{ Version, Status string } |
| + |
| +// CreateImage is one image creation. |
| +type CreateImage struct { |
| + Name, Description, Artifact string |
| + BaseImageARN, BaseVersion, BuildRoleARN string |
| + LogGroup, ClientToken string |
| + MemoryMiB int |
| + Settings Settings |
| + Tags map[string]string |
| +} |
| + |
| +// Created is what a creation returned. |
| +type Created struct{ ImageARN, Name, Version string } |
| + |
| +// Image is an image as read or listed. |
| +type Image struct { |
| + ARN, Name, State, LatestActiveVersion string |
| +} |
| + |
| +// Version is an image version as read. |
| +type Version struct { |
| + State, Status, Reason string |
| + Capabilities, Architectures []string |
| + MemoryMiB []int |
| + HooksPort, RunTimeout int |
| + Artifact, BaseVersion string |
| +} |
| + |
| +// Connector is a network connector as read. |
| +type Connector struct{ ARN, Name, State, Reason string } |
| + |
| +// Provider is AWS as the image tool sees it. awsjob/imageaws implements |
| +// it; each method is one SDK call (or one paged read). |
| +type Provider interface { |
| + Region() string // the region every call goes to |
| + CallerAccount(ctx context.Context) (string, error) |
| + BaseVersions(ctx context.Context, baseARN string) ([]BaseVersion, error) |
| + CreateImage(ctx context.Context, c CreateImage) (Created, error) |
| + GetImage(ctx context.Context, id string) (Image, error) |
| + GetImageVersion(ctx context.Context, imageARN, version string) (Version, error) |
| + ListImages(ctx context.Context, nameFilter string) ([]Image, error) |
| + DeleteImage(ctx context.Context, id string) error |
| + GetConnector(ctx context.Context, id string) (Connector, error) |
| +} |
| + |
| +// Target is where the tool may act: the account, the region and the name |
| +// prefix, all given as flags. |
| +type Target struct{ Account, Region, Prefix string } |
| + |
| +// Clock is time for the waits; tests use a fake one. |
| +type Clock interface { |
| + Now() time.Time |
| + Sleep(time.Duration) |
| +} |
| + |
| +// Wait bounds a wait. |
| +type Wait struct { |
| + Timeout, Interval time.Duration |
| + Clock Clock |
| +} |
| + |
| +// JournalFile is the ledger's journal in the -ledger directory. |
| +const JournalFile = "journal.tsv" |
| + |
| +// BaseImageARN is the managed base image the hosted image builds on. |
| +func BaseImageARN(region string) string { |
| + return "arn:aws:lambda:" + region + ":aws:microvm-image:al2023-1" |
| +} |
| + |
| +// PublishRequest is one publish. |
| +type PublishRequest struct { |
| + Name string |
| + Bucket, Key string |
| + BaseVersion string |
| + AllowStepDown bool |
| + BuildRoleARN string |
| + LogGroup string |
| + Size isolatedjob.Size |
| + Capabilities string |
| + Tags map[string]string |
| + Ledger string // directory holding JournalFile |
| + Out string // the JSON result file |
| + Wait Wait |
| +} |
| + |
| +// Published is a built, active image version. |
| +type Published struct { |
| + Name, ImageArn, ImageVersion, VersionArn string |
| + BaseImageArn, BaseImageVersion string |
| + Size isolatedjob.Size |
| + MemoryMiB int |
| + Artifact, Account, Region string |
| +} |
| + |
| +// maxWait bounds every wait, as livectl's. |
| +const maxWait = 60 * time.Minute |
| + |
| +var ( |
| + accountPattern = regexp.MustCompile(`^[0-9]{12}$`) |
| + regionPattern = regexp.MustCompile(`^[a-z]{2}(-[a-z]+)+-[0-9]$`) |
| + prefixPattern = regexp.MustCompile(`^[a-z][a-z0-9-]{1,62}[a-z0-9]$`) |
| + namePattern = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,127}$`) |
| + bucketPattern = regexp.MustCompile(`^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$`) |
| + keyPattern = regexp.MustCompile(`^[A-Za-z0-9!_.*'()/:+=@-]+$`) |
| + versionPattern = regexp.MustCompile(`^[0-9A-Za-z][0-9A-Za-z.-]{0,63}$`) |
| + logGroupRegex = regexp.MustCompile(`^[A-Za-z0-9_./#-]{1,512}$`) |
| + rolePathRegex = regexp.MustCompile(`^role/[A-Za-z0-9+=,.@_/-]{1,512}$`) |
| + tagKeyPattern = regexp.MustCompile(`^[A-Za-z0-9 _.:/=+@-]{1,128}$`) |
| + tagValPattern = regexp.MustCompile(`^[A-Za-z0-9 _.:/=+@-]{0,256}$`) |
| +) |
| + |
| +func usage(format string, a ...any) *Failure { |
| + return &Failure{Exit: ExitUsage, Kind: "usage", Message: fmt.Sprintf(format, a...)} |
| +} |
| + |
| +func guard(format string, a ...any) *Failure { |
| + return &Failure{Exit: ExitGuard, Kind: "guard", Message: fmt.Sprintf(format, a...)} |
| +} |
| + |
| +func other(format string, a ...any) *Failure { |
| + return &Failure{Exit: ExitOther, Kind: "other", Message: fmt.Sprintf(format, a...)} |
| +} |
| + |
| +// apiFailure describes a failed provider call. |
| +func apiFailure(op string, err error) *Failure { |
| + var ce *CallError |
| + if !errors.As(err, &ce) { |
| + return &Failure{Exit: ExitAPI, Kind: "transport", Op: op, Message: op + " failed before an answer came back"} |
| + } |
| + f := &Failure{Exit: ExitAPI, Kind: "api", Op: ce.Op, Code: ce.Code, Status: ce.Status, Message: ce.Op + " failed", |
| + AWSMessage: ce.AWSMessage, RequestID: ce.RequestID} |
| + if !ce.Answered { |
| + f.Kind, f.Message = "transport", ce.Op+" failed before an answer came back" |
| + } |
| + return f |
| +} |
| + |
| +// Check refuses a target that is not one account, one region and a |
| +// prefix every name the tool touches must carry. |
| +func (t Target) Check() error { |
| + switch { |
| + case !accountPattern.MatchString(t.Account): |
| + return usage("-account %q is not a 12-digit account ID", t.Account) |
| + case !regionPattern.MatchString(t.Region): |
| + return usage("-region %q is not a region such as eu-west-1", t.Region) |
| + case !prefixPattern.MatchString(t.Prefix): |
| + return usage("-prefix %q must be 3 to 64 lower-case letters, digits and '-'", t.Prefix) |
| + } |
| + return nil |
| +} |
| + |
| +// InPrefix reports whether name is the prefix itself or the prefix, a |
| +// '-' and more. |
| +func (t Target) InPrefix(name string) bool { |
| + return namePattern.MatchString(name) && (name == t.Prefix || strings.HasPrefix(name, t.Prefix+"-")) |
| +} |
| + |
| +// arnIn reports whether arn is a Lambda resource of kind in the target's |
| +// account and region, and returns what follows "<kind>:". |
| +func (t Target) arnIn(arn, kind string) (string, bool) { |
| + head := "arn:aws:lambda:" + t.Region + ":" + t.Account + ":" + kind + ":" |
| + rest, ok := strings.CutPrefix(arn, head) |
| + return rest, ok && rest != "" && !strings.ContainsAny(rest, " \t\n/") |
| +} |
| + |
| +// checkCaller is the guard every AWS operation passes first: the provider |
| +// calls the target's region, and STS names the target's account. Nothing |
| +// else is called before it passes. |
| +func checkCaller(ctx context.Context, p Provider, t Target) error { |
| + if r := p.Region(); r != t.Region { |
| + return guard("the client calls region %q, want %s", r, t.Region) |
| + } |
| + a, err := p.CallerAccount(ctx) |
| + if err != nil { |
| + return apiFailure("GetCallerIdentity", err) |
| + } |
| + if a != t.Account { |
| + return guard("caller account is %q, want %s", a, t.Account) |
| + } |
| + return nil |
| +} |
| + |
| +// check refuses a wait the tool will not run. |
| +func (w Wait) check() error { |
| + switch { |
| + case w.Timeout <= 0 || w.Timeout > maxWait: |
| + return usage("-timeout must be above 0 and at most %v", maxWait) |
| + case w.Interval < time.Second: |
| + return usage("-interval must be at least 1s") |
| + case w.Clock == nil: |
| + return other("no clock") |
| + } |
| + return nil |
| +} |
| + |
| +// poll calls check until it reports done, returns an error, or the |
| +// timeout passes (exit 5). The first read is at once. The timeout holds |
| +// on the wait's clock, before each read and again after it, so an answer |
| +// that comes back after the deadline is never taken as success, and as a |
| +// deadline on the reads' context. |
| +func (w Wait) poll(ctx context.Context, what string, check func(ctx context.Context) (bool, error)) error { |
| + ranOut := &Failure{Exit: ExitTimeout, Kind: "timeout", Message: "wait for " + what + " ran out after " + w.Timeout.String()} |
| + ctx, cancel := context.WithTimeout(ctx, w.Timeout) |
| + defer cancel() |
| + deadline := w.Clock.Now().Add(w.Timeout) |
| + for { |
| + if !w.Clock.Now().Before(deadline) || ctx.Err() != nil { |
| + return ranOut |
| + } |
| + done, err := check(ctx) |
| + if !w.Clock.Now().Before(deadline) || ctx.Err() != nil { |
| + return ranOut |
| + } |
| + if done || err != nil { |
| + return err |
| + } |
| + w.Clock.Sleep(min(w.Interval, deadline.Sub(w.Clock.Now()))) |
| + } |
| +} |
| + |
| +func failedState(what, state, reason string) *Failure { |
| + return &Failure{Exit: ExitFailed, Kind: "failed_state", Code: state, Message: what + " reached a failed state", AWSMessage: reason} |
| +} |
| + |
| +// check refuses a request the tool will not send, before any call. |
| +func (r PublishRequest) check(t Target) error { |
| + if !t.InPrefix(r.Name) { |
| + return guard("image name %q is outside prefix %s", r.Name, t.Prefix) |
| + } |
| + role, ok := strings.CutPrefix(r.BuildRoleARN, "arn:aws:iam::"+t.Account+":") |
| + switch { |
| + case !bucketPattern.MatchString(r.Bucket): |
| + return usage("-bucket %q is not a bucket name", r.Bucket) |
| + case len(r.Key) > 1024 || !keyPattern.MatchString(r.Key) || strings.HasPrefix(r.Key, "/") || slices.Contains(strings.Split(r.Key, "/"), "..") || slices.Contains(strings.Split(r.Key, "/"), "."): |
| + return usage("-key %q is not a plain object key", r.Key) |
| + case !versionPattern.MatchString(r.BaseVersion): |
| + return usage("-base-version %q is not a version", r.BaseVersion) |
| + case !ok: |
| + return guard("-build-role-arn %q is not a role in account %s", r.BuildRoleARN, t.Account) |
| + case !rolePathRegex.MatchString(role): |
| + return usage("-build-role-arn %q is not a role ARN", r.BuildRoleARN) |
| + case !logGroupRegex.MatchString(r.LogGroup): |
| + return usage("-log-group %q is not a log group name", r.LogGroup) |
| + case r.Size.MemoryMiB() == 0: |
| + return usage("-size %q must be small or large", r.Size) |
| + case r.Capabilities != "ALL": |
| + return usage("-capabilities %q: the image needs exactly ALL (bubblewrap, spec §15)", r.Capabilities) |
| + case r.Ledger == "": |
| + return usage("-ledger is required") |
| + case r.Out == "": |
| + return usage("-out is required") |
| + } |
| + for k, v := range r.Tags { |
| + if !tagKeyPattern.MatchString(k) || !tagValPattern.MatchString(v) { |
| + return usage("tag %q=%q is not a plain tag", k, v) |
| + } |
| + } |
| + if st, err := os.Stat(r.Ledger); err != nil || !st.IsDir() { |
| + return usage("-ledger %s is not a directory", r.Ledger) |
| + } |
| + if st, err := os.Stat(filepath.Dir(r.Out)); err != nil || !st.IsDir() { |
| + return usage("-out's directory %s does not exist", filepath.Dir(r.Out)) |
| + } |
| + return r.Wait.check() |
| +} |
| + |
| +// chooseBase returns the base version to build on: the pinned one, or |
| +// with stepDown the one listed directly below it. A version AWS does not |
| +// list, or has recalled, is refused; nothing is skipped. |
| +func chooseBase(listed []BaseVersion, pin string, stepDown bool) (string, error) { |
| + vs := slices.Clone(listed) |
| + slices.SortStableFunc(vs, func(a, b BaseVersion) int { return CompareVersions(a.Version, b.Version) }) |
| + i := slices.IndexFunc(vs, func(v BaseVersion) bool { return v.Version == pin }) |
| + if i < 0 { |
| + return "", guard("base version %q is not listed for the managed base image", pin) |
| + } |
| + if stepDown { |
| + if i == 0 { |
| + return "", guard("no base version is listed below %q", pin) |
| + } |
| + i-- |
| + } |
| + if vs[i].Status == "RECALLED" { |
| + return "", guard("base version %q is recalled", vs[i].Version) |
| + } |
| + return vs[i].Version, nil |
| +} |
| + |
| +// clientToken is the create's client token, derived from the whole |
| +// request: the same request again (a rerun after a lost answer) replays |
| +// the same create, which AWS answers with the image it made; any other |
| +// request gets another token. |
| +func clientToken(c CreateImage) (string, error) { |
| + c.ClientToken = "" |
| + b, err := json.Marshal(c) |
| + if err != nil { |
| + return "", err |
| + } |
| + h := sha256.Sum256(b) |
| + return "equipo-image-" + hex.EncodeToString(h[:24]), nil |
| +} |
| + |
| +// journal appends one line, "<UTC time>\t<entry>", to dir's journal and |
| +// syncs it, so the line is on disk before the call it announces. |
| +func journal(dir string, now time.Time, entry string) error { |
| + f, err := os.OpenFile(filepath.Join(dir, JournalFile), os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0o600) |
| + if err != nil { |
| + return other("the journal cannot be opened: %v", err) |
| + } |
| + _, err = fmt.Fprintf(f, "%s\t%s\n", now.UTC().Format("2006-01-02T15:04:05.000Z"), entry) |
| + if err == nil { |
| + err = f.Sync() |
| + } |
| + if cerr := f.Close(); err == nil { |
| + err = cerr |
| + } |
| + if err != nil { |
| + return other("the journal write failed: %v", err) |
| + } |
| + return nil |
| +} |
| + |
| +// writeJSON writes v to path atomically (a temporary file, then a |
| +// rename). |
| +func writeJSON(path string, v any) error { |
| + b, err := json.MarshalIndent(v, "", " ") |
| + if err != nil { |
| + return err |
| + } |
| + tmp, err := os.CreateTemp(filepath.Dir(path), ".equipo-image-out-*") |
| + if err != nil { |
| + return err |
| + } |
| + defer os.Remove(tmp.Name()) |
| + if _, err := tmp.Write(append(b, '\n')); err != nil { |
| + tmp.Close() |
| + return err |
| + } |
| + if err := tmp.Chmod(0o644); err != nil { |
| + tmp.Close() |
| + return err |
| + } |
| + if err := tmp.Sync(); err != nil { |
| + tmp.Close() |
| + return err |
| + } |
| + if err := tmp.Close(); err != nil { |
| + return err |
| + } |
| + return os.Rename(tmp.Name(), path) |
| +} |
| + |
| +// Publish creates the image r names and its one version, waits until the |
| +// version is built and active, checks it is what was asked for, and |
| +// writes r.Out. In order: |
| +// |
| +// 1. the request and target are checked (no call); |
| +// 2. the caller check (checkCaller); |
| +// 3. the managed base image's versions are read, and the base version |
| +// chosen (chooseBase); |
| +// 4. "INTENT microvm-image <name> <client token>" is journalled; |
| +// 5. the create; |
| +// 6. "REC microvm-image <image ARN>" and "REC microvm-image-version |
| +// <image ARN>:<version>" are journalled; |
| +// 7. the bounded wait, then the check of the built version. |
| +// |
| +// VersionArn is "<image ARN>:<version>", the form certificates sign |
| +// (awsjob Config.ImageVersion). The journal keeps the records whatever |
| +// happens after the create. |
| +func Publish(ctx context.Context, p Provider, t Target, r PublishRequest) (Published, error) { |
| + if err := t.Check(); err != nil { |
| + return Published{}, err |
| + } |
| + if err := r.check(t); err != nil { |
| + return Published{}, err |
| + } |
| + if err := checkCaller(ctx, p, t); err != nil { |
| + return Published{}, err |
| + } |
| + baseARN := BaseImageARN(t.Region) |
| + listed, err := p.BaseVersions(ctx, baseARN) |
| + if err != nil { |
| + return Published{}, apiFailure("ListManagedMicrovmImageVersions", err) |
| + } |
| + base, err := chooseBase(listed, r.BaseVersion, r.AllowStepDown) |
| + if err != nil { |
| + return Published{}, err |
| + } |
| + req := CreateImage{ |
| + Name: r.Name, Artifact: "s3://" + r.Bucket + "/" + r.Key, |
| + BaseImageARN: baseARN, BaseVersion: base, BuildRoleARN: r.BuildRoleARN, LogGroup: r.LogGroup, |
| + MemoryMiB: r.Size.MemoryMiB(), Settings: ImageSettings(), Tags: r.Tags, |
| + } |
| + if req.ClientToken, err = clientToken(req); err != nil { |
| + return Published{}, other("the client token: %v", err) |
| + } |
| + if err := journal(r.Ledger, r.Wait.Clock.Now(), "INTENT microvm-image "+r.Name+" "+req.ClientToken); err != nil { |
| + return Published{}, err |
| + } |
| + created, err := p.CreateImage(ctx, req) |
| + if err != nil { |
| + return Published{}, apiFailure("CreateMicrovmImage", err) |
| + } |
| + name, ok := t.arnIn(created.ImageARN, "microvm-image") |
| + if !ok || created.Name != r.Name || (name != r.Name && strings.Contains(name, ":")) || !versionPattern.MatchString(created.Version) { |
| + return Published{}, guard("the create answered image %q, name %q, version %q; not this account, region and name", created.ImageARN, created.Name, created.Version) |
| + } |
| + versionARN := created.ImageARN + ":" + created.Version |
| + if err := journal(r.Ledger, r.Wait.Clock.Now(), "REC microvm-image "+created.ImageARN); err != nil { |
| + return Published{}, err |
| + } |
| + if err := journal(r.Ledger, r.Wait.Clock.Now(), "REC microvm-image-version "+versionARN); err != nil { |
| + return Published{}, err |
| + } |
| + var last Version |
| + err = r.Wait.poll(ctx, "image version built", func(ctx context.Context) (bool, error) { |
| + v, err := p.GetImageVersion(ctx, created.ImageARN, created.Version) |
| + if err != nil { |
| + return false, apiFailure("GetMicrovmImageVersion", err) |
| + } |
| + last = v |
| + switch v.State { |
| + case "SUCCESSFUL": |
| + return v.Status == "ACTIVE", nil |
| + case "FAILED", "DELETING", "DELETED", "DELETE_FAILED": |
| + return false, failedState("image version", v.State, v.Reason) |
| + } |
| + return false, nil |
| + }) |
| + if err != nil { |
| + return Published{}, err |
| + } |
| + if err := sameVersion(last, req); err != nil { |
| + return Published{}, err |
| + } |
| + pub := Published{ |
| + Name: r.Name, ImageArn: created.ImageARN, ImageVersion: created.Version, VersionArn: versionARN, |
| + BaseImageArn: baseARN, BaseImageVersion: base, Size: r.Size, MemoryMiB: req.MemoryMiB, |
| + Artifact: req.Artifact, Account: t.Account, Region: t.Region, |
| + } |
| + if err := writeJSON(r.Out, pub); err != nil { |
| + return pub, other("-out was not written: %v", err) |
| + } |
| + return pub, nil |
| +} |
| + |
| +// sameVersion refuses a built version that is not what req asked for: |
| +// the checks the adapter makes at launch (awsjob checkImageVersion), and |
| +// the hooks, the artifact and the base version. |
| +func sameVersion(v Version, req CreateImage) error { |
| + s := req.Settings |
| + var cpu []string |
| + for _, c := range s.CPU { |
| + cpu = append(cpu, c.Architecture) |
| + } |
| + mismatch := func(what string, got, want any) error { |
| + return &Failure{Exit: ExitFailed, Kind: "mismatch", Message: fmt.Sprintf("the built version's %s is %v, want %v", what, got, want)} |
| + } |
| + switch { |
| + case v.Status != "ACTIVE": |
| + return mismatch("status", v.Status, "ACTIVE") |
| + case !slices.Equal(v.Capabilities, s.Capabilities): |
| + return mismatch("OS capabilities", v.Capabilities, s.Capabilities) |
| + case !slices.Equal(v.Architectures, cpu): |
| + return mismatch("CPU configurations", v.Architectures, cpu) |
| + case !slices.Equal(v.MemoryMiB, []int{req.MemoryMiB}): |
| + return mismatch("memory", v.MemoryMiB, []int{req.MemoryMiB}) |
| + case v.HooksPort != s.Hooks.Port: |
| + return mismatch("hooks port", v.HooksPort, s.Hooks.Port) |
| + case v.RunTimeout != s.Hooks.Microvm.RunTimeout: |
| + return mismatch("run hook timeout", v.RunTimeout, s.Hooks.Microvm.RunTimeout) |
| + case v.Artifact != req.Artifact: |
| + return mismatch("code artifact", v.Artifact, req.Artifact) |
| + case v.BaseVersion != req.BaseVersion: |
| + return mismatch("base version", v.BaseVersion, req.BaseVersion) |
| + } |
| + return nil |
| +} |
| + |
| +// Delete deletes an image of the prefix, then waits until it is gone. The |
| +// ARN must be in the target's account and region (no call otherwise); |
| +// the image is read first and refused unless its name carries the |
| +// prefix. |
| +func Delete(ctx context.Context, p Provider, t Target, arn string, w Wait) (Image, error) { |
| + if err := t.Check(); err != nil { |
| + return Image{}, err |
| + } |
| + if _, ok := t.arnIn(arn, "microvm-image"); !ok { |
| + return Image{}, guard("-arn %q is not an image in account %s, region %s", arn, t.Account, t.Region) |
| + } |
| + if err := w.check(); err != nil { |
| + return Image{}, err |
| + } |
| + if err := checkCaller(ctx, p, t); err != nil { |
| + return Image{}, err |
| + } |
| + img, err := p.GetImage(ctx, arn) |
| + if err != nil { |
| + return Image{}, apiFailure("GetMicrovmImage", err) |
| + } |
| + if img.ARN != arn || !t.InPrefix(img.Name) { |
| + return img, guard("image %q (%s) is outside prefix %s", img.Name, img.ARN, t.Prefix) |
| + } |
| + if err := p.DeleteImage(ctx, arn); err != nil { |
| + return img, apiFailure("DeleteMicrovmImage", err) |
| + } |
| + last := img |
| + err = w.poll(ctx, "image deleted", func(ctx context.Context) (bool, error) { |
| + cur, err := p.GetImage(ctx, arn) |
| + if errors.Is(err, ErrNotFound) { |
| + return true, nil |
| + } |
| + if err != nil { |
| + return false, apiFailure("GetMicrovmImage", err) |
| + } |
| + last = cur |
| + switch cur.State { |
| + case "DELETED": |
| + return true, nil |
| + case "DELETE_FAILED": |
| + return false, failedState("image", cur.State, "") |
| + } |
| + return false, nil |
| + }) |
| + return last, err |
| +} |
| + |
| +// List lists the prefix's images in the target account and region, by |
| +// name. |
| +func List(ctx context.Context, p Provider, t Target) ([]Image, error) { |
| + if err := t.Check(); err != nil { |
| + return nil, err |
| + } |
| + if err := checkCaller(ctx, p, t); err != nil { |
| + return nil, err |
| + } |
| + all, err := p.ListImages(ctx, t.Prefix) |
| + if err != nil { |
| + return nil, apiFailure("ListMicrovmImages", err) |
| + } |
| + var mine []Image |
| + for _, img := range all { |
| + if _, ok := t.arnIn(img.ARN, "microvm-image"); ok && t.InPrefix(img.Name) { |
| + mine = append(mine, img) |
| + } |
| + } |
| + slices.SortFunc(mine, func(a, b Image) int { return strings.Compare(a.Name, b.Name) }) |
| + return mine, nil |
| +} |
| + |
| +// ConnectorWait waits for a network connector of the prefix to be ACTIVE. |
| +// The ARN must be in the target's account and region; every read must |
| +// show a name with the prefix. FAILED, INACTIVE, DELETING and |
| +// DELETE_FAILED end the wait. |
| +func ConnectorWait(ctx context.Context, p Provider, t Target, arn string, w Wait) (Connector, error) { |
| + if err := t.Check(); err != nil { |
| + return Connector{}, err |
| + } |
| + if _, ok := t.arnIn(arn, "network-connector"); !ok { |
| + return Connector{}, guard("-arn %q is not a network connector in account %s, region %s", arn, t.Account, t.Region) |
| + } |
| + if err := w.check(); err != nil { |
| + return Connector{}, err |
| + } |
| + if err := checkCaller(ctx, p, t); err != nil { |
| + return Connector{}, err |
| + } |
| + var last Connector |
| + err := w.poll(ctx, "connector active", func(ctx context.Context) (bool, error) { |
| + c, err := p.GetConnector(ctx, arn) |
| + if err != nil { |
| + return false, apiFailure("GetNetworkConnector", err) |
| + } |
| + last = c |
| + if !t.InPrefix(c.Name) { |
| + return false, guard("connector %q is outside prefix %s", c.Name, t.Prefix) |
| + } |
| + switch c.State { |
| + case "ACTIVE": |
| + return true, nil |
| + case "FAILED", "INACTIVE", "DELETING", "DELETE_FAILED": |
| + return false, failedState("connector", c.State, c.Reason) |
| + } |
| + return false, nil |
| + }) |
| + return last, err |
| +} |
| + |
| +// CompareVersions orders dotted versions by number, part by part ("10" |
| +// after "9", "3.1" after "3"); a part that is not a number compares as |
| +// text. |
| +func CompareVersions(a, b string) int { |
| + pa, pb := strings.Split(a, "."), strings.Split(b, ".") |
| + for i := range max(len(pa), len(pb)) { |
| + if i >= len(pa) { |
| + return -1 |
| + } |
| + if i >= len(pb) { |
| + return 1 |
| + } |
| + na, ea := strconv.Atoi(pa[i]) |
| + nb, eb := strconv.Atoi(pb[i]) |
| + var c int |
| + if ea == nil && eb == nil { |
| + c = na - nb |
| + } else { |
| + c = strings.Compare(pa[i], pb[i]) |
| + } |
| + if c != 0 { |
| + return c |
| + } |
| + } |
| + return 0 |
| +} |
diff --git a/internal/hostedimage/publish_test.go b/internal/hostedimage/publish_test.go| new file mode 100644 |
| index 00000000..9f145f3b |
| --- /dev/null |
| +++ b/internal/hostedimage/publish_test.go |
| @@ -0,0 +1,443 @@ |
| +package hostedimage |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "os" |
| + "path/filepath" |
| + "slices" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/isolatedjob" |
| +) |
| + |
| +const ( |
| + acct = "111122223333" |
| + region = "eu-west-1" |
| + prefix = "equipo-hosted-prod-1201-abcdef" |
| +) |
| + |
| +var target = Target{Account: acct, Region: region, Prefix: prefix} |
| + |
| +// fakeProvider answers from its fields and records every call. It is the |
| +// provider-neutral half's whole view of AWS; the SDK half is tested in |
| +// awsjob/imageaws with SDK middleware. |
| +type fakeProvider struct { |
| + t *testing.T |
| + region string |
| + account string |
| + calls []string |
| + base []BaseVersion |
| + created []CreateImage |
| + versions []Version // successive GetImageVersion answers; the last repeats |
| + images map[string]Image |
| + list []Image |
| + conn []Connector |
| + onCreate func() |
| + createErr error |
| +} |
| + |
| +func newFake(t *testing.T) *fakeProvider { |
| + return &fakeProvider{t: t, region: region, account: acct, |
| + base: []BaseVersion{{Version: "3", Status: "AVAILABLE"}, {Version: "4", Status: "AVAILABLE"}, {Version: "5", Status: "AVAILABLE"}}, |
| + images: map[string]Image{}} |
| +} |
| + |
| +func (f *fakeProvider) Region() string { return f.region } |
| +func (f *fakeProvider) CallerAccount(context.Context) (string, error) { |
| + f.calls = append(f.calls, "CallerAccount") |
| + return f.account, nil |
| +} |
| +func (f *fakeProvider) BaseVersions(_ context.Context, base string) ([]BaseVersion, error) { |
| + f.calls = append(f.calls, "BaseVersions") |
| + if base != BaseImageARN(region) { |
| + f.t.Errorf("BaseVersions(%s), want %s", base, BaseImageARN(region)) |
| + } |
| + return f.base, nil |
| +} |
| +func (f *fakeProvider) CreateImage(_ context.Context, c CreateImage) (Created, error) { |
| + f.calls = append(f.calls, "CreateImage") |
| + if f.onCreate != nil { |
| + f.onCreate() |
| + } |
| + f.created = append(f.created, c) |
| + if f.createErr != nil { |
| + return Created{}, f.createErr |
| + } |
| + return Created{ImageARN: imageARN(c.Name), Name: c.Name, Version: "1"}, nil |
| +} |
| +func imageARN(name string) string { |
| + return "arn:aws:lambda:" + region + ":" + acct + ":microvm-image:" + name |
| +} |
| +func (f *fakeProvider) GetImage(_ context.Context, id string) (Image, error) { |
| + f.calls = append(f.calls, "GetImage") |
| + img, ok := f.images[id] |
| + if !ok { |
| + return Image{}, &CallError{Op: "GetMicrovmImage", Code: "ResourceNotFoundException", Answered: true, Err: ErrNotFound} |
| + } |
| + return img, nil |
| +} |
| +func (f *fakeProvider) GetImageVersion(_ context.Context, arn, version string) (Version, error) { |
| + f.calls = append(f.calls, "GetImageVersion") |
| + if len(f.versions) == 0 { |
| + return Version{}, errors.New("no version answer") |
| + } |
| + v := f.versions[0] |
| + if len(f.versions) > 1 { |
| + f.versions = f.versions[1:] |
| + } |
| + return v, nil |
| +} |
| +func (f *fakeProvider) ListImages(_ context.Context, filter string) ([]Image, error) { |
| + f.calls = append(f.calls, "ListImages") |
| + return f.list, nil |
| +} |
| +func (f *fakeProvider) DeleteImage(_ context.Context, id string) error { |
| + f.calls = append(f.calls, "DeleteImage") |
| + delete(f.images, id) |
| + return nil |
| +} |
| +func (f *fakeProvider) GetConnector(context.Context, string) (Connector, error) { |
| + f.calls = append(f.calls, "GetConnector") |
| + c := f.conn[0] |
| + if len(f.conn) > 1 { |
| + f.conn = f.conn[1:] |
| + } |
| + return c, nil |
| +} |
| + |
| +// fakeClock moves only when slept. |
| +type fakeClock struct{ now time.Time } |
| + |
| +func (c *fakeClock) Now() time.Time { return c.now } |
| +func (c *fakeClock) Sleep(d time.Duration) { c.now = c.now.Add(d) } |
| + |
| +// built is the version a correct build gives for req. |
| +func built(req PublishRequest, base string) Version { |
| + s := ImageSettings() |
| + return Version{State: "SUCCESSFUL", Status: "ACTIVE", Capabilities: []string{"ALL"}, Architectures: []string{"X86_64"}, |
| + MemoryMiB: []int{req.Size.MemoryMiB()}, HooksPort: s.Hooks.Port, RunTimeout: s.Hooks.Microvm.RunTimeout, |
| + Artifact: "s3://" + req.Bucket + "/" + req.Key, BaseVersion: base} |
| +} |
| + |
| +func request(t *testing.T) PublishRequest { |
| + return PublishRequest{ |
| + Name: prefix, Bucket: "equipo-hosted-image-inputs", Key: "images/sha256:" + hex64('a') + ".zip", |
| + BaseVersion: "4", BuildRoleARN: "arn:aws:iam::" + acct + ":role/equipo-hosted-image-build", |
| + LogGroup: "/equipo-hosted/image-build", Size: isolatedjob.SizeLarge, Capabilities: "ALL", |
| + Ledger: t.TempDir(), Out: filepath.Join(t.TempDir(), "image.json"), |
| + Wait: Wait{Timeout: 45 * time.Minute, Interval: 15 * time.Second, Clock: &fakeClock{now: time.Unix(1_800_000_000, 0)}}, |
| + } |
| +} |
| + |
| +func readJournal(t *testing.T, dir string) []string { |
| + t.Helper() |
| + b, err := os.ReadFile(filepath.Join(dir, JournalFile)) |
| + if err != nil { |
| + return nil |
| + } |
| + var out []string |
| + for _, line := range strings.Split(strings.TrimSuffix(string(b), "\n"), "\n") { |
| + _, entry, ok := strings.Cut(line, "\t") |
| + if !ok { |
| + t.Fatalf("journal line %q has no timestamp", line) |
| + } |
| + out = append(out, entry) |
| + } |
| + return out |
| +} |
| + |
| +func failureOf(t *testing.T, err error) *Failure { |
| + t.Helper() |
| + var f *Failure |
| + if !errors.As(err, &f) { |
| + t.Fatalf("error %v is not a *Failure", err) |
| + } |
| + return f |
| +} |
| + |
| +// TestPublishRefusesOtherAccount: when STS names another account, nothing |
| +// else is called, nothing is journalled, and the exit is the guard's. |
| +func TestPublishRefusesOtherAccount(t *testing.T) { |
| + p := newFake(t) |
| + p.account = "444455556666" |
| + req := request(t) |
| + _, err := Publish(context.Background(), p, target, req) |
| + if f := failureOf(t, err); f.Exit != ExitGuard { |
| + t.Fatalf("Publish = %+v, want a guard refusal", f) |
| + } |
| + if !slices.Equal(p.calls, []string{"CallerAccount"}) { |
| + t.Fatalf("calls %v, want only the account check", p.calls) |
| + } |
| + if j := readJournal(t, req.Ledger); len(j) != 0 { |
| + t.Fatalf("journal %v, want nothing", j) |
| + } |
| + if _, err := os.Stat(req.Out); err == nil { |
| + t.Fatal("an -out file was written") |
| + } |
| + |
| + // A client in another region is refused before STS. |
| + p = newFake(t) |
| + p.region = "eu-central-1" |
| + if _, err := Publish(context.Background(), p, target, request(t)); failureOf(t, err).Exit != ExitGuard || len(p.calls) != 0 { |
| + t.Fatalf("Publish from another region = %v with calls %v, want a guard refusal and no call", err, p.calls) |
| + } |
| +} |
| + |
| +// TestPublishRefusesForeignName: a name outside the prefix is refused |
| +// before any call; so is an artifact, build role or option the tool does |
| +// not take. |
| +func TestPublishRefusesForeignName(t *testing.T) { |
| + for name, edit := range map[string]func(*PublishRequest){ |
| + "other name": func(r *PublishRequest) { r.Name = "equipo-hosted-prod-other" }, |
| + "prefix without a dash": func(r *PublishRequest) { r.Name = prefix + "x" }, |
| + "empty name": func(r *PublishRequest) { r.Name = "" }, |
| + "role in another acct": func(r *PublishRequest) { r.BuildRoleARN = "arn:aws:iam::444455556666:role/build" }, |
| + "capabilities not ALL": func(r *PublishRequest) { r.Capabilities = "NONE" }, |
| + "unknown size": func(r *PublishRequest) { r.Size = "huge" }, |
| + "no base version": func(r *PublishRequest) { r.BaseVersion = "" }, |
| + "key escapes": func(r *PublishRequest) { r.Key = "../images/x.zip" }, |
| + "bucket not a bucket": func(r *PublishRequest) { r.Bucket = "Not_A_Bucket" }, |
| + "no ledger": func(r *PublishRequest) { r.Ledger = "" }, |
| + "wait longer than bound": func(r *PublishRequest) { r.Wait.Timeout = 3 * time.Hour }, |
| + "no out": func(r *PublishRequest) { r.Out = "" }, |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + p := newFake(t) |
| + req := request(t) |
| + edit(&req) |
| + _, err := Publish(context.Background(), p, target, req) |
| + if f := failureOf(t, err); f.Exit != ExitGuard && f.Exit != ExitUsage { |
| + t.Fatalf("Publish = %+v, want a guard or usage refusal", f) |
| + } |
| + if len(p.calls) != 0 { |
| + t.Fatalf("calls %v, want none", p.calls) |
| + } |
| + }) |
| + } |
| + if _, err := Publish(context.Background(), newFake(t), Target{Account: acct, Region: region, Prefix: ""}, request(t)); err == nil { |
| + t.Fatal("Publish with no prefix = nil, want a refusal") |
| + } |
| +} |
| + |
| +// TestPublishJournalsBeforeCreate: the intent (name and client token) is |
| +// on disk before the create call; the image and its version are recorded |
| +// as soon as the create returns; -out holds ImageArn and VersionArn in the |
| +// form certificates sign ("<image ARN>:<version>"). |
| +func TestPublishJournalsBeforeCreate(t *testing.T) { |
| + p := newFake(t) |
| + req := request(t) |
| + var atCreate []string |
| + p.onCreate = func() { atCreate = readJournal(t, req.Ledger) } |
| + p.versions = []Version{{State: "PENDING"}, {State: "IN_PROGRESS"}, built(req, "4")} |
| + got, err := Publish(context.Background(), p, target, req) |
| + if err != nil { |
| + t.Fatalf("Publish: %v", err) |
| + } |
| + if len(p.created) != 1 { |
| + t.Fatalf("%d creates, want 1", len(p.created)) |
| + } |
| + c := p.created[0] |
| + wantIntent := "INTENT microvm-image " + prefix + " " + c.ClientToken |
| + if c.ClientToken == "" || !slices.Equal(atCreate, []string{wantIntent}) { |
| + t.Fatalf("journal at the create call = %v, want [%s]", atCreate, wantIntent) |
| + } |
| + arn := imageARN(prefix) |
| + want := []string{wantIntent, "REC microvm-image " + arn, "REC microvm-image-version " + arn + ":1"} |
| + if j := readJournal(t, req.Ledger); !slices.Equal(j, want) { |
| + t.Fatalf("journal = %v, want %v", j, want) |
| + } |
| + if got.ImageArn != arn || got.VersionArn != arn+":1" || got.ImageVersion != "1" || got.BaseImageVersion != "4" { |
| + t.Fatalf("Published = %+v", got) |
| + } |
| + b, err := os.ReadFile(req.Out) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var out map[string]any |
| + if err := json.Unmarshal(b, &out); err != nil || out["ImageArn"] != arn || out["VersionArn"] != arn+":1" { |
| + t.Fatalf("-out = %s (%v)", b, err) |
| + } |
| + |
| + // The request: the tool's settings, the size's memory, the artifact. |
| + s := ImageSettings() |
| + if c.Name != prefix || c.Artifact != "s3://"+req.Bucket+"/"+req.Key || c.BaseImageARN != BaseImageARN(region) || |
| + c.BaseVersion != "4" || c.MemoryMiB != 4096 || c.BuildRoleARN != req.BuildRoleARN || c.LogGroup != req.LogGroup || |
| + c.Settings.Hooks.Port != s.Hooks.Port || !slices.Equal(c.Settings.Capabilities, []string{"ALL"}) { |
| + t.Fatalf("create request = %+v", c) |
| + } |
| + |
| + // The same request again derives the same token: AWS's replay of a |
| + // create that already succeeded returns the same image. |
| + p2 := newFake(t) |
| + p2.versions = []Version{built(req, "4")} |
| + req2 := req |
| + req2.Out = filepath.Join(t.TempDir(), "again.json") |
| + if _, err := Publish(context.Background(), p2, target, req2); err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(p2.created) != 1 || p2.created[0].ClientToken != c.ClientToken { |
| + t.Fatalf("tokens %s and %s for the same request, want one", c.ClientToken, p2.created[0].ClientToken) |
| + } |
| + |
| + // A journal that cannot be written stops the create. |
| + p3 := newFake(t) |
| + req3 := request(t) |
| + req3.Ledger = filepath.Join(t.TempDir(), "missing") |
| + if _, err := Publish(context.Background(), p3, target, req3); err == nil || slices.Contains(p3.calls, "CreateImage") { |
| + t.Fatalf("Publish without a journal = %v, calls %v; want a refusal before the create", err, p3.calls) |
| + } |
| +} |
| + |
| +// TestPublishBaseVersion: the pinned base version is used as given; one |
| +// step down only with AllowStepDown; a version AWS does not list, or has |
| +// recalled, is refused before the create. |
| +func TestPublishBaseVersion(t *testing.T) { |
| + for _, c := range []struct { |
| + name string |
| + pin string |
| + stepDown bool |
| + base []BaseVersion |
| + want string // "" for a refusal |
| + }{ |
| + {"pinned", "4", false, nil, "4"}, |
| + {"one step down", "4", true, nil, "3"}, |
| + {"step down skips nothing", "4", true, []BaseVersion{{"3", "RECALLED"}, {"4", "AVAILABLE"}}, ""}, |
| + {"nothing below", "3", true, nil, ""}, |
| + {"not listed", "9", false, nil, ""}, |
| + {"recalled pin", "4", false, []BaseVersion{{"4", "RECALLED"}}, ""}, |
| + {"deprecated pin", "4", false, []BaseVersion{{"4", "DEPRECATED"}}, "4"}, |
| + {"numeric order", "10", true, []BaseVersion{{"2", "AVAILABLE"}, {"9", "AVAILABLE"}, {"10", "AVAILABLE"}}, "9"}, |
| + } { |
| + t.Run(c.name, func(t *testing.T) { |
| + p := newFake(t) |
| + if c.base != nil { |
| + p.base = c.base |
| + } |
| + req := request(t) |
| + req.BaseVersion, req.AllowStepDown = c.pin, c.stepDown |
| + p.versions = []Version{built(req, c.want)} |
| + got, err := Publish(context.Background(), p, target, req) |
| + if c.want == "" { |
| + if err == nil || slices.Contains(p.calls, "CreateImage") { |
| + t.Fatalf("Publish = %v, calls %v; want a refusal before the create", err, p.calls) |
| + } |
| + return |
| + } |
| + if err != nil || len(p.created) != 1 || p.created[0].BaseVersion != c.want || got.BaseImageVersion != c.want { |
| + t.Fatalf("Publish = %+v, %v; want base %s", got, err, c.want) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// TestPublishWaitBounded: a build that never finishes ends at the timeout |
| +// on the wait's clock; a failed build ends with its state; a built |
| +// version that differs from the request is refused. The records stay in |
| +// the journal either way. |
| +func TestPublishWaitBounded(t *testing.T) { |
| + p := newFake(t) |
| + req := request(t) |
| + req.Wait.Timeout = 10 * time.Minute |
| + p.versions = []Version{{State: "IN_PROGRESS"}} |
| + _, err := Publish(context.Background(), p, target, req) |
| + if f := failureOf(t, err); f.Exit != ExitTimeout { |
| + t.Fatalf("Publish = %+v, want a timeout", f) |
| + } |
| + if n := strings.Count(strings.Join(p.calls, " "), "GetImageVersion"); n < 2 || n > 42 { |
| + t.Fatalf("%d reads in 10 minutes at 15 s, want a bounded number", n) |
| + } |
| + if j := readJournal(t, req.Ledger); len(j) != 3 { |
| + t.Fatalf("journal %v, want the intent and both records", j) |
| + } |
| + |
| + p = newFake(t) |
| + req = request(t) |
| + p.versions = []Version{{State: "FAILED", Reason: "build failed"}} |
| + if f := failureOf(t, func() error { _, err := Publish(context.Background(), p, target, req); return err }()); f.Exit != ExitFailed || f.Code != "FAILED" { |
| + t.Fatalf("failed build = %+v, want exit %d with FAILED", f, ExitFailed) |
| + } |
| + |
| + for name, edit := range map[string]func(*Version){ |
| + "capabilities": func(v *Version) { v.Capabilities = nil }, |
| + "arm": func(v *Version) { v.Architectures = []string{"ARM_64"} }, |
| + "memory": func(v *Version) { v.MemoryMiB = []int{2048} }, |
| + "hooks port": func(v *Version) { v.HooksPort = 8080 }, |
| + "artifact": func(v *Version) { v.Artifact = "s3://other/x.zip" }, |
| + "base": func(v *Version) { v.BaseVersion = "5" }, |
| + "inactive": func(v *Version) { v.Status = "INACTIVE" }, |
| + } { |
| + p = newFake(t) |
| + req = request(t) |
| + v := built(req, "4") |
| + edit(&v) |
| + p.versions = []Version{v} |
| + _, err := Publish(context.Background(), p, target, req) |
| + if err == nil { |
| + t.Errorf("%s: a built version that differs was accepted", name) |
| + } |
| + if _, serr := os.Stat(req.Out); serr == nil { |
| + t.Errorf("%s: -out written for a refused version", name) |
| + } |
| + } |
| +} |
| + |
| +// TestDeleteRefusesForeignImage: delete reads the image first and refuses |
| +// one outside the prefix or the account. |
| +func TestDeleteRefusesForeignImage(t *testing.T) { |
| + p := newFake(t) |
| + other := imageARN("someone-else") |
| + p.images[other] = Image{ARN: other, Name: "someone-else", State: "CREATED"} |
| + if _, err := Delete(context.Background(), p, target, other, request(t).Wait); failureOf(t, err).Exit != ExitGuard || slices.Contains(p.calls, "DeleteImage") { |
| + t.Fatalf("Delete of a foreign image = %v, calls %v", err, p.calls) |
| + } |
| + p = newFake(t) |
| + foreign := "arn:aws:lambda:" + region + ":444455556666:microvm-image:" + prefix |
| + if _, err := Delete(context.Background(), p, target, foreign, request(t).Wait); err == nil || len(p.calls) > 1 { |
| + t.Fatalf("Delete in another account = %v, calls %v", err, p.calls) |
| + } |
| + p = newFake(t) |
| + mine := imageARN(prefix) |
| + p.images[mine] = Image{ARN: mine, Name: prefix, State: "CREATED"} |
| + if _, err := Delete(context.Background(), p, target, mine, request(t).Wait); err != nil || !slices.Contains(p.calls, "DeleteImage") { |
| + t.Fatalf("Delete of the run's image = %v, calls %v", err, p.calls) |
| + } |
| +} |
| + |
| +// TestListOnlyPrefix: list shows only the prefix's images. |
| +func TestListOnlyPrefix(t *testing.T) { |
| + p := newFake(t) |
| + p.list = []Image{{ARN: imageARN(prefix), Name: prefix}, {ARN: imageARN(prefix + "-2"), Name: prefix + "-2"}, |
| + {ARN: imageARN(prefix + "x"), Name: prefix + "x"}, {ARN: imageARN("other"), Name: "other"}} |
| + got, err := List(context.Background(), p, target) |
| + if err != nil || len(got) != 2 || got[0].Name != prefix || got[1].Name != prefix+"-2" { |
| + t.Fatalf("List = %+v, %v", got, err) |
| + } |
| + if p.calls[0] != "CallerAccount" { |
| + t.Fatalf("calls %v, want the account check first", p.calls) |
| + } |
| +} |
| + |
| +// TestConnectorWait: the connector must be the prefix's and becomes |
| +// ACTIVE within the bound; a failed one ends the wait. |
| +func TestConnectorWait(t *testing.T) { |
| + arn := "arn:aws:lambda:" + region + ":" + acct + ":network-connector:nc-1" |
| + p := newFake(t) |
| + p.conn = []Connector{{ARN: arn, Name: prefix + "-egress", State: "PENDING"}, {ARN: arn, Name: prefix + "-egress", State: "ACTIVE"}} |
| + if c, err := ConnectorWait(context.Background(), p, target, arn, request(t).Wait); err != nil || c.State != "ACTIVE" { |
| + t.Fatalf("ConnectorWait = %+v, %v", c, err) |
| + } |
| + p = newFake(t) |
| + p.conn = []Connector{{ARN: arn, Name: "someone-else", State: "ACTIVE"}} |
| + if _, err := ConnectorWait(context.Background(), p, target, arn, request(t).Wait); failureOf(t, err).Exit != ExitGuard { |
| + t.Fatalf("ConnectorWait on a foreign connector = %v", err) |
| + } |
| + p = newFake(t) |
| + p.conn = []Connector{{ARN: arn, Name: prefix, State: "FAILED"}} |
| + if _, err := ConnectorWait(context.Background(), p, target, arn, request(t).Wait); failureOf(t, err).Exit != ExitFailed { |
| + t.Fatalf("ConnectorWait on a failed connector = %v", err) |
| + } |
| +} |
diff --git a/internal/isolatedjob/awsjob/awsctl/awsctl_test.go b/internal/isolatedjob/awsjob/awsctl/awsctl_test.go| new file mode 100644 |
| index 00000000..9a8cfd0a |
| --- /dev/null |
| +++ b/internal/isolatedjob/awsjob/awsctl/awsctl_test.go |
| @@ -0,0 +1,404 @@ |
| +package awsctl |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "io" |
| + "net" |
| + "net/http" |
| + "net/http/httptest" |
| + "os" |
| + "path/filepath" |
| + "regexp" |
| + "strings" |
| + "sync" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/rastrillo/rastrillo/budget" |
| + "github.com/aws/aws-sdk-go-v2/aws" |
| + "github.com/aws/aws-sdk-go-v2/config" |
| + "github.com/aws/aws-sdk-go-v2/service/lambdacore" |
| + vms "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms" |
| + "github.com/aws/aws-sdk-go-v2/service/sts" |
| +) |
| + |
| +func TestMain(m *testing.M) { os.Exit(budget.Main(m)) } |
| + |
| +// These tests are livectl's (slice 1a review round 1 and R41), run here |
| +// without the hostedlive tag because equipo-hosted-image, a production |
| +// tool, uses the same plumbing. No request leaves the process. |
| + |
| +const region = "eu-central-1" |
| + |
| +var offlineKeys = FixedCredentials{Credentials: aws.Credentials{AccessKeyID: "AKIDOFFLINE", SecretAccessKey: "offline"}} |
| + |
| +// recorder is an offline HTTP client: it records each request's host and |
| +// answers from answer. |
| +type recorder struct { |
| + mu sync.Mutex |
| + hosts []string |
| + answer func(*http.Request) (*http.Response, error) |
| +} |
| + |
| +func (r *recorder) Do(req *http.Request) (*http.Response, error) { |
| + r.mu.Lock() |
| + r.hosts = append(r.hosts, req.URL.Host) |
| + r.mu.Unlock() |
| + return r.answer(req) |
| +} |
| + |
| +func (r *recorder) seen() []string { |
| + r.mu.Lock() |
| + defer r.mu.Unlock() |
| + return append([]string(nil), r.hosts...) |
| +} |
| + |
| +func reply(req *http.Request, status int, body string) *http.Response { |
| + h := http.Header{"X-Amzn-Requestid": {"req-9"}} |
| + if strings.Contains(req.URL.Host, "sts") { |
| + h.Set("Content-Type", "text/xml") |
| + } else { |
| + h.Set("Content-Type", "application/json") |
| + } |
| + return &http.Response{StatusCode: status, Header: h, Body: io.NopCloser(strings.NewReader(body)), Request: req} |
| +} |
| + |
| +func stsAnswer(account string) string { |
| + return `<GetCallerIdentityResponse xmlns="https://sts.amazonaws.com/doc/2011-06-15/"><GetCallerIdentityResult>` + |
| + `<Arn>arn:aws:iam::` + account + `:user/agent</Arn><UserId>AID</UserId><Account>` + account + `</Account>` + |
| + `</GetCallerIdentityResult><ResponseMetadata><RequestId>req-9</RequestId></ResponseMetadata></GetCallerIdentityResponse>` |
| +} |
| + |
| +func normal(req *http.Request) (*http.Response, error) { |
| + if strings.Contains(req.URL.Host, "sts") { |
| + return reply(req, 200, stsAnswer("111122223333")), nil |
| + } |
| + return reply(req, 200, `{}`), nil |
| +} |
| + |
| +func callAll(c Clients) []error { |
| + ctx := context.Background() |
| + _, e1 := c.STS.GetCallerIdentity(ctx, &sts.GetCallerIdentityInput{}) |
| + _, e2 := c.VMs.GetMicrovmImage(ctx, &vms.GetMicrovmImageInput{ImageIdentifier: aws.String("img")}) |
| + _, e3 := c.Core.GetNetworkConnector(ctx, &lambdacore.GetNetworkConnectorInput{Identifier: aws.String("nc-1")}) |
| + return []error{e1, e2, e3} |
| +} |
| + |
| +// hostileEnv points every endpoint and retry setting the SDK reads from the |
| +// environment or a profile somewhere else. |
| +func hostileEnv(t *testing.T) { |
| + dir := t.TempDir() |
| + cfgFile := filepath.Join(dir, "config") |
| + body := `[profile hostile] |
| +region = ` + region + ` |
| +endpoint_url = https://evil-profile.invalid |
| +max_attempts = 7 |
| +retry_mode = adaptive |
| +use_fips_endpoint = true |
| +use_dualstack_endpoint = true |
| +services = evil |
| + |
| +[services evil] |
| +sts = |
| + endpoint_url = https://evil-svc-sts.invalid |
| +lambda_microvms = |
| + endpoint_url = https://evil-svc-microvms.invalid |
| +lambda_core = |
| + endpoint_url = https://evil-svc-core.invalid |
| +` |
| + if err := os.WriteFile(cfgFile, []byte(body), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + for k, v := range map[string]string{ |
| + "AWS_CONFIG_FILE": cfgFile, "AWS_SHARED_CREDENTIALS_FILE": filepath.Join(dir, "none"), "AWS_PROFILE": "hostile", |
| + "AWS_ACCESS_KEY_ID": "AKIDOFFLINE", "AWS_SECRET_ACCESS_KEY": "offline", "AWS_SESSION_TOKEN": "", |
| + "AWS_EC2_METADATA_DISABLED": "true", "AWS_REGION": region, |
| + "AWS_ENDPOINT_URL": "https://evil-global.invalid", "AWS_ENDPOINT_URL_STS": "https://evil-sts.invalid", |
| + "AWS_ENDPOINT_URL_LAMBDA_MICROVMS": "https://evil-microvms.invalid", "AWS_ENDPOINT_URL_LAMBDA_CORE": "https://evil-core.invalid", |
| + "AWS_IGNORE_CONFIGURED_ENDPOINT_URLS": "false", "AWS_MAX_ATTEMPTS": "5", "AWS_RETRY_MODE": "standard", |
| + "AWS_USE_FIPS_ENDPOINT": "true", "AWS_USE_DUALSTACK_ENDPOINT": "true", |
| + } { |
| + t.Setenv(k, v) |
| + } |
| +} |
| + |
| +// TestClientsIgnoreEndpointOverrides: with every endpoint override set, |
| +// the clients call the standard endpoints of the region they were given. |
| +func TestClientsIgnoreEndpointOverrides(t *testing.T) { |
| + clean := &recorder{answer: normal} |
| + for i, err := range callAll(NewClients(aws.Config{Region: region, HTTPClient: clean, Credentials: offlineKeys}, region, time.Minute)) { |
| + if err != nil { |
| + t.Fatalf("clean call %d: %v", i, err) |
| + } |
| + } |
| + want := clean.seen() |
| + for _, h := range want { |
| + if !strings.HasSuffix(h, "."+region+".amazonaws.com") || strings.Contains(h, "fips") || strings.Contains(h, "dualstack") { |
| + t.Fatalf("standard host %q is not a plain %s endpoint", h, region) |
| + } |
| + } |
| + |
| + hostileEnv(t) |
| + rec := &recorder{answer: normal} |
| + cfg, err := config.LoadDefaultConfig(context.Background(), config.WithHTTPClient(rec)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if aws.ToString(cfg.BaseEndpoint) == "" { |
| + t.Fatal("the hostile environment set no base endpoint; the test checks nothing") |
| + } |
| + cfg.Region = "us-east-1" // the config's own region does not steer the clients either |
| + for i, err := range callAll(NewClients(cfg, region, time.Minute)) { |
| + if err != nil { |
| + t.Fatalf("call %d under overrides: %v", i, err) |
| + } |
| + } |
| + if got := rec.seen(); strings.Join(got, " ") != strings.Join(want, " ") { |
| + t.Fatalf("hosts under overrides = %v, want the standard %v", got, want) |
| + } |
| + |
| + // The production path: the config built from the resolved static keys. |
| + r, creds, err := ResolveStatic(context.Background(), "") |
| + if err != nil { |
| + t.Fatalf("ResolveStatic under the hostile environment = %v", err) |
| + } |
| + prod := StaticConfig(r, "eu-west-1", creds) |
| + prodRec := &recorder{answer: normal} |
| + prod.HTTPClient = prodRec |
| + for i, err := range callAll(NewClients(prod, region, time.Minute)) { |
| + if err != nil { |
| + t.Fatalf("production call %d: %v", i, err) |
| + } |
| + } |
| + if got := prodRec.seen(); strings.Join(got, " ") != strings.Join(want, " ") { |
| + t.Fatalf("production hosts = %v, want the standard %v", got, want) |
| + } |
| +} |
| + |
| +// TestClientsOneAttempt: a retryable error is one request, whatever |
| +// AWS_MAX_ATTEMPTS and the profile say. |
| +func TestClientsOneAttempt(t *testing.T) { |
| + hostileEnv(t) |
| + for _, c := range []struct { |
| + status int |
| + body string |
| + }{ |
| + {500, `{"__type":"InternalServerException","message":"boom"}`}, |
| + {429, `{"__type":"ThrottlingException","message":"slow"}`}, |
| + } { |
| + rec := &recorder{answer: func(req *http.Request) (*http.Response, error) { return reply(req, c.status, c.body), nil }} |
| + cfg, err := config.LoadDefaultConfig(context.Background(), config.WithHTTPClient(rec)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + cl := NewClients(cfg, region, time.Minute) |
| + _, err = cl.Core.GetNetworkConnector(context.Background(), &lambdacore.GetNetworkConnectorInput{Identifier: aws.String("nc-1")}) |
| + ci := Describe(err) |
| + if err == nil || ci.Status != c.status || !ci.Answered || ci.RequestID != "req-9" { |
| + t.Fatalf("status %d: GetNetworkConnector = %v (described %+v)", c.status, err, ci) |
| + } |
| + _, _ = cl.VMs.GetMicrovmImage(context.Background(), &vms.GetMicrovmImageInput{ImageIdentifier: aws.String("img")}) |
| + if n := len(rec.seen()); n != 2 { |
| + t.Fatalf("status %d: %d requests for two calls, want one each (no retries)", c.status, n) |
| + } |
| + } |
| +} |
| + |
| +// TestClientsBoundEachCall: a request that never answers ends at the |
| +// per-call timeout. |
| +func TestClientsBoundEachCall(t *testing.T) { |
| + timeout := 200 * time.Millisecond |
| + rec := &recorder{answer: func(req *http.Request) (*http.Response, error) { |
| + select { |
| + case <-req.Context().Done(): |
| + return nil, req.Context().Err() |
| + case <-time.After(5 * time.Second): |
| + return nil, errors.New("the request had no deadline") |
| + } |
| + }} |
| + start := time.Now() |
| + for i, err := range callAll(NewClients(aws.Config{Region: region, HTTPClient: rec, Credentials: offlineKeys}, region, timeout)) { |
| + if !errors.Is(err, context.DeadlineExceeded) { |
| + t.Errorf("stalled call %d = %v, want the per-call deadline", i, err) |
| + } |
| + if Describe(err).Answered { |
| + t.Errorf("stalled call %d described as answered", i) |
| + } |
| + } |
| + if d := time.Since(start); d > 3*time.Second { |
| + t.Fatalf("three stalled calls took %v, want about 3 x %v", d, timeout) |
| + } |
| +} |
| + |
| +// TestCheckCaller: the region and then the STS account must match. |
| +func TestCheckCaller(t *testing.T) { |
| + for _, c := range []struct { |
| + name, region, account string |
| + calls int |
| + guard bool |
| + }{ |
| + {"match", region, "111122223333", 1, false}, |
| + {"other account", region, "444455556666", 1, true}, |
| + {"other region", "eu-west-1", "111122223333", 0, true}, |
| + } { |
| + t.Run(c.name, func(t *testing.T) { |
| + rec := &recorder{answer: func(req *http.Request) (*http.Response, error) { return reply(req, 200, stsAnswer(c.account)), nil }} |
| + cl := NewClients(aws.Config{Region: region, HTTPClient: rec, Credentials: offlineKeys}, region, time.Minute) |
| + err := CheckCaller(context.Background(), cl.STS, c.region, region, "111122223333") |
| + var g *GuardError |
| + if errors.As(err, &g) != c.guard || (!c.guard && err != nil) { |
| + t.Fatalf("CheckCaller = %v, want guard %v", err, c.guard) |
| + } |
| + if n := len(rec.seen()); n != c.calls { |
| + t.Fatalf("%d calls, want %d", n, c.calls) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// credEnv gives the test its own config and credentials files and profile |
| +// p, clears every credential setting of the environment, and points every |
| +// credential service the SDK knows at a counting server. |
| +func credEnv(t *testing.T, configBody, credsBody string) (dir string, hits *atomic.Int64) { |
| + t.Helper() |
| + dir = t.TempDir() |
| + hits = &atomic.Int64{} |
| + srv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { |
| + hits.Add(1) |
| + http.Error(w, "no", http.StatusTeapot) |
| + })) |
| + ln, err := net.Listen("tcp", "127.0.0.1:0") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + srv.Listener = ln |
| + srv.Start() |
| + t.Cleanup(srv.Close) |
| + cfgFile, credFile := filepath.Join(dir, "config"), filepath.Join(dir, "credentials") |
| + for p, b := range map[string]string{cfgFile: configBody, credFile: credsBody} { |
| + if err := os.WriteFile(p, []byte(b), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + for k, v := range map[string]string{ |
| + "AWS_CONFIG_FILE": cfgFile, "AWS_SHARED_CREDENTIALS_FILE": credFile, "AWS_PROFILE": "p", "AWS_DEFAULT_PROFILE": "", |
| + "AWS_ACCESS_KEY_ID": "", "AWS_SECRET_ACCESS_KEY": "", "AWS_SESSION_TOKEN": "", "AWS_ACCESS_KEY": "", "AWS_SECRET_KEY": "", |
| + "AWS_WEB_IDENTITY_TOKEN_FILE": "", "AWS_ROLE_ARN": "", "AWS_ROLE_SESSION_NAME": "", |
| + "AWS_CONTAINER_CREDENTIALS_FULL_URI": "", "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI": "", "AWS_REGION": "", "AWS_DEFAULT_REGION": "", |
| + "AWS_EC2_METADATA_SERVICE_ENDPOINT": srv.URL, "AWS_ENDPOINT_URL_STS": srv.URL, "AWS_ENDPOINT_URL_SSO": srv.URL, |
| + "AWS_ENDPOINT_URL_SSO_OIDC": srv.URL, "AWS_ENDPOINT_URL": srv.URL, |
| + } { |
| + t.Setenv(k, v) |
| + } |
| + return dir, hits |
| +} |
| + |
| +const pKeys = "[p]\naws_access_key_id = AKIDPROFILE\naws_secret_access_key = profile-secret\n" |
| + |
| +// TestCredentialKindsRefused: every provider but static keys is refused |
| +// by kind, without reaching any credential service or running any |
| +// credential process. |
| +func TestCredentialKindsRefused(t *testing.T) { |
| + for _, c := range []struct { |
| + name, config, creds string |
| + env map[string]string |
| + kind string |
| + }{ |
| + {"assume role", "[profile p]\nrole_arn = arn:aws:iam::111122223333:role/x\nsource_profile = base\n[profile base]\nregion = eu-west-1\n", |
| + pKeys + "[base]\naws_access_key_id = AKIDBASE\naws_secret_access_key = b\n", nil, "assume role"}, |
| + {"web identity in the profile", "[profile p]\nrole_arn = arn:aws:iam::111122223333:role/x\nweb_identity_token_file = /nonexistent/token\n", |
| + pKeys, nil, "web identity"}, |
| + {"SSO session", "[profile p]\nsso_session = s\nsso_account_id = 111122223333\nsso_role_name = r\n[sso-session s]\nsso_start_url = https://example.invalid/start\nsso_region = eu-west-1\n", |
| + pKeys, nil, "SSO"}, |
| + {"credential_process", "[profile p]\ncredential_process = /bin/sh -c 'touch MARKER'\n", pKeys, nil, "credential_process"}, |
| + {"credential_source instance metadata", "[profile p]\nrole_arn = arn:aws:iam::111122223333:role/x\ncredential_source = Ec2InstanceMetadata\n", |
| + "", nil, "instance metadata"}, |
| + {"web identity in the environment", "[profile p]\nregion = eu-west-1\n", "", |
| + map[string]string{"AWS_WEB_IDENTITY_TOKEN_FILE": "/nonexistent/token", "AWS_ROLE_ARN": "arn:aws:iam::111122223333:role/x"}, "web identity"}, |
| + {"container in the environment", "[profile p]\nregion = eu-west-1\n", "", |
| + map[string]string{"AWS_CONTAINER_CREDENTIALS_FULL_URI": "http://127.0.0.1:1/creds"}, "container credentials"}, |
| + {"nothing static (instance metadata)", "[profile p]\nregion = eu-west-1\n", "", nil, "instance metadata"}, |
| + } { |
| + t.Run(c.name, func(t *testing.T) { |
| + dir, hits := credEnv(t, c.config, c.creds) |
| + t.Chdir(dir) // a credential_process would create MARKER here |
| + for k, v := range c.env { |
| + t.Setenv(k, v) |
| + } |
| + _, _, err := ResolveStatic(context.Background(), "") |
| + var refused *RefusedError |
| + if !errors.As(err, &refused) || refused.Kind != c.kind { |
| + t.Fatalf("ResolveStatic = %v, want a refusal naming %q", err, c.kind) |
| + } |
| + if n := hits.Load(); n != 0 { |
| + t.Fatalf("%d requests reached a credential service during resolution", n) |
| + } |
| + if _, err := os.Stat(filepath.Join(dir, "MARKER")); err == nil { |
| + t.Fatal("the credential process ran") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// TestNamedProfile: -profile reads that profile, not AWS_PROFILE's, and |
| +// refuses keys in the environment beside it. |
| +func TestNamedProfile(t *testing.T) { |
| + credEnv(t, "[profile p]\nregion = eu-west-1\n[profile q]\nregion = "+region+"\n", |
| + pKeys+"[q]\naws_access_key_id = AKIDQ\naws_secret_access_key = q-secret\n") |
| + r, c, err := ResolveStatic(context.Background(), "q") |
| + if err != nil || r != region || c.AccessKeyID != "AKIDQ" { |
| + t.Fatalf("ResolveStatic(q) = %q, %+v, %v", r, c, err) |
| + } |
| + t.Setenv("AWS_ACCESS_KEY_ID", "AKIDENV") |
| + t.Setenv("AWS_SECRET_ACCESS_KEY", "env-secret") |
| + var refused *RefusedError |
| + if _, _, err := ResolveStatic(context.Background(), "q"); !errors.As(err, &refused) { |
| + t.Fatalf("ResolveStatic(q) with keys in the environment = %v, want a refusal", err) |
| + } |
| + if _, c, err := ResolveStatic(context.Background(), ""); err != nil || c.AccessKeyID != "AKIDENV" { |
| + t.Fatalf("ResolveStatic() with keys in the environment = %+v, %v, want the environment's", c, err) |
| + } |
| +} |
| + |
| +var credentialKey = regexp.MustCompile(`Credential=([A-Z0-9]+)/`) |
| + |
| +// TestCredentialsNeverRefresh: the keys are read once; changing the |
| +// environment afterwards changes nothing. |
| +func TestCredentialsNeverRefresh(t *testing.T) { |
| + credEnv(t, "[profile p]\nregion = "+region+"\n", "") |
| + t.Setenv("AWS_ACCESS_KEY_ID", "AKIDFIRST") |
| + t.Setenv("AWS_SECRET_ACCESS_KEY", "first") |
| + r, c, err := ResolveStatic(context.Background(), "") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + cfg := StaticConfig(r, "eu-west-1", c) |
| + var keys []string |
| + var mu sync.Mutex |
| + cfg.HTTPClient = &recorder{answer: func(req *http.Request) (*http.Response, error) { |
| + if m := credentialKey.FindStringSubmatch(req.Header.Get("Authorization")); m != nil { |
| + mu.Lock() |
| + keys = append(keys, m[1]) |
| + mu.Unlock() |
| + } |
| + return normal(req) |
| + }} |
| + cl := NewClients(cfg, region, time.Minute) |
| + if _, err := cl.STS.GetCallerIdentity(context.Background(), &sts.GetCallerIdentityInput{}); err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Setenv("AWS_ACCESS_KEY_ID", "AKIDSECOND") |
| + t.Setenv("AWS_SECRET_ACCESS_KEY", "second") |
| + if _, err := cl.Core.GetNetworkConnector(context.Background(), &lambdacore.GetNetworkConnectorInput{Identifier: aws.String("nc-1")}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if strings.Join(keys, " ") != "AKIDFIRST AKIDFIRST" { |
| + t.Fatalf("requests signed with %v, want the first keys twice", keys) |
| + } |
| + got, err := cfg.Credentials.Retrieve(context.Background()) |
| + if err != nil || got.CanExpire || got.AccessKeyID != "AKIDFIRST" { |
| + t.Fatalf("Retrieve after the change = %+v, %v", got, err) |
| + } |
| +} |
diff --git a/internal/isolatedjob/awsjob/awsctl/clients.go b/internal/isolatedjob/awsjob/awsctl/clients.go| new file mode 100644 |
| index 00000000..294ed3d3 |
| --- /dev/null |
| +++ b/internal/isolatedjob/awsjob/awsctl/clients.go |
| @@ -0,0 +1,134 @@ |
| +package awsctl |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "time" |
| + |
| + "github.com/aws/aws-sdk-go-v2/aws" |
| + awshttp "github.com/aws/aws-sdk-go-v2/aws/transport/http" |
| + "github.com/aws/aws-sdk-go-v2/service/lambdacore" |
| + vms "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms" |
| + "github.com/aws/aws-sdk-go-v2/service/sts" |
| + "github.com/aws/smithy-go" |
| + "github.com/aws/smithy-go/middleware" |
| + smithyhttp "github.com/aws/smithy-go/transport/http" |
| +) |
| + |
| +// Clients are the three clients the tools call through. |
| +type Clients struct { |
| + Core *lambdacore.Client |
| + VMs *vms.Client |
| + STS *sts.Client |
| +} |
| + |
| +// NewClients builds the clients from cfg, pinned so nothing in the |
| +// environment or the profile can steer them: |
| +// |
| +// - endpoints: every configured endpoint override is dropped |
| +// (AWS_ENDPOINT_URL, AWS_ENDPOINT_URL_<SERVICE>, a profile's |
| +// endpoint_url or services section), FIPS and dual-stack are off and |
| +// the region is region, so each call goes to the standard endpoint |
| +// the SDK's own resolver gives for region; the STS answer the account |
| +// check reads therefore comes from the same AWS the Lambda calls |
| +// reach; |
| +// - retries: exactly one attempt per call, whatever AWS_MAX_ATTEMPTS or |
| +// the profile's max_attempts and retry_mode say, so a failed mutation |
| +// is never resent behind the operator's back; |
| +// - deadlines: each call gets timeout on its context. |
| +func NewClients(cfg aws.Config, region string, timeout time.Duration) Clients { |
| + deadline := deadlineEach(timeout) |
| + return Clients{ |
| + Core: lambdacore.NewFromConfig(cfg, func(o *lambdacore.Options) { |
| + o.Region, o.BaseEndpoint = region, nil |
| + o.EndpointOptions = lambdacore.EndpointResolverOptions{} |
| + o.EndpointResolverV2 = lambdacore.NewDefaultEndpointResolverV2() |
| + o.Retryer, o.RetryMaxAttempts = aws.NopRetryer{}, 1 |
| + o.APIOptions = append(o.APIOptions, deadline) |
| + }), |
| + VMs: vms.NewFromConfig(cfg, func(o *vms.Options) { |
| + o.Region, o.BaseEndpoint = region, nil |
| + o.EndpointOptions = vms.EndpointResolverOptions{} |
| + o.EndpointResolverV2 = vms.NewDefaultEndpointResolverV2() |
| + o.Retryer, o.RetryMaxAttempts = aws.NopRetryer{}, 1 |
| + o.APIOptions = append(o.APIOptions, deadline) |
| + }), |
| + STS: sts.NewFromConfig(cfg, func(o *sts.Options) { |
| + o.Region, o.BaseEndpoint = region, nil |
| + o.EndpointOptions = sts.EndpointResolverOptions{} |
| + o.EndpointResolverV2 = sts.NewDefaultEndpointResolverV2() |
| + o.Retryer, o.RetryMaxAttempts = aws.NopRetryer{}, 1 |
| + o.APIOptions = append(o.APIOptions, deadline) |
| + }), |
| + } |
| +} |
| + |
| +// deadlineEach adds timeout to the context of every operation, first in |
| +// the stack, so the whole call (signing, sending, reading the answer) is |
| +// bounded even when the caller's context is not. |
| +func deadlineEach(timeout time.Duration) func(*middleware.Stack) error { |
| + return func(s *middleware.Stack) error { |
| + return s.Initialize.Add(middleware.InitializeMiddlewareFunc("AwsctlCallDeadline", |
| + func(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) (middleware.InitializeOutput, middleware.Metadata, error) { |
| + ctx, cancel := context.WithTimeout(ctx, timeout) |
| + defer cancel() |
| + return next.HandleInitialize(ctx, in) |
| + }), middleware.Before) |
| + } |
| +} |
| + |
| +// STSAPI is the part of the STS client the caller check uses. |
| +type STSAPI interface { |
| + GetCallerIdentity(context.Context, *sts.GetCallerIdentityInput, ...func(*sts.Options)) (*sts.GetCallerIdentityOutput, error) |
| +} |
| + |
| +// GuardError is a caller check that failed: the wrong account or region. |
| +type GuardError struct{ Message string } |
| + |
| +func (e *GuardError) Error() string { return e.Message } |
| + |
| +// CheckCaller is the guard every tool passes before any other call: the |
| +// client region must be wantRegion and STS must name wantAccount. A |
| +// failed STS call is returned as it came (see Describe). |
| +func CheckCaller(ctx context.Context, st STSAPI, region, wantRegion, wantAccount string) error { |
| + if region != wantRegion { |
| + return &GuardError{Message: fmt.Sprintf("region is %q, want %s", region, wantRegion)} |
| + } |
| + out, err := st.GetCallerIdentity(ctx, &sts.GetCallerIdentityInput{}) |
| + if err != nil { |
| + return err |
| + } |
| + if a := aws.ToString(out.Account); a != wantAccount { |
| + return &GuardError{Message: fmt.Sprintf("caller account is %q, want %s", a, wantAccount)} |
| + } |
| + return nil |
| +} |
| + |
| +// CallInfo is what a failed SDK call says about itself. |
| +type CallInfo struct { |
| + Answered bool // the service answered (an API error), not the transport |
| + Code string // the smithy error code |
| + AWSMessage string // the service's own message, never parsed |
| + Status int // the HTTP status, when there was a response |
| + RequestID string |
| +} |
| + |
| +// Describe reads err's error code, message, HTTP status and request ID, |
| +// where the SDK has them. |
| +func Describe(err error) CallInfo { |
| + var ci CallInfo |
| + var ae smithy.APIError |
| + if errors.As(err, &ae) { |
| + ci.Answered, ci.Code, ci.AWSMessage = true, ae.ErrorCode(), ae.ErrorMessage() |
| + } |
| + var he *smithyhttp.ResponseError |
| + if errors.As(err, &he) && he.Response != nil { |
| + ci.Status = he.HTTPStatusCode() |
| + } |
| + var re *awshttp.ResponseError |
| + if errors.As(err, &re) { |
| + ci.RequestID = re.ServiceRequestID() |
| + } |
| + return ci |
| +} |
diff --git a/internal/isolatedjob/awsjob/awsctl/creds.go b/internal/isolatedjob/awsjob/awsctl/creds.go| new file mode 100644 |
| index 00000000..bc6dbec6 |
| --- /dev/null |
| +++ b/internal/isolatedjob/awsjob/awsctl/creds.go |
| @@ -0,0 +1,137 @@ |
| +// Package awsctl holds the guarded SDK plumbing the operator tools share: |
| +// livectl (slice 1a's dev-only live check, hard-wired to one account) and |
| +// equipo-hosted-image (any account and region, given as flags). It is the |
| +// part of those tools that touches the SDK's configuration: |
| +// |
| +// - static credentials, resolved once, before any call (controller |
| +// ruling R41): every other credential provider is refused by kind, |
| +// and none is ever built; |
| +// - clients pinned to one region's standard endpoints, one attempt per |
| +// call, and a deadline on each call (livectl review round 1); |
| +// - the caller check: STS must name the expected account before any |
| +// other call. |
| +// |
| +// Nothing here knows a resource name or an account; the tools bring |
| +// those. |
| +package awsctl |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + |
| + "github.com/aws/aws-sdk-go-v2/aws" |
| + "github.com/aws/aws-sdk-go-v2/config" |
| +) |
| + |
| +// FixedCredentials hands out the same keys for the life of the process. |
| +type FixedCredentials struct{ Credentials aws.Credentials } |
| + |
| +// Retrieve returns the keys, never expiring. |
| +func (f FixedCredentials) Retrieve(context.Context) (aws.Credentials, error) { |
| + c := f.Credentials |
| + c.CanExpire, c.Source = false, "static keys" |
| + return c, nil |
| +} |
| + |
| +// RefusedError is a credential provider the tools will not use. |
| +type RefusedError struct{ Kind string } |
| + |
| +func (e *RefusedError) Error() string { |
| + return "credentials from " + e.Kind + " are refused" |
| +} |
| + |
| +// ConfigError is an AWS environment setting or shared file that did not |
| +// parse. Its text is fixed and says which. |
| +type ConfigError struct{ Message string } |
| + |
| +func (e *ConfigError) Error() string { return e.Message } |
| + |
| +// profileKind names the non-static provider a profile asks for, or "". |
| +func profileKind(sc config.SharedConfig) string { |
| + switch { |
| + case sc.WebIdentityTokenFile != "": |
| + return "web identity" |
| + case sc.SSOSessionName != "" || sc.SSOSession != nil || sc.SSOStartURL != "" || sc.SSOAccountID != "" || sc.SSORoleName != "": |
| + return "SSO" |
| + case sc.CredentialProcess != "": |
| + return "credential_process" |
| + case sc.CredentialSource == "EcsContainer": |
| + return "container credentials" |
| + case sc.CredentialSource == "Ec2InstanceMetadata": |
| + return "instance metadata" |
| + case sc.CredentialSource != "": |
| + return "credential_source" |
| + case sc.RoleARN != "" || sc.SourceProfileName != "" || sc.Source != nil: |
| + return "assume role" |
| + case sc.LoginSession != "": |
| + return "login session" |
| + } |
| + return "" |
| +} |
| + |
| +// ResolveStatic returns the region and the static keys to use, reading |
| +// only the environment and the two shared files, in the SDK's own order: |
| +// keys in the environment; else the profile, refused if it names any |
| +// other provider; else a *RefusedError naming what the SDK would have |
| +// fallen back to (web identity, the container endpoint or instance |
| +// metadata). |
| +// |
| +// profile names the profile to read; "" takes AWS_PROFILE, else |
| +// "default". A named profile and keys in the environment together are |
| +// refused, so an explicit profile is never silently overridden. |
| +func ResolveStatic(ctx context.Context, profile string) (string, aws.Credentials, error) { |
| + ec, err := config.NewEnvConfig() |
| + if err != nil { |
| + return "", aws.Credentials{}, &ConfigError{Message: "the AWS environment settings did not parse"} |
| + } |
| + if profile != "" && ec.Credentials.HasKeys() { |
| + return "", aws.Credentials{}, &RefusedError{Kind: "the environment while a profile is named"} |
| + } |
| + if profile == "" { |
| + profile = ec.SharedConfigProfile |
| + } |
| + if profile == "" { |
| + profile = "default" |
| + } |
| + cfgFile, credFile := ec.SharedConfigFile, ec.SharedCredentialsFile |
| + if cfgFile == "" { |
| + cfgFile = config.DefaultSharedConfigFilename() |
| + } |
| + if credFile == "" { |
| + credFile = config.DefaultSharedCredentialsFilename() |
| + } |
| + sc, err := config.LoadSharedConfigProfile(ctx, profile, func(o *config.LoadSharedConfigOptions) { |
| + o.ConfigFiles, o.CredentialsFiles = []string{cfgFile}, []string{credFile} |
| + }) |
| + var missing config.SharedConfigProfileNotExistError |
| + if err != nil && !errors.As(err, &missing) { |
| + return "", aws.Credentials{}, &ConfigError{Message: "the shared config or credentials file did not parse"} |
| + } |
| + region := ec.Region |
| + if region == "" { |
| + region = sc.Region |
| + } |
| + switch { |
| + case ec.Credentials.HasKeys(): |
| + return region, ec.Credentials, nil |
| + case profileKind(sc) != "": |
| + return "", aws.Credentials{}, &RefusedError{Kind: profileKind(sc)} |
| + case sc.Credentials.HasKeys(): |
| + return region, sc.Credentials, nil |
| + case ec.WebIdentityTokenFilePath != "" || ec.RoleARN != "": |
| + return "", aws.Credentials{}, &RefusedError{Kind: "web identity"} |
| + case ec.ContainerCredentialsEndpoint != "" || ec.ContainerCredentialsRelativePath != "": |
| + return "", aws.Credentials{}, &RefusedError{Kind: "container credentials"} |
| + } |
| + return "", aws.Credentials{}, &RefusedError{Kind: "instance metadata"} |
| +} |
| + |
| +// StaticConfig is the only aws.Config the tools build: the region |
| +// (fallback when region is empty) and the resolved keys. No credential |
| +// chain is ever created. |
| +func StaticConfig(region, fallback string, c aws.Credentials) aws.Config { |
| + if region == "" { |
| + region = fallback |
| + } |
| + return aws.Config{Region: region, Credentials: FixedCredentials{c}} |
| +} |
diff --git a/internal/isolatedjob/awsjob/imageaws/imageaws.go b/internal/isolatedjob/awsjob/imageaws/imageaws.go| new file mode 100644 |
| index 00000000..6129f47a |
| --- /dev/null |
| +++ b/internal/isolatedjob/awsjob/imageaws/imageaws.go |
| @@ -0,0 +1,249 @@ |
| +// Package imageaws is the SDK half of the image tool: it implements |
| +// hostedimage.Provider with one SDK call per method (or one bounded paged |
| +// read) on clients built by awsctl.NewClients, so every call goes to the |
| +// pinned region's standard endpoint, once, under a deadline. The guards |
| +// (account, region, prefix, waits) are hostedimage's; this package only |
| +// translates. |
| +package imageaws |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + |
| + "amadan.net/oficina/equipo/internal/hostedimage" |
| + "amadan.net/oficina/equipo/internal/isolatedjob/awsjob/awsctl" |
| + "github.com/aws/aws-sdk-go-v2/aws" |
| + "github.com/aws/aws-sdk-go-v2/service/lambdacore" |
| + vms "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms" |
| + "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms/types" |
| + "github.com/aws/aws-sdk-go-v2/service/sts" |
| +) |
| + |
| +// VMsAPI is the part of the MicroVMs client the image tool calls. |
| +type VMsAPI interface { |
| + ListManagedMicrovmImageVersions(context.Context, *vms.ListManagedMicrovmImageVersionsInput, ...func(*vms.Options)) (*vms.ListManagedMicrovmImageVersionsOutput, error) |
| + CreateMicrovmImage(context.Context, *vms.CreateMicrovmImageInput, ...func(*vms.Options)) (*vms.CreateMicrovmImageOutput, error) |
| + GetMicrovmImage(context.Context, *vms.GetMicrovmImageInput, ...func(*vms.Options)) (*vms.GetMicrovmImageOutput, error) |
| + GetMicrovmImageVersion(context.Context, *vms.GetMicrovmImageVersionInput, ...func(*vms.Options)) (*vms.GetMicrovmImageVersionOutput, error) |
| + ListMicrovmImages(context.Context, *vms.ListMicrovmImagesInput, ...func(*vms.Options)) (*vms.ListMicrovmImagesOutput, error) |
| + DeleteMicrovmImage(context.Context, *vms.DeleteMicrovmImageInput, ...func(*vms.Options)) (*vms.DeleteMicrovmImageOutput, error) |
| +} |
| + |
| +// CoreAPI is the part of the Lambda core client the image tool calls. |
| +type CoreAPI interface { |
| + GetNetworkConnector(context.Context, *lambdacore.GetNetworkConnectorInput, ...func(*lambdacore.Options)) (*lambdacore.GetNetworkConnectorOutput, error) |
| +} |
| + |
| +// Provider is hostedimage.Provider over the SDK. |
| +type Provider struct { |
| + region string |
| + vms VMsAPI |
| + core CoreAPI |
| + sts awsctl.STSAPI |
| +} |
| + |
| +var _ hostedimage.Provider = (*Provider)(nil) |
| + |
| +// New wraps clients from awsctl.NewClients. Region is the region those |
| +// clients call, read from the clients themselves. |
| +func New(c awsctl.Clients) *Provider { |
| + return &Provider{region: c.VMs.Options().Region, vms: c.VMs, core: c.Core, sts: c.STS} |
| +} |
| + |
| +// maxPages bounds every paged read. |
| +const maxPages = 100 |
| + |
| +func (p *Provider) Region() string { return p.region } |
| + |
| +// callErr describes a failed call; a ResourceNotFoundException wraps |
| +// hostedimage.ErrNotFound. |
| +func callErr(op string, err error) error { |
| + ci := awsctl.Describe(err) |
| + ce := &hostedimage.CallError{Op: op, Answered: ci.Answered, Code: ci.Code, Status: ci.Status, |
| + AWSMessage: ci.AWSMessage, RequestID: ci.RequestID, Err: err} |
| + if ci.Code == "ResourceNotFoundException" { |
| + ce.Err = fmt.Errorf("%w: %w", hostedimage.ErrNotFound, err) |
| + } |
| + return ce |
| +} |
| + |
| +// errPages is a paged read that would not end. |
| +var errPages = errors.New("imageaws: more than 100 pages, or a page token repeated; stopped reading") |
| + |
| +func (p *Provider) CallerAccount(ctx context.Context) (string, error) { |
| + out, err := p.sts.GetCallerIdentity(ctx, &sts.GetCallerIdentityInput{}) |
| + if err != nil { |
| + return "", callErr("GetCallerIdentity", err) |
| + } |
| + return aws.ToString(out.Account), nil |
| +} |
| + |
| +func (p *Provider) BaseVersions(ctx context.Context, baseARN string) ([]hostedimage.BaseVersion, error) { |
| + var all []hostedimage.BaseVersion |
| + var token *string |
| + seen := map[string]bool{} |
| + for range maxPages { |
| + out, err := p.vms.ListManagedMicrovmImageVersions(ctx, &vms.ListManagedMicrovmImageVersionsInput{ |
| + ImageIdentifier: aws.String(baseARN), NextToken: token}) |
| + if err != nil { |
| + return nil, callErr("ListManagedMicrovmImageVersions", err) |
| + } |
| + for _, it := range out.Items { |
| + all = append(all, hostedimage.BaseVersion{Version: aws.ToString(it.ImageVersion), Status: string(it.Status)}) |
| + } |
| + next := aws.ToString(out.NextToken) |
| + if next == "" { |
| + return all, nil |
| + } |
| + if seen[next] { |
| + return nil, errPages |
| + } |
| + seen[next], token = true, out.NextToken |
| + } |
| + return nil, errPages |
| +} |
| + |
| +// hooks is the API's Hooks for s. |
| +func hooks(h hostedimage.Hooks) *types.Hooks { |
| + return &types.Hooks{ |
| + Port: aws.Int32(int32(h.Port)), |
| + MicrovmHooks: &types.MicrovmHooks{ |
| + Run: types.HookState(h.Microvm.Run), RunTimeoutInSeconds: aws.Int32(int32(h.Microvm.RunTimeout)), |
| + Resume: types.HookState(h.Microvm.Resume), ResumeTimeoutInSeconds: aws.Int32(int32(h.Microvm.ResumeTimeout)), |
| + Suspend: types.HookState(h.Microvm.Suspend), SuspendTimeoutInSeconds: aws.Int32(int32(h.Microvm.SuspendTimeout)), |
| + Terminate: types.HookState(h.Microvm.Terminate), TerminateTimeoutInSeconds: aws.Int32(int32(h.Microvm.TerminateTimeout)), |
| + }, |
| + MicrovmImageHooks: &types.MicrovmImageHooks{ |
| + Ready: types.HookState(h.Image.Ready), ReadyTimeoutInSeconds: aws.Int32(int32(h.Image.ReadyTimeout)), |
| + Validate: types.HookState(h.Image.Validate), |
| + }, |
| + } |
| +} |
| + |
| +// createInput is the API request for c. The client token is always set |
| +// (the SDK would otherwise fill a random one, and a rerun could not |
| +// replay the create). |
| +func createInput(c hostedimage.CreateImage) *vms.CreateMicrovmImageInput { |
| + var cpu []types.CpuConfiguration |
| + for _, a := range c.Settings.CPU { |
| + cpu = append(cpu, types.CpuConfiguration{Architecture: types.Architecture(a.Architecture)}) |
| + } |
| + var caps []types.Capability |
| + for _, k := range c.Settings.Capabilities { |
| + caps = append(caps, types.Capability(k)) |
| + } |
| + in := &vms.CreateMicrovmImageInput{ |
| + Name: aws.String(c.Name), |
| + CodeArtifact: &types.CodeArtifactMemberUri{Value: c.Artifact}, |
| + BaseImageArn: aws.String(c.BaseImageARN), |
| + BaseImageVersion: aws.String(c.BaseVersion), |
| + BuildRoleArn: aws.String(c.BuildRoleARN), |
| + CpuConfigurations: cpu, |
| + Resources: []types.Resources{{MinimumMemoryInMiB: aws.Int32(int32(c.MemoryMiB))}}, |
| + AdditionalOsCapabilities: caps, |
| + Hooks: hooks(c.Settings.Hooks), |
| + Logging: &types.LoggingMemberCloudWatch{Value: types.CloudWatchLogging{LogGroup: aws.String(c.LogGroup)}}, |
| + ClientToken: aws.String(c.ClientToken), |
| + } |
| + if c.Description != "" { |
| + in.Description = aws.String(c.Description) |
| + } |
| + if len(c.Tags) > 0 { |
| + in.Tags = c.Tags |
| + } |
| + return in |
| +} |
| + |
| +func (p *Provider) CreateImage(ctx context.Context, c hostedimage.CreateImage) (hostedimage.Created, error) { |
| + if c.ClientToken == "" { |
| + return hostedimage.Created{}, errors.New("imageaws: a create needs a client token") |
| + } |
| + out, err := p.vms.CreateMicrovmImage(ctx, createInput(c)) |
| + if err != nil { |
| + return hostedimage.Created{}, callErr("CreateMicrovmImage", err) |
| + } |
| + return hostedimage.Created{ImageARN: aws.ToString(out.ImageArn), Name: aws.ToString(out.Name), Version: aws.ToString(out.ImageVersion)}, nil |
| +} |
| + |
| +func (p *Provider) GetImage(ctx context.Context, id string) (hostedimage.Image, error) { |
| + out, err := p.vms.GetMicrovmImage(ctx, &vms.GetMicrovmImageInput{ImageIdentifier: aws.String(id)}) |
| + if err != nil { |
| + return hostedimage.Image{}, callErr("GetMicrovmImage", err) |
| + } |
| + return hostedimage.Image{ARN: aws.ToString(out.ImageArn), Name: aws.ToString(out.Name), State: string(out.State), |
| + LatestActiveVersion: aws.ToString(out.LatestActiveImageVersion)}, nil |
| +} |
| + |
| +func (p *Provider) GetImageVersion(ctx context.Context, imageARN, version string) (hostedimage.Version, error) { |
| + out, err := p.vms.GetMicrovmImageVersion(ctx, &vms.GetMicrovmImageVersionInput{ |
| + ImageIdentifier: aws.String(imageARN), ImageVersion: aws.String(version)}) |
| + if err != nil { |
| + return hostedimage.Version{}, callErr("GetMicrovmImageVersion", err) |
| + } |
| + v := hostedimage.Version{State: string(out.State), Status: string(out.Status), Reason: aws.ToString(out.StateReason), |
| + BaseVersion: aws.ToString(out.BaseImageVersion)} |
| + for _, c := range out.AdditionalOsCapabilities { |
| + v.Capabilities = append(v.Capabilities, string(c)) |
| + } |
| + for _, c := range out.CpuConfigurations { |
| + v.Architectures = append(v.Architectures, string(c.Architecture)) |
| + } |
| + for _, r := range out.Resources { |
| + v.MemoryMiB = append(v.MemoryMiB, int(aws.ToInt32(r.MinimumMemoryInMiB))) |
| + } |
| + if out.Hooks != nil { |
| + v.HooksPort = int(aws.ToInt32(out.Hooks.Port)) |
| + if out.Hooks.MicrovmHooks != nil { |
| + v.RunTimeout = int(aws.ToInt32(out.Hooks.MicrovmHooks.RunTimeoutInSeconds)) |
| + } |
| + } |
| + if u, ok := out.CodeArtifact.(*types.CodeArtifactMemberUri); ok { |
| + v.Artifact = u.Value |
| + } |
| + return v, nil |
| +} |
| + |
| +func (p *Provider) ListImages(ctx context.Context, nameFilter string) ([]hostedimage.Image, error) { |
| + var all []hostedimage.Image |
| + var token, filter *string |
| + if nameFilter != "" { |
| + filter = aws.String(nameFilter) |
| + } |
| + seen := map[string]bool{} |
| + for range maxPages { |
| + out, err := p.vms.ListMicrovmImages(ctx, &vms.ListMicrovmImagesInput{NameFilter: filter, NextToken: token}) |
| + if err != nil { |
| + return nil, callErr("ListMicrovmImages", err) |
| + } |
| + for _, it := range out.Items { |
| + all = append(all, hostedimage.Image{ARN: aws.ToString(it.ImageArn), Name: aws.ToString(it.Name), State: string(it.State), |
| + LatestActiveVersion: aws.ToString(it.LatestActiveImageVersion)}) |
| + } |
| + next := aws.ToString(out.NextToken) |
| + if next == "" { |
| + return all, nil |
| + } |
| + if seen[next] { |
| + return nil, errPages |
| + } |
| + seen[next], token = true, out.NextToken |
| + } |
| + return nil, errPages |
| +} |
| + |
| +func (p *Provider) DeleteImage(ctx context.Context, id string) error { |
| + if _, err := p.vms.DeleteMicrovmImage(ctx, &vms.DeleteMicrovmImageInput{ImageIdentifier: aws.String(id)}); err != nil { |
| + return callErr("DeleteMicrovmImage", err) |
| + } |
| + return nil |
| +} |
| + |
| +func (p *Provider) GetConnector(ctx context.Context, id string) (hostedimage.Connector, error) { |
| + out, err := p.core.GetNetworkConnector(ctx, &lambdacore.GetNetworkConnectorInput{Identifier: aws.String(id)}) |
| + if err != nil { |
| + return hostedimage.Connector{}, callErr("GetNetworkConnector", err) |
| + } |
| + return hostedimage.Connector{ARN: aws.ToString(out.Arn), Name: aws.ToString(out.Name), State: string(out.State), |
| + Reason: aws.ToString(out.StateReason)}, nil |
| +} |
diff --git a/internal/isolatedjob/awsjob/imageaws/imageaws_test.go b/internal/isolatedjob/awsjob/imageaws/imageaws_test.go| new file mode 100644 |
| index 00000000..914ecb2d |
| --- /dev/null |
| +++ b/internal/isolatedjob/awsjob/imageaws/imageaws_test.go |
| @@ -0,0 +1,274 @@ |
| +package imageaws |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "net/http" |
| + "os" |
| + "path/filepath" |
| + "slices" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/hostedimage" |
| + "amadan.net/oficina/equipo/internal/isolatedjob" |
| + "amadan.net/oficina/equipo/internal/isolatedjob/awsjob/awsctl" |
| + "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/lambdacore" |
| + coretypes "github.com/aws/aws-sdk-go-v2/service/lambdacore/types" |
| + 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/sts" |
| + "github.com/aws/smithy-go" |
| + "github.com/aws/smithy-go/middleware" |
| +) |
| + |
| +func TestMain(m *testing.M) { os.Exit(budget.Main(m)) } |
| + |
| +const ( |
| + acct = "111122223333" |
| + region = "eu-west-1" |
| + prefix = "equipo-hosted-prod-1201-abcdef" |
| +) |
| + |
| +// stub is SDK middleware that answers every operation without a request |
| +// leaving the process: it records the operation and its input, and |
| +// returns answer's typed output at the end of the finalize step, after |
| +// signing, so the clients are the real ones awsctl.NewClients builds. |
| +type stub struct { |
| + mu sync.Mutex |
| + ops []string |
| + inputs []any |
| + answer func(op string, in any) (any, error) |
| +} |
| + |
| +type paramsKey struct{} |
| + |
| +func (s *stub) apply(stack *middleware.Stack) error { |
| + if err := stack.Initialize.Add(middleware.InitializeMiddlewareFunc("StubCapture", |
| + func(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) (middleware.InitializeOutput, middleware.Metadata, error) { |
| + return next.HandleInitialize(middleware.WithStackValue(ctx, paramsKey{}, in.Parameters), in) |
| + }), middleware.After); err != nil { |
| + return err |
| + } |
| + return stack.Finalize.Add(middleware.FinalizeMiddlewareFunc("StubAnswer", |
| + func(ctx context.Context, _ middleware.FinalizeInput, _ middleware.FinalizeHandler) (middleware.FinalizeOutput, middleware.Metadata, error) { |
| + op, in := awsmiddleware.GetOperationName(ctx), middleware.GetStackValue(ctx, paramsKey{}) |
| + s.mu.Lock() |
| + s.ops, s.inputs = append(s.ops, op), append(s.inputs, in) |
| + s.mu.Unlock() |
| + out, err := s.answer(op, in) |
| + return middleware.FinalizeOutput{Result: out}, middleware.Metadata{}, err |
| + }), middleware.After) |
| +} |
| + |
| +func (s *stub) seen() []string { |
| + s.mu.Lock() |
| + defer s.mu.Unlock() |
| + return slices.Clone(s.ops) |
| +} |
| + |
| +// noNetwork fails every request, so a stub that let one through could |
| +// never reach AWS. |
| +type noNetwork struct{} |
| + |
| +func (noNetwork) Do(*http.Request) (*http.Response, error) { |
| + return nil, errors.New("no request may leave the test") |
| +} |
| + |
| +// provider builds the real pinned clients with s answering them. |
| +func provider(s *stub) *Provider { |
| + cfg := aws.Config{Region: region, HTTPClient: noNetwork{}, |
| + Credentials: awsctl.FixedCredentials{Credentials: aws.Credentials{AccessKeyID: "AKIDOFFLINE", SecretAccessKey: "offline"}}} |
| + cfg.APIOptions = append(cfg.APIOptions, s.apply) |
| + return New(awsctl.NewClients(cfg, region, time.Minute)) |
| +} |
| + |
| +func imageARN(name string) string { |
| + return "arn:aws:lambda:" + region + ":" + acct + ":microvm-image:" + name |
| +} |
| + |
| +// healthy answers as a healthy account would, the caller being account. |
| +func healthy(account string) func(op string, in any) (any, error) { |
| + return func(op string, in any) (any, error) { |
| + switch op { |
| + case "GetCallerIdentity": |
| + return &sts.GetCallerIdentityOutput{Account: aws.String(account)}, nil |
| + case "ListManagedMicrovmImageVersions": |
| + return &vms.ListManagedMicrovmImageVersionsOutput{Items: []types.ManagedMicrovmImageVersion{ |
| + {ImageVersion: aws.String("3"), Status: types.ManagedMicrovmImageVersionStatusAvailable}, |
| + {ImageVersion: aws.String("4"), Status: types.ManagedMicrovmImageVersionStatusAvailable}}}, nil |
| + case "CreateMicrovmImage": |
| + c := in.(*vms.CreateMicrovmImageInput) |
| + return &vms.CreateMicrovmImageOutput{ImageArn: aws.String(imageARN(aws.ToString(c.Name))), Name: c.Name, ImageVersion: aws.String("1")}, nil |
| + case "GetMicrovmImageVersion": |
| + return &vms.GetMicrovmImageVersionOutput{ |
| + State: types.MicrovmImageVersionStateSuccessful, Status: types.MicrovmImageVersionStatusActive, |
| + AdditionalOsCapabilities: []types.Capability{types.CapabilityAll}, |
| + CpuConfigurations: []types.CpuConfiguration{{Architecture: types.ArchitectureX8664}}, |
| + Resources: []types.Resources{{MinimumMemoryInMiB: aws.Int32(4096)}}, |
| + Hooks: &types.Hooks{Port: aws.Int32(9000), MicrovmHooks: &types.MicrovmHooks{RunTimeoutInSeconds: aws.Int32(60)}}, |
| + CodeArtifact: &types.CodeArtifactMemberUri{Value: "s3://equipo-hosted-image-inputs/images/x.zip"}, |
| + BaseImageVersion: aws.String("4"), |
| + }, nil |
| + } |
| + return nil, errors.New("unexpected " + op) |
| + } |
| +} |
| + |
| +type fixedClock struct{ now time.Time } |
| + |
| +func (c *fixedClock) Now() time.Time { return c.now } |
| +func (c *fixedClock) Sleep(d time.Duration) { c.now = c.now.Add(d) } |
| + |
| +func request(t *testing.T) hostedimage.PublishRequest { |
| + return hostedimage.PublishRequest{ |
| + Name: prefix, Bucket: "equipo-hosted-image-inputs", Key: "images/x.zip", BaseVersion: "4", |
| + BuildRoleARN: "arn:aws:iam::" + acct + ":role/build", LogGroup: "/equipo-hosted/image-build", |
| + Size: isolatedjob.SizeLarge, Capabilities: "ALL", Ledger: t.TempDir(), Out: filepath.Join(t.TempDir(), "image.json"), |
| + Wait: hostedimage.Wait{Timeout: 45 * time.Minute, Interval: 15 * time.Second, Clock: &fixedClock{now: time.Unix(1_800_000_000, 0)}}, |
| + } |
| +} |
| + |
| +var target = hostedimage.Target{Account: acct, Region: region, Prefix: prefix} |
| + |
| +// TestPublishRefusesOtherAccountThroughSDK: through the real clients, |
| +// when STS names another account the only operation is |
| +// GetCallerIdentity. |
| +func TestPublishRefusesOtherAccountThroughSDK(t *testing.T) { |
| + s := &stub{answer: healthy("444455556666")} |
| + _, err := hostedimage.Publish(context.Background(), provider(s), target, request(t)) |
| + var f *hostedimage.Failure |
| + if !errors.As(err, &f) || f.Exit != hostedimage.ExitGuard { |
| + t.Fatalf("Publish = %v, want a guard refusal", err) |
| + } |
| + if got := s.seen(); !slices.Equal(got, []string{"GetCallerIdentity"}) { |
| + t.Fatalf("operations %v, want only GetCallerIdentity", got) |
| + } |
| +} |
| + |
| +// TestPublishThroughSDK: the whole publish through the real clients, in |
| +// order, and the create request as the API receives it. |
| +func TestPublishThroughSDK(t *testing.T) { |
| + s := &stub{answer: healthy(acct)} |
| + req := request(t) |
| + got, err := hostedimage.Publish(context.Background(), provider(s), target, req) |
| + if err != nil { |
| + t.Fatalf("Publish: %v", err) |
| + } |
| + want := []string{"GetCallerIdentity", "ListManagedMicrovmImageVersions", "CreateMicrovmImage", "GetMicrovmImageVersion"} |
| + if ops := s.seen(); !slices.Equal(ops, want) { |
| + t.Fatalf("operations %v, want %v", ops, want) |
| + } |
| + if got.VersionArn != imageARN(prefix)+":1" { |
| + t.Fatalf("VersionArn = %s", got.VersionArn) |
| + } |
| + in := s.inputs[2].(*vms.CreateMicrovmImageInput) |
| + h := in.Hooks |
| + switch { |
| + case aws.ToString(in.Name) != prefix, aws.ToString(in.ClientToken) == "", |
| + aws.ToString(in.BaseImageArn) != hostedimage.BaseImageARN(region), aws.ToString(in.BaseImageVersion) != "4", |
| + aws.ToString(in.BuildRoleArn) != req.BuildRoleARN, |
| + !slices.Equal(in.AdditionalOsCapabilities, []types.Capability{types.CapabilityAll}), |
| + len(in.CpuConfigurations) != 1 || in.CpuConfigurations[0].Architecture != types.ArchitectureX8664, |
| + len(in.Resources) != 1 || aws.ToInt32(in.Resources[0].MinimumMemoryInMiB) != 4096, |
| + h == nil || aws.ToInt32(h.Port) != 9000 || h.MicrovmHooks == nil || aws.ToInt32(h.MicrovmHooks.RunTimeoutInSeconds) != 60, |
| + h.MicrovmHooks.Run != types.HookStateEnabled || h.MicrovmImageHooks == nil || h.MicrovmImageHooks.Ready != types.HookStateEnabled, |
| + in.EgressNetworkConnectors != nil, in.EnvironmentVariables != nil: |
| + t.Fatalf("create input = %+v", in) |
| + } |
| + // The token sent is the one journalled before the call, never one the |
| + // SDK made up (it fills a random token when none is set). |
| + j, err := os.ReadFile(filepath.Join(req.Ledger, hostedimage.JournalFile)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + intent := "INTENT microvm-image " + prefix + " " + aws.ToString(in.ClientToken) + "\n" |
| + if !strings.Contains(string(j), "\t"+intent) { |
| + t.Fatalf("client token %q is not the journalled one:\n%s", aws.ToString(in.ClientToken), j) |
| + } |
| + if u, ok := in.CodeArtifact.(*types.CodeArtifactMemberUri); !ok || u.Value != "s3://equipo-hosted-image-inputs/images/x.zip" { |
| + t.Fatalf("code artifact = %#v", in.CodeArtifact) |
| + } |
| + if l, ok := in.Logging.(*types.LoggingMemberCloudWatch); !ok || aws.ToString(l.Value.LogGroup) != req.LogGroup { |
| + t.Fatalf("logging = %#v", in.Logging) |
| + } |
| +} |
| + |
| +// TestErrorsMapped: a not-found answer wraps hostedimage.ErrNotFound and |
| +// keeps the code; other answers keep theirs. |
| +func TestErrorsMapped(t *testing.T) { |
| + s := &stub{answer: func(op string, in any) (any, error) { |
| + if op == "GetMicrovmImage" { |
| + return nil, &smithy.GenericAPIError{Code: "ResourceNotFoundException", Message: "no image"} |
| + } |
| + return nil, &smithy.GenericAPIError{Code: "AccessDeniedException", Message: "no"} |
| + }} |
| + p := provider(s) |
| + _, err := p.GetImage(context.Background(), imageARN(prefix)) |
| + var ce *hostedimage.CallError |
| + if !errors.Is(err, hostedimage.ErrNotFound) || !errors.As(err, &ce) || ce.Code != "ResourceNotFoundException" || !ce.Answered { |
| + t.Fatalf("GetImage = %v, want ErrNotFound with its code", err) |
| + } |
| + err = p.DeleteImage(context.Background(), imageARN(prefix)) |
| + if errors.Is(err, hostedimage.ErrNotFound) || !errors.As(err, &ce) || ce.Code != "AccessDeniedException" || ce.Op != "DeleteMicrovmImage" { |
| + t.Fatalf("DeleteImage = %v", err) |
| + } |
| +} |
| + |
| +// TestPagesBounded: a list whose pages never end, or repeat a token, |
| +// stops with an error rather than reading on. |
| +func TestPagesBounded(t *testing.T) { |
| + n := 0 |
| + s := &stub{answer: func(op string, in any) (any, error) { |
| + n++ |
| + return &vms.ListMicrovmImagesOutput{NextToken: aws.String(strings.Repeat("t", 1+n%1000)), |
| + Items: []types.MicrovmImageSummary{{Name: aws.String(prefix)}}}, nil |
| + }} |
| + if _, err := provider(s).ListImages(context.Background(), prefix); err == nil || len(s.seen()) != 100 { |
| + t.Fatalf("ListImages = %v after %d pages, want an error after 100", err, len(s.seen())) |
| + } |
| + s = &stub{answer: func(op string, in any) (any, error) { |
| + return &vms.ListManagedMicrovmImageVersionsOutput{NextToken: aws.String("same")}, nil |
| + }} |
| + if _, err := provider(s).BaseVersions(context.Background(), "base"); err == nil || len(s.seen()) != 2 { |
| + t.Fatalf("BaseVersions = %v after %d pages, want an error at the repeat", err, len(s.seen())) |
| + } |
| +} |
| + |
| +// TestReadsMapped: the version, image and connector reads carry what the |
| +// guards judge. |
| +func TestReadsMapped(t *testing.T) { |
| + s := &stub{answer: func(op string, in any) (any, error) { |
| + switch op { |
| + case "GetMicrovmImage": |
| + return &vms.GetMicrovmImageOutput{ImageArn: aws.String(imageARN(prefix)), Name: aws.String(prefix), State: types.MicrovmImageStateCreated}, nil |
| + case "GetNetworkConnector": |
| + return &lambdacore.GetNetworkConnectorOutput{Arn: aws.String("arn:c"), Name: aws.String(prefix), State: coretypes.NetworkConnectorStateActive}, nil |
| + } |
| + return healthy(acct)(op, in) |
| + }} |
| + p := provider(s) |
| + if p.Region() != region { |
| + t.Fatalf("Region = %s", p.Region()) |
| + } |
| + v, err := p.GetImageVersion(context.Background(), imageARN(prefix), "1") |
| + if err != nil || v.State != "SUCCESSFUL" || v.Status != "ACTIVE" || !slices.Equal(v.Capabilities, []string{"ALL"}) || |
| + !slices.Equal(v.Architectures, []string{"X86_64"}) || !slices.Equal(v.MemoryMiB, []int{4096}) || v.HooksPort != 9000 || |
| + v.RunTimeout != 60 || v.BaseVersion != "4" || v.Artifact != "s3://equipo-hosted-image-inputs/images/x.zip" { |
| + t.Fatalf("GetImageVersion = %+v, %v", v, err) |
| + } |
| + if img, err := p.GetImage(context.Background(), imageARN(prefix)); err != nil || img.Name != prefix || img.State != "CREATED" { |
| + t.Fatalf("GetImage = %+v, %v", img, err) |
| + } |
| + if c, err := p.GetConnector(context.Background(), "arn:c"); err != nil || c.Name != prefix || c.State != "ACTIVE" { |
| + t.Fatalf("GetConnector = %+v, %v", c, err) |
| + } |
| + if a, err := p.CallerAccount(context.Background()); err != nil || a != acct { |
| + t.Fatalf("CallerAccount = %s, %v", a, err) |
| + } |
| +} |
diff --git a/internal/isolatedjob/awsjob/livectl/clients.go b/internal/isolatedjob/awsjob/livectl/clients.go| index 35c9615f..f6b0bf09 100644 |
| --- a/internal/isolatedjob/awsjob/livectl/clients.go |
| +++ b/internal/isolatedjob/awsjob/livectl/clients.go |
| @@ -3,67 +3,23 @@ |
| package main |
| import ( |
| - "context" |
| "time" |
| + "amadan.net/oficina/equipo/internal/isolatedjob/awsjob/awsctl" |
| "github.com/aws/aws-sdk-go-v2/aws" |
| "github.com/aws/aws-sdk-go-v2/service/lambdacore" |
| vms "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms" |
| "github.com/aws/aws-sdk-go-v2/service/sts" |
| - "github.com/aws/smithy-go/middleware" |
| ) |
| // callTimeout bounds each SDK request, the STS check included. A var so |
| // the offline tests can shorten it. |
| var callTimeout = 60 * time.Second |
| -// newClients builds the three clients from cfg, pinned so nothing in the |
| -// environment or the profile can steer them (livectl review round 1): |
| -// |
| -// - endpoints: every configured endpoint override is dropped |
| -// (AWS_ENDPOINT_URL, AWS_ENDPOINT_URL_<SERVICE>, a profile's |
| -// endpoint_url or services section), FIPS and dual-stack are off and |
| -// the region is wantRegion, so each call goes to the standard |
| -// wantRegion endpoint the SDK's own resolver gives; the STS answer the |
| -// account guard reads therefore comes from the same AWS the Lambda |
| -// calls reach; |
| -// - retries: exactly one attempt per call, whatever AWS_MAX_ATTEMPTS or |
| -// the profile's max_attempts and retry_mode say, so a failed mutation |
| -// is never resent behind the plan's back; |
| -// - deadlines: each call gets callTimeout on its context. |
| +// newClients builds the three clients from cfg, pinned to wantRegion's |
| +// standard endpoints, one attempt per call and callTimeout on each call |
| +// (awsctl.NewClients; livectl review round 1). |
| func newClients(cfg aws.Config) (*lambdacore.Client, *vms.Client, *sts.Client) { |
| - core := lambdacore.NewFromConfig(cfg, func(o *lambdacore.Options) { |
| - o.Region, o.BaseEndpoint = wantRegion, nil |
| - o.EndpointOptions = lambdacore.EndpointResolverOptions{} |
| - o.EndpointResolverV2 = lambdacore.NewDefaultEndpointResolverV2() |
| - o.Retryer, o.RetryMaxAttempts = aws.NopRetryer{}, 1 |
| - o.APIOptions = append(o.APIOptions, deadlineEach) |
| - }) |
| - vm := vms.NewFromConfig(cfg, func(o *vms.Options) { |
| - o.Region, o.BaseEndpoint = wantRegion, nil |
| - o.EndpointOptions = vms.EndpointResolverOptions{} |
| - o.EndpointResolverV2 = vms.NewDefaultEndpointResolverV2() |
| - o.Retryer, o.RetryMaxAttempts = aws.NopRetryer{}, 1 |
| - o.APIOptions = append(o.APIOptions, deadlineEach) |
| - }) |
| - st := sts.NewFromConfig(cfg, func(o *sts.Options) { |
| - o.Region, o.BaseEndpoint = wantRegion, nil |
| - o.EndpointOptions = sts.EndpointResolverOptions{} |
| - o.EndpointResolverV2 = sts.NewDefaultEndpointResolverV2() |
| - o.Retryer, o.RetryMaxAttempts = aws.NopRetryer{}, 1 |
| - o.APIOptions = append(o.APIOptions, deadlineEach) |
| - }) |
| - return core, vm, st |
| -} |
| - |
| -// deadlineEach adds callTimeout to the context of every operation, first in |
| -// the stack, so the whole call (signing, sending, reading the answer) is |
| -// bounded even when the caller's context is not. |
| -func deadlineEach(s *middleware.Stack) error { |
| - return s.Initialize.Add(middleware.InitializeMiddlewareFunc("LivectlCallDeadline", |
| - func(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) (middleware.InitializeOutput, middleware.Metadata, error) { |
| - ctx, cancel := context.WithTimeout(ctx, callTimeout) |
| - defer cancel() |
| - return next.HandleInitialize(ctx, in) |
| - }), middleware.Before) |
| + c := awsctl.NewClients(cfg, wantRegion, callTimeout) |
| + return c.Core, c.VMs, c.STS |
| } |
diff --git a/internal/isolatedjob/awsjob/livectl/creds.go b/internal/isolatedjob/awsjob/livectl/creds.go| index f9005a6c..4b14da9a 100644 |
| --- a/internal/isolatedjob/awsjob/livectl/creds.go |
| +++ b/internal/isolatedjob/awsjob/livectl/creds.go |
| @@ -6,8 +6,8 @@ import ( |
| "context" |
| "errors" |
| + "amadan.net/oficina/equipo/internal/isolatedjob/awsjob/awsctl" |
| "github.com/aws/aws-sdk-go-v2/aws" |
| - "github.com/aws/aws-sdk-go-v2/config" |
| ) |
| // Controller ruling R41: livectl resolves credentials once, at startup, |
| @@ -17,15 +17,15 @@ import ( |
| // provider is refused with exit 4 and a fixed message naming its kind: |
| // none of them is ever built, so no credential service is called, nothing |
| // refreshes, and every later call signs with exactly the keys the account |
| -// check saw. Resolution reads only the environment and the two files. |
| +// check saw. Resolution reads only the environment and the two files. The |
| +// rules live in awsctl, shared with equipo-hosted-image. |
| -// fixedCredentials hands out the same keys for the life of the process. |
| +// fixedCredentials hands out the same keys for the life of the process, |
| +// as awsctl.FixedCredentials does. |
| type fixedCredentials struct{ c aws.Credentials } |
| -func (f fixedCredentials) Retrieve(context.Context) (aws.Credentials, error) { |
| - c := f.c |
| - c.CanExpire, c.Source = false, "livectl static keys" |
| - return c, nil |
| +func (f fixedCredentials) Retrieve(ctx context.Context) (aws.Credentials, error) { |
| + return awsctl.FixedCredentials{Credentials: f.c}.Retrieve(ctx) |
| } |
| // refusedKind is the guard failure for a credential provider livectl will |
| @@ -34,81 +34,25 @@ func refusedKind(kind string) *failure { |
| return guard("credentials from %s are refused; livectl takes only static keys (R41)", kind) |
| } |
| -// profileKind names the non-static provider a profile asks for, or "". |
| -func profileKind(sc config.SharedConfig) string { |
| - switch { |
| - case sc.WebIdentityTokenFile != "": |
| - return "web identity" |
| - case sc.SSOSessionName != "" || sc.SSOSession != nil || sc.SSOStartURL != "" || sc.SSOAccountID != "" || sc.SSORoleName != "": |
| - return "SSO" |
| - case sc.CredentialProcess != "": |
| - return "credential_process" |
| - case sc.CredentialSource == "EcsContainer": |
| - return "container credentials" |
| - case sc.CredentialSource == "Ec2InstanceMetadata": |
| - return "instance metadata" |
| - case sc.CredentialSource != "": |
| - return "credential_source" |
| - case sc.RoleARN != "" || sc.SourceProfileName != "" || sc.Source != nil: |
| - return "assume role" |
| - case sc.LoginSession != "": |
| - return "login session" |
| - } |
| - return "" |
| -} |
| - |
| -// resolveCredentials returns the region and the static keys to use, in the |
| -// SDK's own order: keys in the environment; else the selected profile, |
| -// refused if it names any other provider; else a refusal naming what the |
| -// SDK would have fallen back to (web identity, the container endpoint or |
| -// instance metadata). |
| +// resolveCredentials returns the region and the static keys to use, from |
| +// AWS_PROFILE or the default profile (awsctl.ResolveStatic). |
| func resolveCredentials(ctx context.Context) (string, aws.Credentials, *failure) { |
| - ec, err := config.NewEnvConfig() |
| - if err != nil { |
| - return "", aws.Credentials{}, &failure{exit: exitOther, Kind: "other", Message: "the AWS environment settings did not parse"} |
| - } |
| - profile := ec.SharedConfigProfile |
| - if profile == "" { |
| - profile = "default" |
| - } |
| - cfgFile, credFile := ec.SharedConfigFile, ec.SharedCredentialsFile |
| - if cfgFile == "" { |
| - cfgFile = config.DefaultSharedConfigFilename() |
| - } |
| - if credFile == "" { |
| - credFile = config.DefaultSharedCredentialsFilename() |
| - } |
| - sc, err := config.LoadSharedConfigProfile(ctx, profile, func(o *config.LoadSharedConfigOptions) { |
| - o.ConfigFiles, o.CredentialsFiles = []string{cfgFile}, []string{credFile} |
| - }) |
| - var missing config.SharedConfigProfileNotExistError |
| - if err != nil && !errors.As(err, &missing) { |
| - return "", aws.Credentials{}, &failure{exit: exitOther, Kind: "other", Message: "the shared config or credentials file did not parse"} |
| - } |
| - region := ec.Region |
| - if region == "" { |
| - region = sc.Region |
| - } |
| + region, c, err := awsctl.ResolveStatic(ctx, "") |
| + var refused *awsctl.RefusedError |
| + var bad *awsctl.ConfigError |
| switch { |
| - case ec.Credentials.HasKeys(): |
| - return region, ec.Credentials, nil |
| - case profileKind(sc) != "": |
| - return "", aws.Credentials{}, refusedKind(profileKind(sc)) |
| - case sc.Credentials.HasKeys(): |
| - return region, sc.Credentials, nil |
| - case ec.WebIdentityTokenFilePath != "" || ec.RoleARN != "": |
| - return "", aws.Credentials{}, refusedKind("web identity") |
| - case ec.ContainerCredentialsEndpoint != "" || ec.ContainerCredentialsRelativePath != "": |
| - return "", aws.Credentials{}, refusedKind("container credentials") |
| - } |
| - return "", aws.Credentials{}, refusedKind("instance metadata") |
| + case errors.As(err, &refused): |
| + return "", aws.Credentials{}, refusedKind(refused.Kind) |
| + case errors.As(err, &bad): |
| + return "", aws.Credentials{}, &failure{exit: exitOther, Kind: "other", Message: bad.Message} |
| + case err != nil: |
| + return "", aws.Credentials{}, &failure{exit: exitOther, Kind: "other", Message: err.Error()} |
| + } |
| + return region, c, nil |
| } |
| // staticConfig is the only aws.Config livectl builds: the region and the |
| // resolved keys. No credential chain is ever created. |
| func staticConfig(region string, c aws.Credentials) aws.Config { |
| - if region == "" { |
| - region = wantRegion |
| - } |
| - return aws.Config{Region: region, Credentials: fixedCredentials{c}} |
| + return awsctl.StaticConfig(region, wantRegion, c) |
| } |
diff --git a/internal/isolatedjob/awsjob/livectl/image.go b/internal/isolatedjob/awsjob/livectl/image.go| index c3d24f85..e5c0f86d 100644 |
| --- a/internal/isolatedjob/awsjob/livectl/image.go |
| +++ b/internal/isolatedjob/awsjob/livectl/image.go |
| @@ -5,10 +5,9 @@ package main |
| import ( |
| "flag" |
| "slices" |
| - "strconv" |
| - "strings" |
| "time" |
| + "amadan.net/oficina/equipo/internal/hostedimage" |
| "github.com/aws/aws-sdk-go-v2/aws" |
| vms "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms" |
| "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms/types" |
| @@ -53,31 +52,9 @@ func cmdImageBaseVersions(fs *flag.FlagSet) func(*env) (any, error) { |
| } |
| } |
| -// compareVersions orders dotted versions by number, part by part ("10" after |
| -// "9", "3.1" after "3"); a part that is not a number compares as text. |
| -func compareVersions(a, b string) int { |
| - pa, pb := strings.Split(a, "."), strings.Split(b, ".") |
| - for i := range max(len(pa), len(pb)) { |
| - if i >= len(pa) { |
| - return -1 |
| - } |
| - if i >= len(pb) { |
| - return 1 |
| - } |
| - na, ea := strconv.Atoi(pa[i]) |
| - nb, eb := strconv.Atoi(pb[i]) |
| - var c int |
| - if ea == nil && eb == nil { |
| - c = na - nb |
| - } else { |
| - c = strings.Compare(pa[i], pb[i]) |
| - } |
| - if c != 0 { |
| - return c |
| - } |
| - } |
| - return 0 |
| -} |
| +// compareVersions orders dotted versions by number |
| +// (hostedimage.CompareVersions). |
| +func compareVersions(a, b string) int { return hostedimage.CompareVersions(a, b) } |
| // imageBuild is one image version's build settings, shared by create and |
| // update. The CPU is always x86_64 and the OS capabilities always ALL, as |
diff --git a/internal/isolatedjob/awsjob/livectl/main.go b/internal/isolatedjob/awsjob/livectl/main.go| index 1b0357ad..048ca43e 100644 |
| --- a/internal/isolatedjob/awsjob/livectl/main.go |
| +++ b/internal/isolatedjob/awsjob/livectl/main.go |
| @@ -45,14 +45,13 @@ import ( |
| "strings" |
| "time" |
| + "amadan.net/oficina/equipo/internal/isolatedjob/awsjob/awsctl" |
| "github.com/aws/aws-sdk-go-v2/aws" |
| awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" |
| - awshttp "github.com/aws/aws-sdk-go-v2/aws/transport/http" |
| "github.com/aws/aws-sdk-go-v2/service/lambdacore" |
| vms "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms" |
| "github.com/aws/aws-sdk-go-v2/service/sts" |
| "github.com/aws/smithy-go" |
| - smithyhttp "github.com/aws/smithy-go/transport/http" |
| ) |
| // The one account and region this tool works in. Changing them is a code |
| @@ -156,23 +155,14 @@ func guard(format string, args ...any) *failure { |
| } |
| // apiFailure describes a failed SDK call op: its error code, HTTP status |
| -// and request ID when the SDK has them. |
| +// and request ID when the SDK has them (awsctl.Describe). |
| func apiFailure(op string, err error) *failure { |
| - f := &failure{exit: exitAPI, Kind: "api", Op: op, Message: op + " failed"} |
| - var ae smithy.APIError |
| - if errors.As(err, &ae) { |
| - f.Code, f.AWSMessage = ae.ErrorCode(), ae.ErrorMessage() |
| - } else { |
| + ci := awsctl.Describe(err) |
| + f := &failure{exit: exitAPI, Kind: "api", Op: op, Message: op + " failed", |
| + Code: ci.Code, AWSMessage: ci.AWSMessage, Status: ci.Status, RequestID: ci.RequestID} |
| + if !ci.Answered { |
| f.Kind, f.Message = "transport", op+" failed before an answer came back" |
| } |
| - var he *smithyhttp.ResponseError |
| - if errors.As(err, &he) && he.Response != nil { |
| - f.Status = he.HTTPStatusCode() |
| - } |
| - var re *awshttp.ResponseError |
| - if errors.As(err, &re) { |
| - f.RequestID = re.ServiceRequestID() |
| - } |
| return f |
| } |
| @@ -288,16 +278,14 @@ func init() { |
| // checkCaller is the account and region guard every subcommand passes |
| // first. |
| func checkCaller(e *env) *failure { |
| - if e.region != wantRegion { |
| - return guard("region is %q, want %s", e.region, wantRegion) |
| - } |
| - out, err := e.sts.GetCallerIdentity(e.ctx, &sts.GetCallerIdentityInput{}) |
| - if err != nil { |
| + err := awsctl.CheckCaller(e.ctx, e.sts, e.region, wantRegion, wantAccount) |
| + var g *awsctl.GuardError |
| + switch { |
| + case errors.As(err, &g): |
| + return guard("%s", g.Message) |
| + case err != nil: |
| return apiFailure("GetCallerIdentity", err) |
| } |
| - if a := aws.ToString(out.Account); a != wantAccount { |
| - return guard("caller account is %q, want %s", a, wantAccount) |
| - } |
| return nil |
| } |
diff --git a/internal/isolatedjob/providerguard_test.go b/internal/isolatedjob/providerguard_test.go| index 4f678ea5..c428ad2c 100644 |
| --- a/internal/isolatedjob/providerguard_test.go |
| +++ b/internal/isolatedjob/providerguard_test.go |
| @@ -20,10 +20,13 @@ const guardModule = "amadan.net/oficina/equipo" |
| 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. |
| +// commands belong here: a library package that needs AWS is a leak. |
| +// cmd/equipo-vm-init, the proxy and equipo-hosted-certify import no AWS |
| +// package (slice 2 plan, global constraints); the image tool wires |
| +// awsjob/imageaws into internal/hostedimage, which holds no AWS type. |
| var providerAllowed = []string{ |
| guardModule + "/cmd/equipo-hosted-controller", |
| + guardModule + "/cmd/equipo-hosted-image", |
| } |
| // TestProviderTypesStayInAdapter keeps the AWS SDK and the adapter out of |
diff --git a/internal/vminit/measure.go b/internal/vminit/measure.go| index e34a9925..f6b1a6c2 100644 |
| --- a/internal/vminit/measure.go |
| +++ b/internal/vminit/measure.go |
| @@ -7,9 +7,7 @@ import ( |
| "encoding/hex" |
| "fmt" |
| "io" |
| - "maps" |
| "os" |
| - "slices" |
| "syscall" |
| ) |
| @@ -22,15 +20,6 @@ const ( |
| RootProbeFile = "root.json" |
| ) |
| -// The names in measured.json. Each policy file also appears under |
| -// MeasuredPolicyPrefix and its path. |
| -const ( |
| - MeasuredRunner = "runner" // the runner binary |
| - MeasuredVMInit = "vm_init" // vm-init, read from /proc/self/exe |
| - MeasuredSandboxPolicy = "sandbox_policy" // PolicySetDigest of the policy files |
| - MeasuredPolicyPrefix = "policy:" |
| -) |
| - |
| // measure hashes the runner, vm-init itself and each policy file. |
| func measure(runner, self string, policies []string) (map[string]string, error) { |
| m := map[string]string{} |
| @@ -52,18 +41,6 @@ func measure(runner, self string, policies []string) (map[string]string, error) |
| return m, nil |
| } |
| -// PolicySetDigest is the sandbox policy set's one digest, as a |
| -// certificate's SandboxPolicy records it: the hex SHA-256 of one line |
| -// "<hex SHA-256> <path>\n" per file (sha256sum's format), sorted by |
| -// path. files maps each path to its hex SHA-256. |
| -func PolicySetDigest(files map[string]string) string { |
| - h := sha256.New() |
| - for _, p := range slices.Sorted(maps.Keys(files)) { |
| - fmt.Fprintf(h, "%s %s\n", files[p], p) |
| - } |
| - return hex.EncodeToString(h.Sum(nil)) |
| -} |
| - |
| func fileSHA256(path string) (string, error) { |
| f, err := os.Open(path) |
| if err != nil { |
diff --git a/internal/vminit/measured.go b/internal/vminit/measured.go| new file mode 100644 |
| index 00000000..a520af5b |
| --- /dev/null |
| +++ b/internal/vminit/measured.go |
| @@ -0,0 +1,34 @@ |
| +package vminit |
| + |
| +import ( |
| + "crypto/sha256" |
| + "encoding/hex" |
| + "fmt" |
| + "maps" |
| + "slices" |
| +) |
| + |
| +// This file builds on every platform: the image tool (hostedimage) |
| +// computes the digests vm-init measures, and certification (Task 13) |
| +// compares them, without the rest of root init. |
| + |
| +// The names in measured.json. Each policy file also appears under |
| +// MeasuredPolicyPrefix and its path. |
| +const ( |
| + MeasuredRunner = "runner" // the runner binary |
| + MeasuredVMInit = "vm_init" // vm-init, read from /proc/self/exe |
| + MeasuredSandboxPolicy = "sandbox_policy" // PolicySetDigest of the policy files |
| + MeasuredPolicyPrefix = "policy:" |
| +) |
| + |
| +// PolicySetDigest is the sandbox policy set's one digest, as a |
| +// certificate's SandboxPolicy records it: the hex SHA-256 of one line |
| +// "<hex SHA-256> <path>\n" per file (sha256sum's format), sorted by |
| +// path. files maps each path to its hex SHA-256. |
| +func PolicySetDigest(files map[string]string) string { |
| + h := sha256.New() |
| + for _, p := range slices.Sorted(maps.Keys(files)) { |
| + fmt.Fprintf(h, "%s %s\n", files[p], p) |
| + } |
| + return hex.EncodeToString(h.Sum(nil)) |
| +} |