carlos / platform Public

Merge origin/main into audit-aws-timeouts

Brings in staticcheck in the gate (b064b14). The census chain conflict is
resolved by taking main's chain; census-propose re-adds this branch's
overlay in the next commit.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 55fdf6a245d1366b4dd76d80d3105787d8beebba parent b409deeparent b064b14
64 files changed, +1,355 −117
  • .amadan/README.md +10 −1
  • .amadan/ci.d/10-gate +1 −1
  • .amadan/ci.d/40-staticcheck +19 −0
  • .amadan/test-gate.sh +12 −1
  • AGENTS.md +8 −0
  • Makefile +41 −1
  • README.md +4 −0
  • docs/superpowers/notes/census-proposal-audit-gate-vet-staticcheck.md +23 −0
  • docs/superpowers/notes/census-proposal-audit-request-path.md +25 −0
  • docs/superpowers/notes/census-proposal-sec-unit-app-demobuild.md +26 −0
  • docs/superpowers/plans/2026-11-16-gvisor-flagship-demos.md +166 −0
  • docs/superpowers/reviews/FINDINGS-audit-gate-vet-staticcheck-R1.md +48 −0
  • docs/superpowers/reviews/FINDINGS-audit-request-path-R1.md +52 −0
  • docs/superpowers/reviews/REVIEW-BRIEF-audit-gate-vet-staticcheck.md +70 −0
  • docs/superpowers/reviews/REVIEW-BRIEF-audit-request-path.md +68 −0
  • internal/activator/activator.go +1 −1
  • internal/activator/backend_exec.go +36 −23
  • internal/activator/backend_unit.go +22 −27
  • internal/activator/hasuspect_test.go +1 −0
  • internal/activator/healthaddr_guard_test.go +4 −3
  • internal/activator/healthcheck_redirect_test.go +6 −5
  • internal/activator/healthwait_cancel_test.go +141 −0
  • internal/activator/rootfs_cmd_lease_test.go +2 −1
  • internal/analytics/meter_test.go +1 −1
  • internal/assetcache/store_test.go +1 −1
  • internal/caps/render.go +12 −0
  • internal/caps/render_test.go +45 −0
  • internal/caps/testdata/gotenberg.service.conf +2 −0
  • internal/console/apiinstances.go +0 −2
  • internal/console/demo_jobs.go +1 −1
  • internal/console/jobs_test.go +2 −1
  • internal/dbreads/admission_test.go +2 −1
  • internal/demobuild/unit.go +39 −12
  • internal/demobuild/unit_cache_chmod_test.go +75 −0
  • internal/edge/assetadmit_test.go +1 −0
  • internal/edge/devbox.go +3 −2
  • internal/edge/devboxfront_test.go +1 −1
  • internal/edge/door.go +3 −3
  • internal/edge/edge.go +8 −6
  • internal/edge/idletimeout_test.go +98 −0
  • internal/edge/ingressdrain.go +27 −4
  • internal/edge/lbhealth.go +2 −1
  • internal/edge/plandisabled.go +10 −1
  • internal/edge/plandisabled_test.go +37 −0
  • internal/edge/upstreamdial.go +27 −2
  • internal/edge/upstreamdial_test.go +22 −0
  • internal/grouproll/text_test.go +3 −2
  • internal/host/mailswitch_test.go +2 −2
  • internal/host/movespolicy_test.go +1 −1
  • internal/host/units/carlos-app@.service +28 −0
  • internal/host/units_isolation_test.go +29 −0
  • internal/hostactors/membershipread_test.go +1 −1
  • internal/hostbox/regionalworker.go +2 −3
  • internal/mail/smtppass_test.go +1 −1
  • internal/provision/testdata/plan14-root-reads-audit-gate-vet-staticcheck.tsv +11 −0
  • internal/provision/testdata/plan14-root-reads-audit-request-path.tsv +11 −0
  • internal/provision/testdata/plan14-root-reads-chain.tsv +3 −1
  • internal/provision/testdata/plan14-root-reads-sec-unit-app-demobuild.tsv +14 −0
  • internal/registry/registry.go +7 −0
  • internal/release/ratchet_test.go +1 −1
  • internal/runs/keys_test.go +1 −1
  • internal/schedule/hostgate.go +1 −0
  • internal/tunnelclient/upgrade.go +2 −1
  • staticcheck.conf +32 −0
diff --git a/.amadan/README.md b/.amadan/README.md
index 8d81510a1..3406166fc 100644
--- a/.amadan/README.md
+++ b/.amadan/README.md
@@ -2,7 +2,7 @@
`ci.d/` is this repo's gate, running on a self-hosted amadan runner.
**It is the only one.** `.github/workflows/ci.yml` was deleted on
-2026-08-24; nothing stands behind these three steps. A green run here
+2026-08-24; nothing stands behind these steps. A green run here
is the whole of what "green" means for this repo, and a red one is not
a discrepancy to reconcile against a more official run somewhere else.
@@ -33,6 +33,15 @@ no longer exists.
| `minio-contract` | `30-minio-contract` | MinIO on loopback, no container |
| `gofmt` | `10-gate` | repo-wide, via `make test` — see below |
+Two checks have no ancestor; the deleted workflow never ran them. They
+were added on 2026-11-16 after a code audit found the gate could not see
+them.
+
+| added | here | |
+|---|---|---|
+| tagged vet | `10-gate` | `go vet -tags rootrunner,carlos_cutover_witness ./...`, via `make test`: the root-runner tests are type-checked, not run |
+| `staticcheck` | `40-staticcheck` | `make staticcheck`: v0.8.2, bug checks only; `staticcheck.conf` names the families still off |
+
## `gofmt`: ported by widening it, not by reproducing it
This section is the reason it was safe to delete the workflow, so it is
diff --git a/.amadan/ci.d/10-gate b/.amadan/ci.d/10-gate
index 19a206a80..9bde76e88 100755
--- a/.amadan/ci.d/10-gate
+++ b/.amadan/ci.d/10-gate
@@ -5,7 +5,7 @@
#
# THIS IS THE GATE. Not a second home for one, not a copy kept beside a
# more authoritative run somewhere else: the definition of green for this
-# repo is what these three steps say it is.
+# repo is what these steps say it is.
#
# It did not start that way, and the change is recent enough to be worth
# writing down. Until 2026-08-24 the authority was
diff --git a/.amadan/ci.d/40-staticcheck b/.amadan/ci.d/40-staticcheck
new file mode 100755
index 000000000..359991236
--- /dev/null
+++ b/.amadan/ci.d/40-staticcheck
@@ -0,0 +1,19 @@
+#!/bin/sh
+# staticcheck's bug checks (SA), pinned, over the whole module with the
+# rootrunner tag (the Makefile says why not the cutover witnesses' tag
+# too). `make staticcheck` is the one definition; this step only runs it,
+# so a developer gets the same answer with the same command.
+#
+# Its own step, not part of `make test`: a red here is a finding in the
+# code, and it should read as that, not as a failed test run. It also keeps
+# `make test` no slower for whoever did not ask for staticcheck.
+#
+# Which checks, and which families are off with a follow-up owning them,
+# is staticcheck.conf's business. The step is green only with no output at
+# all: a finding, or a //lint:ignore that no longer matches anything, fails
+# it. A deliberate case takes a `//lint:ignore <check> <reason>` on the
+# line above it.
+set -eu
+. .amadan/go-toolchain.sh
+
+make staticcheck
diff --git a/.amadan/test-gate.sh b/.amadan/test-gate.sh
index aca787753..f3eb2b69b 100755
--- a/.amadan/test-gate.sh
+++ b/.amadan/test-gate.sh
@@ -4,7 +4,9 @@
#
# What it checks is what `make test` always checked: launchctx's vet and
# tests, `go vet ./...`, a repo-wide `gofmt -l .`, and every test in every
-# package with -count=1. What changed is the shape of the run.
+# package with -count=1, plus a second vet with the rootrunner and
+# carlos_cutover_witness tags (see vet-tags below). What changed is the
+# shape of the run.
#
# The gate's wall clock was the slowest single package, because Go runs
# packages side by side but a package's own tests one after another.
@@ -167,6 +169,15 @@ discover() {
start launchctx sh -c 'cd launchctx && go vet ./... && go test ./... -count=1'
start vet go vet ./...
+# The tagged tests: about 130 test files behind `linux && rootrunner` (the
+# root runner's fixtures, nearly all in internal/host) and the cutover
+# witnesses. Only the root runner and the cutover-witness job below ever
+# compiled them, so a refactor could break a root-runner test and stay
+# green. Its own job rather than tags on the line above, because one file,
+# internal/host/departure_queue_default.go, is `!rootrunner` and would
+# drop out of the plain vet. Nothing here runs those tests: they need
+# root.
+start vet-tags go vet -tags rootrunner,carlos_cutover_witness ./...
start gofmt sh -c 'fmt_out=$(gofmt -l .); if [ -n "$fmt_out" ]; then echo "gofmt needed:"; echo "$fmt_out"; exit 1; fi; echo "gofmt -l .: clean"'
# The split packages' test lists, all at once. `go test -list` compiles the
diff --git a/AGENTS.md b/AGENTS.md
index 77d7297c9..3ed0091e9 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -280,6 +280,14 @@ anything.
- **GitHub follows amadan.** If GitHub's `main` is behind amadan's after a
merge, fast-forward it from amadan; never the other way round, and
never with anything that is not already on amadan's `main`.
+- `40-staticcheck` runs `make staticcheck` (v0.8.2, pinned): the `SA`
+ bug checks, with the families still off listed in `staticcheck.conf`.
+ It is green only with no output at all, and it is not part of
+ `make test`. A deliberate case takes `//lint:ignore <check> <reason>`
+ on the line above the one staticcheck reports; it ignores `//nolint`.
+ `make test` also vets with `-tags rootrunner,carlos_cutover_witness`,
+ so the root-runner tests must compile even though only the root runner
+ runs them.
- `20-cross@5` adds `GOOS=darwin`/`windows`/`linux-arm64` compiles, one
per shard. **The gate is not Linux-only**: `internal/host` is linked
into the CLI, which people run on Macs, so a Linux-only type assumption
diff --git a/Makefile b/Makefile
index 8abc7c913..cd6258f01 100644
--- a/Makefile
+++ b/Makefile
@@ -7,7 +7,7 @@ LDFLAGS := -s -w -X github.com/carlosframework/platform/internal/version.Build=$
GOOS ?=
GOARCH ?=
-.PHONY: test build build-console fmt census-card census-propose console-mockup-kit parity-doc
+.PHONY: test build build-console fmt staticcheck census-card census-propose console-mockup-kit parity-doc
# The build gate: vet, format, tests. `.amadan/ci.d/10-gate` runs this same
# target, so what CI checks and what you check are one definition.
@@ -32,6 +32,46 @@ build-console:
fmt:
gofmt -w .
+# staticcheck's bug checks, as CI runs them (.amadan/ci.d/40-staticcheck).
+# Not part of `make test`: it adds a few minutes of CPU that a developer
+# who did not ask for it should not pay. staticcheck.conf at the root says
+# which checks run, and which families are off until a follow-up fixes
+# them.
+#
+# Pinned, and fetched with `go run pkg@version` rather than a tool line in
+# go.mod: a tool's requirements would join the module graph the release
+# binaries are built from, and could move a shared dependency
+# (golang.org/x/tools, x/sync) under them. Bump the pin with the Go
+# toolchain (.amadan/go-toolchain.sh): a staticcheck older than the Go it
+# reads cannot decode that release's export data.
+#
+# -tags rootrunner, so the root-runner tests are read too. The one file
+# that drops out under it, internal/host/departure_queue_default.go, is two
+# one-line stubs; its rootrunner twin is read in its place. The cutover
+# witnesses' tag is not named here: TestCutoverWitnessControlsAreTagged
+# allows it only in .amadan/test-gate.sh and the files it builds, so no
+# Makefile target can ever build with it. Its two files are vetted by the
+# gate's vet-tags job and compiled by its cutover-witness job instead.
+STATICCHECK := honnef.co/go/tools/cmd/staticcheck@v0.8.2
+# staticcheck caches in the user cache directory (~/.cache/staticcheck),
+# which a sandboxed CI runner may mount read-only. Where the environment
+# hands make an absolute GOCACHE, staticcheck's cache goes inside it,
+# writable wherever Go's is and evicted with it. Otherwise (a laptop, this
+# repo's shared dev box) it stays in the default user cache.
+ifneq ($(filter /%,$(firstword $(GOCACHE))),)
+export STATICCHECK_CACHE ?= $(GOCACHE)/staticcheck
+endif
+
+# Green means no findings at all, not just a zero exit: a //lint:ignore
+# that no longer matches anything is reported, and the exit status alone
+# does not promise to count it. Findings go to stdout; go run's own
+# "downloading" lines go to stderr and are left alone.
+staticcheck:
+ @out=$$(go run $(STATICCHECK) -tags rootrunner ./...); rc=$$?; \
+ if [ -n "$$out" ]; then printf '%s\n' "$$out"; fi; \
+ if [ $$rc -ne 0 ] || [ -n "$$out" ]; then echo "staticcheck: findings above (staticcheck.conf says which checks run)" >&2; exit 1; fi; \
+ echo "staticcheck: clean"
+
# Regenerates docs/console-mockup-kit/shell.html: a signed-in console page
# from the real templates with every stylesheet inlined and an empty
# <main> to draw a mockup in (docs/console-mockup-kit/README.md).
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-gate-vet-staticcheck.md b/docs/superpowers/notes/census-proposal-audit-gate-vet-staticcheck.md
new file mode 100644
index 000000000..7b668b3e4
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-audit-gate-vet-staticcheck.md
@@ -0,0 +1,23 @@
+# Census approval: audit-gate-vet-staticcheck
+
+Ruling `census-ruling-audit-gate-vet-staticcheck`. 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 |
+|---|---|---|---|
+| `internal/hostbox/regionalworker.go` `RegionalWorker.runHost` | body | unchanged (5) | removed an empty if whose body was only a comment (staticcheck SA9003/SA4017: strings.HasPrefix result ignored); the comment stays. No behaviour change, no read added. |
+
+Envelopes re-pinned: `.`, `internal/edge`, `internal/hostbox`, `internal/schedule`, `internal/tunnelclient`.
+
+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/hostbox/regionalworker.go` `RegionalWorker.runHost`: authority, task C,J2,J4. Basis: root-input
+
+New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff:
+
+- new `staticcheck.conf:external`: reads +file:external; written legacy, accepted-legacy, frozen
+
+Seal: `3f7dc37d114377b168c6bc1ae48e7bf815dbc1f5a569274af642e00e7d08ca2a` → `d4d3f367ca135da40d2c392d22b51669281d2d8268c0a5aa22ebf738cbe65080`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-audit-gate-vet-staticcheck.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/notes/census-proposal-audit-request-path.md b/docs/superpowers/notes/census-proposal-audit-request-path.md
new file mode 100644
index 000000000..3e2673e97
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-audit-request-path.md
@@ -0,0 +1,25 @@
+# Census approval: audit-request-path
+
+Ruling `census-ruling-audit-request-path`. 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 |
+|---|---|---|---|
+| `internal/edge/door.go` `Edge.openDoor` | body | unchanged (1) | the edge-local door server gains IdleTimeout: publicIdleTimeout (120 s) beside its ReadHeaderTimeout; comment updated. No read added. |
+| `internal/edge/edge.go` `RunWithActivatorReady` | body | unchanged (5) | the dev-mode http.Server gains IdleTimeout: publicIdleTimeout (120 s) beside its ReadHeaderTimeout; comment updated. Same 5 read sites, no read added. |
+
+Envelopes re-pinned: `internal/activator`, `internal/edge`.
+
+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/edge/door.go` `Edge.openDoor`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J4;basis=root-input
+- `internal/edge/edge.go` `RunWithActivatorReady`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-certwarm-wake;basis=registers the cert warm's nudge on OnReload and on the home map's new served-hosts wake (#386); nudge only sends on a buffered channel; no read added, same 5 sites;rev3=census-ruling-edge-roll-blip;basis=the :80/:443 (and dev) listeners are bound on the calling goroutine with net.Listen via listen()/listenAddr (same empty-address defaults as ListenAndServe) before the serve goroutines, which now call Serve/ServeTLS on them, and one log line names the bound addresses; no read added, same 5 sites;rev3=census-ruling-edge-held-streams;basis=the edge in the agent (carlos-edge.service, user carlos): the inline home-map arming (newHomeMap, one boot Refresh, Store, run) moves unchanged into the new Edge.ArmHomeMap and is called here as e.ArmHomeMap(); same refresh, same timeout, same order. The reads are moved, none added.;rev3=census-ruling-agent-start-demo-1;basis=Logs the combined explicit wildcard parents through demoWildcardDomains; no new watcher or read loop.;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: invoke the local admission Close before HTTP/HTTPS draining and door shutdown in both dev and normal listeners. Preserve merged main's startup behavior and its census basis; the same five read sites, no new reads.;rev3=census-ruling-stateless-replicas-3;basis=Task 1b: defer stopping and joining the edge's replica jobs at shutdown. Existing five direct read sites unchanged; no new reader or authority.;rev3=census-ruling-region-ha-p3b;basis=Wrap dev, HTTP and HTTPS listeners through ConfigureGroupHairpin before serving. Indirectly read protected root boot identity and group-ingress.json; kernel local/peer addresses mark local ingress, never HTTP headers. Agent edge uses verified public source for accounting; direct read sites unchanged and absent marker keeps original listeners. CI fix removes interface enumeration: local peer must match snapshot primary IPv4, an ingress IPv4 installed locally by root, or loopback; kernel destination must still be an ingress EIP on port 80/443. Merge 45cebde4 retains deferred stopReplicaProbes alongside group listener wrapping and shutdown admission closure.;rev3=census-ruling-demo-api-site-route;basis=Change the startup failure context from load routes to initialize because origin validation now runs during construction. Existing five read sites unchanged; no new read or runtime authority.;rev3=census-ruling-region-ha-graceful-terminate-t2;basis=Invoke the agent shutdown timestamp hook synchronously at SIGTERM/SIGINT receipt before closing admission in dev and TLS paths. No read added.;rev3=census-ruling-region-ha-held-build;basis=region HA held-requests Task 5: registers the https and http servers with the connection drain (conns.serve) so a drain can close idle keep-alive connections; no read added;rev3=census-ruling-warm-set-published-724;basis=#724: the inline cert warm construction (newCertWarm over warmSet and dnsGate, then OnReload and setServedWake registering warm.nudge) moves unchanged into the new Edge.newIssuerWarm in certwarm.go and is called here with the same apps domain, parents, perHostCert, warmResolver, edgeIPs and store; the loop still starts here. The warm set it wires now reads the published edges files through the home map (OwnServedHosts and ServedHosts, both already polled) instead of the local route table, regional names aside. It is a different source, not a subset: an attached name not yet published as pointing is no longer listed, while a name the route table has already dropped stays listed until this box's next edges file write and the home map's next poll catch up (HostPolicy still refuses an order for a name the registry no longer holds). A name published not pointing is not a warm candidate at all, whether or not its certificate is cached: the warm neither looks it up, orders it nor re-arms its renewal until its home box publishes it pointing again (a cached certificate keeps serving and re-arms on a handshake at the issuer). The warm reads the set only after the issuer gate, and the read is in memory (route table and the home map's last snapshot); it also drops a DNS-miss entry for a name that has left the set before probing it. It keeps a failure record while any box publishes the exact name (the home map DeployedHosts: every box's file, own included, pointing or not, the same in-memory snapshot) or the name is a regional route-table name, and prunes it only once no box publishes it. That retention set has no apps-domain or wildcard filter (those stay on candidacy only), so a name published not pointing, or one a wildcard parent starts covering, keeps the record that explains its backoff; the set is never a source of candidates. No read site added in this unit, same 5 sites.;rev3=census-ruling-w6-ingress-drain;basis=the two public servers are built by e.publicServers (internal/edge/ingressdrain.go): :443 as before (same handler, TLS config and ReadHeaderTimeout 10 s), :80 now wrapped by plainTracked so the ingress drain can count and close its requests (its barrier is never §25's); Serve's error test is listenerFailed(err) = err != nil && !errors.Is(err, http.ErrServerClosed) (was err != ErrServerClosed), so a graceful Shutdown by the drain is not fatal. New Edge.plain connDrain field. Same flags, addresses and listeners; read sites unchanged (5); no read added.;rev3=census-ruling-edge-ppv2;basis=Edge process (uid carlos), not root. Edge gains the proxy atomic.Pointer. Outside dev mode, before either public listener binds and before the ready hook hands the Edge to the agent, calls e.loadProxyIngress(os.Getenv, dataDir): CARLOS_INGRESS_PROXY_SOURCES from the edge's own environment (carlos-edge.service loads the root-owned 0600 host.env) through hostenv.ParseProxySources; blank leaves the edge unarmed with nothing read; a non-empty list arms it and Lstats <dataDir>/edge/trust-barrier (armProxyIngress); a value that does not parse is log.Fatal. After the hairpin configuration, wrapProxyIngress wraps both public listeners outermost (returns them untouched when unarmed); when armed it logs the armed line and starts runProxyJournal (counters to the journal, no reads). The existing 5 read sites are unchanged.
+
+New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff:
+
+- reads `internal/edge/plandisabled.go:Edge.planDisabledAdmit`: +registry:Host ×3; keeps legacy, task accepted-legacy
+
+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/docs/superpowers/reviews/FINDINGS-audit-gate-vet-staticcheck-R1.md b/docs/superpowers/reviews/FINDINGS-audit-gate-vet-staticcheck-R1.md
new file mode 100644
index 000000000..b3d2781ef
--- /dev/null
+++ b/docs/superpowers/reviews/FINDINGS-audit-gate-vet-staticcheck-R1.md
@@ -0,0 +1,48 @@
+Reviewed round 1 at `4d5862b0470a6f55477cadfd438bb8c9a87fc1cc` against base `15b1ee6b6a65a52b82075003d8d6c2bcbb100ca5`. The difference from the brief’s implementation commit, `11602a45`, is the brief itself.
+
+**Findings:** no P1, P2, or P3 findings against this change.
+
+1. **Tagged vet covers the intended files.** The separate plain and tagged invocations at [.amadan/test-gate.sh:171](/home/paulca/amadan.net/carlos/platform-audit-gate-vet-staticcheck/.amadan/test-gate.sh:171) preserve coverage of `departure_queue_default.go` while type-checking the Linux root-runner tests and cutover witnesses. I counted 131 test files with `linux && rootrunner`, plus three supporting non-test files. Vet does not execute their tests.
+
+ Coverage is still incomplete outside this slice: 14 non-Linux test files and the two `race_on_test.go` files remain outside these CI configurations. For example, `devbox_envfile_darwin_test.go` is excluded on Linux, and [.amadan/ci.d/20-cross@5:56](/home/paulca/amadan.net/carlos/platform-audit-gate-vet-staticcheck/.amadan/ci.d/20-cross@5:56) uses `go build`, which excludes tests. These are pre-existing gaps; handle cross-platform test compilation and race coverage separately.
+
+2. **Staticcheck’s pin, failure handling, and cache arrangement are sound.** [Makefile:55](/home/paulca/amadan.net/carlos/platform-audit-gate-vet-staticcheck/Makefile:55) pins v0.8.2 without adding its dependencies to the application module. The recipe rejects either nonempty diagnostic output or a nonzero exit. I exercised those cases with a stubbed `go` command, including output accompanied by exit status zero.
+
+ Staticcheck is independent of `make test`. The Makefile leaves `GOCACHE` unchanged, creates no per-task Go cache, and places staticcheck’s cache beneath an explicitly supplied absolute `GOCACHE`. Otherwise it retains staticcheck’s default user cache. The locally available amadan runner source supplies writable repository caches and permits module-proxy access; that supports the implementation, but does not establish the live runner’s result.
+
+3. **The exclusions are an acceptable staged adoption.** [staticcheck.conf:15](/home/paulca/amadan.net/carlos/platform-audit-gate-vet-staticcheck/staticcheck.conf:15) names SA1012, SA1019, and SA4006 with historical counts and enables the remaining SA checks. I could not reproduce those counts in this sandbox.
+
+ The two named production cases deserve different treatment:
+
+ - At [apisubdomain.go:468](/home/paulca/amadan.net/carlos/platform-audit-gate-vet-staticcheck/internal/console/apisubdomain.go:468), the short declaration inside the missing-claim branch shadows `err`. After losing a create race, the reread updates the inner error, while the subsequent check sees the original `os.ErrNotExist`. A successful reread therefore still produces an unreadable refusal. This is a real, pre-existing correctness bug. Fix it in a focused follow-up by avoiding the shadow and testing the lost-create-race path. Its fault family is **error propagation across namespace claim retries**.
+ - At [replicaplacement.go:126](/home/paulca/amadan.net/carlos/platform-audit-gate-vet-staticcheck/internal/host/replicaplacement.go:126), the publication error is discarded, but publication failures return `done=false`; lines 132–139 retain the work and schedule a retry. I found no lost-retry bug. Error reporting can be considered in the SA4006 follow-up.
+
+ Neither requires expanding this gate-enablement branch into production behavior changes.
+
+4. **Every added suppression has a truthful reason.** The three production SA2001 suppressions preserve deliberate synchronization: the edge probes cache-lock availability, the scheduler waits for active readers, and the tunnel connection waits for writer users after closure. Their census verdicts appear below.
+
+ The test suppressions likewise preserve their witnesses: callback execution outside `a.mu` at [hasuspect_test.go:497](/home/paulca/amadan.net/carlos/platform-audit-gate-vet-staticcheck/internal/activator/hasuspect_test.go:497); lock availability while a kill is held at [rootfs_cmd_lease_test.go:590](/home/paulca/amadan.net/carlos/platform-audit-gate-vet-staticcheck/internal/activator/rootfs_cmd_lease_test.go:590); the intentional nil-map panic at [jobs_test.go:183](/home/paulca/amadan.net/carlos/platform-audit-gate-vet-staticcheck/internal/console/jobs_test.go:183); raw lowercase header removal at [assetadmit_test.go:323](/home/paulca/amadan.net/carlos/platform-audit-gate-vet-staticcheck/internal/edge/assetadmit_test.go:323); and odd-argument rejection at [text_test.go:50](/home/paulca/amadan.net/carlos/platform-audit-gate-vet-staticcheck/internal/grouproll/text_test.go:50).
+
+5. **Production behavior is unchanged.** The removed `hosts` slice in [apiinstances.go:453](/home/paulca/amadan.net/carlos/platform-audit-gate-vet-staticcheck/internal/console/apiinstances.go:453) had no consumer. The renamed callback parameter in [demo_jobs.go:182](/home/paulca/amadan.net/carlos/platform-audit-gate-vet-staticcheck/internal/console/demo_jobs.go:182) was overwritten before use; the transaction still obtains and passes its own `life`. The regional-worker condition had an empty body and a side-effect-free predicate.
+
+6. **The edited tests retain their assertions.** The determinism and shared-instance tests still make two independent calls. Mail-switch tests retain repeated lookups and read-count checks. Admission still checks two read connections, one probe connection, and refusal of a fourth connection. `EqualFold` preserves the visitor-header comparison for the ASCII header names under test. No assertion was removed.
+
+7. **The documentation matches the implementation.** The README additions, AGENTS additions, and revised `10-gate` header accurately describe the separate tagged-vet and staticcheck jobs. The Makefile correctly explains why staticcheck omits the cutover tag: the existing guard restricts where that tag may appear.
+
+**Census verdicts**
+
+| Unit or envelope | Verdict and evidence |
+|---|---|
+| `RegionalWorker.runHost` | **Approve**, retaining `authority`, `C,J2,J4`, basis `root-input`. Read [regionalworker.go:171](/home/paulca/amadan.net/carlos/platform-audit-gate-vet-staticcheck/internal/hostbox/regionalworker.go:171) through line 286 and [park.go:17](/home/paulca/amadan.net/carlos/platform-audit-gate-vet-staticcheck/internal/hostbox/park.go:17) through line 49. Removing the empty condition changes no enrollment, ownership, evidence, request-limit, revision, or execution check. No new read or authority is introduced. |
+| `staticcheck.conf:external` | **Approve** `legacy` / `accepted-legacy`. Read [staticcheck.conf:1](/home/paulca/amadan.net/carlos/platform-audit-gate-vet-staticcheck/staticcheck.conf:1) through line 32 and its Makefile invocation. This is analysis-tool configuration, with no added root-runtime read. |
+| `.` envelope | **Approve.** Reviewed the root-level diff, including Makefile lines 35–73 and `staticcheck.conf`. No root Go implementation or application dependency change. |
+| `internal/edge` envelope | **Approve.** Read [lbhealth.go:53](/home/paulca/amadan.net/carlos/platform-audit-gate-vet-staticcheck/internal/edge/lbhealth.go:53) through line 86 and both changed tests. The production change only replaces the suppression comment; lock acquisition, timeout, and probe completion remain unchanged. |
+| `internal/hostbox` envelope | **Approve.** The only changed implementation is `runHost`, approved above. Its downstream ownership checks remain intact. |
+| `internal/schedule` envelope | **Approve.** Read [hostgate.go:44](/home/paulca/amadan.net/carlos/platform-audit-gate-vet-staticcheck/internal/schedule/hostgate.go:44) through line 87. The exclusive acquisition waits for existing readers; only a suppression comment was added. |
+| `internal/tunnelclient` envelope | **Approve.** Read [upgrade.go:276](/home/paulca/amadan.net/carlos/platform-audit-gate-vet-staticcheck/internal/tunnelclient/upgrade.go:276) through line 430. `finish` closes before fencing; writer and deadline operations retain their read locks and closed checks. The change is comment-only. |
+
+Validation completed: shell syntax, diff whitespace, formatting of every changed Go file, and the staticcheck recipe’s three exit/output cases. Tagged vet and real staticcheck execution were blocked by the read-only filesystem. Census tests were not run. Network restrictions prevented checking amadan CI; the census verdict has not been posted to #280. No files were edited, no subagents were spawned, and no full suites were run.
+
+Round 1 has no P1; the stopping rule ends this review. Exact-tip green CI and recording the census approval remain merge prerequisites.
+
+**READY**
\ No newline at end of file
diff --git a/docs/superpowers/reviews/FINDINGS-audit-request-path-R1.md b/docs/superpowers/reviews/FINDINGS-audit-request-path-R1.md
new file mode 100644
index 000000000..456c5c3d0
--- /dev/null
+++ b/docs/superpowers/reviews/FINDINGS-audit-request-path-R1.md
@@ -0,0 +1,52 @@
+Reviewed `origin/main...2d1f36fdbf4ee5b7b8128ba3893cda755a043d65`, base `15b1ee6b6a65a52b82075003d8d6c2bcbb100ca5`, round 1 of 3. The requested tip adds only the brief after implementation tip `9604346a`.
+
+No P1 findings. Two P2 findings follow; no P3 findings.
+
+1. **P2 — Check 2: the prober’s dial-deadline claim is incorrect.**
+
+ The new comment in [upstreamdial.go:13](/home/paulca/amadan.net/carlos/platform-audit-request-path/internal/edge/upstreamdial.go:13), repeated in commit `c6ec153f`, says both `multiProxy` and the prober bound their dials with context deadlines.
+
+ `multiProxy` does, inside its dial callback. The prober instead installs the unbounded `upstreamDialer().DialContext` and sets `http.Client.Timeout` and `ResponseHeaderTimeout`: [prober.go:136](/home/paulca/amadan.net/carlos/platform-audit-request-path/internal/edge/prober.go:136). Go’s transport explicitly removes request cancellation and deadlines before dialing: [transport.go:1524](/home/paulca/.local/go-dist/src/net/http/transport.go:1524).
+
+ **Failure scenario:** a black-holed probe target causes the HTTP request to time out, but its connection attempt can continue until the kernel’s timeout. Later probe ticks can start additional attempts. The prober closes idle connections on `Stop`, not after each failed probe.
+
+ **Fix:** correct the new comment and branch description to distinguish the HTTP request bound from the dial bound. Record the existing unbounded prober dial as follow-up work. Its eventual fix needs a deadline inside the guarded dial callback or a dialer timeout.
+
+ **Fault family:** outbound connection lifetime must be bounded at the operation that owns the connection. This is a pre-existing implementation gap newly described as already covered, not a regression introduced by this branch.
+
+2. **P2 — Check 5: the cancellation test assumes an in-flight handler settles within 100 ms.**
+
+ [healthwait_cancel_test.go:84](/home/paulca/amadan.net/carlos/platform-audit-request-path/internal/activator/healthwait_cancel_test.go:84) acknowledges that an already-sent probe may reach the handler after the wait returns, then uses a 100 ms sleep before taking its baseline.
+
+ **Failure scenario:** a loaded runner delays that handler beyond the settling sleep. It increments `probes` during the subsequent observation window, and the test reports continued polling even though the client stopped correctly. Request cancellation does not synchronously join the server handler.
+
+ **Fix:** synchronize cancellation with a controlled polling boundary and explicitly acknowledge completion of any outstanding handler. Assert that no new probe starts after cancellation; do not infer that boundary from elapsed wall time.
+
+ **Fault family:** cancellation regression tests must distinguish a new probe from completion of one already sent.
+
+The remaining checks support the implementation:
+
+- **Idle timeout:** all five constructors set `publicIdleTimeout`: HTTP and HTTPS in [ingressdrain.go:96](/home/paulca/amadan.net/carlos/platform-audit-request-path/internal/edge/ingressdrain.go:96), dev in [edge.go:5171](/home/paulca/amadan.net/carlos/platform-audit-request-path/internal/edge/edge.go:5171), devbox in [devbox.go:225](/home/paulca/amadan.net/carlos/platform-audit-request-path/internal/edge/devbox.go:225), and door in [door.go:201](/home/paulca/amadan.net/carlos/platform-audit-request-path/internal/edge/door.go:201). Go applies this after an HTTP/1 request finishes; hijacked connections leave that loop. HTTP/2 inherits the setting and stops its idle timer while streams are open. Held streams, uploads, WebSockets and active tunnel traffic therefore retain their existing lifetimes.
+- **Timeout ordering:** `90 s < 120 s < 350 s` matches the backhaul pool and the configured TCP listeners. Terraform sets no listener idle-time override. AWS confirms the 350-second default: [https://docs.aws.amazon.com/elasticloadbalancing/latest/network/load-balancer-listeners.html](https://docs.aws.amazon.com/elasticloadbalancing/latest/network/load-balancer-listeners.html).
+- **Upstream guard:** `tcpProxy` uses the new guarded dialer both directly and inside local retries. `multiProxy`, the prober and TCP health waits retain their guard. Resolution-time IPv4, IPv6 and mapped-address refusal remains unchanged.
+- **Health waits:** polling is now synchronous, requests carry the wake context, and pauses select on cancellation. Both transports close idle connections on return; Go’s implementation also cancels abandoned pending dials. There is no detached polling loop left. Transport goroutines unwind asynchronously, so this is cancellation and cleanup, not a synchronous join of every internal goroutine.
+- **Preserved health semantics:** responses below 500 succeed, redirects are not followed, `X-Forwarded-Proto` remains set, and the three-second per-request timeout and polling backoff remain. The overall timeout still has its previous possible final-probe overshoot.
+- **Callers checked:** `ExecBackend.startChildAt` ([2438](/home/paulca/amadan.net/carlos/platform-audit-request-path/internal/activator/backend_exec.go:2438)), `ExecBackend.startUnitAt` ([3176](/home/paulca/amadan.net/carlos/platform-audit-request-path/internal/activator/backend_exec.go:3176)), `ExecBackend.startRootfs` ([293](/home/paulca/amadan.net/carlos/platform-audit-request-path/internal/activator/rootfs.go:293)), `Service.genHealthy` ([518](/home/paulca/amadan.net/carlos/platform-audit-request-path/internal/activator/swap.go:518)), and both branches of `UnitBackend.waitHealthy` ([179](/home/paulca/amadan.net/carlos/platform-audit-request-path/internal/activator/backend_unit.go:179)). Existing failure cleanup remains intact. The deleted context-free helpers had no production callers besides the wrappers replaced here.
+- **Throttle keys:** the changed key uses the matched route’s `Host`; the request host appears only in the quoted message. I traced the other callers and found no additional unrestricted remote-input key. Apparent exceptions are constrained by exact published-host membership, registered routes/channels, validated fleet membership, or fixed complaint/path values.
+- **Tests and portability:** the new tests target the old missing timeout, zero-valued dialer settings, per-request-host map growth, and continued probing after cancellation. The server and dialer tests inspect configuration rather than elapsed network behavior. The new dialer test alone does not verify `tcpProxy` wiring; that wiring is correct by inspection. No new Linux-only API or type appears in the changed production code.
+
+Census verdicts for `census-ruling-audit-request-path` at the requested tip:
+
+| Unit or envelope | Verdict | Evidence and basis |
+|---|---|---|
+| `Edge.openDoor` | **APPROVE** | Read [door.go:152](/home/paulca/amadan.net/carlos/platform-audit-request-path/internal/edge/door.go:152) through its return. Only the server timeout and comment change. Socket checks, staged creation, permissions and shutdown remain unchanged. Retain `legacy / accepted-legacy`. |
+| `RunWithActivatorReady` | **APPROVE** | Read the function beginning at [edge.go:5061](/home/paulca/amadan.net/carlos/platform-audit-request-path/internal/edge/edge.go:5061), including dev construction and public listener wiring. No new read or authority; existing five read sites remain. Retain its disposition. |
+| `Edge.planDisabledAdmit` | **APPROVE** | Read [plandisabled.go:76](/home/paulca/amadan.net/carlos/platform-audit-request-path/internal/edge/plandisabled.go:76)–97. The three added `registry:Host` reads use the route already supplied. Admission predicate, status exception and fixed response remain unchanged. Retain `legacy / accepted-legacy`. |
+| `internal/activator` envelope | **APPROVE** | Reviewed the changed health-wait functions, `healthPause`, `probeHealth`, callers and tests. Unix control-endpoint/peer checks, TCP link-local refusal and redirect refusal remain intact. No new destination or root authority. |
+| `internal/edge` envelope | **APPROVE** | Reviewed the five server constructions, `tcpProxy`, both dialer helpers, disabled-route admission and tests. Changes bound connection lifetime and throttle cardinality without widening destinations, filesystem access or admission authority. |
+
+Validation was limited to source review, clean `git diff --check`, and clean `gofmt -l` on changed Go files. The permitted targeted activator test command, run at `nice -n 19` with `GOCACHE` unset, failed before compilation because the read-only sandbox prevented creation of Go’s work directory. Tests, census execution and cross-compilation are therefore unverified here. No files were edited.
+
+Round 1 stops with no P1. Apply the P2 fixes without reopening the review, retaining the required census and changed-security checks.
+
+**READY AFTER FIXES**
\ No newline at end of file
diff --git a/docs/superpowers/reviews/REVIEW-BRIEF-audit-gate-vet-staticcheck.md b/docs/superpowers/reviews/REVIEW-BRIEF-audit-gate-vet-staticcheck.md
new file mode 100644
index 000000000..20a0d22ae
--- /dev/null
+++ b/docs/superpowers/reviews/REVIEW-BRIEF-audit-gate-vet-staticcheck.md
@@ -0,0 +1,70 @@
+# Review brief: branch audit-gate-vet-staticcheck, round 1 of 3
+
+Repo carlos/platform, branch `audit-gate-vet-staticcheck`, commit 11602a453adbac58d12eed62df40e25e921a9c4e.
+Under review: the diff `origin/main...11602a453adbac58d12eed62df40e25e921a9c4e` (base 15b1ee6b).
+Authorities: AGENTS.md on main ("Build & test", "The census", "Stopping
+rules"), .amadan/README.md. Context: amadan discussion #1123 (Go audit
+backlog, first batch item 4).
+
+You are an independent reviewer and the census reviewer. Card:
+`docs/superpowers/notes/census-proposal-audit-gate-vet-staticcheck.md`.
+Give a verdict for every unit and envelope it lists, citing the lines you
+read, per AGENTS.md "Getting a change approved" step 4.
+
+## What to check
+
+1. The new `vet-tags` job in .amadan/test-gate.sh (`go vet -tags
+ rootrunner,carlos_cutover_witness ./...`): does it really compile every
+ tagged test file, and does the plain vet still cover the `!rootrunner`
+ files? Any file with a build tag that is still never compiled by any
+ gate job?
+2. `.amadan/ci.d/40-staticcheck` and `make staticcheck`: pinned, fails on
+ any output, works on the CI runner (module fetch, cache location), does
+ not slow `make test`. Does the GOCACHE rule match the machine policy
+ (default user cache; never a per-task cache)?
+3. `staticcheck.conf`: SA only; the three excluded families (SA1012,
+ SA1019, SA4006) are named with counts. Is any excluded check hiding a
+ real bug that should be fixed here instead? (The implementer reports
+ one: internal/console/apisubdomain.go ~467, a shadowed err; and
+ internal/host/replicaplacement.go:126 ignored errors. Judge whether
+ they belong in this branch or a follow-up.)
+4. Every `//lint:ignore` added: is the reason true? In particular the
+ three production empty critical sections (internal/edge/lbhealth.go,
+ internal/schedule/hostgate.go, internal/tunnelclient/upgrade.go): are
+ they really deliberate barriers?
+5. Production edits (console/apiinstances.go dead slice, demo_jobs.go
+ ignored parameter, hostbox/regionalworker.go empty if): behaviour
+ unchanged?
+6. Test edits for SA4000 etc.: does each test still test what it did?
+7. Docs (.amadan/README.md tables, AGENTS.md, 10-gate header) true to
+ the scripts.
+
+## 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. (The
+ census, and review of any newly changed security, root, termination
+ or production-storage behaviour, still check the fix; see AGENTS.md,
+ "Stopping rules".)
+- **P3**: clarity or polish. Goes on a follow-up list; never a reason for
+ another round.
+
+A P1 states its failure scenario and the evidence (file:line). Do not
+raise a P2 to P1 to keep the review open.
+
+## Output
+
+Findings ranked P1, P2, P3. Each gives the section or task, the problem,
+the evidence (file:line, verified), the failure scenario, a concrete
+fix and the invariant or trust boundary it breaks (that is its fault
+family). Then the census verdict per unit and envelope. End with exactly
+one verdict:
+
+- **READY**: no P1 and no P2.
+- **READY AFTER FIXES**: no P1. The listed P2s are fixed without another
+ round.
+- **NOT READY**: one or more P1s, listed.
+
+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/REVIEW-BRIEF-audit-request-path.md b/docs/superpowers/reviews/REVIEW-BRIEF-audit-request-path.md
new file mode 100644
index 000000000..cef95fea9
--- /dev/null
+++ b/docs/superpowers/reviews/REVIEW-BRIEF-audit-request-path.md
@@ -0,0 +1,68 @@
+# Review brief: branch audit-request-path, round 1 of 3
+
+Repo carlos/platform, branch `audit-request-path`, commit 9604346a0cd833bbe39cbd5d97f5f2d6c2234083.
+Under review: the diff `origin/main...9604346a0cd833bbe39cbd5d97f5f2d6c2234083` (base 15b1ee6b).
+Authorities: AGENTS.md on main ("The census", "Stopping rules"). Context:
+amadan discussion #1123 (Go audit backlog, first batch item 3).
+
+You are an independent reviewer. Read the diff, then the code it touches,
+and check every claim in the commit messages against that code.
+
+You are also the census reviewer for this branch: the card is
+`docs/superpowers/notes/census-proposal-audit-request-path.md`. Give a
+verdict for every unit and envelope it lists, citing the lines you read,
+per AGENTS.md "Getting a change approved" step 4.
+
+## What to check
+
+1. IdleTimeout (120 s, `publicIdleTimeout`) on five public servers: does
+ any of them carry long-lived traffic an idle timeout could cut (held
+ streams #432, WebSockets #471, tunnels, hijacked connections)? Go's
+ IdleTimeout applies only between requests on keep-alive connections;
+ confirm nothing here relies on a different behaviour. Is 120 s right
+ against the NLB's 350 s default and the 90 s backhaul client idle?
+2. `tcpUpstreamDialer` (30 s Timeout and KeepAlive): link-local refusal
+ from 15b1ee6b still enforced on every path that used it?
+3. `waitHealthyCtx` / `waitHealthyAddrCtx`: cancellation is prompt, no
+ goroutine or connection outlives the call, success and timeout paths
+ behave as before for every caller (list the callers you checked). The
+ deleted `waitHealthy`/`waitHealthyAddr`: truly unused outside tests?
+4. Plan-disabled throttle key: now built only from box-controlled values
+ (logThrottled's contract in edge.go)? Any other logThrottled caller
+ still keyed on remote input?
+5. New tests: would each fail against the old code? Do any rely on
+ wall-clock sleeps that could flake on a loaded CI runner?
+6. Cross-compile: anything Linux-only in files the darwin/windows CLI
+ build links?
+
+## 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. (The
+ census, and review of any newly changed security, root, termination
+ or production-storage behaviour, still check the fix; see AGENTS.md,
+ "Stopping rules".)
+- **P3**: clarity or polish. Goes on a follow-up list; never a reason for
+ another round.
+
+A P1 states its failure scenario and the evidence (file:line). Do not
+raise a P2 to P1 to keep the review open.
+
+## Output
+
+Findings ranked P1, P2, P3. Each gives the section or task, the problem,
+the evidence (file:line, verified), the failure scenario, a concrete
+fix and the invariant or trust boundary it breaks (that is its fault
+family). Then the census verdict per unit and envelope. End with exactly
+one verdict:
+
+- **READY**: no P1 and no P2.
+- **READY AFTER FIXES**: no P1. The listed P2s are fixed without another
+ round.
+- **NOT READY**: one or more P1s, listed.
+
+Do not edit files. Do not spawn Anthropic-model reviewers or subagents of
+your own. Do not run the full test suites; targeted `go test -run` on a
+single package at `nice -n 19` is allowed if you need evidence, with
+GOCACHE unset.
diff --git a/internal/activator/activator.go b/internal/activator/activator.go
index 89ee0b5a9..1aab0b8a5 100644
--- a/internal/activator/activator.go
+++ b/internal/activator/activator.go
@@ -4147,7 +4147,7 @@ var errWorkerExitedEarly = errors.New("worker exited during its settle window")
// awaitWorkerSettle is the socketless child's health probe: it is up once it
// says so over the agent socket, or once it has survived sidecarSettle without
-// exiting. Real time, not a.now — like waitHealthy, this bounds a real
+// exiting. Real time, not a.now — like waitHealthyCtx, this bounds a real
// process's first seconds, and the test clock exists to move idle windows, not
// to model a boot.
func (a *Service) awaitWorkerSettle(ctx context.Context, e *actEntry, proc Proc) error {
diff --git a/internal/activator/backend_exec.go b/internal/activator/backend_exec.go
index 41bb7965e..02e019c32 100644
--- a/internal/activator/backend_exec.go
+++ b/internal/activator/backend_exec.go
@@ -2923,7 +2923,7 @@ func seedVars(fileEnv map[string]string, host string) map[string]string {
// already happened and this wins.
//
// The two guards make "only a socket THIS backend's child bound" true
-// rather than merely intended. waitHealthy tolerates a squatter (its own
+// rather than merely intended. waitHealthyCtx tolerates a squatter (its own
// contract: it only dials), so a child that lost the bind race with a
// stray supervisor (EADDRINUSE, exits) can still see the health wait
// succeed off the SQUATTER's answers; a dead child means the socket is
@@ -4031,25 +4031,50 @@ func socketClient(socket string) *http.Client {
}
}
-// waitHealthy blocks until the instance answers an HTTP request on its socket,
-// or the timeout elapses. It retries, so it's robust to the restart window
-// (socket briefly absent, or a stale socket left by an abruptly-killed old
-// process) — and a broken binary that never becomes healthy fails the wake.
-func waitHealthy(socket string, timeout time.Duration) error {
+// waitHealthyCtx blocks until the instance answers an HTTP request on its
+// socket, the timeout elapses, or ctx ends. It retries, so it's robust to
+// the restart window (socket briefly absent, or a stale socket left by an
+// abruptly-killed old process) — and a broken binary that never becomes
+// healthy fails the wake.
+//
+// When ctx ends it returns ctx.Err() and probes no more: the request in
+// flight is cancelled with ctx and no further one starts. An aborted wake
+// must not keep probing a socket nobody wants anymore, since a retried
+// wake binds the same path and a stale probe would land on its process.
+func waitHealthyCtx(ctx context.Context, socket string, timeout time.Duration) error {
deadline := time.Now().Add(timeout)
client := healthClient(socketClient(socket))
+ defer client.CloseIdleConnections()
var last error
var poll time.Duration
for time.Now().Before(deadline) {
- if last = probeHealth(client, "http://carlos/"); last == nil {
+ if err := ctx.Err(); err != nil {
+ return err
+ }
+ if last = probeHealth(ctx, client, "http://carlos/"); last == nil {
return nil
}
poll = nextHealthPoll(poll)
- time.Sleep(poll)
+ if err := healthPause(ctx, poll); err != nil {
+ return err
+ }
}
return fmt.Errorf("instance not healthy within %s: %v", timeout, last)
}
+// healthPause waits d between two health probes, or returns ctx.Err() as
+// soon as ctx ends.
+func healthPause(ctx context.Context, d time.Duration) error {
+ t := time.NewTimer(d)
+ defer t.Stop()
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ case <-t.C:
+ return nil
+ }
+}
+
// healthClient is c made fit for a health probe: it never follows a
// redirect. A redirect is an answer, and under 500, so the app is up.
// Following one is worse than pointless: an app with Rails' force_ssl
@@ -4065,8 +4090,9 @@ func healthClient(c *http.Client) *http.Client {
// says X-Forwarded-Proto: https, as the edge does on every real request
// (they all arrive over TLS), so an app that redirects plain http takes its
// normal path rather than answering the probe with a redirect (#845).
-func probeHealth(client *http.Client, url string) error {
- req, err := http.NewRequest(http.MethodGet, url, nil)
+// ctx cancels the request, in flight or not yet sent.
+func probeHealth(ctx context.Context, client *http.Client, url string) error {
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return err
}
@@ -4097,19 +4123,6 @@ func nextHealthPoll(d time.Duration) time.Duration {
return min(max(2*d, healthPollMin), healthPollMax)
}
-// waitHealthyCtx is waitHealthy bounded by ctx as well as its own timeout, so
-// an aborted wake doesn't keep probing a socket nobody wants anymore.
-func waitHealthyCtx(ctx context.Context, socket string, timeout time.Duration) error {
- done := make(chan error, 1)
- go func() { done <- waitHealthy(socket, timeout) }()
- select {
- case err := <-done:
- return err
- case <-ctx.Done():
- return ctx.Err()
- }
-}
-
// readEnvFile parses a KEY=value EnvironmentFile (blank lines and #comments
// ignored).
func readEnvFile(path string) (map[string]string, error) {
diff --git a/internal/activator/backend_unit.go b/internal/activator/backend_unit.go
index 5dff27268..63edbb2a6 100644
--- a/internal/activator/backend_unit.go
+++ b/internal/activator/backend_unit.go
@@ -262,20 +262,21 @@ type unitRep struct{}
func (unitRep) Err() error { return nil }
func (unitRep) Close(context.Context) error { return nil }
-// waitHealthyAddr is waitHealthy for TCP upstreams (rt.Addr — unit tenants
-// that can't accept a unix listener yet; see the carlos-app@.socket unit's
-// fallback note).
-func waitHealthyAddr(addr string, timeout time.Duration) error {
- return waitHealthyAddrVia(net.Dialer{Timeout: 30 * time.Second, KeepAlive: 30 * time.Second}, addr, timeout)
-}
-
-// waitHealthyAddrVia is waitHealthyAddr dialing with base (a test sets its
-// Resolver) behind upstreamguard: rt.Addr is route-supplied, so a link-local
-// or IMDS destination is refused after resolution and before connect, and
-// that refusal ends the wait at once. The transport is the default one's
-// settings without the environment proxy, so the guard judges the upstream
-// itself rather than a proxy.
-func waitHealthyAddrVia(base net.Dialer, addr string, timeout time.Duration) error {
+// waitHealthyAddrCtx is waitHealthyCtx for TCP upstreams (rt.Addr — unit
+// tenants that can't accept a unix listener yet; see the
+// carlos-app@.socket unit's fallback note), and stops probing when ctx
+// ends in the same way.
+func waitHealthyAddrCtx(ctx context.Context, addr string, timeout time.Duration) error {
+ return waitHealthyAddrVia(ctx, net.Dialer{Timeout: 30 * time.Second, KeepAlive: 30 * time.Second}, addr, timeout)
+}
+
+// waitHealthyAddrVia is waitHealthyAddrCtx dialing with base (a test sets
+// its Resolver) behind upstreamguard: rt.Addr is route-supplied, so a
+// link-local or IMDS destination is refused after resolution and before
+// connect, and that refusal ends the wait at once. The transport is the
+// default one's settings without the environment proxy, so the guard
+// judges the upstream itself rather than a proxy.
+func waitHealthyAddrVia(ctx context.Context, base net.Dialer, addr string, timeout time.Duration) error {
tr := http.DefaultTransport.(*http.Transport).Clone()
tr.Proxy = nil
tr.DialContext = upstreamguard.Dialer(base).DialContext
@@ -285,29 +286,23 @@ func waitHealthyAddrVia(base net.Dialer, addr string, timeout time.Duration) err
var last error
var poll time.Duration
for time.Now().Before(deadline) {
- if last = probeHealth(client, "http://"+addr+"/"); last == nil {
+ if err := ctx.Err(); err != nil {
+ return err
+ }
+ if last = probeHealth(ctx, client, "http://"+addr+"/"); last == nil {
return nil
}
if errors.Is(last, upstreamguard.ErrLinkLocal) {
return fmt.Errorf("instance health check: %w", last)
}
poll = nextHealthPoll(poll)
- time.Sleep(poll)
+ if err := healthPause(ctx, poll); err != nil {
+ return err
+ }
}
return fmt.Errorf("instance not healthy within %s: %v", timeout, last)
}
-func waitHealthyAddrCtx(ctx context.Context, addr string, timeout time.Duration) error {
- done := make(chan error, 1)
- go func() { done <- waitHealthyAddr(addr, timeout) }()
- select {
- case err := <-done:
- return err
- case <-ctx.Done():
- return ctx.Err()
- }
-}
-
// SplitBackend composes the two production backends behind the one Backend
// seam the state machine sees: each call dispatches on the route's Backing,
// so exec children and unit tenants share the singleflight wakes, idle
diff --git a/internal/activator/hasuspect_test.go b/internal/activator/hasuspect_test.go
index dd7e505a8..3c4df52e3 100644
--- a/internal/activator/hasuspect_test.go
+++ b/internal/activator/hasuspect_test.go
@@ -497,6 +497,7 @@ func TestDepartureFailedHolderObservation(t *testing.T) {
s.a.OnDepartureSuspect = func(ref string) {
calls++
s.a.mu.Lock()
+ //lint:ignore SA2001 taking and releasing a.mu proves the callback runs off the lock
s.a.mu.Unlock()
if ref != "b" {
t.Fatalf("suspect %q", ref)
diff --git a/internal/activator/healthaddr_guard_test.go b/internal/activator/healthaddr_guard_test.go
index 38b44aad1..7d118d7aa 100644
--- a/internal/activator/healthaddr_guard_test.go
+++ b/internal/activator/healthaddr_guard_test.go
@@ -1,6 +1,7 @@
package activator
import (
+ "context"
"errors"
"net"
"net/http"
@@ -24,8 +25,8 @@ func TestWaitHealthyAddrRefusesLinkLocal(t *testing.T) {
name string
wait func() error
}{
- {"name resolving to IMDS", func() error { return waitHealthyAddrVia(base, "imds.test:80", 5*time.Second) }},
- {"IMDS literal, production dialer", func() error { return waitHealthyAddr("169.254.169.254:80", 5*time.Second) }},
+ {"name resolving to IMDS", func() error { return waitHealthyAddrVia(context.Background(), base, "imds.test:80", 5*time.Second) }},
+ {"IMDS literal, production dialer", func() error { return waitHealthyAddrCtx(context.Background(), "169.254.169.254:80", 5*time.Second) }},
} {
t.Run(tc.name, func(t *testing.T) {
start := time.Now()
@@ -43,7 +44,7 @@ func TestWaitHealthyAddrRefusesLinkLocal(t *testing.T) {
func TestWaitHealthyAddrLoopbackStillWorks(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
t.Cleanup(srv.Close)
- if err := waitHealthyAddr(strings.TrimPrefix(srv.URL, "http://"), 2*time.Second); err != nil {
+ if err := waitHealthyAddrCtx(context.Background(), strings.TrimPrefix(srv.URL, "http://"), 2*time.Second); err != nil {
t.Fatalf("waitHealthyAddr on loopback: %v", err)
}
}
diff --git a/internal/activator/healthcheck_redirect_test.go b/internal/activator/healthcheck_redirect_test.go
index c7d98be84..eac83b3cc 100644
--- a/internal/activator/healthcheck_redirect_test.go
+++ b/internal/activator/healthcheck_redirect_test.go
@@ -1,6 +1,7 @@
package activator
import (
+ "context"
"net"
"net/http"
"strings"
@@ -51,7 +52,7 @@ func TestWaitHealthySaysHTTPS(t *testing.T) {
t.Fatal(err)
}
https := forceSSLApp(t, ln)
- if err := waitHealthy(sock, 2*time.Second); err != nil {
+ if err := waitHealthyCtx(context.Background(), sock, 2*time.Second); err != nil {
t.Fatalf("waitHealthy: %v", err)
}
if https.Load() == 0 {
@@ -69,7 +70,7 @@ func TestWaitHealthyDoesNotFollowRedirects(t *testing.T) {
t.Fatal(err)
}
redirectingApp(t, ln)
- if err := waitHealthy(sock, 2*time.Second); err != nil {
+ if err := waitHealthyCtx(context.Background(), sock, 2*time.Second); err != nil {
t.Fatalf("waitHealthy on a redirecting app: %v", err)
}
}
@@ -81,7 +82,7 @@ func TestWaitHealthyAddrSaysHTTPSAndDoesNotFollowRedirects(t *testing.T) {
t.Fatal(err)
}
https := forceSSLApp(t, ln)
- if err := waitHealthyAddr(ln.Addr().String(), 2*time.Second); err != nil {
+ if err := waitHealthyAddrCtx(context.Background(), ln.Addr().String(), 2*time.Second); err != nil {
t.Fatalf("waitHealthyAddr: %v", err)
}
if https.Load() == 0 {
@@ -93,7 +94,7 @@ func TestWaitHealthyAddrSaysHTTPSAndDoesNotFollowRedirects(t *testing.T) {
t.Fatal(err)
}
redirectingApp(t, ln2)
- if err := waitHealthyAddr(ln2.Addr().String(), 2*time.Second); err != nil {
+ if err := waitHealthyAddrCtx(context.Background(), ln2.Addr().String(), 2*time.Second); err != nil {
t.Fatalf("waitHealthyAddr on a redirecting app: %v", err)
}
}
@@ -110,7 +111,7 @@ func TestWaitHealthyStillFailsA500(t *testing.T) {
})}
go srv.Serve(ln)
t.Cleanup(func() { srv.Close() })
- err = waitHealthyAddr(ln.Addr().String(), 200*time.Millisecond)
+ err = waitHealthyAddrCtx(context.Background(), ln.Addr().String(), 200*time.Millisecond)
if err == nil || !strings.Contains(err.Error(), "HTTP 500") {
t.Fatalf("waitHealthyAddr on a 500 = %v, want HTTP 500", err)
}
diff --git a/internal/activator/healthwait_cancel_test.go b/internal/activator/healthwait_cancel_test.go
new file mode 100644
index 000000000..7f0bbdaf2
--- /dev/null
+++ b/internal/activator/healthwait_cancel_test.go
@@ -0,0 +1,141 @@
+package activator
+
+import (
+ "context"
+ "errors"
+ "net"
+ "net/http"
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+// healthWaitKinds are the two health waits a wake runs: on the instance's
+// unix socket (exec, rootfs, generations) and on a unit route's TCP addr.
+// Each listens with h and returns the wait to run against it.
+type healthWaitKind func(t *testing.T, h http.Handler) func(ctx context.Context) error
+
+var healthWaitKinds = map[string]healthWaitKind{
+ "socket": func(t *testing.T, h http.Handler) func(ctx context.Context) error {
+ requireUnixSockets(t)
+ sock := tmpSock(t)
+ ln, err := net.Listen("unix", sock)
+ if err != nil {
+ t.Fatal(err)
+ }
+ serveHealth(t, ln, h)
+ return func(ctx context.Context) error { return waitHealthyCtx(ctx, sock, 30*time.Second) }
+ },
+ "addr": func(t *testing.T, h http.Handler) func(ctx context.Context) error {
+ ln, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ serveHealth(t, ln, h)
+ addr := ln.Addr().String()
+ return func(ctx context.Context) error { return waitHealthyAddrCtx(ctx, addr, 30*time.Second) }
+ },
+}
+
+func serveHealth(t *testing.T, ln net.Listener, h http.Handler) {
+ t.Helper()
+ srv := &http.Server{Handler: h}
+ go srv.Serve(ln)
+ t.Cleanup(func() { srv.Close() })
+}
+
+// runWait starts wait in the background and returns its result channel.
+func runWait(ctx context.Context, wait func(context.Context) error) <-chan error {
+ done := make(chan error, 1)
+ go func() { done <- wait(ctx) }()
+ return done
+}
+
+func wantCanceled(t *testing.T, done <-chan error) {
+ t.Helper()
+ wantCanceledWithin(t, done, time.Second)
+}
+
+func wantCanceledWithin(t *testing.T, done <-chan error, d time.Duration) {
+ t.Helper()
+ select {
+ case err := <-done:
+ if !errors.Is(err, context.Canceled) {
+ t.Fatalf("wait = %v, want context.Canceled", err)
+ }
+ case <-time.After(d):
+ t.Fatalf("the wait did not return within %v", d)
+ }
+}
+
+// TestHealthWaitStopsProbingWhenCancelled: a wake that is cancelled while
+// its instance answers 503 stops probing. Before, the wait returned but
+// left its polling loop running for the rest of its 30 s (120 s rootfs), so
+// a retried wake's process on the same socket got the stale probes.
+func TestHealthWaitStopsProbingWhenCancelled(t *testing.T) {
+ for name, listen := range healthWaitKinds {
+ t.Run(name, func(t *testing.T) {
+ // The wake is cancelled from inside the second probe's handler.
+ // The wait sends one probe at a time, so at that moment that
+ // probe is the only one in flight and is already counted: any
+ // later start is a probe begun after the cancel.
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ const cancelAt = 2
+ var probes atomic.Int32
+ wait := listen(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if probes.Add(1) == cancelAt {
+ cancel()
+ }
+ w.WriteHeader(http.StatusServiceUnavailable)
+ }))
+ done := runWait(ctx, wait)
+ wantCanceledWithin(t, done, 5*time.Second)
+ // No new probe may start across several poll intervals
+ // (healthPollMax is 50 ms); before, the loop kept going.
+ time.Sleep(6 * healthPollMax)
+ if got := probes.Load(); got != cancelAt {
+ t.Fatalf("%d probes started after the cancel; a cancelled wait must stop probing", got-cancelAt)
+ }
+ })
+ }
+}
+
+// TestHealthWaitCancelsTheProbeInFlight: an instance that accepts the probe
+// and never answers does not hold a cancelled wait's request for the
+// probe's 3 s client timeout; the request is cancelled with the wake.
+func TestHealthWaitCancelsTheProbeInFlight(t *testing.T) {
+ for name, listen := range healthWaitKinds {
+ t.Run(name, func(t *testing.T) {
+ entered := make(chan struct{}, 1)
+ released := make(chan struct{})
+ wait := listen(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ select {
+ case entered <- struct{}{}:
+ default:
+ }
+ <-r.Context().Done()
+ select {
+ case <-released:
+ default:
+ close(released)
+ }
+ }))
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ done := runWait(ctx, wait)
+ select {
+ case <-entered:
+ case <-time.After(5 * time.Second):
+ t.Fatal("the probe never reached the instance")
+ }
+ cancel()
+ wantCanceled(t, done)
+ select {
+ case <-released:
+ case <-time.After(time.Second):
+ t.Fatal("the instance still holds the probe 1s after the wake was cancelled")
+ }
+ })
+ }
+}
diff --git a/internal/activator/rootfs_cmd_lease_test.go b/internal/activator/rootfs_cmd_lease_test.go
index 730f11aee..c76d3e9a7 100644
--- a/internal/activator/rootfs_cmd_lease_test.go
+++ b/internal/activator/rootfs_cmd_lease_test.go
@@ -602,7 +602,8 @@ func TestHibernatingRootfsTickFallbackKillsItsRun(t *testing.T) {
case <-time.After(5 * time.Second):
t.Fatal("the tick asked no kill")
}
- a.mu.Lock() // the kill runs off a.mu
+ a.mu.Lock()
+ //lint:ignore SA2001 a barrier: taking a.mu proves the kill runs off it
a.mu.Unlock()
letGo()
a.rootfsTick()
diff --git a/internal/analytics/meter_test.go b/internal/analytics/meter_test.go
index e719a13ee..4841604af 100644
--- a/internal/analytics/meter_test.go
+++ b/internal/analytics/meter_test.go
@@ -241,7 +241,7 @@ func TestMeterRestartedPerAppOnStartDay(t *testing.T) {
func TestVisitorHashAndEventName(t *testing.T) {
s1, s2 := []byte("salt-a"), []byte("salt-b")
- if VisitorHash(s1, "h", "ip", "ua") != VisitorHash(s1, "h", "ip", "ua") {
+ if first, again := VisitorHash(s1, "h", "ip", "ua"), VisitorHash(s1, "h", "ip", "ua"); first != again {
t.Fatal("deterministic")
}
if VisitorHash(s1, "h", "ip", "ua") == VisitorHash(s2, "h", "ip", "ua") {
diff --git a/internal/assetcache/store_test.go b/internal/assetcache/store_test.go
index f46b8537a..672c2cc46 100644
--- a/internal/assetcache/store_test.go
+++ b/internal/assetcache/store_test.go
@@ -114,7 +114,7 @@ func openStore(t *testing.T, dir string) *Store {
func TestKeyIDIsStableAndDistinct(t *testing.T) {
a := Key{Account: "abc", App: "shop", Gen: "g1", Host: "shop.example.com", Path: "/a.css", RawQuery: "v=1"}
- if a.ID() != a.ID() {
+ if first, again := a.ID(), a.ID(); first != again {
t.Fatal("same key gave two ids")
}
if len(a.ID()) != 64 || strings.Trim(a.ID(), "0123456789abcdef") != "" {
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/console/apiinstances.go b/internal/console/apiinstances.go
index dd593f746..11acdc052 100644
--- a/internal/console/apiinstances.go
+++ b/internal/console/apiinstances.go
@@ -451,7 +451,6 @@ func (s *Server) instanceHealth(ctx context.Context, recs []provision.Record) (h
// routeFor is the join reduced to the routes that ANSWER for these
// records, built once and used by both loops so the two can never drift.
routeFor := make(map[string]registry.Route, len(recs))
- var hosts []string
unitByHost := map[string]string{}
for _, rec := range recs {
rt, ok := byHost[rec.Host]
@@ -475,7 +474,6 @@ func (s *Server) instanceHealth(ctx context.Context, recs []provision.Record) (h
continue
}
routeFor[rec.Host] = rt
- hosts = append(hosts, rec.Host)
if rt.Unit != "" {
unitByHost[rec.Host] = rt.Unit
}
diff --git a/internal/console/demo_jobs.go b/internal/console/demo_jobs.go
index 65d259e47..2a64879ff 100644
--- a/internal/console/demo_jobs.go
+++ b/internal/console/demo_jobs.go
@@ -179,7 +179,7 @@ func scanDemoJob(row interface{ Scan(...any) error }) (demoJobRow, error) {
// under the app lock. A failed object write leaves the same durable outbox row.
func (s *Server) enqueueDemo(ctx context.Context, d DemoRow, src demobuild.Source) (demobuild.Job, error) {
var job demobuild.Job
- err := s.withDemoLocked(ctx, d.ID, func(current DemoRow, life AppLife) error {
+ err := s.withDemoLocked(ctx, d.ID, func(current DemoRow, _ AppLife) error {
if current.Generation != d.Generation {
return errDemoJob
}
diff --git a/internal/console/jobs_test.go b/internal/console/jobs_test.go
index 75dd0f63c..b2106f8b7 100644
--- a/internal/console/jobs_test.go
+++ b/internal/console/jobs_test.go
@@ -181,7 +181,8 @@ func TestPanickingPassIsRecordedAndTheJobRunsAgain(t *testing.T) {
go func() {
errc <- fx.srv.jobs.Run(context.Background(), "StartAlertEngine", func(context.Context) error {
var m map[string]int
- m["boom"]++ // a nil map write: a runtime panic
+ //lint:ignore SA5000 the nil map write is the runtime panic under test
+ m["boom"]++
return nil
})
}()
diff --git a/internal/dbreads/admission_test.go b/internal/dbreads/admission_test.go
index d6ac5f332..6aaa695cb 100644
--- a/internal/dbreads/admission_test.go
+++ b/internal/dbreads/admission_test.go
@@ -30,7 +30,8 @@ func TestAdmissionTwoReadsThenBusy(t *testing.T) {
t.Fatalf("a third read: %v", err)
}
// The probe still has its connection (spec §7.1, codex 9).
- if !a.opened() || !a.opened() || !a.admitProbe(ctx) || !a.opened() {
+ read1, read2, probe := a.opened(), a.opened(), a.admitProbe(ctx)
+ if !read1 || !read2 || !probe || !a.opened() {
t.Fatal("two reads and a probe do not fit three connections")
}
if a.opened() {
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/edge/assetadmit_test.go b/internal/edge/assetadmit_test.go
index 4641ab14d..bc93ad4b3 100644
--- a/internal/edge/assetadmit_test.go
+++ b/internal/edge/assetadmit_test.go
@@ -331,6 +331,7 @@ func TestStoredHeaderDropsHopAndPlatformHeaders(t *testing.T) {
t.Errorf("%s survived: %v", name, got[name])
}
}
+ //lint:ignore SA1008 the raw lower-case key set on the input above is what must not survive
if _, ok := got["x-carlos-lower"]; ok {
t.Error("a non-canonical x-carlos-* key survived")
}
diff --git a/internal/edge/devbox.go b/internal/edge/devbox.go
index 0caff03a5..93e6dab1f 100644
--- a/internal/edge/devbox.go
+++ b/internal/edge/devbox.go
@@ -218,8 +218,8 @@ func serveDevbox(ctx context.Context, cfg DevboxConfig, seams devboxSeams) error
go w.run()
go e.Watch(stop)
- // ReadHeaderTimeout for the same slow-header reason as Run's servers,
- // and no Read/WriteTimeout, which would cut proxied WebSockets.
+ // ReadHeaderTimeout and IdleTimeout for the same reasons as Run's
+ // servers, and no Read/WriteTimeout, which would cut proxied WebSockets.
selfHost, _, _ := net.SplitHostPort(cfg.ListenAddr)
selfIP, _ := netip.ParseAddr(selfHost) // checked before building the edge
srv := &http.Server{
@@ -231,6 +231,7 @@ func serveDevbox(ctx context.Context, cfg DevboxConfig, seams devboxSeams) error
MinVersion: tls.VersionTLS12,
},
ReadHeaderTimeout: 10 * time.Second,
+ IdleTimeout: publicIdleTimeout,
ErrorLog: seams.errorLog,
}
served := make(chan error, 1)
diff --git a/internal/edge/devboxfront_test.go b/internal/edge/devboxfront_test.go
index 6743ee9dc..6276fa827 100644
--- a/internal/edge/devboxfront_test.go
+++ b/internal/edge/devboxfront_test.go
@@ -39,7 +39,7 @@ func assertNoVisitorHeaders(t *testing.T, h http.Header) {
t.Helper()
for k := range h {
for _, name := range []string{"Carlos-Visitor-Login", "Carlos-Visitor-Name", "Carlos-Visitor-Node"} {
- if strings.ToUpper(strings.ReplaceAll(k, "-", "_")) == strings.ToUpper(strings.ReplaceAll(name, "-", "_")) {
+ if strings.EqualFold(strings.ReplaceAll(k, "-", "_"), strings.ReplaceAll(name, "-", "_")) {
t.Errorf("visitor header remains: %q = %q", k, h[k])
}
}
diff --git a/internal/edge/door.go b/internal/edge/door.go
index 12c9b0206..67533f788 100644
--- a/internal/edge/door.go
+++ b/internal/edge/door.go
@@ -196,9 +196,9 @@ func (e *Edge) openDoor(path string) (closeDoor func(), err error) {
ln.Close()
return nil, err
}
- // ReadHeaderTimeout for the public listeners' Slowloris reason; no
- // Read/WriteTimeout, which would cut long-lived streams.
- srv := &http.Server{Handler: http.HandlerFunc(e.serveDoor), ReadHeaderTimeout: 10 * time.Second}
+ // ReadHeaderTimeout and IdleTimeout for the public listeners' reasons;
+ // no Read/WriteTimeout, which would cut long-lived streams.
+ srv := &http.Server{Handler: http.HandlerFunc(e.serveDoor), ReadHeaderTimeout: 10 * time.Second, IdleTimeout: publicIdleTimeout}
go func() {
if err := srv.Serve(ln); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Printf("edge: edge-local door on %s stopped: %v", path, err)
diff --git a/internal/edge/edge.go b/internal/edge/edge.go
index 6eeba4de1..86e490c37 100644
--- a/internal/edge/edge.go
+++ b/internal/edge/edge.go
@@ -4009,12 +4009,13 @@ func unixProxy(socketPath string) *httputil.ReverseProxy {
// A loopback upstream is this box's own process, so a refused dial there is
// a restart in progress: the dial is retried for hold.dial (one deadline
// fixed per dial) instead of 502ing at once. hold.dial <= 0, or a remote
-// addr, dials once. Either way the dial is upstreamDialer's (hold.dialer is
-// nil in production), which refuses link-local and IMDS addresses.
+// addr, dials once. Either way the dial is tcpUpstreamDialer's (hold.dialer
+// is nil in production), which refuses link-local and IMDS addresses and
+// gives up on a connect after tcpUpstreamDialTimeout.
func tcpProxy(addr string, hold localHold) *httputil.ReverseProxy {
dial := hold.dialer
if dial == nil {
- dial = upstreamDialer().DialContext
+ dial = tcpUpstreamDialer().DialContext
}
tr := &http.Transport{
MaxIdleConns: 32,
@@ -5164,9 +5165,10 @@ func RunWithActivatorReady(args []string, act Activator, cache *Cache, ready fun
log.Printf("edge: edge-local door off in dev mode")
}
// ReadHeaderTimeout guards against Slowloris-style slow-header
- // connection exhaustion. No ReadTimeout/WriteTimeout — those would
- // break long-lived proxied WebSockets.
- srv := &http.Server{Addr: *httpAddr, Handler: e, ReadHeaderTimeout: 10 * time.Second}
+ // connection exhaustion; publicIdleTimeout closes idle keep-alives.
+ // No ReadTimeout/WriteTimeout — those would break long-lived
+ // proxied WebSockets.
+ srv := &http.Server{Addr: *httpAddr, Handler: e, ReadHeaderTimeout: 10 * time.Second, IdleTimeout: publicIdleTimeout}
// Bound here, on this goroutine, as ListenAndServe would; the line
// below means the bind succeeded.
ln, err := listen("http", *httpAddr, ":http")
diff --git a/internal/edge/idletimeout_test.go b/internal/edge/idletimeout_test.go
new file mode 100644
index 000000000..39c624372
--- /dev/null
+++ b/internal/edge/idletimeout_test.go
@@ -0,0 +1,98 @@
+package edge
+
+import (
+ "crypto/tls"
+ "go/ast"
+ "go/parser"
+ "go/token"
+ "net/http"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+)
+
+// TestPublicServersCloseIdleConnections: :80 and :443 close a connection
+// that sits idle, keep the slow-header bound, and set no Read/WriteTimeout
+// (they would cut uploads, held streams and WebSockets). The idle bound
+// stays under the region NLB's 350 s TCP idle timeout.
+func TestPublicServersCloseIdleConnections(t *testing.T) {
+ e := &Edge{}
+ h := http.NotFoundHandler()
+ httpsSrv, httpSrv := e.publicServers(h, h, &tls.Config{}, "", "")
+ for name, srv := range map[string]*http.Server{"https": httpsSrv, "http": httpSrv} {
+ if srv.IdleTimeout != publicIdleTimeout || srv.ReadHeaderTimeout != 10*time.Second {
+ t.Errorf("%s: IdleTimeout %v ReadHeaderTimeout %v, want %v and 10s", name, srv.IdleTimeout, srv.ReadHeaderTimeout, publicIdleTimeout)
+ }
+ if srv.ReadTimeout != 0 || srv.WriteTimeout != 0 {
+ t.Errorf("%s: ReadTimeout %v WriteTimeout %v, want neither", name, srv.ReadTimeout, srv.WriteTimeout)
+ }
+ }
+ if publicIdleTimeout <= 0 || publicIdleTimeout >= 350*time.Second {
+ t.Fatalf("publicIdleTimeout %v must be positive and under the NLB's 350 s", publicIdleTimeout)
+ }
+}
+
+// TestEveryEdgeServerSetsIdleTimeout reads the package's source: every
+// http.Server literal sets IdleTimeout and ReadHeaderTimeout and neither
+// ReadTimeout nor WriteTimeout, so a listener added later (or the dev,
+// devbox and door servers, built inline) cannot quietly hold idle
+// connections forever. The one exception is purge.go's control listener,
+// a per-instance unix socket that only the box's own processes can dial,
+// which is not public and is left as it was.
+func TestEveryEdgeServerSetsIdleTimeout(t *testing.T) {
+ exempt := map[string]bool{"purge.go": true}
+ files, err := filepath.Glob("*.go")
+ if err != nil {
+ t.Fatal(err)
+ }
+ fset := token.NewFileSet()
+ found := 0
+ for _, name := range files {
+ if strings.HasSuffix(name, "_test.go") || exempt[name] {
+ continue
+ }
+ src, err := os.ReadFile(name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ f, err := parser.ParseFile(fset, name, src, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ ast.Inspect(f, func(n ast.Node) bool {
+ lit, ok := n.(*ast.CompositeLit)
+ if !ok {
+ return true
+ }
+ sel, ok := lit.Type.(*ast.SelectorExpr)
+ if !ok || sel.Sel.Name != "Server" {
+ return true
+ }
+ if pkg, ok := sel.X.(*ast.Ident); !ok || pkg.Name != "http" {
+ return true
+ }
+ found++
+ keys := map[string]bool{}
+ for _, el := range lit.Elts {
+ if kv, ok := el.(*ast.KeyValueExpr); ok {
+ if id, ok := kv.Key.(*ast.Ident); ok {
+ keys[id.Name] = true
+ }
+ }
+ }
+ at := fset.Position(lit.Pos())
+ if !keys["IdleTimeout"] || !keys["ReadHeaderTimeout"] {
+ t.Errorf("%s: http.Server without IdleTimeout and ReadHeaderTimeout", at)
+ }
+ if keys["ReadTimeout"] || keys["WriteTimeout"] {
+ t.Errorf("%s: http.Server sets ReadTimeout or WriteTimeout, which cut long streams", at)
+ }
+ return true
+ })
+ }
+ if found < 5 {
+ t.Fatalf("found %d http.Server literals, want at least 5 (:80, :443, dev, devbox, door); has the scan stopped matching?", found)
+ }
+}
diff --git a/internal/edge/ingressdrain.go b/internal/edge/ingressdrain.go
index 54370928f..01710b7ea 100644
--- a/internal/edge/ingressdrain.go
+++ b/internal/edge/ingressdrain.go
@@ -89,14 +89,37 @@ func (e *Edge) plainTracked(h http.Handler) http.Handler {
// address :80's health check never reaches plainTracked or the challenge.
//
// ReadHeaderTimeout guards the public front door against Slowloris-style
-// slow-header connection exhaustion. No ReadTimeout/WriteTimeout: those
-// would break long-lived proxied WebSockets.
+// slow-header connection exhaustion, and publicIdleTimeout closes the
+// connections that sit idle between requests. No ReadTimeout/WriteTimeout:
+// those would break long uploads, edge-held streams (#432) and long-lived
+// proxied WebSockets (#471).
func (e *Edge) publicServers(https, challenge http.Handler, tlsCfg *tls.Config, httpAddr, httpsAddr string) (httpsSrv, httpSrv *http.Server) {
- httpSrv = &http.Server{Addr: httpAddr, Handler: e.plainTracked(challenge), ReadHeaderTimeout: 10 * time.Second}
- httpsSrv = &http.Server{Addr: httpsAddr, Handler: https, TLSConfig: tlsCfg, ReadHeaderTimeout: 10 * time.Second}
+ httpSrv = &http.Server{Addr: httpAddr, Handler: e.plainTracked(challenge), ReadHeaderTimeout: 10 * time.Second, IdleTimeout: publicIdleTimeout}
+ httpsSrv = &http.Server{Addr: httpsAddr, Handler: https, TLSConfig: tlsCfg, ReadHeaderTimeout: 10 * time.Second, IdleTimeout: publicIdleTimeout}
return httpsSrv, httpSrv
}
+// publicIdleTimeout is how long a server the edge exposes (:80, :443, the
+// dev listener, the devbox listener and the edge-local door) keeps a
+// connection with no request on it: an HTTP/1.1 keep-alive connection
+// between requests, or an HTTP/2 connection with no open stream. With
+// IdleTimeout and ReadTimeout both zero, net/http keeps such a connection,
+// its goroutine and its TLS state for as long as the client likes;
+// ReadHeaderTimeout starts only at the next request's first byte. It never
+// touches a request in flight, an edge-held stream (an open request) or a
+// hijacked connection (WebSockets, tunnels), so it is safe where
+// ReadTimeout and WriteTimeout are not.
+//
+// It must stay under the idle timeout of the region NLB in front of a
+// fixed edge: AWS's TCP default of 350 s, since the listeners in
+// infra/modules/region-host/ingress set no tcp_idle_timeout_seconds. The
+// edge then closes first, with a FIN the client sees, instead of the NLB
+// forgetting the flow and the client's next request on it getting a reset.
+// It is also above the 90 s IdleConnTimeout of the edge's own backhaul
+// client, so a box-to-box hop's pool drops a connection before the far
+// edge does.
+const publicIdleTimeout = 120 * time.Second
+
// CloseIngress is step 3's edge half: close the public listeners
// gracefully, waiting up to wait (the connection wait).
//
diff --git a/internal/edge/lbhealth.go b/internal/edge/lbhealth.go
index fcc58612c..3e84c0523 100644
--- a/internal/edge/lbhealth.go
+++ b/internal/edge/lbhealth.go
@@ -70,7 +70,8 @@ func (e *Edge) servingPathLive() bool {
done := make(chan struct{})
go func() {
c.mu.Lock()
- c.mu.Unlock() //nolint:staticcheck // take and release is the probe
+ //lint:ignore SA2001 take and release is the probe
+ c.mu.Unlock()
e.probing.Store(false)
close(done)
}()
diff --git a/internal/edge/plandisabled.go b/internal/edge/plandisabled.go
index 6b55307b7..eb2198b84 100644
--- a/internal/edge/plandisabled.go
+++ b/internal/edge/plandisabled.go
@@ -4,6 +4,7 @@ import (
"bytes"
"html/template"
"net/http"
+ "strconv"
"github.com/carlosframework/platform/internal/registry"
)
@@ -77,7 +78,15 @@ func (e *Edge) planDisabledAdmit(w http.ResponseWriter, r *http.Request, host st
if f == nil || rt.Kind == "status" || !(*f)(rt, host) {
return true
}
- e.logThrottled("plan-disabled "+host, "plan: answered "+host+" with the disabled page (turned off after a lapse)")
+ // Keyed on the route, never the request's host: under a catch-all every
+ // invented label would add a map entry and a journal line
+ // (logThrottled's contract). The line names the route and, when it
+ // differs, the host of the request that was logged, quoted.
+ msg := "plan: answered " + rt.Host + " with the disabled page (turned off after a lapse)"
+ if host != rt.Host {
+ msg += " for host " + strconv.Quote(host)
+ }
+ e.logThrottled("plan-disabled "+rt.Host, msg)
h := w.Header()
h.Set("Content-Type", "text/html; charset=utf-8")
h.Set("Cache-Control", "no-store")
diff --git a/internal/edge/plandisabled_test.go b/internal/edge/plandisabled_test.go
index 19ace8d89..3dd12fdb0 100644
--- a/internal/edge/plandisabled_test.go
+++ b/internal/edge/plandisabled_test.go
@@ -1,6 +1,7 @@
package edge
import (
+ "fmt"
"net/http"
"net/http/httptest"
"strings"
@@ -110,3 +111,39 @@ func TestNoDisabledHookUnchanged(t *testing.T) {
t.Fatalf("a hook answering false: %d", rec.Code)
}
}
+
+// TestDisabledCatchAllLogsOncePerRoute: the throttled log line is keyed on
+// the route a request resolved to, never on the request's host. Under a
+// turned-off catch-all every invented label is answered with the page, and
+// all of them share one throttle entry, so a stranger cannot grow the map
+// (or the journal) one subdomain at a time.
+func TestDisabledCatchAllLogsOncePerRoute(t *testing.T) {
+ t.Parallel()
+ const catchAll = "*.lapsed.example"
+ srv, backend := newGateBackend(t, "app", "")
+ reg := openReg(t)
+ if err := reg.Upsert(registry.Route{Host: catchAll, Kind: "instance", Addr: srv.Listener.Addr().String(),
+ Status: "ready", App: "shop", Account: "bab"}); err != nil {
+ t.Fatal(err)
+ }
+ e, err := New(reg, &fakeActivator{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(e.probers.Stop)
+ e.SetPlanDisabledFor(func(rt registry.Route, _ string) bool { return rt.Host == catchAll })
+
+ const n = 50
+ for i := range n {
+ host := fmt.Sprintf("invented-%d.lapsed.example", i)
+ wantDisabledPage(t, gateDo(e, http.MethodGet, host, "/", ""), host)
+ }
+ if seen, _ := backend.seen(); seen != 0 {
+ t.Fatalf("upstream saw %d requests, want none", seen)
+ }
+ e.logMu.Lock()
+ defer e.logMu.Unlock()
+ if len(e.logN) != 1 || e.logN["plan-disabled "+catchAll] != n {
+ t.Fatalf("throttle map %v, want one entry for %s counting %d", e.logN, catchAll, n)
+ }
+}
diff --git a/internal/edge/upstreamdial.go b/internal/edge/upstreamdial.go
index 28857146e..c9b081407 100644
--- a/internal/edge/upstreamdial.go
+++ b/internal/edge/upstreamdial.go
@@ -2,6 +2,7 @@ package edge
import (
"net"
+ "time"
"github.com/carlosframework/platform/internal/upstreamguard"
)
@@ -9,8 +10,32 @@ import (
// upstreamDialer is the dialer for a TCP upstream when no test dialer is set
// (hold.dialer nil, as in production): the plain net.Dialer the transports
// used before, behind upstreamguard, which refuses link-local and IMDS
-// addresses after resolution and before connect. tcpProxy, multiProxy and
-// the prober use it; unix sockets, backhaul hops and tunnels do not.
+// addresses after resolution and before connect. multiProxy and the prober
+// use it; tcpProxy uses tcpUpstreamDialer; unix sockets, backhaul hops and
+// tunnels use neither. multiProxy bounds each dial with a context deadline
+// (multiDialTimeout). The prober's dial is still unbounded: its
+// http.Client.Timeout and ResponseHeaderTimeout do not reach the dial,
+// since net/http strips the request's deadline before dialing. Bounding it
+// is follow-up work.
func upstreamDialer() *net.Dialer {
return upstreamguard.Dialer(net.Dialer{})
}
+
+// tcpUpstreamDialTimeout and tcpUpstreamKeepAlive are tcpProxy's dial
+// settings. Its transport has no other bound on a connect, so without a
+// Timeout a black-holed remote upstream holds the request, its goroutine
+// and the client's connection for the kernel's connect timeout (about two
+// minutes on Linux) before the 502. The values are net/http's
+// DefaultTransport dialer, the same the activator's wake health check uses
+// on these route addrs (waitHealthyAddr): a real handshake finishes far
+// inside 30 s, so nothing that connects today stops connecting.
+const (
+ tcpUpstreamDialTimeout = 30 * time.Second
+ tcpUpstreamKeepAlive = 30 * time.Second
+)
+
+// tcpUpstreamDialer is upstreamDialer with tcpProxy's connect bound and
+// keep-alive: still behind upstreamguard, so the link-local refusal holds.
+func tcpUpstreamDialer() *net.Dialer {
+ return upstreamguard.Dialer(net.Dialer{Timeout: tcpUpstreamDialTimeout, KeepAlive: tcpUpstreamKeepAlive})
+}
diff --git a/internal/edge/upstreamdial_test.go b/internal/edge/upstreamdial_test.go
index 4c2d367b2..672bf1bd0 100644
--- a/internal/edge/upstreamdial_test.go
+++ b/internal/edge/upstreamdial_test.go
@@ -141,3 +141,25 @@ func TestUpstreamDialSitesRefuseLinkLocal(t *testing.T) {
conn.Close()
})
}
+
+// TestTCPUpstreamDialerIsBounded: tcpProxy's production dialer gives up on a
+// connect after tcpUpstreamDialTimeout instead of the kernel's two minutes,
+// keeps TCP keep-alives on, and is still behind upstreamguard.
+func TestTCPUpstreamDialerIsBounded(t *testing.T) {
+ d := tcpUpstreamDialer()
+ if d.Timeout != tcpUpstreamDialTimeout || d.KeepAlive != tcpUpstreamKeepAlive {
+ t.Fatalf("Timeout %v KeepAlive %v, want %v and %v", d.Timeout, d.KeepAlive, tcpUpstreamDialTimeout, tcpUpstreamKeepAlive)
+ }
+ if d.Timeout <= 0 || d.Timeout > 30*time.Second {
+ t.Fatalf("Timeout %v: want a bound no longer than net/http's 30 s default", d.Timeout)
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ defer cancel()
+ conn, err := d.DialContext(ctx, "tcp", "169.254.169.254:80")
+ if conn != nil {
+ conn.Close()
+ }
+ if !errors.Is(err, upstreamguard.ErrLinkLocal) {
+ t.Fatalf("dial err = %v, want upstreamguard.ErrLinkLocal", err)
+ }
+}
diff --git a/internal/grouproll/text_test.go b/internal/grouproll/text_test.go
index 37b8617c3..cab9b7478 100644
--- a/internal/grouproll/text_test.go
+++ b/internal/grouproll/text_test.go
@@ -47,8 +47,9 @@ func TestTextRefusesProgrammingErrors(t *testing.T) {
for name, call := range map[string]func(){
"unknown key": func() { Text("no_such_key") },
"missing placeholder": func() { Text("journal") },
- "odd args": func() { Text("journal", "path") },
- "unused arg": func() { Text("journal", "path", "/p", "extra", "x") },
+ //lint:ignore SA5012 an odd argument count is the programming error under test
+ "odd args": func() { Text("journal", "path") },
+ "unused arg": func() { Text("journal", "path", "/p", "extra", "x") },
} {
t.Run(name, func(t *testing.T) {
defer func() {
diff --git a/internal/host/mailswitch_test.go b/internal/host/mailswitch_test.go
index 4df301a10..cea10ed6a 100644
--- a/internal/host/mailswitch_test.go
+++ b/internal/host/mailswitch_test.go
@@ -79,7 +79,7 @@ func TestMailSwitchCache(t *testing.T) {
t.Fatalf("a hit read the store again (%d reads)", st.n())
}
// An app with no sender record is off, and cached.
- if c.State("abcxyz", "sheets") != off || c.State("abcxyz", "sheets") != off || st.n() != 2 {
+ if first, again := c.State("abcxyz", "sheets"), c.State("abcxyz", "sheets"); first != off || again != off || st.n() != 2 {
t.Fatalf("absent record: %d reads", st.n())
}
// A record with no submission block, or one switched off, is off.
@@ -107,7 +107,7 @@ func TestMailSwitchCache(t *testing.T) {
// A read error with nothing cached is unknown, never off (P2-2),
// logged once a minute, and retried only after mailSwitchRetryErr.
st.fail = errors.New("store down")
- if c.State("abcxyz", "calendar") != unknown || c.State("abcxyz", "calendar") != unknown {
+ if first, again := c.State("abcxyz", "calendar"), c.State("abcxyz", "calendar"); first != unknown || again != unknown {
t.Fatal("an unreadable switch is not unknown")
}
if len(logs) != 1 || !strings.Contains(logs[0], "abcxyz/calendar") {
diff --git a/internal/host/movespolicy_test.go b/internal/host/movespolicy_test.go
index 9e19dfe0a..397a4321a 100644
--- a/internal/host/movespolicy_test.go
+++ b/internal/host/movespolicy_test.go
@@ -293,7 +293,7 @@ func TestMovesClaimPolicyRefusesOtherRoles(t *testing.T) {
if err := moves(ctx, c, s, hostwrite.Identity{}); !errors.Is(err, context.Canceled) {
t.Fatal(err)
}
- //lint:ignore SA1012 the nil context is the case under test
+ // The nil context is the case under test.
if err := moves(nil, c, s, hostwrite.Identity{}); !errors.Is(err, ErrMovesRefused) { //nolint:staticcheck
t.Fatal(err)
}
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/hostactors/membershipread_test.go b/internal/hostactors/membershipread_test.go
index beb2f38cf..ba03bfc7c 100644
--- a/internal/hostactors/membershipread_test.go
+++ b/internal/hostactors/membershipread_test.go
@@ -289,7 +289,7 @@ var newRef = GroupBoxReference("123", "i-new")
// reference is a pseudonym of account and instance, stable, and outside
// the label space.
func TestGroupBoxReferencesDoNotCollide(t *testing.T) {
- if GroupBoxReference("123", "i-0a61f580df1acfa65") != GroupBoxReference("123", "i-0a61f580df1acfa65") {
+ if first, again := GroupBoxReference("123", "i-0a61f580df1acfa65"), GroupBoxReference("123", "i-0a61f580df1acfa65"); first != again {
t.Fatal("not stable")
}
if GroupBoxReference("123", "i-a") == GroupBoxReference("124", "i-a") {
diff --git a/internal/hostbox/regionalworker.go b/internal/hostbox/regionalworker.go
index a88b5f04a..6520b73be 100644
--- a/internal/hostbox/regionalworker.go
+++ b/internal/hostbox/regionalworker.go
@@ -226,9 +226,8 @@ func (w RegionalWorker) runHost(ctx context.Context, host string) error {
}
o.Park = &scope
}
- if o.Kind == "park-replica" && o.Park != nil && strings.HasPrefix(o.Park.Location, "moves/"+host+"/") {
- // park-staging uses the existing park-replica shape and moves scope.
- }
+ // park-staging uses the existing park-replica shape and moves scope:
+ // a park-replica op under moves/<host>/ needs nothing more here.
if err := w.Regional.Run(ctx, park.Work{Host: host, ID: o.ID, Op: o.Op}); err != nil {
if errors.Is(err, park.ErrPending) {
pending = true
diff --git a/internal/mail/smtppass_test.go b/internal/mail/smtppass_test.go
index 324c06b58..c9f905d98 100644
--- a/internal/mail/smtppass_test.go
+++ b/internal/mail/smtppass_test.go
@@ -39,7 +39,7 @@ func TestSMTPPasswordIsRegionScoped(t *testing.T) {
func TestSMTPPasswordIsDeterministic(t *testing.T) {
secret := "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"
- if SMTPPassword(secret, "eu-west-1") != SMTPPassword(secret, "eu-west-1") {
+ if first, again := SMTPPassword(secret, "eu-west-1"), SMTPPassword(secret, "eu-west-1"); first != again {
t.Fatal("derivation is not deterministic")
}
}
diff --git a/internal/provision/testdata/plan14-root-reads-audit-gate-vet-staticcheck.tsv b/internal/provision/testdata/plan14-root-reads-audit-gate-vet-staticcheck.tsv
new file mode 100644
index 000000000..185d52764
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-audit-gate-vet-staticcheck.tsv
@@ -0,0 +1,11 @@
+# Census overlay audit-gate-vet-staticcheck, written by census-propose (#369). census-ruling-audit-gate-vet-staticcheck, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-audit-gate-vet-staticcheck.md.
+# 1 body, 0 sites, 5 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 6ed96f0dc2e712f8d9b92a596f446a04acc80010c61c6b1484a911076e037dce staticcheck.conf external legacy accepted-legacy accepted-legacy;rev3=census-ruling-audit-gate-vet-staticcheck;basis=new: staticcheck configuration at the module root (which SA checks run). Read only by the staticcheck tool in CI and make staticcheck; nothing in the root binary reads it. No read added. file:external@0 d2b2d75c3f91e6751d17759fec6fc40a8bece2f47fbb31cb8e756a9c8397ccb9
+internal/hostbox/regionalworker.go RegionalWorker.runHost authority C,J2,J4 root-input;rev3=census-ruling-audit-gate-vet-staticcheck;basis=removed an empty if whose body was only a comment (staticcheck SA9003/SA4017: strings.HasPrefix result ignored); the comment stays. No behaviour change, no read added. file:Exec@2438,file:Read@2221,file:Read@227,file:Read@3079,file:Read@513 a834c97e73e57e2c1c50a034492291335b30d3cb4f1e574d8f69011c57acf4ad
+staticcheck.conf external legacy accepted-legacy accepted-legacy;rev3=census-ruling-audit-gate-vet-staticcheck;basis=new: staticcheck configuration at the module root (which SA checks run). Read only by the staticcheck tool in CI and make staticcheck; nothing in the root binary reads it. No read added. file:external@0 d2b2d75c3f91e6751d17759fec6fc40a8bece2f47fbb31cb8e756a9c8397ccb9
+@coverage . 8ffa200e1e12d845e51d43acc487d5e3a699498cc39a63e54e796b55f510fcaa
+@coverage internal/edge d5fef8000a7fe08d0d75ef925033a192fa6682834c83b8e0c173bb78282289fd
+@coverage internal/hostbox 077232c23a8d98b294e456c7196b466249ffb6614ec14e1901283880a5781459
+@coverage internal/schedule e450d3b6c9becdca0324dacc4a90010c62813f74667dc35183a63b6c1648fc96
+@coverage internal/tunnelclient edef6df2f9f7cb71991afde19db500b95f46e2dd5ea7accf1bc4b0290e6bb7ad
diff --git a/internal/provision/testdata/plan14-root-reads-audit-request-path.tsv b/internal/provision/testdata/plan14-root-reads-audit-request-path.tsv
new file mode 100644
index 000000000..0012900d8
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-audit-request-path.tsv
@@ -0,0 +1,11 @@
+# Census overlay audit-request-path, written by census-propose (#369). census-ruling-audit-request-path, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-audit-request-path.md.
+# 2 body, 0 sites, 2 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+# 1 new dispositions: 1 reads re-frozen at their disposition with the claim, 0 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other.
+@legacy f275da6dc384e20dd81d62616a9ef251ca4e16730c3e4d374f238811664d5d06 internal/edge/door.go Edge.openDoor legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-audit-request-path;basis=the edge-local door server gains IdleTimeout: publicIdleTimeout (120 s) beside its ReadHeaderTimeout; comment updated. No read added. file:Lstat@364 65db004d6c86118f601c46acc5abf8a51e7f964b80dc9dec2fb2f99c89a6e327
+@legacy 0209ecbc124213d5822821cc046c43cd39b96dfbf032a4bc20a5959ccfbbec47 internal/edge/edge.go RunWithActivatorReady legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-certwarm-wake;basis=registers the cert warm's nudge on OnReload and on the home map's new served-hosts wake (#386); nudge only sends on a buffered channel; no read added, same 5 sites;rev3=census-ruling-edge-roll-blip;basis=the :80/:443 (and dev) listeners are bound on the calling goroutine with net.Listen via listen()/listenAddr (same empty-address defaults as ListenAndServe) before the serve goroutines, which now call Serve/ServeTLS on them, and one log line names the bound addresses; no read added, same 5 sites;rev3=census-ruling-edge-held-streams;basis=the edge in the agent (carlos-edge.service, user carlos): the inline home-map arming (newHomeMap, one boot Refresh, Store, run) moves unchanged into the new Edge.ArmHomeMap and is called here as e.ArmHomeMap(); same refresh, same timeout, same order. The reads are moved, none added.;rev3=census-ruling-agent-start-demo-1;basis=Logs the combined explicit wildcard parents through demoWildcardDomains; no new watcher or read loop.;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: invoke the local admission Close before HTTP/HTTPS draining and door shutdown in both dev and normal listeners. Preserve merged main's startup behavior and its census basis; the same five read sites, no new reads.;rev3=census-ruling-stateless-replicas-3;basis=Task 1b: defer stopping and joining the edge's replica jobs at shutdown. Existing five direct read sites unchanged; no new reader or authority.;rev3=census-ruling-region-ha-p3b;basis=Wrap dev, HTTP and HTTPS listeners through ConfigureGroupHairpin before serving. Indirectly read protected root boot identity and group-ingress.json; kernel local/peer addresses mark local ingress, never HTTP headers. Agent edge uses verified public source for accounting; direct read sites unchanged and absent marker keeps original listeners. CI fix removes interface enumeration: local peer must match snapshot primary IPv4, an ingress IPv4 installed locally by root, or loopback; kernel destination must still be an ingress EIP on port 80/443. Merge 45cebde4 retains deferred stopReplicaProbes alongside group listener wrapping and shutdown admission closure.;rev3=census-ruling-demo-api-site-route;basis=Change the startup failure context from load routes to initialize because origin validation now runs during construction. Existing five read sites unchanged; no new read or runtime authority.;rev3=census-ruling-region-ha-graceful-terminate-t2;basis=Invoke the agent shutdown timestamp hook synchronously at SIGTERM/SIGINT receipt before closing admission in dev and TLS paths. No read added.;rev3=census-ruling-region-ha-held-build;basis=region HA held-requests Task 5: registers the https and http servers with the connection drain (conns.serve) so a drain can close idle keep-alive connections; no read added;rev3=census-ruling-warm-set-published-724;basis=#724: the inline cert warm construction (newCertWarm over warmSet and dnsGate, then OnReload and setServedWake registering warm.nudge) moves unchanged into the new Edge.newIssuerWarm in certwarm.go and is called here with the same apps domain, parents, perHostCert, warmResolver, edgeIPs and store; the loop still starts here. The warm set it wires now reads the published edges files through the home map (OwnServedHosts and ServedHosts, both already polled) instead of the local route table, regional names aside. It is a different source, not a subset: an attached name not yet published as pointing is no longer listed, while a name the route table has already dropped stays listed until this box's next edges file write and the home map's next poll catch up (HostPolicy still refuses an order for a name the registry no longer holds). A name published not pointing is not a warm candidate at all, whether or not its certificate is cached: the warm neither looks it up, orders it nor re-arms its renewal until its home box publishes it pointing again (a cached certificate keeps serving and re-arms on a handshake at the issuer). The warm reads the set only after the issuer gate, and the read is in memory (route table and the home map's last snapshot); it also drops a DNS-miss entry for a name that has left the set before probing it. It keeps a failure record while any box publishes the exact name (the home map DeployedHosts: every box's file, own included, pointing or not, the same in-memory snapshot) or the name is a regional route-table name, and prunes it only once no box publishes it. That retention set has no apps-domain or wildcard filter (those stay on candidacy only), so a name published not pointing, or one a wildcard parent starts covering, keeps the record that explains its backoff; the set is never a source of candidates. No read site added in this unit, same 5 sites.;rev3=census-ruling-w6-ingress-drain;basis=the two public servers are built by e.publicServers (internal/edge/ingressdrain.go): :443 as before (same handler, TLS config and ReadHeaderTimeout 10 s), :80 now wrapped by plainTracked so the ingress drain can count and close its requests (its barrier is never §25's); Serve's error test is listenerFailed(err) = err != nil && !errors.Is(err, http.ErrServerClosed) (was err != ErrServerClosed), so a graceful Shutdown by the drain is not fatal. New Edge.plain connDrain field. Same flags, addresses and listeners; read sites unchanged (5); no read added.;rev3=census-ruling-edge-ppv2;basis=Edge process (uid carlos), not root. Edge gains the proxy atomic.Pointer. Outside dev mode, before either public listener binds and before the ready hook hands the Edge to the agent, calls e.loadProxyIngress(os.Getenv, dataDir): CARLOS_INGRESS_PROXY_SOURCES from the edge's own environment (carlos-edge.service loads the root-owned 0600 host.env) through hostenv.ParseProxySources; blank leaves the edge unarmed with nothing read; a non-empty list arms it and Lstats <dataDir>/edge/trust-barrier (armProxyIngress); a value that does not parse is log.Fatal. After the hairpin configuration, wrapProxyIngress wraps both public listeners outermost (returns them untouched when unarmed); when armed it logs the armed line and starts runProxyJournal (counters to the journal, no reads). The existing 5 read sites are unchanged.;rev3=census-ruling-audit-request-path;basis=the dev-mode http.Server gains IdleTimeout: publicIdleTimeout (120 s) beside its ReadHeaderTimeout; comment updated. Same 5 read sites, no read added. data-literal@129,data-literal@148,data-literal@284,data-literal@417,file:Open@1013 7875f163b4fee8118408ff066e7bba5c4692079ffa0fb93aa16989303b469df9
+@legacy bdfe5ed96dd2db7c4a7ca9b3d8fecf0d8ff21ba65baf266d176f0f0611845f96 internal/edge/plandisabled.go Edge.planDisabledAdmit legacy accepted-legacy accepted-legacy;rev3=census-ruling-plans-4d-units;basis=the edge inside the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos), serving only: asks the plans turned-off hook (planDisabledFor, passed the row and the request host) and answers a turned-off route with a fixed 503 page rendered from constants, before the meter, gate, cache and activator; reads only the row's kind; echoes nothing from the request (plans 4d).;rev3=census-ruling-retry-after-503;basis=the fixed 503 page status is written through UnavailableNoRetry (still no Retry-After; adds answer/box headers); body and checks unchanged; no read added;rev3=census-ruling-audit-request-path;basis=the logThrottled key is now "plan-disabled "+rt.Host (the matched route, registry data) instead of the request host; the message names rt.Host and, when it differs, the request host via strconv.Quote. The three new rt.Host reads are of the route already in hand; the predicate call, page and refusal are unchanged. registry:Host@507,registry:Host@582,registry:Host@672,registry:Kind@156,whole:Route@185 ddb568faa8f5cb076d8f2e5aed371e54a5504a5092d95e622988a9d2dbdb6f8c
+internal/edge/door.go Edge.openDoor legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-audit-request-path;basis=the edge-local door server gains IdleTimeout: publicIdleTimeout (120 s) beside its ReadHeaderTimeout; comment updated. No read added. file:Lstat@364 65db004d6c86118f601c46acc5abf8a51e7f964b80dc9dec2fb2f99c89a6e327
+internal/edge/edge.go RunWithActivatorReady legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-certwarm-wake;basis=registers the cert warm's nudge on OnReload and on the home map's new served-hosts wake (#386); nudge only sends on a buffered channel; no read added, same 5 sites;rev3=census-ruling-edge-roll-blip;basis=the :80/:443 (and dev) listeners are bound on the calling goroutine with net.Listen via listen()/listenAddr (same empty-address defaults as ListenAndServe) before the serve goroutines, which now call Serve/ServeTLS on them, and one log line names the bound addresses; no read added, same 5 sites;rev3=census-ruling-edge-held-streams;basis=the edge in the agent (carlos-edge.service, user carlos): the inline home-map arming (newHomeMap, one boot Refresh, Store, run) moves unchanged into the new Edge.ArmHomeMap and is called here as e.ArmHomeMap(); same refresh, same timeout, same order. The reads are moved, none added.;rev3=census-ruling-agent-start-demo-1;basis=Logs the combined explicit wildcard parents through demoWildcardDomains; no new watcher or read loop.;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: invoke the local admission Close before HTTP/HTTPS draining and door shutdown in both dev and normal listeners. Preserve merged main's startup behavior and its census basis; the same five read sites, no new reads.;rev3=census-ruling-stateless-replicas-3;basis=Task 1b: defer stopping and joining the edge's replica jobs at shutdown. Existing five direct read sites unchanged; no new reader or authority.;rev3=census-ruling-region-ha-p3b;basis=Wrap dev, HTTP and HTTPS listeners through ConfigureGroupHairpin before serving. Indirectly read protected root boot identity and group-ingress.json; kernel local/peer addresses mark local ingress, never HTTP headers. Agent edge uses verified public source for accounting; direct read sites unchanged and absent marker keeps original listeners. CI fix removes interface enumeration: local peer must match snapshot primary IPv4, an ingress IPv4 installed locally by root, or loopback; kernel destination must still be an ingress EIP on port 80/443. Merge 45cebde4 retains deferred stopReplicaProbes alongside group listener wrapping and shutdown admission closure.;rev3=census-ruling-demo-api-site-route;basis=Change the startup failure context from load routes to initialize because origin validation now runs during construction. Existing five read sites unchanged; no new read or runtime authority.;rev3=census-ruling-region-ha-graceful-terminate-t2;basis=Invoke the agent shutdown timestamp hook synchronously at SIGTERM/SIGINT receipt before closing admission in dev and TLS paths. No read added.;rev3=census-ruling-region-ha-held-build;basis=region HA held-requests Task 5: registers the https and http servers with the connection drain (conns.serve) so a drain can close idle keep-alive connections; no read added;rev3=census-ruling-warm-set-published-724;basis=#724: the inline cert warm construction (newCertWarm over warmSet and dnsGate, then OnReload and setServedWake registering warm.nudge) moves unchanged into the new Edge.newIssuerWarm in certwarm.go and is called here with the same apps domain, parents, perHostCert, warmResolver, edgeIPs and store; the loop still starts here. The warm set it wires now reads the published edges files through the home map (OwnServedHosts and ServedHosts, both already polled) instead of the local route table, regional names aside. It is a different source, not a subset: an attached name not yet published as pointing is no longer listed, while a name the route table has already dropped stays listed until this box's next edges file write and the home map's next poll catch up (HostPolicy still refuses an order for a name the registry no longer holds). A name published not pointing is not a warm candidate at all, whether or not its certificate is cached: the warm neither looks it up, orders it nor re-arms its renewal until its home box publishes it pointing again (a cached certificate keeps serving and re-arms on a handshake at the issuer). The warm reads the set only after the issuer gate, and the read is in memory (route table and the home map's last snapshot); it also drops a DNS-miss entry for a name that has left the set before probing it. It keeps a failure record while any box publishes the exact name (the home map DeployedHosts: every box's file, own included, pointing or not, the same in-memory snapshot) or the name is a regional route-table name, and prunes it only once no box publishes it. That retention set has no apps-domain or wildcard filter (those stay on candidacy only), so a name published not pointing, or one a wildcard parent starts covering, keeps the record that explains its backoff; the set is never a source of candidates. No read site added in this unit, same 5 sites.;rev3=census-ruling-w6-ingress-drain;basis=the two public servers are built by e.publicServers (internal/edge/ingressdrain.go): :443 as before (same handler, TLS config and ReadHeaderTimeout 10 s), :80 now wrapped by plainTracked so the ingress drain can count and close its requests (its barrier is never §25's); Serve's error test is listenerFailed(err) = err != nil && !errors.Is(err, http.ErrServerClosed) (was err != ErrServerClosed), so a graceful Shutdown by the drain is not fatal. New Edge.plain connDrain field. Same flags, addresses and listeners; read sites unchanged (5); no read added.;rev3=census-ruling-edge-ppv2;basis=Edge process (uid carlos), not root. Edge gains the proxy atomic.Pointer. Outside dev mode, before either public listener binds and before the ready hook hands the Edge to the agent, calls e.loadProxyIngress(os.Getenv, dataDir): CARLOS_INGRESS_PROXY_SOURCES from the edge's own environment (carlos-edge.service loads the root-owned 0600 host.env) through hostenv.ParseProxySources; blank leaves the edge unarmed with nothing read; a non-empty list arms it and Lstats <dataDir>/edge/trust-barrier (armProxyIngress); a value that does not parse is log.Fatal. After the hairpin configuration, wrapProxyIngress wraps both public listeners outermost (returns them untouched when unarmed); when armed it logs the armed line and starts runProxyJournal (counters to the journal, no reads). The existing 5 read sites are unchanged.;rev3=census-ruling-audit-request-path;basis=the dev-mode http.Server gains IdleTimeout: publicIdleTimeout (120 s) beside its ReadHeaderTimeout; comment updated. Same 5 read sites, no read added. data-literal@129,data-literal@148,data-literal@284,data-literal@417,file:Open@1013 7875f163b4fee8118408ff066e7bba5c4692079ffa0fb93aa16989303b469df9
+internal/edge/plandisabled.go Edge.planDisabledAdmit legacy accepted-legacy accepted-legacy;rev3=census-ruling-plans-4d-units;basis=the edge inside the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos), serving only: asks the plans turned-off hook (planDisabledFor, passed the row and the request host) and answers a turned-off route with a fixed 503 page rendered from constants, before the meter, gate, cache and activator; reads only the row's kind; echoes nothing from the request (plans 4d).;rev3=census-ruling-retry-after-503;basis=the fixed 503 page status is written through UnavailableNoRetry (still no Retry-After; adds answer/box headers); body and checks unchanged; no read added;rev3=census-ruling-audit-request-path;basis=the logThrottled key is now "plan-disabled "+rt.Host (the matched route, registry data) instead of the request host; the message names rt.Host and, when it differs, the request host via strconv.Quote. The three new rt.Host reads are of the route already in hand; the predicate call, page and refusal are unchanged. registry:Host@507,registry:Host@582,registry:Host@672,registry:Kind@156,whole:Route@185 ddb568faa8f5cb076d8f2e5aed371e54a5504a5092d95e622988a9d2dbdb6f8c
+@coverage internal/activator 4a6ba8b7a5cb6825bc01a14f4d842f67535795edbf0eb2ea50ea68eed6d8c526
+@coverage internal/edge c7041387d997edeea3b2dad2a51bda009c9c0767888ad50af879d1a638a94ee1
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index 98e23c802..a5ff51703 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -233,4 +233,6 @@ 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-aws-timeouts.tsv f5d8ee906a7b9a119a29164f09a660fbf40118ff25d58c2caa38b1d6a3772c73
+plan14-root-reads-sec-unit-app-demobuild.tsv fea6bec1f00dace47aa6006bf8606602efda4cecfa4fe3c3890136c0fb27720c
+plan14-root-reads-audit-request-path.tsv 3f7dc37d114377b168c6bc1ae48e7bf815dbc1f5a569274af642e00e7d08ca2a
+plan14-root-reads-audit-gate-vet-staticcheck.tsv d4d3f367ca135da40d2c392d22b51669281d2d8268c0a5aa22ebf738cbe65080
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)
diff --git a/internal/release/ratchet_test.go b/internal/release/ratchet_test.go
index cea6cf622..f456ce188 100644
--- a/internal/release/ratchet_test.go
+++ b/internal/release/ratchet_test.go
@@ -125,7 +125,7 @@ func TestRatchetDirs(t *testing.T) {
func TestSharedRatchetIsOnePerDirectory(t *testing.T) {
d := t.TempDir()
- if SharedDigestRatchet(d, nil, false) != SharedDigestRatchet(d, nil, false) {
+ if first, again := SharedDigestRatchet(d, nil, false), SharedDigestRatchet(d, nil, false); first != again {
t.Fatal("two calls for the same directory built two ratchets")
}
}
diff --git a/internal/runs/keys_test.go b/internal/runs/keys_test.go
index 120991aef..92e524220 100644
--- a/internal/runs/keys_test.go
+++ b/internal/runs/keys_test.go
@@ -114,7 +114,7 @@ func TestValidFileHash(t *testing.T) {
}
func TestCallerOfSeparatesCallers(t *testing.T) {
- if CallerOf("svc:a") == CallerOf("user:a") || CallerOf("svc:a") != CallerOf("svc:a") || len(CallerOf("x")) != 64 {
+ if first, again := CallerOf("svc:a"), CallerOf("svc:a"); first == CallerOf("user:a") || first != again || len(CallerOf("x")) != 64 {
t.Fatal("CallerOf does not name callers apart")
}
if CallerOf("svc:a") == ScopedKey("svc:a", "") {
diff --git a/internal/schedule/hostgate.go b/internal/schedule/hostgate.go
index 9ed8cea0d..2008eeea0 100644
--- a/internal/schedule/hostgate.go
+++ b/internal/schedule/hostgate.go
@@ -74,6 +74,7 @@ func (g *HostGate) Drain(ctx context.Context, host string) error {
go func() {
// The barrier is the acquisition itself: nothing runs inside it.
l.Lock()
+ //lint:ignore SA2001 an empty critical section is the barrier
l.Unlock()
close(done)
}()
diff --git a/internal/tunnelclient/upgrade.go b/internal/tunnelclient/upgrade.go
index c071ec79c..d5630e8ed 100644
--- a/internal/tunnelclient/upgrade.go
+++ b/internal/tunnelclient/upgrade.go
@@ -388,7 +388,8 @@ func (c *upgradedConn) fence() {
if c.hookFence != nil {
c.hookFence()
}
- c.life.Lock() // an empty critical section: a barrier, not a guard
+ c.life.Lock()
+ //lint:ignore SA2001 an empty critical section: a barrier, not a guard
c.life.Unlock()
}
diff --git a/staticcheck.conf b/staticcheck.conf
new file mode 100644
index 000000000..a66272fd2
--- /dev/null
+++ b/staticcheck.conf
@@ -0,0 +1,32 @@
+# staticcheck's bug checks (SA) and nothing else, for now. `make
+# staticcheck` reads this, and so does CI's 40-staticcheck step.
+#
+# Off for now, on purpose: S (simplifications), ST (style), QF (quick
+# fixes) and U1000 (unused code). They are not bugs, and the audit's run
+# of staticcheck v0.8.2 (on 5b6d5374, 2026-11-16) found about 270 of
+# them: ST1005 118, U1000 68, ST1013 35, S1038 26. Turning one on is its
+# own branch, with the tree cleaned first, so the gate stays green.
+#
+# Three SA checks are off too, each a family too large to fix safely in
+# the branch that added this file. Counts are from that branch's run on
+# 15b1ee6b, with -tags rootrunner,carlos_cutover_witness. A follow-up owns each one:
+# fix the sites, then delete the line here.
+#
+# SA1012 177 sites: a nil context.Context passed to a function. 153 are
+# internal/registry production code (registry.go alone has 84),
+# which is in the root binary's graph, so a fix is a census
+# change; 20 more in internal/activator (3 outside tests).
+# SA1019 70 sites (20 outside tests): deprecated APIs, mostly
+# golang.org/x/net/http2's ClientConn, Transport and Server
+# (moved into net/http), then go/parser.ParseDir,
+# httputil.ReverseProxy's Director and ecdsa's raw key
+# coordinates. Each needs a real migration, not a rename.
+# SA4006 70 sites (10 outside tests): a value assigned and never
+# read. Most are test leftovers, but some outside tests hide a
+# real error that is never looked at, so each wants reading,
+# not deleting.
+#
+# Deliberate cases of an enabled check carry a `//lint:ignore <check>
+# <reason>` on the line above them (the empty critical sections that are
+# barriers, for instance). staticcheck ignores `//nolint` comments.
+checks = ["SA*", "-SA1012", "-SA1019", "-SA4006"]