oficina / equipo Public

hostedimage: scan payloads, bwrap at /usr/bin, check whole hooks

Task 10 review round 1. The build scans every pinned input before it
writes the zip, with the repository's gitleaks configuration and a
forbidden-path check, opening the Go tarball and each RPM's payload;
reviewed findings are allowed only by exact member and digest. The
pinned bwrap goes to /usr/bin/bwrap, where the containment suite runs
it, and every pinned binary is checked at its final path. Publish reads
back and compares the whole hook configuration. Each command checks its
own arguments before reading credentials, and a release must pin
packages.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev c46f3073b6766ab5fa6b8101f66fecade017328d parent 68a373f
19 files changed, +1,334 −81
  • Makefile +7 −4
  • cmd/equipo-hosted-image/main.go +21 −6
  • cmd/equipo-hosted-image/main_test.go +43 −6
  • docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md +55 −0
  • go.mod +2 −2
  • infra/hosted/image/Dockerfile.tmpl +5 −1
  • infra/hosted/image/manifest.json +3 −2
  • internal/hostedimage/build.go +43 −4
  • internal/hostedimage/build_test.go +33 −11
  • internal/hostedimage/hostedimagetest/hostedimagetest.go +173 −0
  • internal/hostedimage/manifest.go +41 −4
  • internal/hostedimage/manifest_test.go +17 −0
  • internal/hostedimage/publish.go +46 −27
  • internal/hostedimage/publish_test.go +15 −5
  • internal/hostedimage/rpm.go +265 −0
  • internal/hostedimage/scan.go +273 −0
  • internal/hostedimage/scan_test.go +212 −0
  • internal/isolatedjob/awsjob/imageaws/imageaws.go +24 −6
  • internal/isolatedjob/awsjob/imageaws/imageaws_test.go +56 −3
diff --git a/Makefile b/Makefile
index ffb4c59c..149685a3 100644
--- a/Makefile
+++ b/Makefile
@@ -220,12 +220,15 @@ gitleaks:
# 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.
+# image's own checks: every input pinned, the zip byte-reproducible, the
+# payload scan refusing a secret or forbidden path inside a pinned binary,
+# tarball or RPM, and bubblewrap installed where the containment suite
+# runs it. The real payloads are scanned by the build itself
+# (equipo-hosted-image build), with this repository's .gitleaks.toml. 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
+ CGO_ENABLED=0 go test ./internal/hostedimage -run '^(TestManifestPinsEverything|TestBuildReproducible|TestBuildChecksPins|TestImageInputsHaveNoSecrets|TestBuildScansPayload|TestScanAllowExact|TestBuildNeedsGitleaksConfig|TestImageLayoutMatchesContainmentSuite)$$' -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
diff --git a/cmd/equipo-hosted-image/main.go b/cmd/equipo-hosted-image/main.go
index b6320bdf..c8ece9d3 100644
--- a/cmd/equipo-hosted-image/main.go
+++ b/cmd/equipo-hosted-image/main.go
@@ -3,8 +3,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
+// build -manifest FILE -inputs DIR [-gitleaks-config FILE] -out FILE
+// scans every pinned input (archives and RPMs file by file) with the
+// repository's gitleaks configuration and the forbidden-path check,
+// then 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
@@ -144,11 +146,15 @@ func run(ctx context.Context, args []string, stdout, stderr io.Writer, connect c
}
fs := flag.NewFlagSet(rest[0], flag.ContinueOnError)
fs.SetOutput(io.Discard)
+ // step is the command; check refuses its arguments, global and its
+ // own, before any credential is read.
var step func(hostedimage.Provider) (any, error)
+ check := t.Check
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")
+ gitleaks := fs.String("gitleaks-config", "", "the gitleaks configuration the payload scan uses (default: the nearest .gitleaks.toml above the manifest)")
out := fs.String("out", "", "the zip to write")
if err := parse(fs, rest[1:]); err != nil {
return report(stderr, err)
@@ -156,7 +162,7 @@ func run(ctx context.Context, args []string, stdout, stderr io.Writer, connect c
if *manifest == "" || *inputs == "" || *out == "" {
return report(stderr, usage("build needs -manifest, -inputs and -out"))
}
- res, err := build(*manifest, *inputs, *out)
+ res, err := build(*manifest, *inputs, *gitleaks, *out)
return finish(stdout, stderr, res, err)
case "publish":
var r hostedimage.PublishRequest
@@ -178,6 +184,7 @@ func run(ctx context.Context, args []string, stdout, stderr io.Writer, connect c
return report(stderr, err)
}
r.Size, r.Tags, r.Wait = isolatedjob.Size(*size), tags, wait()
+ check = func() error { return r.Check(t) }
step = func(p hostedimage.Provider) (any, error) { return hostedimage.Publish(ctx, p, t, r) }
case "list":
if err := parse(fs, rest[1:]); err != nil {
@@ -193,6 +200,7 @@ func run(ctx context.Context, args []string, stdout, stderr io.Writer, connect c
if err := parse(fs, rest[1:]); err != nil {
return report(stderr, err)
}
+ check = func() error { return hostedimage.CheckDelete(t, *arn, wait()) }
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")
@@ -200,12 +208,13 @@ func run(ctx context.Context, args []string, stdout, stderr io.Writer, connect c
if err := parse(fs, rest[1:]); err != nil {
return report(stderr, err)
}
+ check = func() error { return hostedimage.CheckConnectorWait(t, *arn, wait()) }
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 {
+ // Every argument is checked before any credential is read.
+ if err := check(); err != nil {
return report(stderr, err)
}
p, err := connect(ctx, *profile, t.Region)
@@ -247,12 +256,18 @@ type buildResult struct {
Measured map[string]string // what vm-init's measured.json must hold
}
-func build(manifest, inputs, out string) (buildResult, error) {
+func build(manifest, inputs, gitleaks, out string) (buildResult, error) {
m, err := hostedimage.LoadManifest(manifest)
if err != nil {
return buildResult{}, usage("%v", err)
}
m.Inputs = inputs
+ if gitleaks != "" {
+ m.GitleaksConfig = gitleaks
+ }
+ if m.GitleaksConfig == "" {
+ return buildResult{}, usage("no .gitleaks.toml above %s; give -gitleaks-config", m.Dir)
+ }
inv, err := hostedimage.Build(m, out)
if err != nil {
return buildResult{}, err
diff --git a/cmd/equipo-hosted-image/main_test.go b/cmd/equipo-hosted-image/main_test.go
index 9662724a..188f9bcc 100644
--- a/cmd/equipo-hosted-image/main_test.go
+++ b/cmd/equipo-hosted-image/main_test.go
@@ -13,6 +13,7 @@ import (
"testing"
"amadan.net/oficina/equipo/internal/hostedimage"
+ "amadan.net/oficina/equipo/internal/hostedimage/hostedimagetest"
"amadan.net/rastrillo/rastrillo/budget"
)
@@ -67,9 +68,16 @@ func TestBuildReadsNoCredentials(t *testing.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 {
+ bodies := map[string][]byte{
+ "go1.26.11.linux-amd64.tar.gz": hostedimagetest.TarGz(map[string][]byte{"go/bin/go": []byte("fake go")}),
+ "pkgs/git.rpm": hostedimagetest.RPM(map[string][]byte{"/usr/bin/git": []byte("fake git")}, "gzip"),
+ }
+ for _, name := range []string{"equipo-runner", "equipo-vm-init", "bwrap", "codex", "containment.test", "go1.26.11.linux-amd64.tar.gz", "pkgs/git.rpm"} {
+ body, ok := bodies[name]
+ if !ok {
+ body = []byte("fake " + name)
+ }
+ if err := os.MkdirAll(filepath.Join(in, "pkgs"), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(in, name), body, 0o755); err != nil {
@@ -89,7 +97,7 @@ func TestBuildReadsNoCredentials(t *testing.T) {
"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"},
+ "Packages": []map[string]string{{"Name": "git.rpm", "SHA256": sums["pkgs/git.rpm"]}}, "Policies": []string{hostedimage.PathBwrap}, "Resolvers": []string{"10.0.0.2"},
"Metadata": []string{"169.254.169.254:80"},
}
b, _ := json.Marshal(m)
@@ -97,7 +105,8 @@ func TestBuildReadsNoCredentials(t *testing.T) {
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)...)
+ gl := "-gitleaks-config=../../.gitleaks.toml"
+ code, stdout, stderr := runCmd(t, noConnect(t), append(global, "build", "-manifest", filepath.Join(dir, "manifest.json"), "-inputs", in, gl, "-out", out)...)
if code != 0 {
t.Fatalf("build = %d: %s", code, stderr)
}
@@ -121,7 +130,7 @@ func TestBuildReadsNoCredentials(t *testing.T) {
}
// 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 {
+ if code, _, stderr := runCmd(t, noConnect(t), "build", "-manifest", filepath.Join(dir, "manifest.json"), "-inputs", in, gl, "-out", out); code != 0 {
t.Fatalf("build without global flags = %d: %s", code, stderr)
}
}
@@ -142,6 +151,34 @@ func TestFlagsCheckedBeforeCredentials(t *testing.T) {
}
}
+// TestCommandArgsCheckedBeforeCredentials (review round 1, finding 4):
+// with good global flags, a command's own bad arguments are refused
+// before any credential is read.
+func TestCommandArgsCheckedBeforeCredentials(t *testing.T) {
+ marker := credentialTrap(t)
+ good := []string{"-ledger", t.TempDir(), "-name", prefix, "-bucket", "equipo-hosted-image-inputs", "-key", "images/x.zip",
+ "-base-version", "4", "-build-role-arn", "arn:aws:iam::" + acct + ":role/build", "-log-group", "/equipo-hosted/image-build",
+ "-size", "large", "-capabilities", "ALL", "-out", filepath.Join(t.TempDir(), "image.json")}
+ for name, args := range map[string][]string{
+ "publish, unknown size": append(append([]string{"publish"}, good...), "-size", "huge"),
+ "publish, foreign name": append(append([]string{"publish"}, good...), "-name", "someone-else"),
+ "publish, role in another acct": append(append([]string{"publish"}, good...), "-build-role-arn", "arn:aws:iam::444455556666:role/b"),
+ "publish, wait too long": append(append([]string{"publish"}, good...), "-timeout", "3h"),
+ "delete, image of another acct": {"delete", "-arn", "arn:aws:lambda:" + region + ":444455556666:microvm-image:" + prefix},
+ "delete, no arn": {"delete"},
+ "connector-wait, not a connector": {"connector-wait", "-arn", "arn:aws:lambda:" + region + ":" + acct + ":microvm-image:" + prefix},
+ "connector-wait, interval 0": {"connector-wait", "-arn", "arn:aws:lambda:" + region + ":" + acct + ":network-connector:nc-1", "-interval", "0s"},
+ } {
+ code, _, stderr := runCmd(t, noConnect(t), append(slices.Clone(global), args...)...)
+ if code != hostedimage.ExitUsage && code != hostedimage.ExitGuard {
+ t.Errorf("%s = %d %s, want a usage or guard refusal", name, code, stderr)
+ }
+ }
+ if _, err := os.Stat(marker); err == nil {
+ t.Fatal("credentials were resolved")
+ }
+}
+
// 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) {
diff --git a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
index 16041eb7..e40e0060 100644
--- a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
+++ b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
@@ -538,3 +538,58 @@ Mutation checks (each applied by script, the named test run with `CGO_ENABLED=0
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.
+
+### Task 10 review round 1 (t10-r1.md: all four findings fixed, and empty Packages)
+
+1. **Payload scan.**
+ - `Build` now scans every pinned input before it writes the zip (`internal/hostedimage/scan.go`, `rpm.go`). It uses gitleaks as a library, with the repository's `.gitleaks.toml`: `LoadManifest` finds the nearest one above the manifest, and `build -gitleaks-config` overrides it.
+ - It scans:
+ - each plain binary whole;
+ - each member of the Go tarball, by name and by bytes;
+ - each RPM by the names its header lists and the files of its cpio payload. The payload can be gzip, bzip2, xz, lzma or zstd; an unknown compressor, payload format or cpio header stops the build.
+ - Names also go through `ForbiddenPath`: SSH, AWS, Codex, Claude and other homes, `.git`, netrc, git, docker and npm configuration, `auth.json`, `credentials`, `id_*` keys and key files.
+ - A finding stops the build. The only exception is a manifest `ScanAllow` entry naming that exact input, member and the member's SHA-256, with a reason. An allowance that matches nothing also stops it.
+ - Large members are scanned in overlapping 1 MiB chunks. The refusal names the place and the rule, never the secret.
+ - Each input is read once for the scan and once for the copy, and both reads are checked against the same pin.
+ - gitleaks extends a config with its defaults through a package counter it never resets, so the translated config is cached per process, keyed by the config text.
+ - The fixtures are a real tarball and real RPMs (`internal/hostedimage/hostedimagetest`). Their secrets are assembled at run time, so the repository's own gitleaks scan stays clean.
+ - TestImageInputsHaveNoSecrets now reads the `files/` entries too. It keeps the files-beside-the-inputs exclusion.
+2. **bwrap path.**
+ - `PathBwrap` is now `/usr/bin/bwrap`, the path the containment suite runs. The Dockerfile installs it after the packages.
+ - The last step checks every installed pinned binary at its final path (`sha256sum --check`).
+ - The checked-in policy set is `["/usr/bin/bwrap"]`, measured there. New TestImageLayoutMatchesContainmentSuite reads the suite's sources for the host bwrap path, then checks the rendered Dockerfile's order and final check, the measured digest and vm-init's `-policy`.
+3. **Hooks.**
+ - `Version.Hooks` is now the whole configuration, nil when the answer has none. `imageaws.readHooks` maps every field, and a missing structure reads as zero.
+ - Publish refuses any difference from `ImageSettings().Hooks`: the port, every hook's state and timeout, `/ready` enabled and validate disabled.
+ - New cases in TestPublishWaitBounded: ready, run or terminate disabled; validate enabled; run or ready timeout changed; no hooks; no image hooks; no VM hooks.
+ - New TestHooksReadBackWhole, through the real clients: ready or run disabled; image, VM or all hooks missing; a run timeout changed; a ready timeout or the port absent.
+ - The SDK fixture's version answer is now the full configuration, written out as the API gives it.
+4. **Command arguments.** `PublishRequest.Check`, `CheckDelete` and `CheckConnectorWait` are exported. The command runs each one before `connect`. New TestCommandArgsCheckedBeforeCredentials covers a bad size, a foreign name, a role in another account, a wait over the bound, a delete in another account or with no ARN, a wait on a non-connector ARN, and a 0 s interval, each refused without resolving credentials.
+5. **Packages.** `Validate` now refuses an empty `Packages`; `ValidateStatic` still allows it. TestManifestPinsEverything checks both, and checks that the checked-in scaffold fails the full check.
+
+`go.mod`: `go mod tidy` moved `klauspost/compress` and `ulikunitz/xz` from indirect to direct requires, with no version change.
+
+Mutation checks. Each was applied by script and the named test run with `CGO_ENABLED=0 go test <pkg> -run '^<Test>$' -count=1`. Every run compiled and failed on its assertion, and the file was restored and checked by SHA-256.
+
+30. Payload scan skipped. TestBuildScansPayload: FAIL, `scan_test.go:73: Build = <nil>, want a payload scan refusal`. Restored.
+31. Tarball members not opened. TestBuildScansPayload: FAIL, `scan_test.go:73` (the tarball cases). Restored.
+32. RPM payload not read. TestBuildScansPayload: FAIL, `scan_test.go:73` (the RPM cases). Restored.
+33. RPM header-only names not judged. TestBuildScansPayload: FAIL, `scan_test.go:73` (netrc ghost). Restored.
+34. Forbidden paths not checked. TestBuildScansPayload: FAIL, `scan_test.go:73` (SSH, git, AWS credentials, OAuth home). Restored.
+35. Allowance ignores the member's digest. TestScanAllowExact: FAIL, `scan_test.go:123: Build with an allowance for other bytes = <nil>, want the finding and the unused allowance`. Restored.
+36. Unused allowance ignored. TestScanAllowExact: FAIL, `scan_test.go:123: ... (forbidden-path); ... (private-key), want the finding and the unused allowance`. Restored.
+37. bwrap back at /usr/local/bin. TestImageLayoutMatchesContainmentSuite: FAIL, `scan_test.go:181: the containment suite runs bwrap from map[/usr/bin/bwrap:true]; the image installs it at /usr/local/bin/bwrap`. Restored.
+38. Final in-place digest check dropped from Dockerfile.tmpl. TestImageLayoutMatchesContainmentSuite: FAIL, `scan_test.go:199: the Dockerfile does not check /usr/bin/bwrap against its pin at the end`. Restored.
+39. Packages installed after bwrap. TestImageLayoutMatchesContainmentSuite: FAIL, `scan_test.go:197: the pinned bwrap is not installed after the packages`. Restored.
+40. Hook configuration not compared. TestPublishWaitBounded: FAIL, `publish_test.go:390: terminate disabled: a built version that differs was accepted`, `:393: -out written`. Restored.
+41. Missing image hooks read as declared (readHooks fills them from the settings). TestHooksReadBackWhole: FAIL, `imageaws_test.go:166: Publish = <nil>, want a mismatch refusal`. Restored.
+42. Command arguments checked after credentials. TestCommandArgsCheckedBeforeCredentials: FAIL, `main_test.go:33: the command read credentials`. Restored.
+43. Empty package list accepted. TestManifestPinsEverything: FAIL, `manifest_test.go:98: no packages: Validate = nil, want a refusal`, `:161`. Restored.
+44. No gitleaks configuration means no scan. The first form only made the scan conditional; it passed because Build's own empty-config check refuses first. The second form removes both layers. TestBuildNeedsGitleaksConfig: FAIL, `scan_test.go:139: Build without a gitleaks configuration = nil`. Restored.
+
+Also run:
+- `CGO_ENABLED=0 go test ./internal/hostedimage/... ./internal/isolatedjob/... ./internal/vminit ./cmd/equipo-hosted-image -count=1`: ok.
+- livectl with `-tags hostedlive`: ok.
+- `make budget build vet hosted-image-check`: ok (134 directories within budget).
+- lanes-check, staticcheck v0.7.0 and gitleaks `dir` on the new directories: clean. `detect.Fragment` carries one `lint:ignore SA1019`, because gitleaks v8's `Detect` takes that type.
+- gofmt and `git diff --check`: clean.
diff --git a/go.mod b/go.mod
index d24264e2..b9c3cca8 100644
--- a/go.mod
+++ b/go.mod
@@ -30,9 +30,11 @@ require (
github.com/aws/aws-sdk-go-v2/service/sns v1.48.0
github.com/aws/aws-sdk-go-v2/service/sts v1.53.0
github.com/aws/smithy-go v1.28.9
+ github.com/klauspost/compress v1.20.2
github.com/rs/zerolog v1.33.0
github.com/spf13/viper v1.19.0
github.com/sqids/sqids-go v0.4.1
+ github.com/ulikunitz/xz v0.5.15
golang.org/x/crypto v0.55.0
golang.org/x/net v0.58.0
)
@@ -77,7 +79,6 @@ require (
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/huandu/xstrings v1.5.0 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
- github.com/klauspost/compress v1.20.2 // indirect
github.com/klauspost/pgzip v1.2.6 // indirect
github.com/lucasb-eyer/go-colorful v1.2.0 // indirect
github.com/magiconair/properties v1.8.9 // indirect
@@ -112,7 +113,6 @@ require (
github.com/tdewolff/parse/v2 v2.8.16 // indirect
github.com/tetratelabs/wazero v1.9.0 // indirect
github.com/therootcompany/xz v1.0.1 // indirect
- github.com/ulikunitz/xz v0.5.15 // indirect
github.com/wasilibs/go-re2 v1.9.0 // indirect
github.com/wasilibs/wazero-helpers v0.0.0-20240620070341-3dff1577cd52 // indirect
github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
diff --git a/infra/hosted/image/Dockerfile.tmpl b/infra/hosted/image/Dockerfile.tmpl
index 67ac603c..ce191ba5 100644
--- a/infra/hosted/image/Dockerfile.tmpl
+++ b/infra/hosted/image/Dockerfile.tmpl
@@ -3,7 +3,10 @@
# 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).
+# empty (vm-init's /ready hook refuses the build otherwise). The pinned
+# files go in after the packages, bubblewrap at /usr/bin/bwrap where the
+# containment suite runs it, and the last step checks each one again at
+# its final path, so no package or later step can stand in for it.
FROM public.ecr.aws/lambda/microvms:al2023-minimal
COPY files/ /tmp/equipo-image/
RUN set -eu; \
@@ -30,6 +33,7 @@ RUN set -eu; \
cp -a /etc {{.EtcSource}}; \
rm -f {{.EtcSource}}/resolv.conf; \
install -m 0644 -o root -g root /dev/null {{.EtcSource}}/resolv.conf; \
+ printf '%s\n'{{range .Installed}} '{{.}}'{{end}} | sha256sum --check --strict; \
cd /; \
rm -rf /tmp/equipo-image
CMD {{.Cmd}}
diff --git a/infra/hosted/image/manifest.json b/infra/hosted/image/manifest.json
index e0f0d72f..ed5881ff 100644
--- a/infra/hosted/image/manifest.json
+++ b/infra/hosted/image/manifest.json
@@ -9,7 +9,8 @@
"CodexSHA256": "c06a67fd8ac76508dc78bd99ce20c9f317b8d568beda59485f3f4134df9962d5",
"ContainmentTestSHA256": "",
"Packages": [],
- "Policies": ["/usr/local/bin/bwrap"],
+ "Policies": ["/usr/bin/bwrap"],
"Resolvers": [],
- "Metadata": ["169.254.169.254:80"]
+ "Metadata": ["169.254.169.254:80"],
+ "ScanAllow": []
}
diff --git a/internal/hostedimage/build.go b/internal/hostedimage/build.go
index 56825c1f..c55c768e 100644
--- a/internal/hostedimage/build.go
+++ b/internal/hostedimage/build.go
@@ -134,8 +134,8 @@ 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")
+ if m.Dir == "" || m.Inputs == "" || m.GitleaksConfig == "" {
+ return Inventory{}, errors.New("hostedimage: build needs the manifest's directory, the inputs directory and the gitleaks configuration")
}
dockerfile, err := renderDockerfile(m)
if err != nil {
@@ -154,9 +154,12 @@ func Build(m Manifest, out string) (Inventory, error) {
{name: "image.json", mode: 0o644, data: append(settings, '\n')},
{name: "manifest.json", mode: 0o644, data: append(manifest, '\n')},
}
+ if err := scanPayload(m, entries); err != nil {
+ return Inventory{}, err
+ }
for _, f := range m.files() {
mode := os.FileMode(0o644)
- if strings.HasPrefix(f.dest, "/usr/local/") && f.dest != "/usr/local/go" {
+ if f.dest != "" && f.dest != "/usr/local/go" {
mode = 0o755
}
entries = append(entries, entry{name: f.entry, mode: mode, input: f})
@@ -219,6 +222,38 @@ func Build(m Manifest, out string) (Inventory, error) {
return inv, nil
}
+// scanPayload is the payload scan (scan.go): every pinned input, read and
+// checked against its pin, and the entries made here. It runs before the
+// zip is written; the copy that follows checks each pin again, so the
+// bytes scanned are the bytes carried.
+func scanPayload(m Manifest, made []entry) error {
+ d, err := loadDetector(m.GitleaksConfig)
+ if err != nil {
+ return err
+ }
+ s := &scanner{d: d}
+ for _, e := range made {
+ s.scanBytes(e.name, "", e.data)
+ }
+ for _, f := range m.files() {
+ var b bytes.Buffer
+ if err := copyInput(&b, filepath.Join(m.Inputs, filepath.FromSlash(f.input))); err != nil {
+ return err
+ }
+ if got := sha256Hex(b.Bytes()); got != f.sha {
+ return fmt.Errorf("hostedimage: input %s is %s, the manifest pins %s", f.input, got, f.sha)
+ }
+ if err := s.scanInput(f.input, b.Bytes()); err != nil {
+ return err
+ }
+ }
+ left, unused := judge(s.findings, m.ScanAllow)
+ if len(left) > 0 || len(unused) > 0 {
+ return &ScanError{Findings: left, Unused: unused}
+ }
+ return 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 {
@@ -253,7 +288,7 @@ const TemplateFile = "Dockerfile.tmpl"
// names, addresses).
type dockerData struct {
Manifest Manifest
- Sums []string
+ Sums, Installed []string
PathRunner, PathVMInit, PathBwrap, PathCodex, PathContainmentTest string
StateDir, ResultsDir, EtcSource, EtcParent, RunnerUser string
Cmd string
@@ -297,8 +332,12 @@ func renderDockerfile(m Manifest) ([]byte, error) {
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/"))
+ if f.dest != "" && f.dest != "/usr/local/go" {
+ d.Installed = append(d.Installed, f.sha+" "+f.dest)
+ }
}
slices.Sort(d.Sums)
+ slices.Sort(d.Installed)
var b bytes.Buffer
if err := tmpl.Execute(&b, d); err != nil {
return nil, fmt.Errorf("hostedimage: %s: %w", TemplateFile, err)
diff --git a/internal/hostedimage/build_test.go b/internal/hostedimage/build_test.go
index a70aa5e4..a0789fbc 100644
--- a/internal/hostedimage/build_test.go
+++ b/internal/hostedimage/build_test.go
@@ -14,37 +14,62 @@ import (
"strings"
"testing"
"time"
+
+ "amadan.net/oficina/equipo/internal/hostedimage/hostedimagetest"
)
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.
+// complete manifest pinning them, with the checked-in Dockerfile.tmpl and
+// the repository's gitleaks configuration. The Go toolchain is a real
+// tarball and the package a real RPM, so the payload scan opens them.
func fixture(t *testing.T) Manifest {
t.Helper()
in := t.TempDir()
m := validManifest()
m.Dir = filepath.Join(repoRoot, "infra", "hosted", "image")
+ m.GitleaksConfig = filepath.Join(repoRoot, ".gitleaks.toml")
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,
+ "equipo-runner": &m.RunnerSHA256,
+ "equipo-vm-init": &m.VMInitSHA256,
+ "bwrap": &m.BubblewrapSHA256,
+ "codex": &m.CodexSHA256,
+ "containment.test": &m.ContainmentTestSHA256,
}
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")
+ goTar := hostedimagetest.TarGz(map[string][]byte{"go/bin/go": []byte("fake go\n"), "go/VERSION": []byte("go1.26.11\n")})
+ write(t, filepath.Join(in, m.GoToolchain+".linux-amd64.tar.gz"), goTar, 0o644)
+ m.GoToolchainSHA256 = sum(goTar)
+ body := hostedimagetest.RPM(map[string][]byte{"/usr/bin/git": []byte("fake git\n")}, "gzip")
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
}
+// setInput replaces one input of m with body and pins it.
+func setInput(t *testing.T, m *Manifest, input string, body []byte) {
+ t.Helper()
+ write(t, filepath.Join(m.Inputs, input), body, 0o644)
+ switch input {
+ case "equipo-runner":
+ m.RunnerSHA256 = sum(body)
+ case "codex":
+ m.CodexSHA256 = sum(body)
+ case m.GoToolchain + ".linux-amd64.tar.gz":
+ m.GoToolchainSHA256 = sum(body)
+ case "pkgs/" + m.Packages[0].Name:
+ m.Packages = []Pinned{{Name: m.Packages[0].Name, SHA256: sum(body)}}
+ default:
+ t.Fatalf("setInput: no pin for %s", input)
+ }
+}
+
func write(t *testing.T, path string, body []byte, mode os.FileMode) {
t.Helper()
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
@@ -288,9 +313,6 @@ func TestImageInputsHaveNoSecrets(t *testing.T) {
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()
diff --git a/internal/hostedimage/hostedimagetest/hostedimagetest.go b/internal/hostedimage/hostedimagetest/hostedimagetest.go
new file mode 100644
index 00000000..42e5b358
--- /dev/null
+++ b/internal/hostedimage/hostedimagetest/hostedimagetest.go
@@ -0,0 +1,173 @@
+// Package hostedimagetest builds the archives the image tool's tests
+// carry as pinned inputs: a gzip tarball and an RPM with a cpio payload,
+// each holding the files a test chooses. Tests only.
+package hostedimagetest
+
+import (
+ "archive/tar"
+ "bytes"
+ "compress/gzip"
+ "encoding/binary"
+ "fmt"
+ "path"
+ "slices"
+ "strings"
+
+ "github.com/klauspost/compress/zstd"
+ "github.com/ulikunitz/xz"
+)
+
+// TarGz is a gzip tarball of files (name to bytes), in name order, with
+// each file's parent directories.
+func TarGz(files map[string][]byte) []byte {
+ var b bytes.Buffer
+ zw := gzip.NewWriter(&b)
+ tw := tar.NewWriter(zw)
+ dirs := map[string]bool{}
+ for _, name := range slices.Sorted(mapKeys(files)) {
+ for d := path.Dir(name); d != "." && !dirs[d]; d = path.Dir(d) {
+ dirs[d] = true
+ }
+ }
+ for _, d := range slices.Sorted(mapKeys(dirs)) {
+ _ = tw.WriteHeader(&tar.Header{Name: d + "/", Typeflag: tar.TypeDir, Mode: 0o755})
+ }
+ for _, name := range slices.Sorted(mapKeys(files)) {
+ _ = tw.WriteHeader(&tar.Header{Name: name, Typeflag: tar.TypeReg, Mode: 0o644, Size: int64(len(files[name]))})
+ _, _ = tw.Write(files[name])
+ }
+ _ = tw.Close()
+ _ = zw.Close()
+ return b.Bytes()
+}
+
+func mapKeys[V any](m map[string]V) func(func(string) bool) {
+ return func(yield func(string) bool) {
+ for k := range m {
+ if !yield(k) {
+ return
+ }
+ }
+ }
+}
+
+// RPM is an RPM whose header lists files (absolute paths to bytes) and
+// whose payload is a newc cpio archive of them, compressed with
+// compressor ("gzip", "zstd" or "xz"). ghosts are listed in the header
+// but not carried.
+func RPM(files map[string][]byte, compressor string, ghosts ...string) []byte {
+ var out bytes.Buffer
+ lead := make([]byte, 96)
+ copy(lead, []byte{0xed, 0xab, 0xee, 0xdb, 3, 0})
+ out.Write(lead)
+ out.Write(header(nil)) // signature header: no entries, 16 bytes, aligned
+ names := slices.Sorted(mapKeys(files))
+ listed := append(slices.Clone(names), ghosts...)
+ var dirs, bases []string
+ var idx []int32
+ for _, n := range listed {
+ d, b := path.Dir(n)+"/", path.Base(n)
+ i := slices.Index(dirs, d)
+ if i < 0 {
+ dirs, i = append(dirs, d), len(dirs)
+ }
+ bases, idx = append(bases, b), append(idx, int32(i))
+ }
+ out.Write(header([]entry{
+ {1117, 8, strs(bases...), len(bases)},
+ {1118, 8, strs(dirs...), len(dirs)},
+ {1116, 4, ints(idx...), len(idx)},
+ {1124, 6, strs("cpio"), 1},
+ {1125, 6, strs(compressor), 1},
+ }))
+ var cp bytes.Buffer
+ pad := func() {
+ for cp.Len()%4 != 0 {
+ cp.WriteByte(0)
+ }
+ }
+ write := func(name string, mode int, data []byte) {
+ fmt.Fprintf(&cp, "070701%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x",
+ 1, mode, 0, 0, 1, 0, len(data), 0, 0, 0, 0, len(name)+1, 0)
+ cp.WriteString(name)
+ cp.WriteByte(0)
+ pad()
+ cp.Write(data)
+ pad()
+ }
+ for _, n := range names {
+ write("."+n, 0o100644, files[n])
+ }
+ write("TRAILER!!!", 0, nil)
+ switch compressor {
+ case "zstd":
+ w, _ := zstd.NewWriter(&out)
+ _, _ = w.Write(cp.Bytes())
+ _ = w.Close()
+ case "xz":
+ w, _ := xz.NewWriter(&out)
+ _, _ = w.Write(cp.Bytes())
+ _ = w.Close()
+ default:
+ w := gzip.NewWriter(&out)
+ _, _ = w.Write(cp.Bytes())
+ _ = w.Close()
+ }
+ return out.Bytes()
+}
+
+type entry struct {
+ tag, typ int
+ data []byte
+ count int
+}
+
+func strs(s ...string) []byte { return []byte(strings.Join(s, "\x00") + "\x00") }
+
+func ints(v ...int32) []byte {
+ b := make([]byte, 4*len(v))
+ for i, x := range v {
+ binary.BigEndian.PutUint32(b[i*4:], uint32(x))
+ }
+ return b
+}
+
+func header(es []entry) []byte {
+ var index, data bytes.Buffer
+ for _, e := range es {
+ for e.typ == 4 && data.Len()%4 != 0 {
+ data.WriteByte(0)
+ }
+ var ie [16]byte
+ binary.BigEndian.PutUint32(ie[0:], uint32(e.tag))
+ binary.BigEndian.PutUint32(ie[4:], uint32(e.typ))
+ binary.BigEndian.PutUint32(ie[8:], uint32(data.Len()))
+ binary.BigEndian.PutUint32(ie[12:], uint32(e.count))
+ index.Write(ie[:])
+ data.Write(e.data)
+ }
+ var h bytes.Buffer
+ h.Write([]byte{0x8e, 0xad, 0xe8, 0x01, 0, 0, 0, 0})
+ var n [8]byte
+ binary.BigEndian.PutUint32(n[0:], uint32(len(es)))
+ binary.BigEndian.PutUint32(n[4:], uint32(data.Len()))
+ h.Write(n[:])
+ h.Write(index.Bytes())
+ h.Write(data.Bytes())
+ return h.Bytes()
+}
+
+// The secret-shaped values the scan tests plant. They are assembled at
+// run time so this file's own text holds none of them.
+var (
+ // AWSKey is an access key ID of the shape gitleaks' aws-access-token
+ // rule matches.
+ AWSKey = "AKIA" + "QYLPMN5HJWFRZAM2"
+ // PrivateKey is a PEM private key block.
+ PrivateKey = "-----BEGIN " + "OPENSSH PRIVATE KEY-----\n" +
+ strings.Repeat("b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAAB", 4) + "\n" +
+ "-----END " + "OPENSSH PRIVATE KEY-----\n"
+ // GitHubToken is a personal access token of the shape gitleaks'
+ // github-pat rule matches.
+ GitHubToken = "gh" + "p_" + "Zq8RvT2mK9xLw4NpB7cY3dHf6JgS1aE5uV0i"
+)
diff --git a/internal/hostedimage/manifest.go b/internal/hostedimage/manifest.go
index e84aa876..3dfcacdf 100644
--- a/internal/hostedimage/manifest.go
+++ b/internal/hostedimage/manifest.go
@@ -24,6 +24,7 @@ import (
"reflect"
"regexp"
"slices"
+ "strings"
"amadan.net/oficina/equipo/internal/vminit"
)
@@ -64,6 +65,10 @@ type Manifest struct {
// the MicroVM's values live.
Resolvers []string
Metadata []string
+ // ScanAllow are reviewed payload-scan findings the build accepts, each
+ // bound to one member's SHA-256 (scan.go). Empty unless a release's
+ // real inputs need one.
+ ScanAllow []ScanAllowed
// Dir is the directory holding manifest.json and Dockerfile.tmpl;
// LoadManifest sets it.
@@ -71,14 +76,21 @@ type Manifest struct {
// Inputs is the directory holding the pinned files, by their input
// names (InputName). Nothing else in it is read.
Inputs string `json:"-"`
+ // GitleaksConfig is the repository's .gitleaks.toml, which the
+ // payload scan uses; LoadManifest finds the nearest one above Dir.
+ GitleaksConfig 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"
+ PathRunner = "/usr/local/bin/equipo-runner"
+ PathVMInit = "/usr/local/sbin/equipo-vm-init"
+ // PathBwrap is where the containment suite and the runner's
+ // sandbox expect bubblewrap (internal/runner/containment uses
+ // /usr/bin/bwrap): the pinned binary goes there, after the packages,
+ // so no distribution copy can stand in for it.
+ PathBwrap = "/usr/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
@@ -156,6 +168,12 @@ func (m Manifest) validate(static bool) error {
if !goRelease.MatchString(m.GoToolchain) {
return bad("GoToolchain", "%q is not a Go release such as go1.26.11", m.GoToolchain)
}
+ if len(m.Packages) == 0 && !static {
+ // git (GitSHA256) and whatever else the base lacks come only
+ // from pinned packages; a release with none cannot pass the
+ // Dockerfile's git check.
+ return bad("Packages", "a release pins at least one package (git comes from them)")
+ }
seen := map[string]bool{}
for _, p := range m.Packages {
if !rpmName.MatchString(p.Name) || seen[p.Name] {
@@ -166,12 +184,30 @@ func (m Manifest) validate(static bool) error {
return bad("Packages", "%s's digest %q is not 64 lower-case hex digits", p.Name, p.SHA256)
}
}
- installed := map[string]bool{}
+ installed, inputs := map[string]bool{}, map[string]bool{}
for _, f := range m.files() {
+ inputs[f.input] = true
if f.dest != "" {
installed[f.dest] = true
}
}
+ seen = map[string]bool{}
+ for _, a := range m.ScanAllow {
+ key := a.Input + "\x00" + a.Member
+ switch {
+ case !inputs[a.Input]:
+ return bad("ScanAllow", "%q is not a pinned input", a.Input)
+ case a.Member != "" && (path.IsAbs(a.Member) || path.Clean(a.Member) != a.Member || strings.HasPrefix(a.Member, "../")):
+ return bad("ScanAllow", "member %q is not a clean relative path", a.Member)
+ case !hexDigest.MatchString(a.SHA256):
+ return bad("ScanAllow", "%s:%s's digest %q is not 64 lower-case hex digits", a.Input, a.Member, a.SHA256)
+ case strings.TrimSpace(a.Reason) == "":
+ return bad("ScanAllow", "%s:%s has no reason", a.Input, a.Member)
+ case seen[key]:
+ return bad("ScanAllow", "%s:%s is listed twice", a.Input, a.Member)
+ }
+ seen[key] = true
+ }
if len(m.Policies) == 0 {
return bad("Policies", "the sandbox policy set is empty")
}
@@ -245,6 +281,7 @@ func LoadManifest(file string) (Manifest, error) {
return Manifest{}, fmt.Errorf("hostedimage: %s: %w", file, err)
}
m.Dir = filepath.Dir(file)
+ m.GitleaksConfig = FindGitleaksConfig(m.Dir)
return m, nil
}
diff --git a/internal/hostedimage/manifest_test.go b/internal/hostedimage/manifest_test.go
index 680504f6..1125556c 100644
--- a/internal/hostedimage/manifest_test.go
+++ b/internal/hostedimage/manifest_test.go
@@ -83,6 +83,13 @@ func TestManifestPinsEverything(t *testing.T) {
"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" },
+ "no packages": func(m *Manifest) { m.Packages = nil },
+ "allowance for no input": func(m *Manifest) { m.ScanAllow = []ScanAllowed{{Input: "other", SHA256: hex64('a'), Reason: "r"}} },
+ "allowance without a reason": func(m *Manifest) { m.ScanAllow = []ScanAllowed{{Input: "codex", SHA256: hex64('a')}} },
+ "allowance without a digest": func(m *Manifest) { m.ScanAllow = []ScanAllowed{{Input: "codex", Reason: "r"}} },
+ "allowance escaping its input": func(m *Manifest) {
+ m.ScanAllow = []ScanAllowed{{Input: "codex", Member: "../x", SHA256: hex64('a'), Reason: "r"}}
+ },
} {
m := validManifest()
m.Packages = append([]Pinned(nil), m.Packages...)
@@ -146,6 +153,16 @@ func TestManifestPinsEverything(t *testing.T) {
if len(checked.Metadata) == 0 {
t.Error("checked-in manifest has no metadata endpoint for vm-init")
}
+ // A release with no packages fails the full check but is a valid
+ // scaffold between releases.
+ noPkgs := validManifest()
+ noPkgs.Packages = nil
+ if noPkgs.ValidateStatic() != nil || noPkgs.Validate() == nil {
+ t.Error("an empty package list: want ValidateStatic to pass and Validate to refuse")
+ }
+ if err := checked.Validate(); err == nil {
+ t.Error("the checked-in scaffold passes the full check; a release must fill it first")
+ }
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
index 1d34fc66..bc4426ba 100644
--- a/internal/hostedimage/publish.go
+++ b/internal/hostedimage/publish.go
@@ -82,12 +82,14 @@ type Image struct {
ARN, Name, State, LatestActiveVersion string
}
-// Version is an image version as read.
+// Version is an image version as read. Hooks is nil when the answer has
+// no hook configuration; a missing inner structure reads as its zero
+// value (no state, no timeout).
type Version struct {
State, Status, Reason string
Capabilities, Architectures []string
MemoryMiB []int
- HooksPort, RunTimeout int
+ Hooks *Hooks
Artifact, BaseVersion string
}
@@ -287,8 +289,12 @@ 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 {
+// Check refuses a target or request the tool will not send, before any
+// call and before any credential is read.
+func (r PublishRequest) Check(t Target) error {
+ if err := t.Check(); err != nil {
+ return err
+ }
if !t.InPrefix(r.Name) {
return guard("image name %q is outside prefix %s", r.Name, t.Prefix)
}
@@ -433,10 +439,7 @@ func writeJSON(path string, v any) error {
// (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 {
+ if err := r.Check(t); err != nil {
return Published{}, err
}
if err := checkCaller(ctx, p, t); err != nil {
@@ -511,7 +514,7 @@ func Publish(ctx context.Context, p Provider, t Target, r PublishRequest) (Publi
// 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.
+// the whole hook configuration, the artifact and the base version.
func sameVersion(v Version, req CreateImage) error {
s := req.Settings
var cpu []string
@@ -530,10 +533,14 @@ func sameVersion(v Version, req CreateImage) error {
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.Hooks == nil:
+ return mismatch("hook configuration", "missing", s.Hooks)
+ case *v.Hooks != s.Hooks:
+ // Every hook the image declares, as declared: the port, /run and
+ // the other VM hooks enabled with their timeouts, /ready enabled
+ // (it refuses a build whose state directory is not empty), and
+ // validate disabled.
+ return mismatch("hook configuration", *v.Hooks, s.Hooks)
case v.Artifact != req.Artifact:
return mismatch("code artifact", v.Artifact, req.Artifact)
case v.BaseVersion != req.BaseVersion:
@@ -547,13 +554,7 @@ func sameVersion(v Version, req CreateImage) error {
// 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 {
+ if err := CheckDelete(t, arn, w); err != nil {
return Image{}, err
}
if err := checkCaller(ctx, p, t); err != nil {
@@ -590,6 +591,30 @@ func Delete(ctx context.Context, p Provider, t Target, arn string, w Wait) (Imag
return last, err
}
+// CheckDelete refuses a delete the tool will not run, before any call:
+// the ARN must be an image in the target's account and region.
+func CheckDelete(t Target, arn string, w Wait) error {
+ if err := t.Check(); err != nil {
+ return err
+ }
+ if _, ok := t.arnIn(arn, "microvm-image"); !ok {
+ return guard("-arn %q is not an image in account %s, region %s", arn, t.Account, t.Region)
+ }
+ return w.check()
+}
+
+// CheckConnectorWait refuses a connector wait the tool will not run,
+// before any call.
+func CheckConnectorWait(t Target, arn string, w Wait) error {
+ if err := t.Check(); err != nil {
+ return err
+ }
+ if _, ok := t.arnIn(arn, "network-connector"); !ok {
+ return guard("-arn %q is not a network connector in account %s, region %s", arn, t.Account, t.Region)
+ }
+ return w.check()
+}
+
// 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) {
@@ -618,13 +643,7 @@ func List(ctx context.Context, p Provider, t Target) ([]Image, error) {
// 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 {
+ if err := CheckConnectorWait(t, arn, w); err != nil {
return Connector{}, err
}
if err := checkCaller(ctx, p, t); err != nil {
diff --git a/internal/hostedimage/publish_test.go b/internal/hostedimage/publish_test.go
index 9f145f3b..90f36324 100644
--- a/internal/hostedimage/publish_test.go
+++ b/internal/hostedimage/publish_test.go
@@ -119,7 +119,7 @@ func (c *fakeClock) Sleep(d time.Duration) { c.now = c.now.Add(d) }
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,
+ MemoryMiB: []int{req.Size.MemoryMiB()}, Hooks: &s.Hooks,
Artifact: "s3://" + req.Bucket + "/" + req.Key, BaseVersion: base}
}
@@ -365,10 +365,20 @@ func TestPublishWaitBounded(t *testing.T) {
"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" },
+ "hooks port": func(v *Version) { v.Hooks.Port = 8080 },
+ // The hook configuration, whole (review round 1, finding 3).
+ "ready disabled": func(v *Version) { v.Hooks.Image.Ready = "DISABLED" },
+ "run disabled": func(v *Version) { v.Hooks.Microvm.Run = "DISABLED" },
+ "terminate disabled": func(v *Version) { v.Hooks.Microvm.Terminate = "DISABLED" },
+ "validate enabled": func(v *Version) { v.Hooks.Image.Validate = "ENABLED" },
+ "run timeout changed": func(v *Version) { v.Hooks.Microvm.RunTimeout = 30 },
+ "ready timeout changed": func(v *Version) { v.Hooks.Image.ReadyTimeout = 60 },
+ "no hook configuration": func(v *Version) { v.Hooks = nil },
+ "no image hooks": func(v *Version) { v.Hooks.Image = ImageHooks{} },
+ "no microvm hooks": func(v *Version) { v.Hooks.Microvm = MicrovmHooks{} },
+ "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)
diff --git a/internal/hostedimage/rpm.go b/internal/hostedimage/rpm.go
new file mode 100644
index 00000000..18dc48ef
--- /dev/null
+++ b/internal/hostedimage/rpm.go
@@ -0,0 +1,265 @@
+package hostedimage
+
+import (
+ "bufio"
+ "bytes"
+ "compress/bzip2"
+ "compress/gzip"
+ "encoding/binary"
+ "errors"
+ "fmt"
+ "io"
+ "path"
+ "strconv"
+ "strings"
+
+ "github.com/klauspost/compress/zstd"
+ "github.com/ulikunitz/xz"
+ "github.com/ulikunitz/xz/lzma"
+)
+
+// An RPM file is a 96-byte lead, a signature header padded to 8 bytes, the
+// main header and a compressed cpio payload. The scan reads the file names
+// the main header lists and every file of the payload. Anything it cannot
+// read (another payload format, an unknown compressor, a cpio header it
+// does not know) stops the build: an input that cannot be scanned is not
+// carried.
+
+// The header tags the scan reads.
+const (
+ rpmTagOldFilenames = 1027
+ rpmTagDirIndexes = 1116
+ rpmTagBasenames = 1117
+ rpmTagDirNames = 1118
+ rpmTagPayloadFormat = 1124
+ rpmTagPayloadCompressor = 1125
+)
+
+var (
+ rpmLeadMagic = []byte{0xed, 0xab, 0xee, 0xdb}
+ rpmHeaderMagic = []byte{0x8e, 0xad, 0xe8, 0x01}
+)
+
+// rpmHeader is one header structure's tags: strings and string arrays
+// as []string, int32 arrays as []int32.
+type rpmHeader struct {
+ strs map[int32][]string
+ ints map[int32][]int32
+}
+
+// maxRPMHeader bounds a header's index and data.
+const maxRPMHeader = 64 << 20
+
+// readRPMHeader reads one header structure from r and returns it and its
+// length in bytes.
+func readRPMHeader(r io.Reader) (rpmHeader, int, error) {
+ var pre [16]byte
+ if _, err := io.ReadFull(r, pre[:]); err != nil {
+ return rpmHeader{}, 0, err
+ }
+ if !bytes.Equal(pre[:4], rpmHeaderMagic) {
+ return rpmHeader{}, 0, errors.New("bad header magic")
+ }
+ n, size := binary.BigEndian.Uint32(pre[8:12]), binary.BigEndian.Uint32(pre[12:16])
+ if uint64(n)*16+uint64(size) > maxRPMHeader {
+ return rpmHeader{}, 0, errors.New("header too large")
+ }
+ index := make([]byte, int(n)*16)
+ data := make([]byte, int(size))
+ if _, err := io.ReadFull(r, index); err != nil {
+ return rpmHeader{}, 0, err
+ }
+ if _, err := io.ReadFull(r, data); err != nil {
+ return rpmHeader{}, 0, err
+ }
+ h := rpmHeader{strs: map[int32][]string{}, ints: map[int32][]int32{}}
+ for i := range int(n) {
+ e := index[i*16:]
+ tag := int32(binary.BigEndian.Uint32(e[0:4]))
+ typ := binary.BigEndian.Uint32(e[4:8])
+ off := binary.BigEndian.Uint32(e[8:12])
+ count := binary.BigEndian.Uint32(e[12:16])
+ if off > size {
+ return rpmHeader{}, 0, errors.New("header entry outside its data")
+ }
+ d := data[off:]
+ switch typ {
+ case 4: // INT32
+ if uint64(count)*4 > uint64(len(d)) {
+ return rpmHeader{}, 0, errors.New("header entry outside its data")
+ }
+ for j := range int(count) {
+ h.ints[tag] = append(h.ints[tag], int32(binary.BigEndian.Uint32(d[j*4:])))
+ }
+ case 6, 8, 9: // STRING, STRING_ARRAY, I18NSTRING
+ if typ == 6 {
+ count = 1
+ }
+ for range int(count) {
+ end := bytes.IndexByte(d, 0)
+ if end < 0 {
+ return rpmHeader{}, 0, errors.New("unterminated header string")
+ }
+ h.strs[tag] = append(h.strs[tag], string(d[:end]))
+ d = d[end+1:]
+ }
+ }
+ }
+ return h, 16 + len(index) + len(data), nil
+}
+
+// rpmFiles is the file list a main header gives.
+func (h rpmHeader) files() ([]string, error) {
+ if old := h.strs[rpmTagOldFilenames]; len(old) > 0 {
+ return old, nil
+ }
+ base, dirs, idx := h.strs[rpmTagBasenames], h.strs[rpmTagDirNames], h.ints[rpmTagDirIndexes]
+ if len(base) != len(idx) {
+ return nil, errors.New("file list tags disagree")
+ }
+ var out []string
+ for i, b := range base {
+ if idx[i] < 0 || int(idx[i]) >= len(dirs) {
+ return nil, errors.New("file list tags disagree")
+ }
+ out = append(out, dirs[idx[i]]+b)
+ }
+ return out, nil
+}
+
+// payloadReader decompresses an RPM payload.
+func payloadReader(compressor string, r io.Reader) (io.Reader, error) {
+ switch compressor {
+ case "gzip", "":
+ return gzip.NewReader(r)
+ case "bzip2":
+ return bzip2.NewReader(r), nil
+ case "xz":
+ return xz.NewReader(r)
+ case "lzma":
+ return lzma.NewReader(r)
+ case "zstd":
+ d, err := zstd.NewReader(r)
+ if err != nil {
+ return nil, err
+ }
+ return d.IOReadCloser(), nil
+ }
+ return nil, fmt.Errorf("payload compressor %q is not one the scan reads", compressor)
+}
+
+func (s *scanner) scanRPM(input string, b []byte) error {
+ bad := func(format string, a ...any) error {
+ return fmt.Errorf("hostedimage: %s: "+format, append([]any{input}, a...)...)
+ }
+ if len(b) < 96 || !bytes.Equal(b[:4], rpmLeadMagic) {
+ return bad("not an RPM")
+ }
+ r := bytes.NewReader(b[96:])
+ _, n, err := readRPMHeader(r)
+ if err != nil {
+ return bad("signature header: %v", err)
+ }
+ if pad := (8 - n%8) % 8; pad > 0 {
+ if _, err := r.Seek(int64(pad), io.SeekCurrent); err != nil {
+ return bad("signature header: %v", err)
+ }
+ }
+ h, _, err := readRPMHeader(r)
+ if err != nil {
+ return bad("main header: %v", err)
+ }
+ files, err := h.files()
+ if err != nil {
+ return bad("%v", err)
+ }
+ if f := first(h.strs[rpmTagPayloadFormat]); f != "cpio" && f != "" {
+ return bad("payload format %q is not one the scan reads", f)
+ }
+ pr, err := payloadReader(first(h.strs[rpmTagPayloadCompressor]), r)
+ if err != nil {
+ return bad("payload: %v", err)
+ }
+ seen := map[string]bool{}
+ if err := s.scanCpio(input, bufio.NewReader(pr), seen); err != nil {
+ return err
+ }
+ // A name the header lists but the payload does not carry (a %ghost
+ // file) is judged by its name alone.
+ for _, f := range files {
+ if name := strings.TrimPrefix(path.Clean(f), "/"); !seen[name] {
+ s.scanName(input, name, "")
+ }
+ }
+ return nil
+}
+
+func first(s []string) string {
+ if len(s) == 0 {
+ return ""
+ }
+ return s[0]
+}
+
+// scanCpio scans each file of a "newc" cpio archive (magic 070701) by
+// name and bytes, and marks each name in seen.
+func (s *scanner) scanCpio(input string, r io.Reader, seen map[string]bool) error {
+ bad := func(format string, a ...any) error {
+ return fmt.Errorf("hostedimage: %s payload: "+format, append([]any{input}, a...)...)
+ }
+ var pos int64
+ skip := func(n int64) error {
+ _, err := io.CopyN(io.Discard, r, n)
+ pos += n
+ return err
+ }
+ pad4 := func() error { return skip((4 - pos%4) % 4) }
+ for {
+ var hdr [110]byte
+ if _, err := io.ReadFull(r, hdr[:]); err != nil {
+ return bad("cpio header: %v", err)
+ }
+ pos += 110
+ if string(hdr[:6]) != "070701" {
+ return bad("cpio magic %q is not newc", hdr[:6])
+ }
+ field := func(i int) (int64, error) {
+ return strconv.ParseInt(string(hdr[6+i*8:14+i*8]), 16, 64)
+ }
+ mode, err1 := field(1)
+ size, err2 := field(6)
+ nameSize, err3 := field(11)
+ if err := errors.Join(err1, err2, err3); err != nil || nameSize < 1 || nameSize > 4096 || size < 0 || size > maxMember {
+ return bad("cpio header fields")
+ }
+ nameBuf := make([]byte, nameSize)
+ if _, err := io.ReadFull(r, nameBuf); err != nil {
+ return bad("cpio name: %v", err)
+ }
+ pos += nameSize
+ name := string(bytes.TrimRight(nameBuf, "\x00"))
+ if err := pad4(); err != nil {
+ return bad("cpio: %v", err)
+ }
+ if name == "TRAILER!!!" {
+ return nil
+ }
+ name = strings.TrimPrefix(path.Clean(strings.TrimPrefix(name, ".")), "/")
+ seen[name] = true
+ body := make([]byte, size)
+ if _, err := io.ReadFull(r, body); err != nil {
+ return bad("cpio data: %v", err)
+ }
+ pos += size
+ if err := pad4(); err != nil {
+ return bad("cpio: %v", err)
+ }
+ if mode&0o170000 == 0o100000 { // a regular file
+ sum := sha256Hex(body)
+ s.scanName(input, name, sum)
+ s.scanBytes(input, name, body)
+ } else {
+ s.scanName(input, name, "")
+ }
+ }
+}
diff --git a/internal/hostedimage/scan.go b/internal/hostedimage/scan.go
new file mode 100644
index 00000000..223e3f6a
--- /dev/null
+++ b/internal/hostedimage/scan.go
@@ -0,0 +1,273 @@
+package hostedimage
+
+import (
+ "archive/tar"
+ "bytes"
+ "compress/gzip"
+ "crypto/sha256"
+ "encoding/hex"
+ "errors"
+ "fmt"
+ "io"
+ "os"
+ "path"
+ "path/filepath"
+ "regexp"
+ "slices"
+ "strings"
+ "sync"
+
+ "github.com/spf13/viper"
+ "github.com/zricethezav/gitleaks/v8/config"
+ "github.com/zricethezav/gitleaks/v8/detect"
+)
+
+// The payload scan (spec §4: the image holds no token, key, OAuth home,
+// forge credential, person's configuration or repository). A checksum
+// proves which bytes the image carries, not that they are clean, so Build
+// scans every pinned input before it writes the zip:
+//
+// - each plain file (the binaries) whole;
+// - each member of the Go tarball, by its name and its bytes;
+// - each file of each RPM, by the names its header lists and by the
+// bytes of its payload (rpm.go).
+//
+// Bytes go through gitleaks with the repository's own configuration
+// (.gitleaks.toml, extending gitleaks' defaults); names go through
+// ForbiddenPath. Nested archives inside a member are scanned as bytes,
+// not opened. A finding stops the build unless the manifest's ScanAllow
+// names that exact member and its SHA-256 (a reviewed false positive,
+// such as a test key in the Go tree's testdata); an allowance that
+// matches nothing also stops it, so the list stays exact.
+
+// ForbiddenPath matches paths that would put a credential, a person's
+// configuration or a repository in the image: SSH, AWS, Codex, Claude and
+// other tool homes, git repositories and configuration, netrc, docker and
+// npm configuration, OAuth token files, credential files and key files.
+var ForbiddenPath = regexp.MustCompile(`(?i)(^|/)(\.ssh|\.aws|\.codex|\.claude|\.config|\.git|\.gnupg|\.kube|\.docker|\.netrc|_netrc|\.gitconfig|\.git-credentials|\.npmrc|\.pypirc|auth\.json|credentials(\.json)?|id_(rsa|dsa|ecdsa|ed25519)(_sk)?|[^/]*\.(pem|key|p12|pfx|jks|keystore))(/|$)`)
+
+// ScanAllowed is one reviewed scan finding the build accepts: the input
+// (its name in the inputs directory), the member inside it ("" for the
+// file itself), that member's SHA-256, and why.
+type ScanAllowed struct {
+ Input, Member, SHA256, Reason string
+}
+
+// Finding is one scan result. It names the rule, never the matched text.
+type Finding struct {
+ Input, Member, SHA256 string
+ Rule string // a gitleaks rule ID, or "forbidden-path"
+ Line int
+}
+
+func (f Finding) String() string {
+ where := f.Input
+ if f.Member != "" {
+ where += ":" + f.Member
+ }
+ if f.Line > 0 {
+ where += fmt.Sprintf(" line %d", f.Line)
+ }
+ return where + " (" + f.Rule + ")"
+}
+
+// scanChunk and scanOverlap split large members for gitleaks: each chunk
+// overlaps the next, so a secret across a boundary is still seen whole.
+const (
+ scanChunk = 1 << 20
+ scanOverlap = 8 << 10
+)
+
+// gitleaksMu guards the global viper instance gitleaks reads its
+// configuration through, and gitleaksConfigs. gitleaks extends a
+// configuration with its defaults through a package counter it never
+// resets, so a configuration is translated once per process and kept,
+// by the SHA-256 of its text.
+var (
+ gitleaksMu sync.Mutex
+ gitleaksConfigs = map[string]config.Config{}
+)
+
+// loadDetector builds a gitleaks detector from the configuration file at
+// path.
+func loadDetector(path string) (*detect.Detector, error) {
+ raw, err := os.ReadFile(path)
+ if err != nil {
+ return nil, fmt.Errorf("hostedimage: gitleaks configuration: %w", err)
+ }
+ gitleaksMu.Lock()
+ defer gitleaksMu.Unlock()
+ key := sha256Hex(raw)
+ if cfg, ok := gitleaksConfigs[key]; ok {
+ return detect.NewDetector(cfg), nil
+ }
+ viper.Reset()
+ defer viper.Reset()
+ viper.SetConfigType("toml")
+ if err := viper.ReadConfig(bytes.NewReader(raw)); err != nil {
+ return nil, fmt.Errorf("hostedimage: gitleaks configuration %s: %w", path, err)
+ }
+ var vc config.ViperConfig
+ if err := viper.Unmarshal(&vc); err != nil {
+ return nil, fmt.Errorf("hostedimage: gitleaks configuration %s: %w", path, err)
+ }
+ cfg, err := vc.Translate()
+ if err != nil {
+ return nil, fmt.Errorf("hostedimage: gitleaks configuration %s: %w", path, err)
+ }
+ if len(cfg.Rules) == 0 {
+ return nil, fmt.Errorf("hostedimage: gitleaks configuration %s has no rules", path)
+ }
+ gitleaksConfigs[key] = cfg
+ return detect.NewDetector(cfg), nil
+}
+
+// scanner collects findings over the inputs.
+type scanner struct {
+ d *detect.Detector
+ findings []Finding
+}
+
+func sha256Hex(b []byte) string { h := sha256.Sum256(b); return hex.EncodeToString(h[:]) }
+
+// scanName checks one path the image would hold.
+func (s *scanner) scanName(input, member, sum string) {
+ if ForbiddenPath.MatchString(member) {
+ s.findings = append(s.findings, Finding{Input: input, Member: member, SHA256: sum, Rule: "forbidden-path"})
+ }
+}
+
+// scanBytes runs gitleaks over b, in overlapping chunks.
+func (s *scanner) scanBytes(input, member string, b []byte) {
+ sum := sha256Hex(b)
+ seen := map[string]bool{}
+ for start := 0; ; start += scanChunk {
+ end := min(start+scanChunk+scanOverlap, len(b))
+ fp := input
+ if member != "" {
+ fp += "/" + member
+ }
+ //lint:ignore SA1019 Detect takes this type in gitleaks v8; v9 renames it.
+ for _, f := range s.d.Detect(detect.Fragment{Raw: string(b[start:end]), FilePath: fp}) {
+ key := f.RuleID + "\x00" + f.Match
+ if seen[key] {
+ continue // the same match in an overlap
+ }
+ seen[key] = true
+ s.findings = append(s.findings, Finding{Input: input, Member: member, SHA256: sum, Rule: f.RuleID,
+ Line: f.StartLine + 1})
+ }
+ if end == len(b) {
+ return
+ }
+ }
+}
+
+// scanInput scans one pinned input, held in memory: a tarball member by
+// member, an RPM by its file names and payload, anything else whole.
+func (s *scanner) scanInput(input string, b []byte) error {
+ switch {
+ case strings.HasSuffix(input, ".tar.gz"):
+ return s.scanTarGz(input, b)
+ case strings.HasSuffix(input, ".rpm"):
+ return s.scanRPM(input, b)
+ }
+ s.scanBytes(input, "", b)
+ return nil
+}
+
+// maxMember bounds one archive member read into memory.
+const maxMember = 1 << 30
+
+func (s *scanner) scanTarGz(input string, b []byte) error {
+ zr, err := gzip.NewReader(bytes.NewReader(b))
+ if err != nil {
+ return fmt.Errorf("hostedimage: %s is not gzip: %w", input, err)
+ }
+ tr := tar.NewReader(zr)
+ for {
+ h, err := tr.Next()
+ if errors.Is(err, io.EOF) {
+ return nil
+ }
+ if err != nil {
+ return fmt.Errorf("hostedimage: %s: %w", input, err)
+ }
+ name := path.Clean(strings.TrimPrefix(h.Name, "./"))
+ if path.IsAbs(h.Name) || name == ".." || strings.HasPrefix(name, "../") {
+ return fmt.Errorf("hostedimage: %s: member %q leaves the archive", input, h.Name)
+ }
+ if h.Typeflag != tar.TypeReg {
+ s.scanName(input, name, "")
+ continue
+ }
+ if h.Size > maxMember {
+ return fmt.Errorf("hostedimage: %s: member %q is over 1 GiB", input, name)
+ }
+ body, err := io.ReadAll(io.LimitReader(tr, maxMember))
+ if err != nil {
+ return fmt.Errorf("hostedimage: %s: %w", input, err)
+ }
+ s.scanName(input, name, sha256Hex(body))
+ s.scanBytes(input, name, body)
+ }
+}
+
+// judge drops the findings allow covers and returns what is left, plus
+// any allowance that matched nothing.
+func judge(findings []Finding, allow []ScanAllowed) (left []Finding, unused []ScanAllowed) {
+ used := make([]bool, len(allow))
+ for _, f := range findings {
+ i := slices.IndexFunc(allow, func(a ScanAllowed) bool {
+ return a.Input == f.Input && a.Member == f.Member && a.SHA256 == f.SHA256 && f.SHA256 != ""
+ })
+ if i < 0 {
+ left = append(left, f)
+ continue
+ }
+ used[i] = true
+ }
+ for i, u := range used {
+ if !u {
+ unused = append(unused, allow[i])
+ }
+ }
+ return left, unused
+}
+
+// ScanError lists what the payload scan refused.
+type ScanError struct {
+ Findings []Finding
+ Unused []ScanAllowed
+}
+
+func (e *ScanError) Error() string {
+ var parts []string
+ for _, f := range e.Findings {
+ parts = append(parts, f.String())
+ }
+ for _, a := range e.Unused {
+ parts = append(parts, "allowance for "+a.Input+":"+a.Member+" matched nothing")
+ }
+ return "hostedimage: the payload scan refused the inputs: " + strings.Join(parts, "; ")
+}
+
+// FindGitleaksConfig returns the nearest .gitleaks.toml at or above dir,
+// or "".
+func FindGitleaksConfig(dir string) string {
+ abs, err := filepath.Abs(dir)
+ if err != nil {
+ return ""
+ }
+ for {
+ p := filepath.Join(abs, ".gitleaks.toml")
+ if st, err := os.Stat(p); err == nil && st.Mode().IsRegular() {
+ return p
+ }
+ up := filepath.Dir(abs)
+ if up == abs {
+ return ""
+ }
+ abs = up
+ }
+}
diff --git a/internal/hostedimage/scan_test.go b/internal/hostedimage/scan_test.go
new file mode 100644
index 00000000..047e257d
--- /dev/null
+++ b/internal/hostedimage/scan_test.go
@@ -0,0 +1,212 @@
+package hostedimage
+
+import (
+ "errors"
+ "os"
+ "path/filepath"
+ "regexp"
+ "slices"
+ "strings"
+ "testing"
+
+ "amadan.net/oficina/equipo/internal/hostedimage/hostedimagetest"
+ "amadan.net/oficina/equipo/internal/vminit"
+)
+
+// TestBuildScansPayload: a pinned input that carries a secret or a
+// forbidden path is refused even though its checksum is right: in a
+// binary, inside the Go tarball, inside an RPM's payload (gzip, zstd and
+// xz) or only in its header. The repository's gitleaks configuration
+// judges the bytes. Nothing is left at -out.
+func TestBuildScansPayload(t *testing.T) {
+ goTar := func(files map[string][]byte) func(t *testing.T, m *Manifest) {
+ return func(t *testing.T, m *Manifest) {
+ files["go/bin/go"] = []byte("fake go\n")
+ setInput(t, m, m.GoToolchain+".linux-amd64.tar.gz", hostedimagetest.TarGz(files))
+ }
+ }
+ rpm := func(files map[string][]byte, compressor string, ghosts ...string) func(t *testing.T, m *Manifest) {
+ return func(t *testing.T, m *Manifest) {
+ files["/usr/bin/git"] = []byte("fake git\n")
+ setInput(t, m, "pkgs/"+m.Packages[0].Name, hostedimagetest.RPM(files, compressor, ghosts...))
+ }
+ }
+ for _, c := range []struct {
+ name string
+ plant func(t *testing.T, m *Manifest)
+ member string // the finding's place, input:member
+ rule string
+ }{
+ {"AWS key in a binary", func(t *testing.T, m *Manifest) {
+ setInput(t, m, "codex", []byte("\x7fELF\x00\x01binary\naws_access_key_id = "+hostedimagetest.AWSKey+"\n\x00more"))
+ }, "codex", "aws-access-token"},
+ {"private key in the runner", func(t *testing.T, m *Manifest) {
+ setInput(t, m, "equipo-runner", []byte("\x7fELF\x00"+hostedimagetest.PrivateKey))
+ }, "equipo-runner", "private-key"},
+ {"token in a tarball member", goTar(map[string][]byte{"go/src/x/notes.txt": []byte("token: " + hostedimagetest.GitHubToken + "\n")}),
+ "go1.26.11.linux-amd64.tar.gz:go/src/x/notes.txt", "github-pat"},
+ {"SSH key path in the tarball", goTar(map[string][]byte{"go/.ssh/id_ed25519": []byte("x\n")}),
+ "go1.26.11.linux-amd64.tar.gz:go/.ssh", "forbidden-path"},
+ {"git repository in the tarball", goTar(map[string][]byte{"go/src/.git/config": []byte("[core]\n")}),
+ "go1.26.11.linux-amd64.tar.gz:go/src/.git", "forbidden-path"},
+ {"AWS credentials in an RPM", rpm(map[string][]byte{"/root/.aws/credentials": []byte("[default]\n")}, "gzip"),
+ "pkgs/git-core-2.47.1-1.amzn2023.x86_64.rpm:root/.aws", "forbidden-path"},
+ {"netrc ghost in an RPM header", rpm(map[string][]byte{}, "gzip", "/root/.netrc"),
+ "pkgs/git-core-2.47.1-1.amzn2023.x86_64.rpm:root/.netrc", "forbidden-path"},
+ {"secret in a zstd RPM payload", rpm(map[string][]byte{"/usr/share/doc/git/x.txt": []byte("k = " + hostedimagetest.AWSKey + "\n")}, "zstd"),
+ "pkgs/git-core-2.47.1-1.amzn2023.x86_64.rpm:usr/share/doc/git/x.txt", "aws-access-token"},
+ {"secret in an xz RPM payload", rpm(map[string][]byte{"/etc/gitconfig.d/x": []byte(hostedimagetest.PrivateKey)}, "xz"),
+ "pkgs/git-core-2.47.1-1.amzn2023.x86_64.rpm:etc/gitconfig.d/x", "private-key"},
+ {"OAuth home in an RPM", rpm(map[string][]byte{"/home/u/.codex/auth.json": []byte("{}\n")}, "gzip"),
+ "pkgs/git-core-2.47.1-1.amzn2023.x86_64.rpm:home/u/.codex", "forbidden-path"},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ m := fixture(t)
+ c.plant(t, &m)
+ if err := m.Validate(); err != nil {
+ t.Fatalf("the planted manifest is not valid: %v", err)
+ }
+ out := filepath.Join(t.TempDir(), "image.zip")
+ _, err := Build(m, out)
+ var se *ScanError
+ if !errors.As(err, &se) {
+ t.Fatalf("Build = %v, want a payload scan refusal", err)
+ }
+ found := slices.ContainsFunc(se.Findings, func(f Finding) bool {
+ where := f.Input
+ if f.Member != "" {
+ where += ":" + f.Member
+ }
+ return strings.HasPrefix(where, c.member) && f.Rule == c.rule
+ })
+ if !found {
+ t.Fatalf("findings %v, want %s at %s", se.Findings, c.rule, c.member)
+ }
+ for _, s := range []string{hostedimagetest.AWSKey, hostedimagetest.GitHubToken, "OPENSSH PRIVATE"} {
+ if strings.Contains(err.Error(), s) {
+ t.Fatalf("the refusal quotes the secret: %v", err)
+ }
+ }
+ if _, serr := os.Stat(out); serr == nil {
+ t.Fatal("a zip was written")
+ }
+ })
+ }
+}
+
+// TestScanAllowExact: a reviewed finding is accepted only for the exact
+// member and bytes it names; an allowance that matches nothing is itself
+// refused.
+func TestScanAllowExact(t *testing.T) {
+ key := []byte(hostedimagetest.PrivateKey)
+ plant := func(t *testing.T, m *Manifest) {
+ setInput(t, m, m.GoToolchain+".linux-amd64.tar.gz", hostedimagetest.TarGz(map[string][]byte{
+ "go/bin/go": []byte("fake go\n"), "go/src/crypto/tls/testdata/example-key.pem": key}))
+ }
+ allow := ScanAllowed{Input: "go1.26.11.linux-amd64.tar.gz", Member: "go/src/crypto/tls/testdata/example-key.pem",
+ SHA256: sum(key), Reason: "the Go tree's TLS test key"}
+
+ m := fixture(t)
+ plant(t, &m)
+ m.ScanAllow = []ScanAllowed{allow}
+ if _, err := Build(m, filepath.Join(t.TempDir(), "a.zip")); err != nil {
+ t.Fatalf("Build with the exact allowance = %v", err)
+ }
+
+ m = fixture(t)
+ plant(t, &m)
+ wrong := allow
+ wrong.SHA256 = hex64('e')
+ m.ScanAllow = []ScanAllowed{wrong}
+ var se *ScanError
+ if _, err := Build(m, filepath.Join(t.TempDir(), "b.zip")); !errors.As(err, &se) || len(se.Findings) == 0 || len(se.Unused) != 1 {
+ t.Fatalf("Build with an allowance for other bytes = %v, want the finding and the unused allowance", err)
+ }
+
+ m = fixture(t)
+ m.ScanAllow = []ScanAllowed{allow}
+ if _, err := Build(m, filepath.Join(t.TempDir(), "c.zip")); !errors.As(err, &se) || len(se.Unused) != 1 {
+ t.Fatalf("Build with an allowance nothing needs = %v, want a refusal", err)
+ }
+}
+
+// TestBuildNeedsGitleaksConfig: without the configuration, or with one
+// that does not parse, nothing is built.
+func TestBuildNeedsGitleaksConfig(t *testing.T) {
+ m := fixture(t)
+ m.GitleaksConfig = ""
+ if _, err := Build(m, filepath.Join(t.TempDir(), "a.zip")); err == nil {
+ t.Fatal("Build without a gitleaks configuration = nil")
+ }
+ m = fixture(t)
+ bad := filepath.Join(t.TempDir(), ".gitleaks.toml")
+ write(t, bad, []byte("[[rules\n"), 0o644)
+ m.GitleaksConfig = bad
+ if _, err := Build(m, filepath.Join(t.TempDir(), "b.zip")); err == nil {
+ t.Fatal("Build with a broken gitleaks configuration = nil")
+ }
+ if got := FindGitleaksConfig(m.Dir); filepath.Base(got) != ".gitleaks.toml" {
+ t.Fatalf("FindGitleaksConfig(%s) = %q, want the repository's", m.Dir, got)
+ }
+}
+
+// TestImageLayoutMatchesContainmentSuite: the containment suite runs
+// bubblewrap from one host path; the image installs the pinned binary at
+// exactly that path, after the packages, checks it there at the end, and
+// measures it there as the sandbox policy set.
+func TestImageLayoutMatchesContainmentSuite(t *testing.T) {
+ dir := filepath.Join(repoRoot, "internal", "runner", "containment")
+ entries, err := os.ReadDir(dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ // The host binary the suite runs: Config.Binary, a policy's Bwrap, and
+ // the first word of a sandbox argv. Mount targets inside a sandbox
+ // (Target: "/opt/bwrap") are not host paths.
+ uses := regexp.MustCompile(`(?:Binary:\s*|Bwrap:\s*|\[\]string\{)"(/[^"]*/bwrap)"`)
+ paths := map[string]bool{}
+ for _, e := range entries {
+ if !strings.HasSuffix(e.Name(), ".go") {
+ continue
+ }
+ b, err := os.ReadFile(filepath.Join(dir, e.Name()))
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, m := range uses.FindAllStringSubmatch(string(b), -1) {
+ paths[m[1]] = true
+ }
+ }
+ if len(paths) != 1 || !paths[PathBwrap] {
+ t.Fatalf("the containment suite runs bwrap from %v; the image installs it at %s", paths, PathBwrap)
+ }
+
+ m := fixture(t)
+ df, err := renderDockerfile(m)
+ if err != nil {
+ t.Fatal(err)
+ }
+ text := string(df)
+ install := strings.Index(text, "install -D -m 0755 -o root -g root bwrap "+PathBwrap+";")
+ pkgs := strings.Index(text, "rpm --install")
+ final := strings.Index(text, "'"+m.BubblewrapSHA256+" "+PathBwrap+"'")
+ switch {
+ case install < 0:
+ t.Fatalf("the Dockerfile does not install the pinned bwrap at %s", PathBwrap)
+ case pkgs < 0 || pkgs > install:
+ t.Fatal("the pinned bwrap is not installed after the packages")
+ case final < install || !strings.Contains(text[final:], "sha256sum --check --strict"):
+ t.Fatalf("the Dockerfile does not check %s against its pin at the end", PathBwrap)
+ }
+ want := vminit.PolicySetDigest(map[string]string{PathBwrap: m.BubblewrapSHA256})
+ if got := m.Measured()[vminit.MeasuredSandboxPolicy]; got != want {
+ t.Fatalf("sandbox_policy = %s, want bwrap at %s measured (%s)", got, PathBwrap, want)
+ }
+ checked, err := LoadManifest(filepath.Join(repoRoot, "infra", "hosted", "image", "manifest.json"))
+ if err != nil || !slices.Equal(checked.Policies, []string{PathBwrap}) {
+ t.Fatalf("checked-in Policies = %v (%v), want [%s]", checked.Policies, err, PathBwrap)
+ }
+ if !slices.Contains(VMInitArgs(checked), PathBwrap) {
+ t.Fatal("vm-init is not told to measure the bwrap the suite runs")
+ }
+}
diff --git a/internal/isolatedjob/awsjob/imageaws/imageaws.go b/internal/isolatedjob/awsjob/imageaws/imageaws.go
index 6129f47a..ad8a9596 100644
--- a/internal/isolatedjob/awsjob/imageaws/imageaws.go
+++ b/internal/isolatedjob/awsjob/imageaws/imageaws.go
@@ -121,6 +121,29 @@ func hooks(h hostedimage.Hooks) *types.Hooks {
}
}
+// readHooks is the hook configuration an answer gives, nil when it has
+// none. A missing inner structure, state or timeout reads as zero, which
+// no image's settings hold, so the publish check refuses it.
+func readHooks(h *types.Hooks) *hostedimage.Hooks {
+ if h == nil {
+ return nil
+ }
+ out := &hostedimage.Hooks{Port: int(aws.ToInt32(h.Port))}
+ if m := h.MicrovmHooks; m != nil {
+ out.Microvm = hostedimage.MicrovmHooks{
+ Run: string(m.Run), RunTimeout: int(aws.ToInt32(m.RunTimeoutInSeconds)),
+ Resume: string(m.Resume), ResumeTimeout: int(aws.ToInt32(m.ResumeTimeoutInSeconds)),
+ Suspend: string(m.Suspend), SuspendTimeout: int(aws.ToInt32(m.SuspendTimeoutInSeconds)),
+ Terminate: string(m.Terminate), TerminateTimeout: int(aws.ToInt32(m.TerminateTimeoutInSeconds)),
+ }
+ }
+ if i := h.MicrovmImageHooks; i != nil {
+ out.Image = hostedimage.ImageHooks{Ready: string(i.Ready), ReadyTimeout: int(aws.ToInt32(i.ReadyTimeoutInSeconds)),
+ Validate: string(i.Validate)}
+ }
+ return out
+}
+
// 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).
@@ -192,12 +215,7 @@ func (p *Provider) GetImageVersion(ctx context.Context, imageARN, version string
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))
- }
- }
+ v.Hooks = readHooks(out.Hooks)
if u, ok := out.CodeArtifact.(*types.CodeArtifactMemberUri); ok {
v.Artifact = u.Value
}
diff --git a/internal/isolatedjob/awsjob/imageaws/imageaws_test.go b/internal/isolatedjob/awsjob/imageaws/imageaws_test.go
index 914ecb2d..d725ce02 100644
--- a/internal/isolatedjob/awsjob/imageaws/imageaws_test.go
+++ b/internal/isolatedjob/awsjob/imageaws/imageaws_test.go
@@ -111,7 +111,7 @@ func healthy(account string) func(op string, in any) (any, error) {
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)}},
+ Hooks: apiHooks(),
CodeArtifact: &types.CodeArtifactMemberUri{Value: "s3://equipo-hosted-image-inputs/images/x.zip"},
BaseImageVersion: aws.String("4"),
}, nil
@@ -120,6 +120,58 @@ func healthy(account string) func(op string, in any) (any, error) {
}
}
+// apiHooks is the hook configuration a correct build answers with, written
+// out as the API gives it rather than derived from the code under test.
+func apiHooks() *types.Hooks {
+ return &types.Hooks{
+ Port: aws.Int32(9000),
+ MicrovmHooks: &types.MicrovmHooks{
+ Run: types.HookStateEnabled, RunTimeoutInSeconds: aws.Int32(60),
+ Resume: types.HookStateEnabled, ResumeTimeoutInSeconds: aws.Int32(10),
+ Suspend: types.HookStateEnabled, SuspendTimeoutInSeconds: aws.Int32(10),
+ Terminate: types.HookStateEnabled, TerminateTimeoutInSeconds: aws.Int32(10),
+ },
+ MicrovmImageHooks: &types.MicrovmImageHooks{
+ Ready: types.HookStateEnabled, ReadyTimeoutInSeconds: aws.Int32(120), Validate: types.HookStateDisabled,
+ },
+ }
+}
+
+// TestHooksReadBackWhole (review round 1, finding 3): the version's hook
+// configuration is read whole, and publish refuses a version whose hooks
+// are missing, disabled or retimed, through the real clients.
+func TestHooksReadBackWhole(t *testing.T) {
+ for name, edit := range map[string]func(h *types.Hooks) *types.Hooks{
+ "ready disabled": func(h *types.Hooks) *types.Hooks { h.MicrovmImageHooks.Ready = types.HookStateDisabled; return h },
+ "run disabled": func(h *types.Hooks) *types.Hooks { h.MicrovmHooks.Run = types.HookStateDisabled; return h },
+ "no image hooks": func(h *types.Hooks) *types.Hooks { h.MicrovmImageHooks = nil; return h },
+ "no microvm hooks": func(h *types.Hooks) *types.Hooks { h.MicrovmHooks = nil; return h },
+ "no hooks at all": func(*types.Hooks) *types.Hooks { return nil },
+ "run timeout changed": func(h *types.Hooks) *types.Hooks { h.MicrovmHooks.RunTimeoutInSeconds = aws.Int32(30); return h },
+ "ready timeout absent": func(h *types.Hooks) *types.Hooks { h.MicrovmImageHooks.ReadyTimeoutInSeconds = nil; return h },
+ "port absent": func(h *types.Hooks) *types.Hooks { h.Port = nil; return h },
+ } {
+ t.Run(name, func(t *testing.T) {
+ s := &stub{answer: func(op string, in any) (any, error) {
+ out, err := healthy(acct)(op, in)
+ if v, ok := out.(*vms.GetMicrovmImageVersionOutput); ok {
+ v.Hooks = edit(apiHooks())
+ }
+ return out, err
+ }}
+ req := request(t)
+ _, err := hostedimage.Publish(context.Background(), provider(s), target, req)
+ var f *hostedimage.Failure
+ if !errors.As(err, &f) || f.Kind != "mismatch" {
+ t.Fatalf("Publish = %v, want a mismatch refusal", err)
+ }
+ if _, err := os.Stat(req.Out); err == nil {
+ t.Fatal("-out written for a version with the wrong hooks")
+ }
+ })
+ }
+}
+
type fixedClock struct{ now time.Time }
func (c *fixedClock) Now() time.Time { return c.now }
@@ -258,8 +310,9 @@ func TestReadsMapped(t *testing.T) {
}
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" {
+ !slices.Equal(v.Architectures, []string{"X86_64"}) || !slices.Equal(v.MemoryMiB, []int{4096}) ||
+ v.Hooks == nil || *v.Hooks != hostedimage.ImageSettings().Hooks ||
+ 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" {