carlos / platform Public

Merge main into audit-request-path

# Conflicts:
#	internal/provision/testdata/plan14-root-reads-chain.tsv
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev e01d942c419b223f34420d980441c76871bc9f92 parent 688c8e3parent 1e2958c
14 files changed, +450 −14
  • README.md +4 −0
  • docs/superpowers/notes/census-proposal-audit-request-path.md +1 −1
  • docs/superpowers/notes/census-proposal-sec-unit-app-demobuild.md +26 −0
  • docs/superpowers/plans/2026-11-16-gvisor-flagship-demos.md +166 −0
  • internal/caps/render.go +12 −0
  • internal/caps/render_test.go +45 −0
  • internal/caps/testdata/gotenberg.service.conf +2 −0
  • internal/demobuild/unit.go +39 −12
  • internal/demobuild/unit_cache_chmod_test.go +75 −0
  • internal/host/units/carlos-app@.service +28 −0
  • internal/host/units_isolation_test.go +29 −0
  • internal/provision/testdata/plan14-root-reads-chain.tsv +2 −1
  • internal/provision/testdata/plan14-root-reads-sec-unit-app-demobuild.tsv +14 −0
  • internal/registry/registry.go +7 −0

CI passed — run details

diff --git a/README.md b/README.md
index 6c448fc4d..df7f03104 100644
--- a/README.md
+++ b/README.md
@@ -1381,6 +1381,10 @@ design's §5 migration steps). Stamping it arms the **hourly**
`carlos-adopt.timer`, and `carlos adopt` for a `daemon` route enables and
STARTS the service — so the data copy comes before the stamp, not after it.
+**Unit backing is for operator-trusted tenants only.** A `carlos-app@<host>`
+tenant can reach loopback, the VPC and abstract unix sockets, so never set
+`--backing unit` for a tenant you would not give a shell on the box.
+
A declared-but-ungranted capability does not fail the app or fail adoption:
the drop-in simply is not written, and the hourly adopt pass logs one line
naming the route, the capability, and the exact grant command. The mirror
diff --git a/docs/superpowers/notes/census-proposal-audit-request-path.md b/docs/superpowers/notes/census-proposal-audit-request-path.md
index ed9e59aca..3e2673e97 100644
--- a/docs/superpowers/notes/census-proposal-audit-request-path.md
+++ b/docs/superpowers/notes/census-proposal-audit-request-path.md
@@ -20,6 +20,6 @@ New dispositions, which census-propose wrote and the reviewer checks against the
- reads `internal/edge/plandisabled.go:Edge.planDisabledAdmit`: +registry:Host ×3; keeps legacy, task accepted-legacy
-Seal: `4eda67fee53800e2cfa4177b954c7f0fce6bdfcfbfe1aa2547ddcec3027b668b` → `d4519bad26d6ce5254a9de18c85ac51c8b954b071f4a874c85988d9c37fed9b2`.
+Seal: `fea6bec1f00dace47aa6006bf8606602efda4cecfa4fe3c3890136c0fb27720c` → `3f7dc37d114377b168c6bc1ae48e7bf815dbc1f5a569274af642e00e7d08ca2a`.
Overlay: `internal/provision/testdata/plan14-root-reads-audit-request-path.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/notes/census-proposal-sec-unit-app-demobuild.md b/docs/superpowers/notes/census-proposal-sec-unit-app-demobuild.md
new file mode 100644
index 000000000..21559822a
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-sec-unit-app-demobuild.md
@@ -0,0 +1,26 @@
+# Census approval: sec-unit-app-demobuild
+
+Ruling `census-ruling-sec-unit-app-demobuild`. The independent reviewer approves or rejects every change below, 2 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+
+| unit | change | read sites | what changed |
+|---|---|---|---|
+| `internal/caps/render.go` `RenderService` | body | unchanged (2) | sec-review 2026-11-16 D1: a granted doc_engine block also emits the constant lines SystemCallFilter= and SystemCallErrorNumber=, clearing the template's new tenant syscall filter for that tenant only, so a conversion engine keeps the syscall surface it had before this branch. Constant strings, no input reaches them; no other capability changes; no read added. |
+| `internal/host/units/carlos-app@.service` `external` | body | unchanged (1) | sec-review 2026-11-16 D1: the header states unit backing is for operator-trusted tenants only (Paul, 2026-11-16) and set only by box root; the [Service] section gains PrivateIPC=yes, TemporaryFileSystem=/dev/mqueue:ro, ProtectControlGroups=yes, SystemCallArchitectures=native, SystemCallFilter=@system-service, SystemCallFilter=~@keyring io_uring_setup io_uring_enter io_uring_register userfaultfd and SystemCallErrorNumber=ENOSYS, copied from carlos-instance@ (a comment notes that a granted doc_engine drop-in clears the filter). ExecStart, EnvironmentFile, StateDirectory, the /opt binds and IPAddressDeny are unchanged; it only narrows the tenant sandbox. No root read added. |
+
+Envelopes re-pinned: `internal/caps`, `internal/demobuild`, `internal/host/units`, `internal/registry`.
+
+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:
+
+- `internal/caps/render.go` `RenderService`: authority, task E4,J1,J4. Basis: root-input
+- `internal/host/units/carlos-app@.service` `external`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J4;basis=root-input
+
+New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff:
+
+- new `internal/demobuild/unit.go:chmodCacheDirs`: reads +file:WalkDir; written legacy, accepted-legacy, frozen
+- quiet `internal/demobuild/unit.go:Worker.prepareUnit`: reads nothing now; retired while it reads nothing (or its row keeps no sites)
+
+Seal: `4eda67fee53800e2cfa4177b954c7f0fce6bdfcfbfe1aa2547ddcec3027b668b` → `fea6bec1f00dace47aa6006bf8606602efda4cecfa4fe3c3890136c0fb27720c`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-sec-unit-app-demobuild.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/plans/2026-11-16-gvisor-flagship-demos.md b/docs/superpowers/plans/2026-11-16-gvisor-flagship-demos.md
new file mode 100644
index 000000000..6a77d2b51
--- /dev/null
+++ b/docs/superpowers/plans/2026-11-16-gvisor-flagship-demos.md
@@ -0,0 +1,166 @@
+# gVisor on flagship demo boxes: plan (rev 2.1)
+
+**Goal:** flagship demo boxes run anonymous demo code under gVisor (runsc), not the native systemd sandbox. A demo box that isn't explicitly configured for one or the other admits no demos.
+
+**Why now:** flagship demos have been live since 2026-11-11 under the native sandbox. gVisor was built for exactly this workload and has run on the dev demo box since 2026-11-11 (v0.34.47, witness PASS). Paul agreed on 2026-11-16 that we should have a plan.
+
+**Authorities (merged on main):** `docs/superpowers/specs/2026-11-08-gvisor-demos-design.md` (rev 5.5; §4.1 sequences the default), `docs/superpowers/runbooks/gvisor-demos.md` (the dev rollout, whose checks slice 4 carries forward), `docs/superpowers/plans/2026-11-08-gvisor-demos.md`.
+
+**Evidence:** a Fable 5.2 audit of the gVisor path at 3793aa49 (2026-11-16; summary on discussion #1096; findings F1 to F10). It found no path from the payload to root, other tenants or platform state.
+
+**Review history:** round 1 (Astra) was NOT READY, with 4 P1s and 6 P2s; rev 2 answered them. Round 2 (Astra) found no P1 and 7 P2s; rev 2.1 applies those P2s without another round (AGENTS.md stopping rule 1). Both findings files are in `~/.cache/sec-review-20261116/reviews/` on docs-t1 (G-R1-astra.md and G-R2-astra.md).
+
+**Scope:** demo boxes only. Shared pools are a separate, later plan: they need networked egress under gVisor and a cost ruling.
+
+## Facts settled
+
+- **Architecture (F1):** `carlos-flagship-demo-box-1` is t4g.small, arm64 (checked 2026-11-16, profile keymail), the only witnessed architecture. The amd64 witness is owed only if an amd64 demo box is ever added.
+- **One demo box, demos only:** the flagship demo box serves nothing but demos, so a demo-triggered disk or memory exhaustion there takes down the demo service on that box, not other tenants. That is why F5 is cut to its own design below.
+- **Where the setting lives:** `CARLOS_DEMO_BOX` and the demo tuple live in each demo box's root-owned `/etc/carlos/host.env`, preserved by the same per-box mechanism as `CARLOS_FLEET` (README "demo box settings"). `CARLOS_EXEC_SANDBOX` goes in the same file through the same mechanism. Slice 2's first task finds that producer for flagship. If it lives in an infra repo, that change needs scoped approval (AGENTS.md production infrastructure rule).
+
+## Sessions and finish lines
+
+Each slice is its own branch and its own session, and each ends when that slice merges. The handoff (`amadan branch handoff`) carries this plan's review history. Slice 4 is an operation, run in a #421 window by whoever holds the release lock (8a3d302), not a build session.
+
+## Slice 1: bound the root control service's memory (F3) and purge (F6)
+
+Both apply today under the native sandbox, so this slice ships first and protects flagship now.
+
+1. **F3: build output can OOM the root control service.**
+ - **Problem:**
+ - root reads a build output of up to 32 MiB (`internal/demobuild/runner.go` `ValidateOutput`, `io.ReadAll`);
+ - it carries it as `BuildOutput.Binary []byte` (`internal/demobuild/job.go`);
+ - it JSON-encodes it, as base64, into the control response (`internal/instancectl/demo_build.go`);
+ - all of this happens inside `carlos-instance-control` (`MemoryMax=64M`), with up to 4 build slots.
+ - **Fix: bound the peak rather than re-architecting the transport.**
+ - Validate by streaming: `elf.NewFile` over the open file, and sha256 by `io.Copy`.
+ - Admit one output transfer at a time, behind a process-wide semaphore of 1 held from read through response write; other finished builds wait their turn.
+ - Raise the control service's `MemoryMax` to a measured figure covering one transfer (about 32 MiB raw, about 43 MiB base64, plus encoder buffers) on top of today's baseline. 192M is the starting estimate; the measured peak sets the final value.
+ - Keep the size, ELF-segment and digest checks unchanged.
+ - Cleanup: today `Worker.Build` runs its deferred output-dir cleanup before returning, and `handleDemoBuild` encodes afterwards from the in-memory bytes (`worker.go:272`, `demo_build.go:167-174`). Keep that ordering, since the response holds the bytes. Streaming from the file would need an explicit change of who owns the file and when it is cleaned up, which this slice does not make.
+ - **Acceptance:**
+ - The authority is the whole control service under its proposed cgroup cap on the dev demo box. Run builds at the supported concurrency (4 slots, at least one 32 MiB output) and record the cgroup's `memory.peak` and `memory.events` oom/oom_kill counts. Pass: peak under `MemoryMax`, zero OOM events.
+ - Unit tests: four concurrent finished builds serialise and all succeed, and the unit-text test pins the new `MemoryMax`.
+ - Heap sampling is a diagnostic only.
+ - **Why not stream the binary to the agent (fd passing):** it changes the client/upload contract across root and the agent, for a box class that runs only demos. It can be a follow-up if build concurrency grows.
+2. **F6: purge fails on deep or huge trees.**
+ - **Problem:** `internal/instancefs/dirs_linux.go` `removeAt` refuses depth > 64 and calls `Readdirnames(-1)`.
+ - **Fix:** an iterative removal with a fixed budget of at most 3 live directory descriptors, temporary ones included.
+ - It keeps a stack of name components, not fds. To reach a directory it walks from the purge root ONE COMPONENT AT A TIME: `openat2(parentfd, name, RESOLVE_BENEATH|RESOLVE_NO_SYMLINKS|RESOLVE_NO_MAGICLINKS)`, then closes the parent. No joined pathname is ever passed to the kernel, so total path length (beyond PATH_MAX) does not matter. The walk is quadratic in depth, which is accepted.
+ - It reads entries in batches of 256.
+ - The name stack is bounded at 65,536 components (at most about 16 MiB of names). Past that, purge refuses with "too deep", leaves the tree, and marks the demo for operator recovery (`carlos` box verb, documented in the runbook). This is a reachable refusal, accepted; the guest has no directory-depth limit.
+ - **Tests:**
+ - a tree whose total path is over 64 KiB (long 255-byte names), and a 10,000-deep tree, both purge with `RLIMIT_NOFILE` set to 16;
+ - a 100k-entry directory purges with bounded memory;
+ - a directory swapped for a symlink between batches is not followed;
+ - an interrupted purge (error injected mid-walk) resumes and completes on retry.
+
+The census applies (`internal/demobuild`, `internal/instancefs`, `internal/instancectl` and `internal/host/units`). Release with the usual dev-first roll; the dev demo box witnesses one large build and one deep purge.
+
+## Slice 2: demo boxes must state their sandbox (F2), with an alert and a pinned argv (F7)
+
+1. **Explicit, not `auto`.**
+ - A demo box (`CARLOS_DEMO_BOX=1`) whose `CARLOS_EXEC_SANDBOX` is unset or `auto` refuses demo admission and builds, and reports `sandbox: unset on a demo box` in its status. It must state `gvisor`, or `systemd` as an explicit, visible opt-out.
+ - This replaces the design §4.1 `auto` flip. It does not depend on recognising a demo box before its configuration exists: an unconfigured box isn't a demo box and admits no demos.
+ - **Downgrade safety:** the box keeps explicit `gvisor` in host.env, so an older aware release (protocol 1) honours it, and nothing ever relies on `auto`.
+ - **Tests:** config table tests for demo box × {unset, auto, systemd, gvisor} × {aware, older floor}; the admission refusal end to end; and the status field.
+2. **Flagship sequencing (answers the "slice 2 activates early" finding).**
+ - Before slice 2 rolls to flagship, set `CARLOS_EXEC_SANDBOX=systemd` explicitly in the flagship demo box's host.env through the producer, with a backup copy kept. That makes the slice-2 roll a no-op for the mode.
+ - The roll then changes nothing until slice 4 flips that one line. Dev's demo box already says `gvisor`.
+3. **Alert.**
+ - **Expected boxes:** enumerate the demo fleet's non-detached boxes through `registry.ListFleetBoxes` (`internal/registry/fleets.go:685`), with the fleet from the console's `CARLOS_DEMO_FLEET`. Then join each box's report from `fleets/<fleet>/status/boxes/` onto those identities. A registered box with no report, an aged-out or deleted report, or a failed registry or listing read raises the alert as "unknown".
+ - **Intent:**
+ - Add a `sandbox_intent` column to demo settings (`internal/console/demo_store.go`; an additive migration, default `systemd`).
+ - It changes only through an ops-owner CLI/API door with step-up: `carlos demo sandbox-intent gvisor|systemd`, audited.
+ - Slice 4 sets it to `gvisor` when it flips.
+ - **Fires** when a box's effective sandbox differs from the intent.
+ - **Review gates:** the alert's text, and any sandbox field shown in the console, go through the UX pass and copy review before merge (AGENTS.md).
+ - **Also fires** when the report is absent, unreadable or older than 3 heartbeat intervals, when gVisor reports blocked (not Ready), and when the mode is unset.
+ - **Detached boxes** and a deliberate rollback, recorded by setting intent back to `systemd`, are quiet.
+ - "Quiet" never counts as success: slice 4's witness also requires a fresh positive report.
+ - **Tests:** rule registration, the incident lifecycle (open, resolve) and notification, through the existing alerts engine tests.
+4. **F7:** add `--platform=systrap` and an explicit `--directfs=` value (the value chosen in slice 3 step 1; until then the release's current default, written out) to the one argv constructor (`internal/execsandbox/command.go`), and to the `systemctl show` assertions derived from it.
+
+**Switch-on date:** the code is live on merge (it refuses unset demo boxes; flagship is explicit `systemd` first, so nothing changes there). The gVisor switch-on is slice 4's window. This branch must not merge until that window is booked with 8a3d302 (AGENTS.md stopping rule 5).
+
+## Slice 3: host-side runsc containment (F4) and diagnostics streams (F9)
+
+1. **F4: measure, then pin, in this order.**
+ 1. Choose the `--directfs` value (it changes which host capabilities the gofer and sentry need).
+ 2. On the disposable root runner (`root-runner`, its own approval scope), measure the minimal capability set and syscall needs for run, build, probe and the stop hooks together. The `instance-exit` hook needs `fchown`. The pinned gofer retains CHOWN, DAC_OVERRIDE, DAC_READ_SEARCH, FOWNER, FSETID and SYS_CHROOT, and runtime setup adds more: measure, don't guess.
+ 3. Pin these in every gVisor template (`carlos-instance-gvisor@`, `carlos-demo-build-gvisor@`, `carlos-instance-gvisor-probe`) AND in the shared assertion set (`internal/execsandbox/hardening.go` `GVisorHardening`, consumed by `internal/instancectl/gvisorunit.go`):
+ - `CapabilityBoundingSet=` (the measured set);
+ - `IPAddressDeny=any` (no host IP traffic expected with `--network=none`; confirmed by witness);
+ - `InaccessiblePaths=/etc/carlos` plus any other root secret path;
+ - `NoNewPrivileges=yes`, if runsc tolerates it.
+ 4. Witness the effective denial: from inside the unit's own context, an attempted host IP connect and a read of `/etc/carlos` both fail. Then witness the full dev runbook on the dev demo box (a separate approval scope from the root runner).
+2. **F9: separate the streams.**
+ - **Problem:** pinned runsc passes its own stderr through to the guest, so `StandardError=journal` would also take the app's stderr away.
+ - **Fix:** route runsc's own diagnostics with runsc's `--debug-log`/`--log` flags to a root-owned file or the journal. Keep guest stdout and stderr on the existing log socket.
+ - **Root hooks:** the `carlos instance-exit` hook and every runsc lifecycle command the unit runs (`gvisorCommands`: run, kill, delete and the probe) never inherit tenant-facing stderr. Each writes its diagnostics to the journal, through `systemd-cat` in the command line or the binary logging to the journal directly. Pick whichever needs no new unit privilege.
+ - Cap the listener (`internal/activator/loglistener.go`) before BOTH sinks: the tenant sink, which already has 1 MiB/minute and a ring (`internal/applog/sink.go`), and agent stdout, which today is uncapped. Bytes over the cap are still drained, and counted in a "dropped" line.
+ - **Tests:** guest stdout and stderr both still reach the tenant log; a runsc error doesn't, and neither does a forced `instance-exit` failure; a flood is drained and reported as dropped.
+
+Slice 3 is required before shared pools. For the demo flip, Paul decides at slice 4 whether it is required or waived.
+
+## Slice 4: flagship flip (an operation, in a #421 window)
+
+**Preconditions:**
+- Slices 1 and 2 are released and rolled to flagship, with the demo box's host.env saying `systemd` explicitly.
+- Slice 3 is released, or waived by Paul.
+- The dev witnesses the earlier rollout deferred are done on dev:
+ - the claim finished by a person under gVisor;
+ - two concurrent builds and two concurrent demos;
+ - a roll that changes the runsc pin;
+ - a rollback from gVisor to systemd.
+
+**Steps,** in the window, with Paul's go and the version from 8a3d302, in the runbook's order with the box name substituted:
+1. **Before the change:** approval recorded; the five runsc assets readable through the box's own store access; privileged acceptance on the current commit; baseline. Then native Ready and drain.
+2. **The change:** flip host.env `systemd` to `gvisor` through the producer, keeping a backup copy, then the coordinated restart of control and the agent.
+3. **After the change, the gVisor witnesses:**
+ - the Ready/probe result;
+ - the five installed member hashes;
+ - instance sandbox status;
+ - full starter build and `Worker.Initialize`;
+ - a disposable demo created, updated, woken and claimed;
+ - a fresh `X-Carlos-Version` receipt;
+ - `/proc/net/dev` read INSIDE the guest, showing loopback only;
+ - a fresh positive report of effective `gvisor`.
+
+ Only then set the console's sandbox intent to `gvisor`.
+
+Rollback is a conditional procedure, not part of the initial run (below).
+
+**Witness demos are disposable:** create, update, wake and claim a throwaway demo. Its claim and deletion are not undone by a rollback, so never use a real visitor's demo. Record the account, region, resources and cleanup in the roll log.
+
+**Rollback:** follow the runbook's rollback: drain, prove the gVisor family is gone, set host.env back to `systemd`, record the intent, restart, and check for a fresh positive `systemd` report. The alert stays quiet because intent matches.
+
+## Cut: per-demo disk bound (F5) gets its own design
+
+- **Why not a scan:** the round-1 review showed a scanned cap cannot stop exhaustion. Unlinked open files and fast writes outrun it, and stopping outside the activator's fences is unsafe (`internal/instancectl/hardening.go:539`).
+- **What a real fix needs:** an enforced boundary. That means a per-demo or aggregate demo filesystem with reserved backing space, inode limits, mount, recovery and purge handling, survival across hibernation, readability during claim export, and native/gVisor parity. That is a design, not a plan task.
+- **Interim (no new code), and what it actually covers:** the flagship demo box runs only demos, so exhaustion is a demo-service outage on that box, not another tenant's.
+ - The existing early disk alert (`internal/host/probes.go` `readDiskFrac`) measures free blocks on `/data` only.
+ - Before relying on it, confirm that the flagship demo box's alert delivery is configured, and record the evidence on #1096.
+ - **Accepted, uncovered:** `/run` tmpfs exhaustion and inode exhaustion can take the demo service down with no warning. That outage is accepted until the F5 design lands.
+ - File the design as a follow-up on #1096.
+
+## Not in this plan
+
+- Shared pools.
+- F8 (guest `noexec` parity) and F10 (fail-closed 503s during rolls); both go on the #1096 follow-up list.
+
+## Round 1 dispositions
+
+| Finding | Disposition |
+|---|---|
+| P1 F3 OOM path | Accepted. Slice 1.1 bounds the peak (one-at-a-time transfer, measured cap, heap high-water test) instead of only streaming validation. |
+| P1 F5 scan insufficient | Accepted. Cut to its own design, with the interim reasoning stated. |
+| P1 slice 2 activates early | Accepted. Explicit `systemd` goes on flagship before the roll, and the flip is the slice 4 line change. |
+| P1 F2 fresh box / downgrade | Accepted. Explicit setting required on demo boxes, `auto` not relied on, admission refused when unset. |
+| P2 alert source and unknown state | Accepted (slice 2.3). |
+| P2 F6 descriptors | Accepted (slice 1.2: 2 fds, name stack, low-NOFILE test, interruption, symlink swap). |
+| P2 F4 scope | Accepted (slice 3.1: directfs first, all templates plus shared assertions, effective-denial witness, separate approval scopes). |
+| P2 F9 streams | Accepted (slice 3.2). |
+| P2 slice 4 evidence | Accepted (runbook checks verbatim, guest-side `/proc/net/dev`, disposable demos, full rollback). |
+| P2 sessions and switch-on | Accepted (sessions section; slice 2 waits for a booked window). |
diff --git a/internal/caps/render.go b/internal/caps/render.go
index 1e2c58b2a..a780167c3 100644
--- a/internal/caps/render.go
+++ b/internal/caps/render.go
@@ -213,6 +213,18 @@ func RenderService(app string, s *Set, g Grants) ([]byte, error) {
"TasksMax="+docEngineTasksMax,
)
+ // The template's tenant syscall filter (sec review 2026-11-16) may
+ // add only what cannot break a tenant, and no conversion engine has
+ // been run under it: Chromium and V8 reach for calls outside
+ // @system-service (pkey_*, ptrace, seccomp). An empty assignment
+ // clears the list, allow and deny halves alike, so an engine keeps
+ // exactly the syscall surface it had before the filter; the error
+ // number goes back to its default with it. PrivateIPC=,
+ // ProtectControlGroups= and SystemCallArchitectures= stay: headless
+ // Chromium and LibreOffice use neither SysV/POSIX IPC across units
+ // nor cgroupfs writes, and run native.
+ lines = append(lines, "SystemCallFilter=", "SystemCallErrorNumber=")
+
// The fence that pays for all of the above. Empty assignment first
// resets the list — same documented systemd pattern the ExecStart
// reset uses — so these bytes are self-contained and do not depend on
diff --git a/internal/caps/render_test.go b/internal/caps/render_test.go
index 2e583c8ec..3cd8da47f 100644
--- a/internal/caps/render_test.go
+++ b/internal/caps/render_test.go
@@ -560,3 +560,48 @@ func TestCommandIdenticalToTemplateDefaultStillEmitsReset(t *testing.T) {
t.Fatalf("got %q, want %q", got, want)
}
}
+
+// TestOnlyDocEngineResetsTheSyscallFilter: carlos-app@ carries the tenant
+// syscall filter (sec review 2026-11-16), which may only add what cannot
+// break a tenant. A conversion engine (Chromium, LibreOffice) has not been
+// run under it, so a granted doc_engine clears it and keeps the behaviour
+// it had before the filter; no other capability touches it.
+func TestOnlyDocEngineResetsTheSyscallFilter(t *testing.T) {
+ syscallLines := func(b []byte) []string {
+ var out []string
+ for _, line := range strings.Split(string(b), "\n") {
+ if strings.HasPrefix(line, "SystemCall") {
+ out = append(out, line)
+ }
+ }
+ return out
+ }
+ engine, err := RenderService("gotenberg", gotenbergSet(t), gotenbergGrants())
+ if err != nil {
+ t.Fatalf("RenderService(gotenberg): %v", err)
+ }
+ if got, want := strings.Join(syscallLines(engine), "|"), "SystemCallFilter=|SystemCallErrorNumber="; got != want {
+ t.Errorf("doc_engine drop-in syscall lines = %q, want %q:\n%s", got, want, engine)
+ }
+
+ others := map[string]func() ([]byte, error){
+ "keymail": func() ([]byte, error) { return RenderService("keymail", keymailSet(t), keymailGrants()) },
+ "console": func() ([]byte, error) { return RenderService("console", consoleSet(t), consoleGrants()) },
+ "engine ungranted": func() ([]byte, error) { return RenderService("gotenberg", gotenbergSet(t), Grants{}) },
+ "children only": func() ([]byte, error) { return RenderService("app", &Set{V: 1, Children: true}, Grants{}) },
+ "runtime_dir only": func() ([]byte, error) { return RenderService("app", &Set{V: 1, RuntimeDir: "app"}, Grants{}) },
+ "engine grant alone": func() ([]byte, error) {
+ return RenderService("app", &Set{V: 1, Command: "serve"}, Grants{DocEngine: true})
+ },
+ "socket": func() ([]byte, error) { return RenderSocket(keymailSet(t), keymailGrants()) },
+ }
+ for name, render := range others {
+ b, err := render()
+ if err != nil {
+ t.Fatalf("%s: %v", name, err)
+ }
+ if l := syscallLines(b); len(l) != 0 {
+ t.Errorf("%s renders %q; only a granted doc_engine resets the syscall filter", name, l)
+ }
+ }
+}
diff --git a/internal/caps/testdata/gotenberg.service.conf b/internal/caps/testdata/gotenberg.service.conf
index 9f3d48bc6..fbbb744ab 100644
--- a/internal/caps/testdata/gotenberg.service.conf
+++ b/internal/caps/testdata/gotenberg.service.conf
@@ -7,5 +7,7 @@ MemoryDenyWriteExecute=no
MemoryMax=4G
MemoryHigh=3680M
TasksMax=2048
+SystemCallFilter=
+SystemCallErrorNumber=
IPAddressDeny=
IPAddressDeny=0.0.0.0/8 10.0.0.0/8 100.64.0.0/10 169.254.0.0/16 169.254.169.254/32 172.16.0.0/12 192.0.0.0/24 192.168.0.0/16 198.18.0.0/15 224.0.0.0/4 240.0.0.0/4 64:ff9b::/96 fc00::/7 fd00:ec2::254/128 fe80::/10 fec0::/10 ff00::/8
diff --git a/internal/demobuild/unit.go b/internal/demobuild/unit.go
index 55705913a..ebecd28d9 100644
--- a/internal/demobuild/unit.go
+++ b/internal/demobuild/unit.go
@@ -225,18 +225,7 @@ func (w *Worker) prepareUnit(ctx context.Context, dir string, src Source) (clean
if err != nil {
return cleanup, err
}
- } else if err = filepath.WalkDir(l.cache, func(p string, de fs.DirEntry, e error) error {
- if e != nil {
- return e
- }
- if de.Type()&os.ModeSymlink != 0 {
- return ErrBuild
- }
- if de.IsDir() {
- return os.Chmod(p, 0777)
- }
- return nil
- }); err != nil {
+ } else if err = chmodCacheDirs(l.cache, 0777); err != nil {
return cleanup, err
}
step = "open-unit-root"
@@ -707,3 +696,41 @@ func buildFailure(step string, err error) error {
log.Printf("demo-build: %s: %v", step, err)
return ErrBuild
}
+
+// beforeCacheChmod is a test seam: where a directory swapped for a link
+// after the walk listed it would race a chmod by path.
+var beforeCacheChmod = func(path string) {}
+
+// chmodCacheDirs sets mode on every directory of the build cache. The walk
+// refuses a link it lists, as before, but a listing is not the chmod: the
+// previous build's tenant wrote this tree, and a directory it swaps for a
+// link after the listing would take a chmod by path, as root, to wherever
+// the link points. So each directory is opened beneath the cache with no
+// link at any component (instancefs.OpenDirBeneath, as ownBuildDirectories
+// does for the gVisor family) and chmodded through that descriptor. Linux
+// only, like the systemd family that calls it; elsewhere OpenDirBeneath
+// answers ErrUnsupported.
+func chmodCacheDirs(cache string, mode os.FileMode) error {
+ return filepath.WalkDir(cache, func(p string, de fs.DirEntry, e error) error {
+ if e != nil {
+ return e
+ }
+ if de.Type()&os.ModeSymlink != 0 {
+ return ErrBuild
+ }
+ if !de.IsDir() {
+ return nil
+ }
+ rel, err := filepath.Rel(cache, p)
+ if err != nil {
+ return err
+ }
+ beforeCacheChmod(p)
+ f, err := instancefs.OpenDirBeneath(cache, rel)
+ if err != nil {
+ return err
+ }
+ defer f.Close()
+ return f.Chmod(mode)
+ })
+}
diff --git a/internal/demobuild/unit_cache_chmod_test.go b/internal/demobuild/unit_cache_chmod_test.go
new file mode 100644
index 000000000..66213905a
--- /dev/null
+++ b/internal/demobuild/unit_cache_chmod_test.go
@@ -0,0 +1,75 @@
+//go:build linux
+
+package demobuild
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+)
+
+// The systemd-family build cache is made world-writable directory by
+// directory, as root, on a tree the previous build's tenant wrote. A
+// directory swapped for a link to somewhere else between the walk listing
+// it and the chmod must not hand that somewhere else mode 0777: the chmod
+// goes through a descriptor opened beneath the cache with no link at any
+// component, so the swap is refused, and ordinary directories still end
+// 0777.
+func TestCacheDirsChmodThroughFD(t *testing.T) {
+ root := t.TempDir()
+ cache := filepath.Join(root, "cache")
+ outside := filepath.Join(root, "outside")
+ for _, d := range []string{filepath.Join(cache, "a", "deep"), filepath.Join(cache, "swap"), outside} {
+ if err := os.MkdirAll(d, 0700); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := os.WriteFile(filepath.Join(cache, "a", "file"), []byte("x"), 0600); err != nil {
+ t.Fatal(err)
+ }
+
+ if err := chmodCacheDirs(cache, 0777); err != nil {
+ t.Fatalf("ordinary tree: %v", err)
+ }
+ for _, d := range []string{cache, filepath.Join(cache, "a"), filepath.Join(cache, "a", "deep"), filepath.Join(cache, "swap")} {
+ if m := cachePerm(t, d); m != 0777 {
+ t.Errorf("%s is %v, want 0777", d, m)
+ }
+ }
+ if m := cachePerm(t, filepath.Join(cache, "a", "file")); m != 0600 {
+ t.Errorf("a file was chmodded: %v", m)
+ }
+
+ if err := os.Chmod(filepath.Join(cache, "swap"), 0700); err != nil {
+ t.Fatal(err)
+ }
+ swap := filepath.Join(cache, "swap")
+ prev := beforeCacheChmod
+ t.Cleanup(func() { beforeCacheChmod = prev })
+ beforeCacheChmod = func(p string) {
+ if p != swap {
+ return
+ }
+ if err := os.Remove(swap); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Symlink(outside, swap); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := chmodCacheDirs(cache, 0777); err == nil {
+ t.Error("a directory swapped for a link was chmodded without an error")
+ }
+ if m := cachePerm(t, outside); m != 0700 {
+ t.Errorf("the link's target is %v after the walk, want 0700: the chmod followed the swapped-in link", m)
+ }
+}
+
+func cachePerm(t *testing.T, p string) os.FileMode {
+ t.Helper()
+ fi, err := os.Lstat(p)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return fi.Mode().Perm()
+}
diff --git a/internal/host/units/carlos-app@.service b/internal/host/units/carlos-app@.service
index 3b79b44bf..b50546f1d 100644
--- a/internal/host/units/carlos-app@.service
+++ b/internal/host/units/carlos-app@.service
@@ -2,6 +2,17 @@
# is also the live/<host> symlink the adopt pass repoints and the unit
# the agent's restartRoute try-restarts).
#
+# Trust: unit backing is for operator-trusted tenants only (Paul,
+# 2026-11-16). It is set only by box root through
+# `carlos route --backing unit` / `carlos add --backing unit`, never by
+# the console. It does not carry the instance sandbox's network fence or
+# abstract-socket scoping: a unit tenant can reach loopback, the VPC and
+# abstract unix sockets. Never set it for a tenant you would not give a
+# shell on the box. The hardening below is only what cannot break such a
+# tenant: no PrivatePIDs= (#528), and no loopback or private-range
+# IPAddressDeny (the edge dials Addr tenants on loopback, and the box's
+# resolver may sit in the VPC).
+#
# DynamicUser: systemd mints an ephemeral uid per service at start — apps
# share no identity with each other or the platform, and nobody manages
# user accounts. State lives in /var/lib/carlos-app/<host> (chowned to
@@ -61,6 +72,14 @@ ProtectKernelLogs=yes
ProtectClock=yes
ProtectHostname=yes
RemoveIPC=yes
+# Each unit gets its own SysV and POSIX IPC namespace (#178). PrivateDevices=
+# carries the host's /dev/mqueue into the private /dev, and that mount would
+# still reach the host namespace's queues, so it is replaced.
+PrivateIPC=yes
+TemporaryFileSystem=/dev/mqueue:ro
+# /sys/fs/cgroup read-only: no write to another unit's cgroup.kill or
+# cgroup.freeze.
+ProtectControlGroups=yes
LockPersonality=yes
RestrictRealtime=yes
RestrictNamespaces=yes
@@ -68,6 +87,15 @@ CapabilityBoundingSet=
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
IPAddressDeny=169.254.169.254/32 fd00:ec2::254/128
MemoryDenyWriteExecute=yes
+SystemCallArchitectures=native
+# The tenant syscall surface (#527 Q5), as on carlos-instance@: systemd's
+# baseline for an ordinary service, less io_uring, the kernel keyring and
+# userfaultfd. A refused call answers ENOSYS, so runtimes take the fallback
+# they already have rather than being killed. A granted doc_engine's
+# drop-in clears it (internal/caps/render.go): no engine has run under it.
+SystemCallFilter=@system-service
+SystemCallFilter=~@keyring io_uring_setup io_uring_enter io_uring_register userfaultfd
+SystemCallErrorNumber=ENOSYS
MemoryMax=512M
# Throttle-and-reclaim before the kill — the same band the exec path's
# memory.high gives (internal/cgroup applyLimit, 90% of max).
diff --git a/internal/host/units_isolation_test.go b/internal/host/units_isolation_test.go
index 9deda0edd..c1b745a1f 100644
--- a/internal/host/units_isolation_test.go
+++ b/internal/host/units_isolation_test.go
@@ -824,3 +824,32 @@ func TestMailerUnitShape(t *testing.T) {
}
}
}
+
+// carlos-app@ is for operator-trusted tenants only (Paul, 2026-11-16): it
+// keeps loopback, the VPC and abstract sockets open, so it gets only the
+// hardening that cannot break such a tenant. The syscall floor and private
+// IPC come from the instance template; PrivatePIDs= (#528's stop race) and
+// a loopback or RFC 1918 fence (the edge dials Addr tenants on loopback,
+// and the box's DNS may sit in the VPC) do not. The IMDS pair stays exact:
+// widening it to 169.254.0.0/16 would cut the VPC resolver at .253.
+func TestAppUnitHardeningFloor(t *testing.T) {
+ u := readUnit(t, "carlos-app@.service")
+ for _, want := range append(slices.Clone(syscallBlock),
+ "ProtectControlGroups=yes", "PrivateIPC=yes", "TemporaryFileSystem=/dev/mqueue:ro",
+ "IPAddressDeny=169.254.169.254/32 fd00:ec2::254/128") {
+ if !hasDirective(u, want) {
+ t.Errorf("carlos-app@.service lacks %q", want)
+ }
+ }
+ for _, d := range directives(u) {
+ if strings.HasPrefix(d, "PrivatePIDs=") {
+ t.Errorf("carlos-app@.service carries %q (#528)", d)
+ }
+ if strings.HasPrefix(d, "IPAddressDeny=") && d != "IPAddressDeny=169.254.169.254/32 fd00:ec2::254/128" {
+ t.Errorf("carlos-app@.service carries %q; only the IMDS pair is fenced here", d)
+ }
+ }
+ if !strings.Contains(u, "operator-trusted tenants only") {
+ t.Error("carlos-app@.service does not state that unit backing is for operator-trusted tenants only")
+ }
+}
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index 372aa8d1f..164b0856c 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -233,4 +233,5 @@ plan14-root-reads-fleet-first-reconcile-speed.tsv 9206205b2a3bf27b8b85310f4a44f9
plan14-root-reads-free-storage-250.tsv 9206205b2a3bf27b8b85310f4a44f94ef0c5886d85d6e55dbf2f22e073a8af11
plan14-root-reads-fleet-first-reconcile-speed-4.tsv 4eda67fee53800e2cfa4177b954c7f0fce6bdfcfbfe1aa2547ddcec3027b668b
plan14-root-reads-sec-edge-redirect-linklocal.tsv 4eda67fee53800e2cfa4177b954c7f0fce6bdfcfbfe1aa2547ddcec3027b668b
-plan14-root-reads-audit-request-path.tsv d4519bad26d6ce5254a9de18c85ac51c8b954b071f4a874c85988d9c37fed9b2
+plan14-root-reads-sec-unit-app-demobuild.tsv fea6bec1f00dace47aa6006bf8606602efda4cecfa4fe3c3890136c0fb27720c
+plan14-root-reads-audit-request-path.tsv 3f7dc37d114377b168c6bc1ae48e7bf815dbc1f5a569274af642e00e7d08ca2a
diff --git a/internal/provision/testdata/plan14-root-reads-sec-unit-app-demobuild.tsv b/internal/provision/testdata/plan14-root-reads-sec-unit-app-demobuild.tsv
new file mode 100644
index 000000000..fb0c6e60a
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-sec-unit-app-demobuild.tsv
@@ -0,0 +1,14 @@
+# Census overlay sec-unit-app-demobuild, written by census-propose (#369). census-ruling-sec-unit-app-demobuild, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-sec-unit-app-demobuild.md.
+# 2 body, 0 sites, 4 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+# 2 new dispositions: 0 reads re-frozen at their disposition with the claim, 1 new units frozen accepted-legacy, 1 quiet units retired while they read nothing, 0 other.
+@legacy a7ce64ca5d18a4206b3c734fc5e19cb19e822f8530e49cd554402b32bf2ffe43 internal/host/units/carlos-app@.service external legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-sec-unit-app-demobuild;basis=sec-review 2026-11-16 D1: the header states unit backing is for operator-trusted tenants only (Paul, 2026-11-16) and set only by box root; the [Service] section gains PrivateIPC=yes, TemporaryFileSystem=/dev/mqueue:ro, ProtectControlGroups=yes, SystemCallArchitectures=native, SystemCallFilter=@system-service, SystemCallFilter=~@keyring io_uring_setup io_uring_enter io_uring_register userfaultfd and SystemCallErrorNumber=ENOSYS, copied from carlos-instance@ (a comment notes that a granted doc_engine drop-in clears the filter). ExecStart, EnvironmentFile, StateDirectory, the /opt binds and IPAddressDeny are unchanged; it only narrows the tenant sandbox. No root read added. file:external@0 b6fcd5eebb2c268734597d44e3f066bdffdbea97d1c1a24884e3c31e571cb4a8
+@legacy 0357359d139f60ef4d8716abaf6baa78faeb313cfb6697111134bd8224f34b1d internal/demobuild/unit.go chmodCacheDirs legacy accepted-legacy accepted-legacy;rev3=census-ruling-sec-unit-app-demobuild;basis=sec-review 2026-11-16 D2: the systemd-family cache chmod, extracted from Worker.prepareUnit. Root walks the build cache (filepath.WalkDir, the same read as before) and still refuses a listed link with ErrBuild; each directory is now opened with instancefs.OpenDirBeneath(cache, rel) (openat2, no link at any component, fstat must be a directory) and chmodded 0777 through that descriptor instead of os.Chmod(path). A directory the previous tenant swaps for a link after the listing is refused, not followed. Reads nothing new; follows less. file:WalkDir@68 a4c07d2bb742a04658e1bd0f851eb02a477569db90f7f68f3f9b45b11d0794ca
+internal/caps/render.go RenderService authority E4,J1,J4 root-input;rev3=census-ruling-sec-unit-app-demobuild;basis=sec-review 2026-11-16 D1: a granted doc_engine block also emits the constant lines SystemCallFilter= and SystemCallErrorNumber=, clearing the template's new tenant syscall filter for that tenant only, so a conversion engine keeps the syscall surface it had before this branch. Constant strings, no input reaches them; no other capability changes; no read added. file:Command@201,file:Command@486 1e7c91e75bc043b352c8ac87f3370d5bc545506e49cd214da8cab8ee01042314
+internal/host/units/carlos-app@.service external legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-sec-unit-app-demobuild;basis=sec-review 2026-11-16 D1: the header states unit backing is for operator-trusted tenants only (Paul, 2026-11-16) and set only by box root; the [Service] section gains PrivateIPC=yes, TemporaryFileSystem=/dev/mqueue:ro, ProtectControlGroups=yes, SystemCallArchitectures=native, SystemCallFilter=@system-service, SystemCallFilter=~@keyring io_uring_setup io_uring_enter io_uring_register userfaultfd and SystemCallErrorNumber=ENOSYS, copied from carlos-instance@ (a comment notes that a granted doc_engine drop-in clears the filter). ExecStart, EnvironmentFile, StateDirectory, the /opt binds and IPAddressDeny are unchanged; it only narrows the tenant sandbox. No root read added. file:external@0 b6fcd5eebb2c268734597d44e3f066bdffdbea97d1c1a24884e3c31e571cb4a8
+internal/demobuild/unit.go chmodCacheDirs legacy accepted-legacy accepted-legacy;rev3=census-ruling-sec-unit-app-demobuild;basis=sec-review 2026-11-16 D2: the systemd-family cache chmod, extracted from Worker.prepareUnit. Root walks the build cache (filepath.WalkDir, the same read as before) and still refuses a listed link with ErrBuild; each directory is now opened with instancefs.OpenDirBeneath(cache, rel) (openat2, no link at any component, fstat must be a directory) and chmodded 0777 through that descriptor instead of os.Chmod(path). A directory the previous tenant swaps for a link after the listing is refused, not followed. Reads nothing new; follows less. file:WalkDir@68 a4c07d2bb742a04658e1bd0f851eb02a477569db90f7f68f3f9b45b11d0794ca
+@remove internal/demobuild/unit.go Worker.prepareUnit
+@removed internal/demobuild/unit.go Worker.prepareUnit H3 census-ruling-sec-unit-app-demobuild;basis=sec-review 2026-11-16 D2: its cache WalkDir moved into chmodCacheDirs, which it calls for the systemd family with mode 0777; nothing else changes.
+@coverage internal/caps 72918a59045a8573edd814c086a1814e51e7273cdbad6108ced14b74ee57d94e
+@coverage internal/demobuild bb7a3cd592cb9f21b62ebb1722e29b93ca6f44661405d6ce7d7261f0dbe8e144
+@coverage internal/host/units fe8840568777278f27cca03af72ba97f2a975f0d7df1cf45f71fad24d29c8fa8
+@coverage internal/registry 1a542542fc8e8e1683fde0f8309b47ceecfec05ee41108bc85e25aa1b5a0bd4d
diff --git a/internal/registry/registry.go b/internal/registry/registry.go
index 05b31ad4c..cf2f74a73 100644
--- a/internal/registry/registry.go
+++ b/internal/registry/registry.go
@@ -307,6 +307,8 @@ type Route struct {
// agent (the activator spawns live/<host> itself — the Eleven shape), or
// BackingUnit = a carlos-app@<host> systemd unit (whole-app tenants:
// DynamicUser, StateDirectory) that the activator drives via systemctl.
+ // Unit backing is for operator-trusted tenants only: the unit has no
+ // network fence or abstract-socket scoping (carlos-app@.service).
Backing string
// Unit is the systemd unit that owns this route's process when it is
@@ -2343,6 +2345,11 @@ func (r *Registry) SetInstancePaths(host, fromDB, fromSock, toDB, toSock string)
// merges into (SetCaps's case) and not a value an hourly pass rewrites
// (SetDBPath's): it is one operator, at one step of a documented migration,
// naming the value they want.
+//
+// BackingUnit is for operator-trusted tenants only: a carlos-app@ tenant
+// can reach loopback, the VPC and abstract unix sockets
+// (carlos-app@.service's header), so never stamp it for a tenant you would
+// not give a shell on the box.
func (r *Registry) SetBacking(host, backing string) error {
if r.remote != nil {
_, err := r.remote.call(nil, remoteRequest{Method: "SetBacking", Host: host, Backing: backing}, nil)