carlos / platform Public

carlos ship --check keeps its data volume between containers (#366, found by rootfs Plan 4 Task 11 on r10r). The data volume was a tmpfs local volume that Docker and Podman unmount when no container holds it, so the release container's migrations were gone before web started and examples/rails-shop failed the Rails guide's check with a 500. The data volume is now a plain local named volume; a one-shot helper container <prefix>_prepare (named outside the worker grammar) runs the CLI's own linux binary already mounted as the probe, with the hidden verb __rootfs-check-prepare, as root with only CAP_CHOWN, --read-only, --network none and no-new-privileges: it Lstats the directory, refuses a symlink or non-directory, chmods 0700 then lchowns 65534:65534, no recursion. Every volume mount carries :nocopy, so no runtime refills an empty volume from the image and resets its owner. Cleanup covers the helper on every path. Box witness on r10r (rootful podman): shop and a variant with an empty /data/instances/check both pass (release 2.9 s, web 200 after 2.8 s, worker running), no leftovers. No new user copy. Reviews: Astra R1 NOT READY (P1 helper name collision with a worker named prepare, P2 test gap), R2 NOT READY (P1 copy-up resets the owner), R3 READY; census rootfs-check-volumes approved by Astra on #280. Not released.

Squashed from rootfs-check-volumes into main.
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 43c8677af4e43959beabb10de1d6fb7391209cc3 parent 1fa2a99
17 files changed, +789 −50
  • docs/superpowers/notes/census-proposal-rootfs-check-volumes.md +23 −0
  • docs/superpowers/reviews/CODEX-FINDINGS-rootfs-check-volumes-R1.md +17 −0
  • docs/superpowers/reviews/CODEX-FINDINGS-rootfs-check-volumes-R2.md +26 −0
  • docs/superpowers/reviews/CODEX-FINDINGS-rootfs-check-volumes-R3.md +18 −0
  • docs/superpowers/reviews/CODEX-REVIEW-BRIEF-rootfs-check-volumes-R2.md +11 −0
  • docs/superpowers/reviews/CODEX-REVIEW-BRIEF-rootfs-check-volumes-R3.md +13 −0
  • docs/superpowers/reviews/CODEX-REVIEW-BRIEF-rootfs-check-volumes.md +33 −0
  • internal/provision/plan9_b8_census_test.go +1 −1
  • internal/provision/rootfs_check_volumes_census_test.go +37 −0
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −0
  • internal/provision/testdata/plan14-root-reads-rootfs-check-volumes.tsv +8 −0
  • main.go +4 −0
  • ship_check.go +114 −29
  • ship_check_prepare_test.go +210 −0
  • ship_check_probe.go +47 −0
  • ship_check_test.go +225 −20
  • ship_rootfs_unix_test.go +1 −0

CI failed — run details

diff --git a/docs/superpowers/notes/census-proposal-rootfs-check-volumes.md b/docs/superpowers/notes/census-proposal-rootfs-check-volumes.md
new file mode 100644
index 000000000..c23666568
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-rootfs-check-volumes.md
@@ -0,0 +1,23 @@
+# Census approval: rootfs-check-volumes
+
+Ruling `census-ruling-rootfs-check-volumes`. The independent reviewer approves or rejects every change below, 1 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+
+| unit | change | read sites | what changed |
+|---|---|---|---|
+| `ship_check.go` `rootfsCheck.runArgs` | body | unchanged (2) | R2 P1: the data and run volume mounts (-v) now carry :nocopy through rootfsCheck.volumeMount, so Docker and Podman never fill an empty check volume from the image directory at the mount point (which would reset the prepared owner and mode); same volumes, same paths, same probe mount, nothing else in the argv changed. Runs on the person's machine as the person; no box unit; no read added. |
+
+Envelopes re-pinned: `.`.
+
+Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner.
+
+Recorded dispositions, which each change must still satisfy:
+
+- `ship_check.go` `rootfsCheck.runArgs`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-rootfs-apps-1;basis=root-input (J4, as main's db.go units); the carlos CLI on a person's machine, as the person (no box unit): new (rootfs Plan 1), builds the docker or podman run argv for one check container; the scanner matches the word Command, here a field of release.Process (a process's argv), not os/exec; reads no file; decides nothing for root
+
+New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff:
+
+- new `ship_check_probe.go:prepareCheckDir`: reads +file:Lstat; written legacy, accepted-legacy, frozen
+
+Seal: `94b8ccf921f64be24a4773f72d55a8e24ceba3acfb40eefe3b56af6f5b008138` → `042684bf5af6f61ce8b87f10b68a42b08d131ba4cb5bcab16320c7b032a724e6`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-rootfs-check-volumes.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/reviews/CODEX-FINDINGS-rootfs-check-volumes-R1.md b/docs/superpowers/reviews/CODEX-FINDINGS-rootfs-check-volumes-R1.md
new file mode 100644
index 000000000..e2be49076
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-FINDINGS-rootfs-check-volumes-R1.md
@@ -0,0 +1,17 @@
+Reviewed `03e08f569cb2ecd07e0ecdc1ceba5d29f9b8cbad`, round 1/3.
+
+- **P1 — Helper container collides with a valid worker named `prepare`.** Verified in [ship_check.go:210](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/rootfs-check-volumes/ship_check.go:210): the helper requests `<prefix>-prepare`, remains until deferred cleanup, and `start` at line 300 assigns that same name to worker `prepare`. `ValidWorkerName` permits it (`internal/release/rootfs.go:70–85`). A healthy app with this worker fails its check when the runtime rejects the duplicate container name. **Fix:** give the helper a name outside the worker-name grammar and add a regression test whose fake rejects duplicate names. **Invariant:** internal helper names must not overlap valid process names.
+
+- **P2 — Tests do not pin the ownership transition or chmod-before-chown ordering.** [ship_check_prepare_test.go:20](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/rootfs-check-volumes/ship_check_prepare_test.go:20) passes the directory’s existing UID/GID at line 39. Verified by inspection: deleting `Lchown`, or moving it before `Chmod`, would satisfy these assertions. Such regressions would prevent UID 65534 from writing, or make chmod fail without `CAP_FOWNER`. **Fix:** add a capability-constrained integration test that changes ownership from root to 65534 and confirms that user can write; verify both mutations fail. **Invariant:** preparation must establish writable ownership using only `CAP_CHOWN`.
+
+No P3 findings.
+
+Census verdicts:
+
+- **APPROVE — `ship_check_probe.go:prepareCheckDir`.** Read lines 108–140. The `file:Lstat` read and `legacy / accepted-legacy` disposition match the container-only caller. It refuses a final symlink or non-directory, changes mode before ownership, and does not recurse.
+- **APPROVE — envelope `.`.** Read changed code in `main.go:21–51`, `ship_check.go:132–153,180–239,299–365`, and `ship_check_probe.go:108–140`; traced import, probe selection and cleanup. Import discards source execution metadata, the helper runs the selected probe with fixed arguments, and no box-root caller gains a new input path. The P1 collision is a functional defect.
+- **APPROVE — record-write re-pin `main.go:main`.** Read the dispatch and `internal/provision/rootfs_check_volumes_census_test.go:16–37`. The new dispatch writes no record; the `instances` and `sidecars` literals remain unchanged.
+
+Targeted check and census tests were attempted but stopped before compilation: Go could not create its work directory under read-only `$TMPDIR`. `GOCACHE` remained unset. No files changed; no full suites or mutation runs executed.
+
+NOT READY
\ No newline at end of file
diff --git a/docs/superpowers/reviews/CODEX-FINDINGS-rootfs-check-volumes-R2.md b/docs/superpowers/reviews/CODEX-FINDINGS-rootfs-check-volumes-R2.md
new file mode 100644
index 000000000..cad84514b
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-FINDINGS-rootfs-check-volumes-R2.md
@@ -0,0 +1,26 @@
+- **R1 P1 — resolved.** The helper uses `<prefix>_prepare`, outside the worker-name grammar ([ship_check.go:215](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/rootfs-check-volumes/ship_check.go:215)). The fake rejects duplicate names, and the regression covers worker `prepare`.
+- **R1 P2 — resolved.** [ship_check_prepare_test.go:86](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/rootfs-check-volumes/ship_check_prepare_test.go:86) asserts chmod 0700 before lchown 65534:65534, through both function and verb. Removing or reversing those calls breaks the assertion.
+
+Reviewed `d57b4bf04c4908f519fc17f6255e0e0dc2a3acc9`, round 2/3.
+
+**P1 — Docker volume population can undo preparation before the first app process starts.** Both the helper ([ship_check.go:220](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/rootfs-check-volumes/ship_check.go:220)) and app processes ([ship_check.go:286](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/rootfs-check-volumes/ship_check.go:286)) mount the data volume without disabling image-content copying.
+
+Failure scenario: a valid image contains an empty `/data/instances/check` directory, mode 0755. Import normalizes its owner to 0:0. Preparation leaves the volume empty but changes its owner to 65534:65534. When Docker creates release—or web without release—it populates the still-empty volume again, restoring the image directory’s ownership and mode. UID 65534 then cannot create `CARLOS_DB`, so a healthy app fails its check.
+
+Verified by source inspection, not a runtime reproduction: Docker skips population only when the destination contains entries; its copy implementation restores directory metadata.
+
+[https://raw.githubusercontent.com/moby/moby/v27.5.1/container/container_unix.go](https://raw.githubusercontent.com/moby/moby/v27.5.1/container/container_unix.go), [https://raw.githubusercontent.com/containerd/continuity/main/fs/copy.go](https://raw.githubusercontent.com/containerd/continuity/main/fs/copy.go), [https://raw.githubusercontent.com/containerd/continuity/main/fs/copy_linux.go](https://raw.githubusercontent.com/containerd/continuity/main/fs/copy_linux.go)
+
+**Fix:** disable image-content copying on every data-volume mount, using syntax supported by each runtime. Add a regression with that empty directory present in the image, asserting UID 65534 can write after the next container starts. **Invariant/fault family:** prepared data-volume ownership must remain writable by the check user across container launches.
+
+No new P2 or P3 findings.
+
+Census verdicts:
+
+- **APPROVE — `ship_check_probe.go:prepareCheckDir`.** Read lines 108–147. `file:Lstat` and `legacy / accepted-legacy` match the container-only caller. Final symlinks and non-directories are refused; chmod precedes lchown; neither recurses.
+- **APPROVE — envelope `.`.** Read `main.go:21–51`, `ship_check.go:132–243,303–369`, and `ship_check_probe.go:108–147`; traced import, probe selection and cleanup. No box-root caller gains an input path or weaker validation. The finding above concerns local-check functionality.
+- **APPROVE — record-write re-pin `main.go:main`.** Read the dispatch and `internal/provision/rootfs_check_volumes_census_test.go:16–37`. The added dispatch writes no record; the `instances` and `sidecars` literals remain unchanged.
+
+Targeted check and census tests stopped before compilation because `$TMPDIR` is read-only. GOCACHE remained unset. No full suites ran; no files changed.
+
+NOT READY
\ No newline at end of file
diff --git a/docs/superpowers/reviews/CODEX-FINDINGS-rootfs-check-volumes-R3.md b/docs/superpowers/reviews/CODEX-FINDINGS-rootfs-check-volumes-R3.md
new file mode 100644
index 000000000..65e77fbbb
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-FINDINGS-rootfs-check-volumes-R3.md
@@ -0,0 +1,18 @@
+- **R1 P1 — resolved.** Helper name `<prefix>_prepare` cannot collide with worker names ([ship_check.go:215](ship_check.go:215)); the regression fake rejects duplicate names.
+- **R1 P2 — resolved.** Tests pin chmod 0700 before lchown 65534:65534, including the verb’s arguments ([ship_check_prepare_test.go:86](ship_check_prepare_test.go:86)).
+- **R2 P1 — resolved.** Every data/run volume mount uses `:nocopy`; the regression covers prepare, release, web and worker ([ship_check_test.go:695](ship_check_test.go:695)).
+
+Reviewed commit `05e4e6b23c28351d178580865545998173cec811`, round 3/3, including the R2 fix and whole branch against `1fa2a99b`.
+
+No new P1, P2 or P3 findings. Runtime syntax was cross-checked against the Moby parser and Podman documentation: [https://raw.githubusercontent.com/moby/moby/v27.5.1/volume/mounts/linux_parser.go](https://raw.githubusercontent.com/moby/moby/v27.5.1/volume/mounts/linux_parser.go), [https://docs.podman.io/en/v5.2.2/markdown/podman-run.1.html](https://docs.podman.io/en/v5.2.2/markdown/podman-run.1.html).
+
+Census verdicts:
+
+- **APPROVE — `ship_check_probe.go:prepareCheckDir`.** Read lines 108–147. `file:Lstat`, `legacy / accepted-legacy` remains appropriate for the container-only caller. Final symlinks and non-directories are refused; chmod precedes lchown; neither recurses.
+- **APPROVE — `ship_check.go:rootfsCheck.runArgs`.** Read lines 246–312. The body change adds `:nocopy` through `volumeMount`; paths, probe mount, privileges and command construction retain their checks. No file read or box-root authority is added; the existing disposition remains appropriate.
+- **APPROVE — envelope `.`.** Read `main.go:21–51`, `ship_check.go:108–382,526–544`, and `ship_check_probe.go:108–147,223–259`; traced import and normalization. The helper executes the selected probe with fixed arguments, cleanup records resources before creation, and release failure/timeout behavior is preserved. No box-root input path or weaker validation is introduced.
+- **APPROVE — record-write re-pin `main.go:main`.** Read the dispatch diff and `internal/provision/rootfs_check_volumes_census_test.go:16–37`. The new dispatch writes no record; the `instances` and `sidecars` literals are unchanged.
+
+Targeted check and census tests stopped before compilation because `$TMPDIR` is read-only. GOCACHE remained unset. Formatting and diff checks passed. No full suites ran; no files changed.
+
+READY
\ No newline at end of file
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-rootfs-check-volumes-R2.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-rootfs-check-volumes-R2.md
new file mode 100644
index 000000000..7a3233ada
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-rootfs-check-volumes-R2.md
@@ -0,0 +1,11 @@
+# Review brief: rootfs-check-volumes, round 2 of 3
+
+Same branch, authorities and "what to check" as docs/superpowers/reviews/CODEX-REVIEW-BRIEF-rootfs-check-volumes.md (read it). Review the diff 03e08f56..<this brief's parent> for the fixes, and the whole branch diff 1fa2a99b..HEAD for anything they broke.
+
+Earlier rounds: R1 (docs/superpowers/reviews/CODEX-FINDINGS-rootfs-check-volumes-R1.md): P1 helper container name collides with a worker named `prepare`; P2 tests do not pin chmod-before-chown or the 65534 owner. Fix commits 29e0c39a (helper `<prefix>_prepare`, outside ^[a-z][a-z0-9-]{0,15}$; fake rejects duplicate names; TestRootfsCheckWorkerNamedLikeTheHelper) and 500ec2ba (checkChmod/checkLchown package vars; TestPrepareCheckDirSetsModeThenOwner). Census re-proposed 2d5be53e (same unit and read; seal 4fb2a2ad; envelope . re-pinned).
+
+First give one line per R1 P1/P2: resolved, partly, or not. Then new findings. Then census verdicts again for every unit and envelope on the current card (docs/superpowers/notes/census-proposal-rootfs-check-volumes.md) and the main.go main re-pin.
+
+Severity, output format and rules as in round 1. End with exactly one verdict: READY, READY AFTER FIXES, or NOT READY.
+
+Do not edit files. Do not spawn Anthropic-model reviewers or subagents of your own. Do not run the full test suites.
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-rootfs-check-volumes-R3.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-rootfs-check-volumes-R3.md
new file mode 100644
index 000000000..02ec094ad
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-rootfs-check-volumes-R3.md
@@ -0,0 +1,13 @@
+# Review brief: rootfs-check-volumes, round 3 of 3 (LAST)
+
+Same branch, authorities and "what to check" as docs/superpowers/reviews/CODEX-REVIEW-BRIEF-rootfs-check-volumes.md. Review the fix diff from the R2 tip d57b4bf0 to <this brief's parent>, and the whole branch 1fa2a99b..HEAD for anything it broke.
+
+Earlier rounds: R1 (CODEX-FINDINGS-rootfs-check-volumes-R1.md) and R2 (CODEX-FINDINGS-rootfs-check-volumes-R2.md). R2's P1 (Docker/Podman copy-up of an empty named volume resets the prepared owner) is answered by d203093b: every data and run volume mount goes through rootfsCheck.volumeMount and ends in `:nocopy` (prepare helper, release, web, workers); TestRootfsCheckVolumesNeverCopyUp. Box witness on r10r (rootful podman): shop.tar and a variant image with an empty 0:0 755 /data/instances/check both pass; no leftovers. Docker was not available to run; the Docker side rests on Docker's documented -v nocopy option.
+
+First give one line per R1 and R2 P1/P2: resolved, partly, or not. Then new findings. Then census verdicts for every unit and envelope on the current card (docs/superpowers/notes/census-proposal-rootfs-check-volumes.md: prepareCheckDir unchanged; rootfsCheck.runArgs body change, `:nocopy` only; envelope `.`) and the main.go main re-pin.
+
+This is round 3: a NOT READY must say whether its P1s share one cause, and whether refusing the case up front or cutting the feature would remove them.
+
+Severity, output and rules as in round 1. End with exactly one verdict: READY, READY AFTER FIXES, or NOT READY.
+
+Do not edit files. Do not spawn Anthropic-model reviewers or subagents of your own. Do not run the full test suites.
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-rootfs-check-volumes.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-rootfs-check-volumes.md
new file mode 100644
index 000000000..70116c4c8
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-rootfs-check-volumes.md
@@ -0,0 +1,33 @@
+# Review brief: rootfs-check-volumes (carlos ship --check keeps its data volume), round 1 of 3
+
+Repo carlos/platform, branch `rootfs-check-volumes`, review the diff `1fa2a99b..ece268bc7ae69b17307bbb97981189049462bee0` (this brief's commit follows it).
+Authorities on main: docs/superpowers/specs/2026-10-24-rootfs-apps-design.md (§5.8 the local check, §5.2 the launch contract), docs/superpowers/plans/2026-10-24-rootfs-apps-1-ship.md (Task 11, the check), AGENTS.md (census, copy, stopping rules).
+
+You are an independent reviewer. Read the diff, then the code it names, and check every claim against that code.
+
+## The bug
+`carlos ship --check` made the data volume a local-driver tmpfs volume. Docker and Podman unmount it when no container holds it, so what the `release` container wrote (migrations into CARLOS_DB) was gone before `web` started; examples/rails-shop failed with a 500. Box witness after the fix (r10r, podman): release 2.9 s, web 200 after 2.8 s, worker running after 5 s, passed, no leftovers.
+
+## Fixed: do not re-argue
+- Controller's design: data volume a plain local named volume; run volume stays tmpfs; a one-shot prepare container running the CLI's own linux binary (mounted at checkProbeMount) with hidden verb `__rootfs-check-prepare`, as root with only CAP_CHOWN, chmods then chowns that one directory. Report only mechanisms that fail it.
+
+## What to check
+1. The prepare container's privileges: `--user 0:0 --read-only --network none --cap-drop ALL --cap-add CHOWN --security-opt no-new-privileges`, mounts limited to the data volume and the probe. Can the image under check influence what runs as root (entrypoint, env, working dir, the volume's content, a symlink planted at the mount point, image metadata like USER/ENTRYPOINT/HEALTHCHECK, an ONBUILD)? The verb Lstats and refuses a symlink, no recursion, mode before owner (no CAP_FOWNER): correct?
+2. Docker and Podman both (rootful and rootless podman, Docker Desktop VM): does a plain local named volume persist between containers, and does chown to 65534 inside the prepare container give the check's user write access in each? macOS/Windows hosts: the probe binary is a linux build already required by the check.
+3. Cleanup on every path (success, prepare failure, Ctrl-C between steps): every container, volume and image the check made is removed; the persisted data volume does not survive the check.
+4. The refactor of start/runRelease into launch/waitExit: release behaviour unchanged (timeouts, failure lines, report wording).
+5. User-visible strings: the diff should add none needing copy review (a failed prepare reports through existing runtimeFailed wording). Flag any new human text.
+6. Census: card docs/superpowers/notes/census-proposal-rootfs-check-volumes.md (new unit ship_check_probe.go:prepareCheckDir, +file:Lstat; envelope `.` re-pinned) and internal/provision/rootfs_check_volumes_census_test.go (main.go main re-pinned). Give a verdict for every unit and envelope on the card per AGENTS.md "Getting a change approved". Note: this code runs in the user's CLI and inside a throwaway container, never as root on a box.
+7. Tests: do the new tests and mutations (listed in the commit) actually pin 1-3?
+
+## Severity
+- **P1**: unsafe, would not compile, a test fails, or it would not work. Blocks merge.
+- **P2**: wrong or missing. Fixed without reopening this review.
+- **P3**: clarity or polish. Follow-up list only.
+
+A P1 states its failure scenario and the evidence (file:line).
+
+## Output
+Findings ranked P1, P2, P3, each with the problem, evidence (file:line, verified), failure scenario, concrete fix and the invariant it breaks. Census verdicts per unit/envelope (APPROVE or REJECT with lines read). End with exactly one verdict: READY, READY AFTER FIXES, or NOT READY.
+
+Do not edit files. Do not spawn Anthropic-model reviewers or subagents of your own. Do not run the full test suites.
diff --git a/internal/provision/plan9_b8_census_test.go b/internal/provision/plan9_b8_census_test.go
index 4527593f2..3ac707aa4 100644
--- a/internal/provision/plan9_b8_census_test.go
+++ b/internal/provision/plan9_b8_census_test.go
@@ -366,7 +366,7 @@ func TestPlan9B8RecordWriteCensus(t *testing.T) {
if len(got) < 100 {
t.Fatalf("census found only %d units under %s; the walk is broken", len(got), root)
}
- inventory := fleetSecretsKeyWriteCensusInventory()
+ inventory := rootfsCheckVolumesWriteCensusInventory()
problems := append(censusDiff(inventory, got), censusPolicy(inventory)...)
if len(problems) > 0 {
t.Fatalf("record-write census rejected %d site(s); update the explicit inventory only after reviewing the source:\n %s", len(problems), strings.Join(problems, "\n "))
diff --git a/internal/provision/rootfs_check_volumes_census_test.go b/internal/provision/rootfs_check_volumes_census_test.go
new file mode 100644
index 000000000..79496b2cb
--- /dev/null
+++ b/internal/provision/rootfs_check_volumes_census_test.go
@@ -0,0 +1,37 @@
+package provision
+
+// Record-write census entries for the ship --check data volume fix (#366,
+// branch rootfs-check-volumes), layered on fleetSecretsKeyWriteCensusInventory
+// (main's newest at the branch's base 1fa2a99b). Reviewed by the branch
+// author against the source; the census approval is recorded on #280 with
+// the root-read card
+// (docs/superpowers/notes/census-proposal-rootfs-check-volumes.md).
+//
+// One re-pin, no new unit:
+// - main.go main (key-site): dispatches __rootfs-check-prepare, the
+// carlos ship --check verb that makes the check's data volume its user's
+// inside a container on the person's machine, beside
+// __rootfs-check-probe and before the command switch; its instances and
+// sidecars literals are unchanged. It writes no record.
+func rootfsCheckVolumesWriteCensusInventory() []censusEntry {
+ entries := append([]censusEntry(nil), fleetSecretsKeyWriteCensusInventory()...)
+ repins := []censusEntry{
+ // rootfs-check-volumes: the __rootfs-check-prepare dispatch beside __rootfs-check-probe; the same literals.
+ {"main.go", "main", "key-site", "lit:instances,lit:sidecars", "9ce797683088785d55882487096e45cdbbd664fc692ccfe67c4eaea76c1be863"},
+ }
+ for _, r := range repins {
+ found := false
+ for i, e := range entries {
+ if e.File == r.File && e.Unit == r.Unit {
+ if e.Class != r.Class || e.Kinds != r.Kinds {
+ panic("rootfs-check-volumes re-pin changes the class or kinds of " + r.File + ":" + r.Unit)
+ }
+ entries[i], found = r, true
+ }
+ }
+ if !found {
+ panic("rootfs-check-volumes re-pin of an unlisted unit " + r.File + ":" + r.Unit)
+ }
+ }
+ return entries
+}
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index 8d944141b..33b508de6 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -34,3 +34,4 @@ plan14-root-reads-static-dir-slash.tsv fb7cd756f7c3eb2dc019c8fd55fea5475e2df7ee3
plan14-root-reads-named-unit-delivery-114.tsv d92c9d40eb2a9e66c859e2fe6df3af10a1b9d3a83b1d717ec928cb432eebb1aa
plan14-root-reads-fleet-secrets-key.tsv 9df7f5aca9a502966c9643b7062829c1c25bfbd86fa20e92d764d66f676d2cd6
plan14-root-reads-static-headers.tsv 94b8ccf921f64be24a4773f72d55a8e24ceba3acfb40eefe3b56af6f5b008138
+plan14-root-reads-rootfs-check-volumes.tsv 042684bf5af6f61ce8b87f10b68a42b08d131ba4cb5bcab16320c7b032a724e6
diff --git a/internal/provision/testdata/plan14-root-reads-rootfs-check-volumes.tsv b/internal/provision/testdata/plan14-root-reads-rootfs-check-volumes.tsv
new file mode 100644
index 000000000..714a190c3
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-rootfs-check-volumes.tsv
@@ -0,0 +1,8 @@
+# Census overlay rootfs-check-volumes, written by census-propose (#369). census-ruling-rootfs-check-volumes, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-rootfs-check-volumes.md.
+# 1 body, 0 sites, 1 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+# 1 new dispositions: 0 reads re-frozen at their disposition with the claim, 1 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other.
+@legacy 055963a9e0d8e690476664799c9ab21df3fcd3ab42960247a6abe38fbf2baa17 ship_check.go rootfsCheck.runArgs legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-1;basis=root-input (J4, as main's db.go units); the carlos CLI on a person's machine, as the person (no box unit): new (rootfs Plan 1), builds the docker or podman run argv for one check container; the scanner matches the word Command, here a field of release.Process (a process's argv), not os/exec; reads no file; decides nothing for root;rev3=census-ruling-rootfs-check-volumes;basis=R2 P1: the data and run volume mounts (-v) now carry :nocopy through rootfsCheck.volumeMount, so Docker and Podman never fill an empty check volume from the image directory at the mount point (which would reset the prepared owner and mode); same volumes, same paths, same probe mount, nothing else in the argv changed. Runs on the person's machine as the person; no box unit; no read added. file:Command@764,file:Command@848 a7bd986343e647262402a363cfb374c34bdd3ecf35cbb452d9e8816d88d4a02c
+@legacy b88e56ecd81527322832b883453084fda8bde581689e0e13fbe3a79170889c2e ship_check_probe.go prepareCheckDir legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-check-volumes;basis=new: __rootfs-check-prepare (carlos ship --check), run only inside the check's prepare container on the person's machine (as 0:0 with CAP_CHOWN alone, no network, read-only root), never by a box: Lstats the one directory it is given (the check's data volume at /data/instances/check), refuses a symlink or non-directory, then chmod 0700 and lchown to --uid:--uid; no recursion. Read added: file:Lstat of that path. R1 P2: the chmod and lchown go through package vars checkChmod/checkLchown (os.Chmod, os.Lchown; only tests change them) so a test pins the order; same calls, same arguments. main.go dispatches the verb before the command switch beside __rootfs-check-probe; no root unit calls it. file:Lstat@67 8633a0299cf2abee0b320ba4701137f31ada646c0d6c8310b6052054d5dad87f
+ship_check.go rootfsCheck.runArgs legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-1;basis=root-input (J4, as main's db.go units); the carlos CLI on a person's machine, as the person (no box unit): new (rootfs Plan 1), builds the docker or podman run argv for one check container; the scanner matches the word Command, here a field of release.Process (a process's argv), not os/exec; reads no file; decides nothing for root;rev3=census-ruling-rootfs-check-volumes;basis=R2 P1: the data and run volume mounts (-v) now carry :nocopy through rootfsCheck.volumeMount, so Docker and Podman never fill an empty check volume from the image directory at the mount point (which would reset the prepared owner and mode); same volumes, same paths, same probe mount, nothing else in the argv changed. Runs on the person's machine as the person; no box unit; no read added. file:Command@764,file:Command@848 a7bd986343e647262402a363cfb374c34bdd3ecf35cbb452d9e8816d88d4a02c
+ship_check_probe.go prepareCheckDir legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-check-volumes;basis=new: __rootfs-check-prepare (carlos ship --check), run only inside the check's prepare container on the person's machine (as 0:0 with CAP_CHOWN alone, no network, read-only root), never by a box: Lstats the one directory it is given (the check's data volume at /data/instances/check), refuses a symlink or non-directory, then chmod 0700 and lchown to --uid:--uid; no recursion. Read added: file:Lstat of that path. R1 P2: the chmod and lchown go through package vars checkChmod/checkLchown (os.Chmod, os.Lchown; only tests change them) so a test pins the order; same calls, same arguments. main.go dispatches the verb before the command switch beside __rootfs-check-probe; no root unit calls it. file:Lstat@67 8633a0299cf2abee0b320ba4701137f31ada646c0d6c8310b6052054d5dad87f
+@coverage . b86ad1c792b5fb3a92985bad439972463cdec87b3f066fe5e37f0beb32954d7d
diff --git a/main.go b/main.go
index cd4d1ecaf..62f138eb2 100644
--- a/main.go
+++ b/main.go
@@ -45,6 +45,10 @@ func main() {
if cmd == "__rootfs-check-probe" {
os.Exit(runRootfsCheckProbe(args))
}
+ // And the container that makes the check's data volume its user's.
+ if cmd == "__rootfs-check-prepare" {
+ os.Exit(runRootfsCheckPrepare(args))
+ }
switch cmd {
// Asking for help is not an error: it prints on stdout and exits 0, so
// `carlos help | less` works. A bare `carlos` still fails (stderr, 2).
diff --git a/ship_check.go b/ship_check.go
index 0cec4f41f..2e3abe4fb 100644
--- a/ship_check.go
+++ b/ship_check.go
@@ -29,6 +29,9 @@ const (
checkHost = "shop.example.com"
workerSettle = 5 * time.Second
checkLogLines = 20
+ // checkPrepareTimeout bounds the prepare container, which changes one
+ // directory's owner and mode, even under emulation.
+ checkPrepareTimeout = 60 * time.Second
)
// The instance's paths in every check container, as a box lays them out.
@@ -95,8 +98,8 @@ type checkProbeResult struct {
Ports []int `json:"ports"`
}
-// runRootfsCheck runs b's image with rt: release, if declared, to its end;
-// then web, probed with the binary at probe; then each worker, after a
+// runRootfsCheck runs b's image with rt: a container that makes the data
+// volume the check user's; release, if declared, to its end; then web, probed with the binary at probe; then each worker, after a
// healthy web. console is never started (spec §5.10). It writes each line
// of its report to out as it goes. Every container, volume and image it
// made is removed before it returns, on every path, and a removal that
@@ -137,7 +140,7 @@ func (c *rootfsCheck) check(ctx context.Context) {
c.say(fmt.Sprintf("the %s process runs %s, which needs a JIT, and this release does not declare one. it passes here but stops at start on a box. ship it with --jit", name, prog))
}
}
- if !c.checkArch(ctx) || !c.makeImageAndVolumes(ctx) {
+ if !c.checkArch(ctx) || !c.makeImageAndVolumes(ctx) || !c.prepareData(ctx) {
return
}
if _, ok := c.b.procs[release.ProcessRelease]; ok && !c.runRelease(ctx) {
@@ -166,25 +169,92 @@ func (c *rootfsCheck) checkArch(ctx context.Context) bool {
}
// makeImageAndVolumes imports the tree and makes the instance's two
-// directories, each a tmpfs volume owned by the check's user. Each name is
-// recorded before the runtime is asked, so a call cut short is cleaned up.
+// directories as volumes. The data volume is a plain local volume, so what
+// release writes there (a migrated CARLOS_DB) is still there for web and
+// the workers, as on a box's disk: Docker and Podman unmount a tmpfs
+// volume, and so empty it, whenever no container holds it. It starts out
+// root's; prepareData gives it to the check's user. The run volume holds
+// only the socket, which web makes afresh, so it stays a tmpfs volume
+// owned by the check's user. Each name is recorded before the runtime is
+// asked, so a call cut short is cleaned up.
func (c *rootfsCheck) makeImageAndVolumes(ctx context.Context) bool {
c.image = c.prefix + ":latest"
if err := c.rt.importTree(ctx, c.b.tree, c.image); err != nil {
return c.runtimeFailed(ctx, "import", err)
}
- for _, v := range []string{c.prefix + "-data", c.prefix + "-run"} {
- c.volumes = append(c.volumes, v)
- _, err := c.rt.run(ctx, nil, "volume", "create", "--label", "carlos-check="+c.id, "--driver", "local",
- "--opt", "type=tmpfs", "--opt", "device=tmpfs",
- "--opt", fmt.Sprintf("o=uid=%d,gid=%d,mode=0700", checkUID, checkUID), v)
- if err != nil {
+ for _, v := range []struct {
+ name string
+ opts []string
+ }{
+ {c.prefix + "-data", nil},
+ {c.prefix + "-run", []string{"--opt", "type=tmpfs", "--opt", "device=tmpfs",
+ "--opt", fmt.Sprintf("o=uid=%d,gid=%d,mode=0700", checkUID, checkUID)}},
+ } {
+ c.volumes = append(c.volumes, v.name)
+ args := append([]string{"volume", "create", "--label", "carlos-check=" + c.id, "--driver", "local"}, v.opts...)
+ if _, err := c.rt.run(ctx, nil, append(args, v.name)...); err != nil {
return c.runtimeFailed(ctx, "volume create", err)
}
}
return true
}
+// prepareData makes the data volume's root the check user's, mode 0700, as
+// a box makes an instance's directory, before any process runs. A
+// container of its own runs the probe binary's __rootfs-check-prepare as
+// root with CAP_CHOWN alone, no new privileges, no network, a read-only
+// root, and nothing mounted but the data volume and the probe; the check
+// waits for it to exit 0. It is recorded like every container, so the
+// cleanup removes it.
+func (c *rootfsCheck) prepareData(ctx context.Context) bool {
+ // A process's container is <prefix>-<name>, and a worker may be named
+ // prepare (release.ValidWorkerName). The helper's "_" is outside that
+ // grammar, and inside the runtimes' container names
+ // ([a-zA-Z0-9][a-zA-Z0-9_.-]*), so the two never meet. Volumes and the
+ // image are named in namespaces of their own.
+ ctr := c.prefix + "_prepare"
+ args := []string{"run", "-d", "--name", ctr,
+ "--read-only", "--network", "none",
+ "--cap-drop", "ALL", "--cap-add", "CHOWN", "--security-opt", "no-new-privileges",
+ "--platform", "linux/arm64", "--user", "0:0",
+ "-v", c.volumeMount(0, checkDataDir),
+ "-v", c.probe + ":" + checkProbeMount + ":ro",
+ "--entrypoint", checkProbeMount,
+ "--label", "carlos-check=" + c.id,
+ c.image,
+ "__rootfs-check-prepare", "--dir", checkDataDir, "--uid", strconv.Itoa(checkUID),
+ }
+ if !c.launch(ctx, ctr, args) {
+ return false
+ }
+ code, _, err := c.waitExit(ctx, ctr, checkPrepareTimeout)
+ if err != nil {
+ return c.runtimeFailed(ctx, "wait", err)
+ }
+ if code == 0 {
+ return true
+ }
+ logs := c.logs(ctx, ctr)
+ if execFormatError(logs...) {
+ return c.fail(checkNoEmulation)
+ }
+ c.runtimeFailed(ctx, "run", fmt.Errorf("__rootfs-check-prepare exited with status %d", code))
+ c.sayLogs(logs)
+ return false
+}
+
+// volumeMount is the -v value that mounts the check's volume i at path,
+// with nocopy, which Docker and Podman both take for a named volume.
+// Without it both fill an empty volume from the image's directory at path
+// each time a container starts, the directory's owner and mode included:
+// an image holding an empty /data/instances/check would hand the prepared
+// data volume back to root when release or web started, and the run
+// volume, a tmpfs volume emptied whenever no container holds it, would be
+// re-owned the same way at every start. Every mount of either says nocopy.
+func (c *rootfsCheck) volumeMount(i int, path string) string {
+ return c.volumes[i] + ":" + path + ":nocopy"
+}
+
// processVars is process name's environment in the check: its own env,
// then --env's values, then the instance's CARLOS_* values (validation keeps CARLOS_ names out of
// a process's env). There is no CARLOS_CONTROL_SOCKET or CARLOS_PURGE:
@@ -225,8 +295,8 @@ func (c *rootfsCheck) runArgs(ctr, name string) []string {
"--memory", mem, "--memory-swap", mem,
"--cap-drop", "ALL", "--security-opt", "no-new-privileges",
"--platform", "linux/arm64", "--user", user,
- "-v", c.volumes[0] + ":" + checkDataDir,
- "-v", c.volumes[1] + ":" + checkRunDir,
+ "-v", c.volumeMount(0, checkDataDir),
+ "-v", c.volumeMount(1, checkRunDir),
"-v", c.probe + ":" + checkProbeMount + ":ro",
}
vars := c.processVars(name)
@@ -242,19 +312,41 @@ func (c *rootfsCheck) runArgs(ctr, name string) []string {
return append(args, p.Command[1:]...)
}
-// start runs process name detached and answers its container. A run the
-// runtime refused is reported: an arm64 program this machine cannot run is
-// RFS-1-C62.
+// start runs process name detached and answers its container.
func (c *rootfsCheck) start(ctx context.Context, name string) (string, bool) {
ctr := c.prefix + "-" + name
+ return ctr, c.launch(ctx, ctr, c.runArgs(ctr, name))
+}
+
+// launch records container ctr, then asks the runtime to run args, which
+// name it. A run the runtime refused is reported: an arm64 program this
+// machine cannot run is RFS-1-C62.
+func (c *rootfsCheck) launch(ctx context.Context, ctr string, args []string) bool {
c.containers = append(c.containers, ctr)
- if _, err := c.rt.run(ctx, nil, c.runArgs(ctr, name)...); err != nil {
+ if _, err := c.rt.run(ctx, nil, args...); err != nil {
if ctx.Err() == nil && execFormatError(err.Error()) {
- return ctr, c.fail(checkNoEmulation)
+ return c.fail(checkNoEmulation)
}
- return ctr, c.runtimeFailed(ctx, "run", err)
+ return c.runtimeFailed(ctx, "run", err)
+ }
+ return true
+}
+
+// waitExit waits up to timeout for ctr to exit and answers its status.
+// timedOut says the wait ran out of time rather than ctx ending.
+func (c *rootfsCheck) waitExit(ctx context.Context, ctr string, timeout time.Duration) (code int, timedOut bool, err error) {
+ wctx, cancel := context.WithTimeout(ctx, timeout)
+ out, err := c.rt.run(wctx, nil, "wait", ctr)
+ timedOut = wctx.Err() != nil && ctx.Err() == nil
+ cancel()
+ if err != nil {
+ return 0, timedOut, err
+ }
+ code, err = strconv.Atoi(lastLine(string(out)))
+ if err != nil {
+ return 0, false, fmt.Errorf("%q is not an exit status", strings.TrimSpace(string(out)))
}
- return ctr, true
+ return code, false, nil
}
// runRelease runs release to its end, under its timeout. A failure stops
@@ -269,20 +361,13 @@ func (c *rootfsCheck) runRelease(ctx context.Context) bool {
if s := c.b.procs[release.ProcessRelease].TimeoutSec; s > 0 {
timeout = time.Duration(s) * time.Second
}
- wctx, cancel := context.WithTimeout(ctx, timeout)
- out, err := c.rt.run(wctx, nil, "wait", ctr)
- timedOut := wctx.Err() != nil
- cancel()
+ code, timedOut, err := c.waitExit(ctx, ctr, timeout)
if err != nil {
- if ctx.Err() == nil && timedOut {
+ if timedOut {
return c.fail(fmt.Sprintf("release did not finish within %s", checkDuration(timeout)))
}
return c.runtimeFailed(ctx, "wait", err)
}
- code, err := strconv.Atoi(lastLine(string(out)))
- if err != nil {
- return c.runtimeFailed(ctx, "wait", fmt.Errorf("%q is not an exit status", strings.TrimSpace(string(out))))
- }
if code == 0 {
c.say(fmt.Sprintf("release finished in %s", checkDuration(time.Since(began))))
return true
diff --git a/ship_check_prepare_test.go b/ship_check_prepare_test.go
new file mode 100644
index 000000000..d0cbc331f
--- /dev/null
+++ b/ship_check_prepare_test.go
@@ -0,0 +1,210 @@
+//go:build unix
+
+package main
+
+import (
+ "errors"
+ "fmt"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "slices"
+ "strconv"
+ "strings"
+ "syscall"
+ "testing"
+)
+
+// __rootfs-check-prepare makes one directory the given user's, mode 0700:
+// that directory alone, never what is in it, and never through a symlink.
+// The test chowns to its own user and group, which needs no privilege.
+func TestPrepareCheckDir(t *testing.T) {
+ uid, gid := os.Getuid(), os.Getgid()
+ owner := func(t *testing.T, p string) (os.FileMode, int, int) {
+ t.Helper()
+ fi, err := os.Lstat(p)
+ if err != nil {
+ t.Fatal(err)
+ }
+ st := fi.Sys().(*syscall.Stat_t)
+ return fi.Mode().Perm(), int(st.Uid), int(st.Gid)
+ }
+
+ dir := filepath.Join(t.TempDir(), "check")
+ if err := os.Mkdir(dir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ inside := filepath.Join(dir, "shop.db")
+ if err := os.WriteFile(inside, nil, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if err := prepareCheckDir(dir, uid, gid); err != nil {
+ t.Fatalf("prepareCheckDir: %v", err)
+ }
+ if mode, u, g := owner(t, dir); mode != 0o700 || u != uid || g != gid {
+ t.Errorf("dir is %v %d:%d, want 0700 %d:%d", mode, u, g, uid, gid)
+ }
+ if mode, _, _ := owner(t, inside); mode != 0o644 {
+ t.Errorf("a file inside became %v: prepare recursed", mode)
+ }
+
+ // A symlink is refused, and its target is left as it was.
+ target := filepath.Join(t.TempDir(), "elsewhere")
+ if err := os.Mkdir(target, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ link := filepath.Join(t.TempDir(), "check")
+ if err := os.Symlink(target, link); err != nil {
+ t.Fatal(err)
+ }
+ if err := prepareCheckDir(link, uid, gid); err == nil {
+ t.Error("prepareCheckDir followed a symlink")
+ }
+ if mode, _, _ := owner(t, target); mode != 0o755 {
+ t.Errorf("the symlink's target became %v", mode)
+ }
+
+ // A file, and a path that is not there, are refused.
+ if err := prepareCheckDir(inside, uid, gid); err == nil {
+ t.Error("prepareCheckDir took a file")
+ }
+ if mode, _, _ := owner(t, inside); mode != 0o644 {
+ t.Errorf("a refused file became %v", mode)
+ }
+ if err := prepareCheckDir(filepath.Join(dir, "missing"), uid, gid); err == nil {
+ t.Error("prepareCheckDir took a missing path")
+ }
+}
+
+// prepareCheckDir sets the mode, then the owner, with exactly the
+// arguments the check needs. The order is the property: in the prepare
+// container root holds CAP_CHOWN alone, so once the directory is 65534's it
+// could no longer chmod it (that needs CAP_FOWNER). CI has no root to give
+// a directory away, so this pins the calls through the checkChmod and
+// checkLchown seams; the capabilities themselves are witnessed by the
+// rootful Podman run on a dev box (rootfs Plan 4 Task 11, 2026-10-29).
+func TestPrepareCheckDirSetsModeThenOwner(t *testing.T) {
+ var calls []string
+ oldChmod, oldLchown := checkChmod, checkLchown
+ t.Cleanup(func() { checkChmod, checkLchown = oldChmod, oldLchown })
+ checkChmod = func(name string, mode os.FileMode) error {
+ calls = append(calls, fmt.Sprintf("chmod %s %#o", name, mode))
+ return nil
+ }
+ checkLchown = func(name string, uid, gid int) error {
+ calls = append(calls, fmt.Sprintf("lchown %s %d:%d", name, uid, gid))
+ return nil
+ }
+
+ dir := filepath.Join(t.TempDir(), "check")
+ if err := os.Mkdir(dir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := prepareCheckDir(dir, 65534, 65534); err != nil {
+ t.Fatalf("prepareCheckDir: %v", err)
+ }
+ want := []string{"chmod " + dir + " 0700", "lchown " + dir + " 65534:65534"}
+ if !slices.Equal(calls, want) {
+ t.Errorf("calls %q, want %q", calls, want)
+ }
+
+ // The verb gives --uid as the group too.
+ calls = nil
+ if got := runRootfsCheckPrepare([]string{"--dir", dir, "--uid", "65534"}); got != 0 || !slices.Equal(calls, want) {
+ t.Errorf("the verb: exit %d, calls %q, want 0 and %q", got, calls, want)
+ }
+
+ // A refused path is never changed; a chmod that fails stops the chown.
+ link := filepath.Join(t.TempDir(), "link")
+ if err := os.Symlink(dir, link); err != nil {
+ t.Fatal(err)
+ }
+ calls = nil
+ if err := prepareCheckDir(link, 65534, 65534); err == nil || len(calls) != 0 {
+ t.Errorf("a symlink: %v, calls %q", err, calls)
+ }
+ checkChmod = func(string, os.FileMode) error { return errors.New("operation not permitted") }
+ calls = nil
+ if err := prepareCheckDir(dir, 65534, 65534); err == nil || len(calls) != 0 {
+ t.Errorf("a failed chmod: %v, calls %q", err, calls)
+ }
+}
+
+// The verb's exit statuses: 0 done, 1 refused, 2 a flag error.
+func TestRunRootfsCheckPrepareExits(t *testing.T) {
+ dir := filepath.Join(t.TempDir(), "check")
+ if err := os.Mkdir(dir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ link := filepath.Join(t.TempDir(), "link")
+ if err := os.Symlink(dir, link); err != nil {
+ t.Fatal(err)
+ }
+ // The verb gives --uid as both user and group, so run it with the group
+ // it would set only when this user's group has the same number.
+ if os.Getuid() == os.Getgid() {
+ if got := runRootfsCheckPrepare([]string{"--dir", dir, "--uid", strconv.Itoa(os.Getuid())}); got != 0 {
+ t.Errorf("a directory: exit %d, want 0", got)
+ }
+ }
+ if got := runRootfsCheckPrepare([]string{"--dir", link, "--uid", strconv.Itoa(os.Getuid())}); got != 1 {
+ t.Errorf("a symlink: exit %d, want 1", got)
+ }
+ for _, args := range [][]string{
+ nil,
+ {"--uid", "65534"},
+ {"--dir", dir},
+ {"--dir", dir, "--uid", "-1"},
+ {"--dir", dir, "--uid", "x"},
+ {"--dir", dir, "--uid", "65534", "extra"},
+ {"--nope"},
+ } {
+ if got := runRootfsCheckPrepare(args); got != 2 {
+ t.Errorf("%q: exit %d, want 2", args, got)
+ }
+ }
+}
+
+// The binary dispatches the verb before its command switch, as it does
+// __rootfs-check-probe: the prepare container runs it by that name.
+func TestRootfsCheckPrepareThroughTheBinary(t *testing.T) {
+ if testing.Short() {
+ t.Skip("runs the carlos binary")
+ }
+ if os.Getuid() != os.Getgid() {
+ t.Skip("the verb sets --uid as the group too, which this user may not")
+ }
+ bin := buildCarlos(t)
+ dir := filepath.Join(t.TempDir(), "check")
+ if err := os.Mkdir(dir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ link := filepath.Join(t.TempDir(), "link")
+ if err := os.Symlink(dir, link); err != nil {
+ t.Fatal(err)
+ }
+ run := func(args ...string) (int, string) {
+ cmd := exec.Command(bin, append([]string{"__rootfs-check-prepare"}, args...)...)
+ cmd.Env = carlosTestEnv(t)
+ cmd.Dir = t.TempDir()
+ out, err := cmd.CombinedOutput()
+ var ee *exec.ExitError
+ if errors.As(err, &ee) {
+ return ee.ExitCode(), string(out)
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ return 0, string(out)
+ }
+ uid := strconv.Itoa(os.Getuid())
+ if code, out := run("--dir", link, "--uid", uid); code != 1 || !strings.Contains(out, "is not a directory") {
+ t.Errorf("a symlink: exit %d, %q; want 1 and the reason", code, out)
+ }
+ if code, out := run("--dir", dir, "--uid", uid); code != 0 {
+ t.Fatalf("a directory: exit %d, %q", code, out)
+ }
+ if fi, err := os.Lstat(dir); err != nil || fi.Mode().Perm() != 0o700 {
+ t.Errorf("after the verb the directory is %v (%v), want 0700", fi.Mode().Perm(), err)
+ }
+}
diff --git a/ship_check_probe.go b/ship_check_probe.go
index 0be29f778..96184ff4c 100644
--- a/ship_check_probe.go
+++ b/ship_check_probe.go
@@ -100,6 +100,53 @@ func runRootfsCheckProbe(args []string) int {
}
}
+// runRootfsCheckPrepare is __rootfs-check-prepare, run in the check's
+// prepare container as root with CAP_CHOWN alone: it makes the directory at
+// --dir mode 0700 and owned by --uid, as user and group (prepareCheckDir).
+// Exit 0 when done, 1 when refused or failed (the reason on stderr, which
+// the check shows as the container's last lines), 2 on a flag error.
+func runRootfsCheckPrepare(args []string) int {
+ fs := flag.NewFlagSet("__rootfs-check-prepare", flag.ContinueOnError)
+ fs.SetOutput(io.Discard)
+ dir := fs.String("dir", "", "the directory to prepare")
+ uid := fs.Int("uid", -1, "its owner, as user and group")
+ if err := fs.Parse(args); err != nil || *dir == "" || *uid < 0 || fs.NArg() > 0 {
+ return 2
+ }
+ if err := prepareCheckDir(*dir, *uid, *uid); err != nil {
+ fmt.Fprintln(os.Stderr, err)
+ return 1
+ }
+ return 0
+}
+
+// checkChmod and checkLchown are prepareCheckDir's two changes. Vars so a
+// test can pin their order and arguments: CI has no root to give a
+// directory away. Production never changes them.
+var (
+ checkChmod = os.Chmod
+ checkLchown = os.Lchown
+)
+
+// prepareCheckDir makes dir mode 0700 and owned by uid:gid: dir alone,
+// never what is in it, and never through a symlink, which Lstat refuses
+// with anything else that is not a directory. The mode goes first: once
+// the directory is another user's, root without CAP_FOWNER could no longer
+// change it.
+func prepareCheckDir(dir string, uid, gid int) error {
+ fi, err := os.Lstat(dir)
+ if err != nil {
+ return err
+ }
+ if !fi.IsDir() {
+ return fmt.Errorf("%s is not a directory", dir)
+ }
+ if err := checkChmod(dir, 0o700); err != nil {
+ return err
+ }
+ return checkLchown(dir, uid, gid)
+}
+
// checkProbeGet asks GET / once, for the check's host, and answers the
// status.
func checkProbeGet(ctx context.Context, client *http.Client) (int, error) {
diff --git a/ship_check_test.go b/ship_check_test.go
index 95cf367a0..cd59958b2 100644
--- a/ship_check_test.go
+++ b/ship_check_test.go
@@ -27,7 +27,9 @@ import (
// objects the check made, which must end empty.
// checkName is the shape of every name the check gives the runtime.
-var checkName = regexp.MustCompile(`^carlos-check-[0-9a-f]{8}(-[a-z][a-z0-9-]*|:latest)$`)
+// A process's container is <prefix>-<process>; the check's own helper is
+// <prefix>_<helper>, a form no process name can take.
+var checkName = regexp.MustCompile(`^carlos-check-[0-9a-f]{8}(-[a-z][a-z0-9-]*|_[a-z]+|:latest)$`)
type fakeCheck struct {
t *testing.T
@@ -39,8 +41,9 @@ type fakeCheck struct {
cleaning bool
arch string
- waitOut string
- waitHang bool
+ waitOut string // every wait's answer, unless waitBy has the process
+ waitBy map[string]string // wait's answer, by process
+ waitHang string // the process whose wait never returns
probeOut string
probeErr error
runErr map[string]error // by process
@@ -60,6 +63,7 @@ func newFakeCheck(t *testing.T) *fakeCheck {
t: t, made: map[string]bool{}, live: map[string]bool{},
arch: "aarch64", waitOut: "0\n", probeOut: `{"status":200,"after_ms":42}` + "\n",
runErr: map[string]error{}, state: map[string]string{}, logs: map[string]string{},
+ waitBy: map[string]string{},
failAt: -1, cancelAt: -1, out: &bytes.Buffer{},
removeErr: map[string]error{},
}
@@ -67,9 +71,10 @@ func newFakeCheck(t *testing.T) *fakeCheck {
func (f *fakeCheck) rt() containerRuntime { return containerRuntime{name: "docker", run: f.run} }
-// procOf is the process a container is named for.
+// procOf is the process a container is named for, or "_" and the helper's
+// name for one of the check's own (<prefix>_prepare is "_prepare").
func procOf(ctr string) string {
- return strings.TrimPrefix(ctr, ctr[:len("carlos-check-")+9])
+ return strings.TrimPrefix(ctr[len("carlos-check-")+8:], "-")
}
func flagValue(args []string, flag string) string {
@@ -129,9 +134,14 @@ func (f *fakeCheck) run(ctx context.Context, stdin io.Reader, args ...string) ([
makes = "container:" + ctr
}
if makes != "" {
- if name := makes[strings.IndexByte(makes, ':')+1:]; !checkName.MatchString(name) {
+ name := makes[strings.IndexByte(makes, ':')+1:]
+ if !checkName.MatchString(name) {
f.t.Errorf("%v names %q", args, name)
}
+ // Docker and Podman refuse a second container by a name in use.
+ if args[0] == "run" && f.made[makes] {
+ return nil, fmt.Errorf(`Error: creating container storage: the container name %q is already in use`, name)
+ }
f.made[makes] = true
}
if args[0] == "import" {
@@ -160,10 +170,14 @@ func (f *fakeCheck) run(ctx context.Context, stdin io.Reader, args ...string) ([
case "run":
return []byte("0123abcd\n"), f.runErr[procOf(flagValue(args, "--name"))]
case "wait":
- if f.waitHang {
+ proc := procOf(last)
+ if f.waitHang == proc {
<-ctx.Done()
return nil, ctx.Err()
}
+ if out, ok := f.waitBy[proc]; ok {
+ return []byte(out), nil
+ }
return []byte(f.waitOut), nil
case "exec":
return []byte(f.probeOut), f.probeErr
@@ -295,8 +309,9 @@ func TestRootfsCheckHappyPath(t *testing.T) {
want := []string{
"info", "import", "volume create data", "volume create run",
+ "run _prepare", "wait _prepare",
"run release", "wait release", "run web", "exec web", "run jobs", "inspect jobs",
- "rm -f release", "rm -f web", "rm -f jobs", "volume rm data", "volume rm run", "rmi",
+ "rm -f _prepare", "rm -f release", "rm -f web", "rm -f jobs", "volume rm data", "volume rm run", "rmi",
}
if got := f.summary(); !slices.Equal(got, want) {
t.Errorf("calls:\n got %q\nwant %q", got, want)
@@ -401,8 +416,8 @@ func TestRootfsCheckRunArgs(t *testing.T) {
}
}
wantMounts := []string{
- prefix + "-data:/data/instances/check",
- prefix + "-run:/run/carlos/instances/check",
+ prefix + "-data:/data/instances/check:nocopy",
+ prefix + "-run:/run/carlos/instances/check:nocopy",
"/probe/carlos:/opt/carlos/carlos:ro",
}
if !slices.Equal(mounts, wantMounts) {
@@ -457,12 +472,30 @@ func TestRootfsCheckRunArgs(t *testing.T) {
if want := []string{"exec", name, "/opt/carlos/carlos", "__rootfs-check-probe", "--socket", "/run/carlos/instances/check/app.sock", "--timeout", "120s"}; !slices.Equal(exec, want) {
t.Errorf("exec = %q, want %q", exec, want)
}
- // Volumes are tmpfs, owned by the check's user.
- if want := []string{"volume", "create", "--label", "carlos-check=" + id, "--driver", "local", "--opt", "type=tmpfs", "--opt", "device=tmpfs", "--opt", "o=uid=65534,gid=65534,mode=0700", prefix + "-data"}; !slices.Equal(f.calls[2], want) {
- t.Errorf("volume create = %q, want %q", f.calls[2], want)
+ // The data volume is a plain local volume, so what release writes is
+ // still there for web, as on a box's disk: a tmpfs volume is emptied
+ // whenever no container holds it. The run volume, the socket's, is
+ // tmpfs, owned by the check's user.
+ creates := map[string][]string{}
+ for _, c := range f.calls {
+ if c[0] == "volume" && c[1] == "create" {
+ creates[procOf(c[len(c)-1])] = c
+ }
+ }
+ if want := []string{"volume", "create", "--label", "carlos-check=" + id, "--driver", "local", prefix + "-data"}; !slices.Equal(creates["data"], want) {
+ t.Errorf("data volume create = %q, want %q", creates["data"], want)
}
- if want := []string{"inspect", "--format", "{{json .State}}", prefix + "-jobs"}; !slices.Equal(f.calls[9], want) {
- t.Errorf("inspect = %q, want %q", f.calls[9], want)
+ if want := []string{"volume", "create", "--label", "carlos-check=" + id, "--driver", "local", "--opt", "type=tmpfs", "--opt", "device=tmpfs", "--opt", "o=uid=65534,gid=65534,mode=0700", prefix + "-run"}; !slices.Equal(creates["run"], want) {
+ t.Errorf("run volume create = %q, want %q", creates["run"], want)
+ }
+ var inspect []string
+ for _, c := range f.calls {
+ if c[0] == "inspect" {
+ inspect = c
+ }
+ }
+ if want := []string{"inspect", "--format", "{{json .State}}", prefix + "-jobs"}; !slices.Equal(inspect, want) {
+ t.Errorf("inspect = %q, want %q", inspect, want)
}
}
@@ -535,7 +568,7 @@ func TestRootfsCheckReleaseFailureStopsTheCheck(t *testing.T) {
noSettle(t)
t.Run("an exit", func(t *testing.T) {
f := newFakeCheck(t)
- f.waitOut = "3\n"
+ f.waitBy["release"] = "3\n"
f.logs["release"] = "migrating\nno such table: orders\n"
r := runRootfsCheck(context.Background(), f.rt(), shopBuild(t, shopProcs()), "/probe/carlos", f.out)
want := []string{"release exited with status 3. its last lines:", " migrating", " no such table: orders", checkC75}
@@ -549,7 +582,7 @@ func TestRootfsCheckReleaseFailureStopsTheCheck(t *testing.T) {
})
t.Run("a timeout", func(t *testing.T) {
f := newFakeCheck(t)
- f.waitHang = true
+ f.waitHang = release.ProcessRelease
procs := shopProcs()
procs[release.ProcessRelease] = release.Process{Command: []string{"/srv/migrate"}, TimeoutSec: 1}
r := runRootfsCheck(context.Background(), f.rt(), shopBuild(t, procs), "/probe/carlos", f.out)
@@ -564,6 +597,175 @@ func TestRootfsCheckReleaseFailureStopsTheCheck(t *testing.T) {
})
}
+// The data volume is a new local volume, so root's: before any process
+// runs, one container of its own makes it the check user's, mode 0700, as
+// root with CAP_CHOWN alone, no network, and only that volume and the
+// probe binary mounted.
+func TestRootfsCheckPreparesTheDataVolume(t *testing.T) {
+ noSettle(t)
+ for _, c := range []struct {
+ name string
+ procs map[string]release.Process
+ first string // the first process after prepare
+ }{
+ {"with release", shopProcs(), "run release"},
+ {"web alone", map[string]release.Process{release.ProcessWeb: shopProcs()[release.ProcessWeb]}, "run web"},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ f := newFakeCheck(t)
+ r := runRootfsCheck(context.Background(), f.rt(), shopBuild(t, c.procs), "/probe/carlos", f.out)
+ if r.failed {
+ t.Fatalf("report = %q", r.lines)
+ }
+ sum := f.summary()
+ at := slices.Index(sum, "run _prepare")
+ if at < 0 || at+2 >= len(sum) || sum[at+1] != "wait _prepare" || sum[at+2] != c.first {
+ t.Fatalf("calls %q: want run _prepare, wait _prepare, then %s", sum, c.first)
+ }
+ if create := slices.Index(sum, "volume create data"); create < 0 || create > at {
+ t.Errorf("calls %q: prepare before the data volume exists", sum)
+ }
+ prep := f.runOf("_prepare")
+ name := flagValue(prep, "--name")
+ prefix := strings.TrimSuffix(name, "_prepare")
+ id := strings.TrimPrefix(prefix, "carlos-check-")
+ want := []string{"run", "-d", "--name", name,
+ "--read-only", "--network", "none",
+ "--cap-drop", "ALL", "--cap-add", "CHOWN", "--security-opt", "no-new-privileges",
+ "--platform", "linux/arm64", "--user", "0:0",
+ "-v", prefix + "-data:/data/instances/check:nocopy",
+ "-v", "/probe/carlos:/opt/carlos/carlos:ro",
+ "--entrypoint", "/opt/carlos/carlos",
+ "--label", "carlos-check=" + id,
+ prefix + ":latest",
+ "__rootfs-check-prepare", "--dir", "/data/instances/check", "--uid", "65534",
+ }
+ if !slices.Equal(prep, want) {
+ t.Errorf("prepare's argv\n got %q\nwant %q", prep, want)
+ }
+ var caps []string
+ for i, a := range prep {
+ if a == "--cap-add" {
+ caps = append(caps, prep[i+1])
+ }
+ }
+ if !slices.Equal(caps, []string{"CHOWN"}) {
+ t.Errorf("prepare adds %q, want CHOWN alone", caps)
+ }
+ if !slices.Contains(sum, "rm -f _prepare") {
+ t.Errorf("calls %q: the prepare container is never removed", sum)
+ }
+ f.checkLeftNothing(t)
+ })
+ }
+}
+
+// The helper's container is named outside the process names' grammar, so a
+// release may declare a worker named prepare, and it runs as any worker.
+func TestRootfsCheckWorkerNamedLikeTheHelper(t *testing.T) {
+ noSettle(t)
+ if !release.ValidWorkerName("prepare") {
+ t.Fatal("prepare is no longer a valid worker name; pick another of the helper's names")
+ }
+ f := newFakeCheck(t)
+ procs := shopProcs()
+ procs["prepare"] = release.Process{Command: []string{"/srv/jobs", "prepare"}}
+ r := runRootfsCheck(context.Background(), f.rt(), shopBuild(t, procs), "/probe/carlos", f.out)
+ if r.failed {
+ t.Fatalf("report = %q", r.lines)
+ }
+ if !slices.Contains(r.lines, "prepare is still running after 5.0 s") {
+ t.Errorf("report = %q, want the prepare worker running", r.lines)
+ }
+ if w := f.runOf("prepare"); w == nil || flagValue(w, "--entrypoint") != "/srv/jobs" {
+ t.Errorf("the prepare worker ran as %q", w)
+ }
+ if h := f.runOf("_prepare"); h == nil || flagValue(h, "--entrypoint") != "/opt/carlos/carlos" {
+ t.Errorf("the helper ran as %q", h)
+ }
+ f.checkLeftNothing(t)
+}
+
+// Docker and Podman fill an empty named volume from the image's directory
+// at the mount point each time a container starts, owner and mode
+// included. The data volume stays empty after prepare, so an image with an
+// empty /data/instances/check would hand it back to root at release's or
+// web's start; the run volume, tmpfs, is empty at every start. So every
+// mount of either volume, in every container the check runs, says nocopy.
+func TestRootfsCheckVolumesNeverCopyUp(t *testing.T) {
+ noSettle(t)
+ f := newFakeCheck(t)
+ if r := runRootfsCheck(context.Background(), f.rt(), shopBuild(t, shopProcs()), "/probe/carlos", f.out); r.failed {
+ t.Fatalf("report = %q", r.lines)
+ }
+ runs := 0
+ for _, c := range f.calls {
+ if c[0] != "run" {
+ continue
+ }
+ runs++
+ name := flagValue(c, "--name")
+ prefix := name[:len("carlos-check-")+8]
+ var vols []string
+ for i, a := range c {
+ if a == "-v" && strings.HasPrefix(c[i+1], prefix+"-") {
+ vols = append(vols, c[i+1])
+ }
+ }
+ want := []string{prefix + "-data:/data/instances/check:nocopy", prefix + "-run:/run/carlos/instances/check:nocopy"}
+ if procOf(name) == "_prepare" {
+ want = want[:1]
+ }
+ if !slices.Equal(vols, want) {
+ t.Errorf("%s mounts %q, want %q", procOf(name), vols, want)
+ }
+ }
+ if runs != 4 {
+ t.Errorf("%d runs, want prepare, release, web and jobs", runs)
+ }
+}
+
+// A prepare that does not exit 0 fails the check before any process runs,
+// and the check still removes everything it made.
+func TestRootfsCheckPrepareFailureStopsTheCheck(t *testing.T) {
+ noSettle(t)
+ for _, c := range []struct {
+ name string
+ setup func(f *fakeCheck)
+ want []string
+ }{
+ {"an exit", func(f *fakeCheck) {
+ f.waitBy["_prepare"] = "1\n"
+ f.logs["_prepare"] = "chown /data/instances/check: operation not permitted\n"
+ }, []string{"docker run: __rootfs-check-prepare exited with status 1", " chown /data/instances/check: operation not permitted", checkC75}},
+ {"an amd64 probe", func(f *fakeCheck) {
+ f.waitBy["_prepare"] = "255\n"
+ f.logs["_prepare"] = `exec /opt/carlos/carlos: exec format error` + "\n"
+ }, []string{checkNoEmulation, checkC75}},
+ {"not an exit status", func(f *fakeCheck) {
+ f.waitBy["_prepare"] = "gone\n"
+ }, []string{`docker wait: "gone" is not an exit status`, checkC75}},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ f := newFakeCheck(t)
+ c.setup(f)
+ r := runRootfsCheck(context.Background(), f.rt(), shopBuild(t, shopProcs()), "/probe/carlos", f.out)
+ if !r.failed || !slices.Equal(r.lines[1:], c.want) {
+ t.Errorf("report = %q (failed %v), want C60 then %q", r.lines, r.failed, c.want)
+ }
+ for _, s := range f.summary() {
+ if s == "run release" || s == "run web" || s == "run jobs" {
+ t.Errorf("%q after prepare failed", s)
+ }
+ }
+ if !slices.Contains(f.summary(), "rm -f _prepare") {
+ t.Errorf("calls %q: the prepare container is never removed", f.summary())
+ }
+ f.checkLeftNothing(t)
+ })
+ }
+}
+
func TestRootfsCheckWorkerThatExits(t *testing.T) {
noSettle(t)
f := newFakeCheck(t)
@@ -787,6 +989,7 @@ run) env | LC_ALL=C sort > "$work/env-run"
done
find "$TMPDIR" -name '*.env' >> "$log" ;;
exec) echo "$FAKE_PROBE"; exit "$FAKE_PROBE_EXIT" ;;
+wait) echo 0 ;;
inspect) echo '{"Running":true}' ;;
esac
exit 0
@@ -833,7 +1036,8 @@ exit 0
}
log, _ := os.ReadFile(logPath)
for _, want := range []string{"rm -f carlos-check-", "volume rm carlos-check-", "rmi carlos-check-",
- " -e HTTP_PROXY=http://proxy.example.com:3128 ", " -e docker_host=tcp://example.com:2375 "} {
+ " -e HTTP_PROXY=http://proxy.example.com:3128 ", " -e docker_host=tcp://example.com:2375 ",
+ " --cap-add CHOWN ", " __rootfs-check-prepare --dir /data/instances/check --uid 65534\n"} {
if !strings.Contains(string(log), want) {
t.Errorf("the runtime never saw %q:\n%s", want, log)
}
@@ -947,8 +1151,8 @@ func TestShipCheckWithoutEnvUnchanged(t *testing.T) {
"--memory", "1073741824", "--memory-swap", "1073741824",
"--cap-drop", "ALL", "--security-opt", "no-new-privileges",
"--platform", "linux/arm64", "--user", "65534:65534",
- "-v", prefix + "-data:/data/instances/check",
- "-v", prefix + "-run:/run/carlos/instances/check",
+ "-v", prefix + "-data:/data/instances/check:nocopy",
+ "-v", prefix + "-run:/run/carlos/instances/check:nocopy",
"-v", "/probe/carlos:/opt/carlos/carlos:ro",
"-e", "A_FIRST=1",
"-e", "CARLOS_DB=/data/instances/check/shop.example.com.db",
@@ -1148,6 +1352,7 @@ run) env | LC_ALL=C sort > "$work/env-run"
prev=$a
done ;;
exec) echo '{"status":200,"after_ms":7}' ;;
+wait) echo 0 ;;
inspect) echo '{"Running":true}' ;;
esac
exit 0
diff --git a/ship_rootfs_unix_test.go b/ship_rootfs_unix_test.go
index f85f9197b..18d1ad00a 100644
--- a/ship_rootfs_unix_test.go
+++ b/ship_rootfs_unix_test.go
@@ -111,6 +111,7 @@ func TestShipRootfsCheckCleansUpOnInterrupt(t *testing.T) {
case "$1" in
info) echo aarch64 ;;
import) cat > /dev/null ;;
+wait) echo 0 ;;
exec) : > "$FAKE_READY"; exec sleep 60 ;;
esac
exit 0