carlos / platform Public

edge fence: same-box calls through the edge, and nothing else (#990)

Since v0.28.17 (#367) nested instances are denied every address of their
own box, and systemd's IPAddressDeny= has no ports, so the edge was
closed too: an app could not call another app on its own box by
hostname, though it could on any other box.

A cgroup-scoped nft table (internal/edgefence) lets
carlos.slice/carlos-instances.slice reach the box's own global
addresses on TCP 80 and 443 only (other TCP reset, the rest dropped).
instance-control takes an address out of the slice deny only while the
table reads back exactly as loaded; every failure applies the whole
deny. Every unit start checks it first; the refresh re-reads it every
10 s, reloads it after an nftables flush or a slice recreation, and
checks it from what it remembered when the box's addresses cannot be
read. Units: AF_NETLINK for instance-control, RefuseManualStop on both
slices. Probe: box-addr-ports, box-addr-edge. carlos status --layout
prints "same-box calls: on|off (reason)|unknown" per box. Off on group
boxes, in claims mode, with CARLOS_EDGE_FENCE=off, and with no public
address on the box.

Plan, evidence and drill:
docs/superpowers/plans/2026-11-13-same-box-calls-edge-fence.md.
Review: Codex, round 1 NOT READY (1 P1, 1 P2, fixed), round 2 READY.
Census approved by the same reviewer (#280).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Squashed from same-box-edge-fence into main.
James Adam pushed by claude agent, operated by james@keymail.dev ddd234a67bc60e978df8188ac328b1ed81f9b358 parent 26272c9
32 files changed, +2,574 −36
  • docs/superpowers/notes/census-claims-same-box-edge-fence.tsv +20 −0
  • docs/superpowers/notes/census-proposal-same-box-edge-fence.md +42 −0
  • docs/superpowers/plans/2026-11-13-same-box-calls-edge-fence.md +475 −0
  • docs/superpowers/reviews/CODEX-REVIEW-BRIEF-same-box-edge-fence-R2.md +57 −0
  • docs/superpowers/reviews/CODEX-REVIEW-BRIEF-same-box-edge-fence.md +117 −0
  • internal/console/apistatuslayout.go +2 −0
  • internal/console/apistatuslayout_test.go +6 −2
  • internal/edgefence/edgefence.go +220 −0
  • internal/edgefence/edgefence_test.go +272 −0
  • internal/edgefence/testdata/readback-v4-v6.txt +11 −0
  • internal/host/agent.go +1 −0
  • internal/host/claimunit.go +3 −1
  • internal/host/claimunit_test.go +2 −2
  • internal/host/execsandboxstatus.go +24 −0
  • internal/host/group_hairpin_test.go +6 −1
  • internal/host/layoutleg.go +2 −1
  • internal/host/units/carlos-instance-control.service +7 −1
  • internal/host/units/carlos-instances.slice +11 −0
  • internal/host/units/carlos.slice +6 −0
  • internal/instancectl/client.go +13 −0
  • internal/instancectl/edgefence.go +292 −0
  • internal/instancectl/edgefence_test.go +567 −0
  • internal/instancectl/hardening.go +64 −6
  • internal/instancectl/names.go +22 −0
  • internal/instancectl/server.go +30 −0
  • internal/instanceexec/probe_hardening.go +103 −19
  • internal/instanceexec/probe_hardening_test.go +94 −0
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −0
  • internal/provision/testdata/plan14-root-reads-same-box-edge-fence.tsv +31 −0
  • internal/status/snapshot.go +14 −3
  • status_instances.go +29 −0
  • status_instances_test.go +30 −0

CI passed — run details

diff --git a/docs/superpowers/notes/census-claims-same-box-edge-fence.tsv b/docs/superpowers/notes/census-claims-same-box-edge-fence.tsv
new file mode 100644
index 000000000..b80b13680
--- /dev/null
+++ b/docs/superpowers/notes/census-claims-same-box-edge-fence.tsv
@@ -0,0 +1,20 @@
+# Same-box calls through the edge: the edge fence (#990; branch same-box-edge-fence; plan docs/superpowers/plans/2026-11-13-same-box-calls-edge-fence.md). Identities: instance-control is root (carlos-instance-control.service); the probes run as carlos inside their own units under carlos-instances.slice; the agent and edge are uid carlos; the CLI runs on an operator's machine.
+# Envelopes (no claim key; for the reviewer):
+# internal/edgefence: new package. Renders the nft table carlos_edge_fence from a sorted list of the box's own global addresses (Fenceable: single global unicast, never IPv4-mapped, outside the instance templates' static IPAddressDeny), loads it with `nft -f -` (stdin: add table/delete table/the table) and reads it back with `nft -s -nn -y list table inet carlos_edge_fence`. Arguments and stdin are fixed text plus addresses root read from /proc/net/fib_trie and /proc/net/if_inet6 (the existing localPrefixes); nothing from a tenant, app or agent reaches them. Verify compares the readback with the render, whitespace aside, and refuses anything else.
+# internal/instancectl: edgefence.go (new): edgeFenceDeny exempts an address from the slice deny only after the fence for exactly those addresses reads back as loaded; every failure keeps the whole deny. guardStarts wraps the Server's Systemctl so every start/restart/try-restart first runs fenceBeforeStart (readback; on a mismatch the deny is worked out again before the start; a start is refused until a deny has been applied since the service started). bindEgressFence chains the same check before the egress asserter's restarts. Off on group boxes, in claims mode, with CARLOS_EDGE_FENCE=off, with no global address. hardening.go: denyLocalAddrs split into denyLocalAddrsWith/Locked (refresh skips an unchanged set-property); denyLoopWith re-reads while exempting or after a failure; writeProbeBoxAddrs appends " edge" to fenced addresses. names.go: ProbeReport.EdgeFence (set only by /ready), EdgeFenceReport, BoxAddrFenceMark. client.go: Client.EdgeFence reads /ready. No new file read by root.
+# internal/instanceexec: probe lines box-addr-ports (TCP 22 must not connect on any box address) and box-addr-edge (TCP 443 or 80 answers on fenced addresses; never fail). readBoxAddrs parses root's box-addrs (now "<addr>[ edge]").
+# internal/host (agent, uid carlos): execsandboxstatus.go adds edgeFenceStatusReport (asks root's /ready over the existing control socket client); status snapshot gains LayoutReport.EdgeFence.
+# internal/status: LayoutReport.EdgeFence, EdgeFence{State, Reason}. No reads.
+internal/host/agent.go:runAgent Agent (uid carlos), not root. One added line: armEdgeFenceStatus(ctl.EdgeFence), beside the existing armExecSandboxStatus, so the layout report can ask root's /ready for the edge fence state over the control socket client the agent already holds. No read added.
+internal/host/claimunit.go:claimUnitContent Root unit rendering (claims mode). The control unit's families line is now `RestrictAddressFamilies=AF_UNIX AF_NETLINK`; the claims rewrite matches that line (it matched the old one exactly, and would otherwise have silently dropped AF_INET/AF_INET6) and renders `AF_UNIX AF_NETLINK AF_INET AF_INET6`. No read added; no other directive changed.
+internal/host/layoutleg.go:layoutStatusReport Agent (uid carlos). Both returns set LayoutReport.EdgeFence from edgeFenceStatusReport() (root's /ready answer through the existing client, under DeadlineReady; nil when root cannot be asked). Its existing reads are unchanged.
+internal/host/units/carlos-instance-control.service:external RestrictAddressFamilies gains AF_NETLINK (nft talks netlink), with a comment; the group drop-in already granted it on group boxes. No capability, path, environment or ExecStart change. Without it nft fails and the whole #367 deny stays.
+internal/host/units/carlos-instances.slice:external RefuseManualStop=yes, with a comment naming the remaining stop levers (stop 'carlos-instances-*.slice', kill carlos-instances.slice). Defence in depth for the fence (a recreated slice leaves nft's rules matching an old cgroup id); no read, no other directive.
+internal/host/units/carlos.slice:external RefuseManualStop=yes, with a comment: a stop of carlos.slice propagates to carlos-instances.slice and recreates it. Memory limits unchanged; no read.
+internal/instancectl/server.go:type Server Field declarations only: NFT (the nft runner; nil never loads the fence), EdgeFenceOff (host.env CARLOS_EDGE_FENCE=off), and under the existing denyMu/mu: fenceAddrs, fenceReason, fenceRetry, denyApplied. No read added.
+internal/instancectl/server.go:runWithClaim Root. Sets NFT: edgefence.Exec (runs /usr/sbin/nft from PATH with fixed arguments and root-derived stdin, see the envelope) and EdgeFenceOff from os.Getenv; wraps s.Systemctl with guardStarts and calls bindEgressFence; calls denyLocalAddrs once before Serve so a leftover runtime exemption is checked or replaced by the whole deny before any request is served. No new file read; the exec is nft's.
+internal/instanceexec/probe_hardening.go:networkAndIPCChecks Probe (uid carlos inside the probe units; no root). Two more verdict lines after box-addr: box-addr-ports (TCP connect to port 22 on each address in root's box-addrs must not succeed) and box-addr-edge (TCP 443 or 80 on fenced addresses; ok or unverified, never fail). Decides nothing for root beyond one more line that can fail readiness.
+internal/instanceexec/probe_hardening.go:readBoxAddrs Probe (uid carlos). New: reads root's box-addrs (the same fixed BoxAddrsPath boxAddrClosed read before) and parses `<addr>` or `<addr> edge`; any other line is refused. boxAddrClosed, boxAddrPorts and boxAddrEdge call it.
+internal/edgefence/edgefence.go:Exec Root (called from instance-control only through Server.NFT). Runs args[0] with fixed arguments; every caller in this package passes "nft" and text rendered from root-read addresses. Output returned to the caller for comparison only.
+status_instances.go:printStatusLayout CLI (operator's machine), not on a box. One more call, printEdgeFenceStatus, printing one line per box from the console's JSON: same-box calls: on / off (reason) / not needed (reason) / unknown. No read.
+internal/instanceexec/probe_hardening.go:boxAddrClosed Probe (uid carlos). Its ReadFile of box-addrs moved into readBoxAddrs, which it now calls; it reads nothing itself. The verdict rule is unchanged: a UDP datagram to every listed address must get EPERM (fenced addresses get it from the fence's drop rule).
diff --git a/docs/superpowers/notes/census-proposal-same-box-edge-fence.md b/docs/superpowers/notes/census-proposal-same-box-edge-fence.md
new file mode 100644
index 000000000..dcc68b1ab
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-same-box-edge-fence.md
@@ -0,0 +1,42 @@
+# Census approval: same-box-edge-fence
+
+Ruling `census-ruling-same-box-edge-fence`. The independent reviewer approves or rejects every change below, 4 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+
+| unit | change | read sites | what changed |
+|---|---|---|---|
+| `internal/host/agent.go` `runAgent` | body | unchanged (6) | Agent (uid carlos), not root. One added line: armEdgeFenceStatus(ctl.EdgeFence), beside the existing armExecSandboxStatus, so the layout report can ask root's /ready for the edge fence state over the control socket client the agent already holds. No read added. |
+| `internal/host/claimunit.go` `claimUnitContent` | body | unchanged (1) | Root unit rendering (claims mode). The control unit's families line is now `RestrictAddressFamilies=AF_UNIX AF_NETLINK`; the claims rewrite matches that line (it matched the old one exactly, and would otherwise have silently dropped AF_INET/AF_INET6) and renders `AF_UNIX AF_NETLINK AF_INET AF_INET6`. No read added; no other directive changed. |
+| `internal/host/layoutleg.go` `layoutStatusReport` | body | unchanged (18) | Agent (uid carlos). Both returns set LayoutReport.EdgeFence from edgeFenceStatusReport() (root's /ready answer through the existing client, under DeadlineReady; nil when root cannot be asked). Its existing reads are unchanged. |
+| `internal/host/units/carlos-instance-control.service` `external` | body | unchanged (1) | RestrictAddressFamilies gains AF_NETLINK (nft talks netlink), with a comment; the group drop-in already granted it on group boxes. No capability, path, environment or ExecStart change. Without it nft fails and the whole #367 deny stays. |
+| `internal/host/units/carlos-instances.slice` `external` | body | unchanged (1) | RefuseManualStop=yes, with a comment naming the remaining stop levers (stop 'carlos-instances-*.slice', kill carlos-instances.slice). Defence in depth for the fence (a recreated slice leaves nft's rules matching an old cgroup id); no read, no other directive. |
+| `internal/host/units/carlos.slice` `external` | body | unchanged (1) | RefuseManualStop=yes, with a comment: a stop of carlos.slice propagates to carlos-instances.slice and recreates it. Memory limits unchanged; no read. |
+| `internal/instancectl/server.go` `type Server` | body | unchanged (1) | Field declarations only: NFT (the nft runner; nil never loads the fence), EdgeFenceOff (host.env CARLOS_EDGE_FENCE=off), and under the existing denyMu/mu: fenceAddrs, fenceReason, fenceRetry, denyApplied. No read added. |
+| `internal/instanceexec/probe_hardening.go` `networkAndIPCChecks` | body | unchanged (2) | Probe (uid carlos inside the probe units; no root). Two more verdict lines after box-addr: box-addr-ports (TCP connect to port 22 on each address in root's box-addrs must not succeed) and box-addr-edge (TCP 443 or 80 on fenced addresses; ok or unverified, never fail). Decides nothing for root beyond one more line that can fail readiness. |
+| `status_instances.go` `printStatusLayout` | body | unchanged (1) | CLI (operator's machine), not on a box. One more call, printEdgeFenceStatus, printing one line per box from the console's JSON: same-box calls: on / off (reason) / not needed (reason) / unknown. No read. |
+
+Envelopes re-pinned: `.`, `internal/edgefence`, `internal/host`, `internal/host/units`, `internal/instancectl`, `internal/instanceexec`, `internal/status`.
+
+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/host/agent.go` `runAgent`: authority, task B,C,D,F. Basis: rev3=census-ruling-self-serve-moves-1;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): builds the box's lifetime judge once (newBoxJudge, nil with host claims on) and hands it to the seed placement, the moves and runs workers and every loop it starts; read sites unchanged, offsets moved; B,C,D,F authority retained; self-serve moves 1 Task 8: derives the box's lifetimes switch from the judge once (lifetimes := boxJudge != nil) and hands it to the edges file loop; read sites unchanged, offsets moved;rev3=census-ruling-plans-4d-lapse;basis=arms two more plans hooks from the same snapshot: e.SetPlanDisabledFor(planDisabledFor) beside SetPlanGovernedFor, and svc.SetDisabledFor(planDisabledRoute) beside SetMaxRunFor (plans 4d); the reads live in those units (plans-4d-units decision); read sites unchanged, offsets moved;rev3=census-ruling-rootfs-apps-2;basis=main's body as of the merge of origin/main 9b81d97b (with main's plan rate ceiling, edge request records, regional box names, self-serve moves plan 1, plans 4d-1 lapse and its other later changes under main's own census rulings) plus the rootfs placement wiring in the activator start: an agentRootfs built from eb.NestedOK, CARLOS_DEPLOYMENT_SINGLE_TENANT, CARLOS_POOLS, the claim flag, swapArming's answer, the control client's /ready/rootfs and, on a fleet box whose identity resolved, fleetOwnerCheck over the deploy store main already opens for the fleet label (fleetStore), then arm and armedRootfs.Store; this body reads nothing new itself; the closures it wires read later, at a rootfs wake and each status tick: GET /ready/rootfs over the control socket, NestedOK's checks, and release.FleetOwnerKey for the judged row's own account and this box's fleet from the deploy store;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328 plan 2 Tasks 7 and 11, #329 plan 3 Task 7 and plan 1 Task 7's policy cache: the control client is built once and handed to eb.Control, to the status tick (egressStatus) and to a new egressNudgeLoop goroutine; armSizeSource(svc, "/sys/fs/cgroup") after the activator Service; armPolicyCache() after armChangeIndex; statusLoop takes egressStatus. The reads are those units' own (decision rows); this body reads nothing new: the same five sites, offsets moved, in the agent; B,C,D,F authority retained.;rev3=census-ruling-remote-instance-metrics;basis=builds the metrics loop's owners closure (metricsOwners over the agent's registry, the activator and cgm.Leftover) when an activator exists and hands it to metricsLoop; reads nothing new itself;rev3=census-ruling-edge-asset-cache-3;basis=adds file:Statfs. runAgent keeps its authority (B,C,D,F). The new site is assetcache.Statfs, an exported assetcache.FS interface value (var Statfs FS = statfsFS{}), not a function value and not a call in runAgent: the ready hook passes it to armEdgeAssetCache as the store's filesystem, and armEdgeAssetCache calls its Space method on the configured data directory (dataDir(): $CARLOS_DATA_DIR, else /data), which calls unix.Statfs there (statfsFS.Space, accepted legacy at census-ruling-edge-asset-cache-2). No request-supplied pathname reaches it.;rev3=census-ruling-remote-metrics-nested;basis=main's body (merged origin/main acfa4f80, under main's own census rulings) plus: snapshots the nested layout (snapshotNestedUnits over /sys/fs/cgroup/carlos.slice/carlos-instances.slice) once at start, before the activator, and hands the metrics loop a unitSources struct (stamped units, routeHostNames, that root and the snapshot); reads nothing new itself;rev3=census-ruling-region-ha-p1a;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): wires region HA P1a into the activator: cfg.Record = haRecordFacts(openDeployStore, boxJudge) (the box's lifetime judge this body already builds with newBoxJudge, nil with host claims on; CI fix) and cfg.Self = lease.CurrentSelf; eb.Lifetimes (the process's lifetime index), eb.Registry, eb.StartupSwept (seedSweptAtStart.Load), eb.FilesStore from newProductionFilesStore (now lease.NewFilesStore, rootaws-loaded, a log line on failure) and lease.SetObligationDir(<data>/.ha-owed) (logged on failure; HA acquires then refuse); this body reads nothing new itself, the same five sites; the reads are those units' own (haRecordFacts and lease's SetObligationDir are new rows on this card); merge of origin/main d7ae1d76: main's own later changes to this body are kept as main has them, under main's rulings (census-ruling-remote-instance-metrics: the metricsOwners closure for metricsLoop; census-ruling-edge-asset-cache-3: the +file:Statfs site, assetcache.Statfs handed to the asset ready hook); this branch's change is the same as above;rev3=census-ruling-region-ha-p1b1;basis=region HA P1b-1: builds one termfence.Confirmer (Self from lease.CurrentSelf at each call, EC2 DescribeInstances method only, client from rootaws.LoadDefaultConfig with retries off, built lazily on first use) and sets eb.OwnerTerminated; this body reads nothing new itself, the same six sites;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Task 7: the startup Sweep literal hands its answer to startupSwept, which logs as before and, only on a clean sweep, marks rootfs admission swept (MarkRootfsSwept); same Sweep call, no read added;rev3=census-ruling-managed-fleets-1b;basis=managed fleets 1b (controller ruling after branch review R1, and Paul's R2 ruling): sets svc.Fleet = fleetWakeFor(os.Getenv, identity, identErr, fleetStore) from the identity it already resolves once and the deployment store the fleet loops already opened, and logs an ERROR naming the identity error when the box is on a fleet with an invalid identity. fleetWakeFor reads CARLOS_REGION and CARLOS_FLEET from the same environment. Read sites unchanged (6). Agent, not root; a platform box is unchanged.;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 12: one call more beside armRunsPass, armInteractivePass(svc, reg, rolloutSink, boxJudge), in the same activator Configure hook, handing it the same box judge; fix round 1 (Astra P2, shutdown): after svc.Shutdown(ctx), shutdownInteractive(ctx) ends and joins every interactive session under the same shutdown budget; the worker's own reads are its units' (interactive.go); this body reads nothing new, the same six sites; merge of origin/main 6f1f6ca6: main's svc.Fleet = fleetWakeFor(...) and its invalid-identity ERROR line are kept as main has them (census-ruling-managed-fleets-1b); this branch's change is the same as above; read sites unchanged (6);rev3=census-ruling-fix-set-aside-exdev;basis=set-aside EXDEV fix: one field more on the agent ExecBackend literal, RawInstanceDir: layout.RawInstanceDir (a pure path join: <dataDir>/.instances/<InstanceID(host)>), so the start rule set-aside moves a copy out through the raw directory instead of through the nosymfollow bind; this body reads nothing new, the same six sites;rev3=census-ruling-durability-3a-escrow;basis=durability 3a Task 3: one more assignment beside eb.FilesStore: eb.EscrowKey = haEscrowKey(os.Getenv("CARLOS_SECRETS_KEY")), the agent's own environment parsed by appconfig.ParsePrivateKey as the moves pass parses it (unset or unparseable: a log line and nil, and HA publication refuses on the box). No path is opened or read, no read site added; the same six sites, offsets moved; B,C,D,F authority retained. Durability 3a Task 4: one more goroutine beside configSyncLoop: go escrowLoop(agentCtx, reg, svc), the escrow sweep every 30 s over the same registry and Service. This body reads nothing new itself; the same six sites, offsets moved; B,C,D,F authority retained. Durability 3a Task 5: one more call beside eb.EscrowKey: wireRawSecretPages(eb, PageOperator, metricsBoxLabel(os.Getenv, readMachineID())), which sets eb.OnRawSecret to page an operator (alerting.Page through PageOperator, LevelIncident) on its own goroutine with a 20 s timeout; metricsBoxLabel and readMachineID are the reads this body already makes for the moves refusal log; no new read site; the same six sites, offsets moved; B,C,D,F authority retained. Merge of origin/main 90c4d3aa: main's own later changes to this body are kept as main has them, under main's rulings; this branch's change is the same as above. Merge of origin/main 00bf5b8c (fleet set-aside EXDEV fix): main's change to this body is kept as main has it, under its own census ruling; this branch's change is unchanged.;rev3=census-ruling-probe-burst-limit;basis=two more sink wirings beside setAnalyticsSink: setProtectionSink(e.SetProtectionRecordOnly) and setAssetOwnersSource(e.AssetOwners), function values the telemetry pass calls; this body reads nothing new, the same six sites; authority B,C,D,F retained; no new root read or write kind;rev3=census-ruling-region-ha-p1b3a;basis=Arm HA placement exactly once on the existing Service before activatorStart and edges publication, wiring AwakeApps and the PageOperator callback; existing six read sites unchanged, no new root authority.;rev3=census-ruling-stateless-replicas-1;basis=Final review I3: start the concrete coordinator's renewal worker with agent setup; existing closeReplicaCoordinator shutdown cancels and joins it before release. No new read sites or credentials. Merge origin/main c59715e7: retain main's armHAPlacement(svc, PageOperator) wiring beside the existing activator setup; stateless coordinator and shutdown wiring remain. Same read sites; no new root read or credential.;rev3=census-ruling-edge-held-streams;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): in the edge-ready callback, calls act.SetHeldWakeHook(e.HeldWake) when act is non-nil (installing the non-blocking wake callback) and stores e.HeldStreamsForStatus in heldStreamsSource. Wiring of in-memory callbacks only; no read added.;rev3=census-ruling-region-ha-p1b3b-t;basis=Wire Service.SetDutyView to the live edge DutySnapshot in the ready callback. No new read; no new loop or cloud operation. B2 wires the registry as the persistent DutyStore before service startup; no new cloud or filesystem path. B3b: arm one journal-backed termination consumer before service startup using agentCtx and the shared confirmer; expose edge tick and join at edge shutdown. No new direct read sites.;rev3=census-ruling-agent-start-demo-1;basis=Passes the existing registry, data store and hibernation prefix into the demo worker, and the existing instance-control client into the demo before-exec hook. No alternate data store or polling loop. Merge resolution against origin/main 9bd45488 retains main's HA departure controller, lifecycle and duty wiring alongside the demo data store and worker; no read site added by the resolution.;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: install closed fixed admission before every launch source, bind activator/backend and edge, wire the real termination Started lifecycle and role reader after the change index; close before cancellation/child shutdown. No new external reads or cloud authority. Fix R1: move bind/lifecycle/edge-option wiring into wireAgentAdmission and worker listing into runWorkerBootPassAfterAdmission. Worker boot waits for admission before listing then uses unchanged bounded wakes and per-host serialization; whole Route read moves to the helper. No new storage, cloud, or root execution authority. Preserve merged main's agent wiring and census basis; the branch removes one whole Route use by moving worker iteration to the helper, with no added read kind.;rev3=census-ruling-stateless-replicas-2;basis=Slice 3b: arms a fleet-only worker using the existing registry, activator, backend and authenticated console transport. Owned worker stops and joins at shutdown. No new bucket reader. merge of origin/main 9b8b2c50: retain HA duty/departure lifecycle, wake-slot and existing agent wiring alongside the replica placement worker; no new read introduced by resolution. merge of origin/main 6be08467: Retain main demo configuration, admission, build and expiry wiring alongside the replica worker; merge-only body change, no additional read. merge of origin/main 7920cccf: Retain main box-role/group admission wiring and boot publication beside the owned replica worker and shutdown; main moves the boot registry List into runWorkerBootPassAfterAdmission, removing its inline whole Route site. No new read introduced by conflict resolution.;rev3=census-ruling-stateless-replicas-3;basis=Task 1 fix round 1 M3: retain the private snapshot source and cancel/join ownership, but use the replica-health-specific retry loop. It logs its first failure only and retains the existing exponential backoff capped at 30 seconds; unsupported builds return nil. Existing five direct read sites unchanged; no new credentials, bucket reader or app lifecycle action. Fix round 1 Q20: publish Edge.ReplicaSnapshots as a separate in-memory status source, leaving the tenant-visible Upstreams source unchanged. No new external reader or authority.;rev3=census-ruling-region-ha-p3b;basis=Load root-written group marker/configuration, configure signed boot binding and agent receipt completer, wire cancellable admission into departure work and expose cached GroupReaderSnapshot. New indirect boot reads use protected root files; agent-owned receipt controls duplicate initial completion only, never root restart permission. Same five direct sites. Merge 45cebde4 retains the replica health socket lifecycle and setReplicaSource beside GroupReaderSnapshot; no extra read beyond main.;rev3=census-ruling-agent-start-demo-2;basis=agent.go:309-329 opens demo-traffic.db beside the operator-configured registry when a demo domain exists, closes it at shutdown and wires drain-before-purge; :1010-1019 shares the worker and write gate; :1164-1177 installs the fleet identity and closed-until-worker serving callback. One added whole Route pass; the new indirect filesystem/SQL reads are claimed in openDemoTraffic and worker/store units. No request chooses the database pathname.;rev3=census-ruling-region-ha-p1b3b-s;basis=Wire the service duty view to authoritative cached sidecar manifest placement in LifetimeIndex and the edge sidecar projection; missing policy denies duty. Existing instance duty wiring remains.;rev3=census-ruling-region-ha-g2-t3;basis=T3a: wire eb.Page = PageOperator beside OwnerTerminated before departures arm, so suspect-holder pages work if departure setup fails; no new read; existing nine sites and authority unchanged; pages through the existing sink. T3b: publish the same backend through an atomic pointer for the metrics observer, and clear it on return; no new external read or authority.;rev3=census-ruling-agent-start-demo-3;basis=Wire the claim activator and root snapshot client into the demo worker; pass moved readiness to status reporting. Census read-site delta: unchanged (9).;rev3=census-ruling-region-ha-g2-fixes;basis=Wire local pool evidence, live withdrawal activator, startup ingress scan and alias publication, and edge lookup; no new direct sites; new indirect record/claim reads use existing store/judge paths described in ingress helpers.;rev3=census-ruling-region-ha-g2r-fixes;basis=W3: starts the existing record-view backstop loop with a departure-inventory listener (non-blocking, coalesced signal) even without an armed RecordView; it requests the existing full pass (backstopFullDue) there. Same nine read sites; no new read or authority.;rev3=census-ruling-region-ha-graceful-terminate-t2;basis=Derive one signal-time deadline with a 90-second budget; cap departure stop and startup/seed/service shutdown joins by it. No read added.;rev3=census-ruling-static-sweep-periodic;basis=in the edge-ready callback, publishes e.LargestStaticTree in staticTreeSource for the disk alert line (diskAlertFrac in the metrics loop); in-memory wiring only, no read added; read sites unchanged (9);rev3=census-ruling-edge-page-cache-1;basis=wires the exec backend's CurrentInputs into the edge cache (wireCurrentInputs) and, in the ready hook after armEdgeAssetCache (whose returned store it now keeps), calls armEdgePageCache, which does nothing unless CARLOS_PAGE_CACHE=1; read sites unchanged (9); no read added;rev3=census-ruling-gvisor-demos;basis=Capture sandbox resolution and refusal once; log errors once; gate route admission and BeforeExec before process launch. No new root read. Task 5: pass the once-captured sandbox effective mode/config error into ExecBackend, UnitBackend and the immutable Client expectation. Same startup environment/registry reads; swapArming declines gVisor before placement. Task 8: arm read-only status projection with the existing Client.SandboxStatus callback. Agent status now queries the existing root /ready endpoint; no new root authority or guest-file input. Merge2 e8a1ddde: retain main wireCurrentInputs and armEdgePageCache through the existing asset-store ready hook alongside branch once-captured sandbox mode, wake gates and root status wiring. No new direct read; main page-cache helpers retain their own census overlays.;rev3=census-ruling-region-ha-held-build;basis=wires the drain state: svc.SetDrainingSource(boxDrain.IsDraining), svc.SetPeerDrainView(e.PeerDraining), e.SetPeerDrainedHook(svc.DropHoldersNaming); in-memory only; no read added; region HA held-requests Task 5: on group members, starts the drain driver over the activator, the edge and boxDrain, and serves its root-only drain socket; no read added beyond the socket's own Branch review r1: the drain state follows the root start fence on group members (the fence reader is the existing fenceLocation.read, a root-owned fixed path); e.SetPeerUndrainedHook(svc.AllowHoldersNaming) beside the drained hook (memory only); the drain socket serves only the agent's own user. No read added.;rev3=census-ruling-security-review-mitigations;basis=Wire the cached operator flat-layout choice into the exec backend's new-resident refusal; no read source added, existing authority retained.;rev3=census-ruling-w6-ingress-drain;basis=agent (user carlos), not root. Builds the ingress drain (newIngressDrain) with arming read at ask time from os.Getenv (CARLOS_REGION_HA, CARLOS_INGRESS_TARGET_GROUPS, both from the root-owned host.env), the fixed admission and lease.CurrentSelf (existing IMDS identity); its reader is awstg.Load, the box role's credentials calling ELB DescribeTargetHealth/DescribeTargetGroupAttributes (new AWS reads, by the agent). Wires admission.closeStartsForIngressDrain, the lbhealth drain condition, ingress.setEdge, and ingress.shutdownStarted in WithShutdownStarted. The drain socket (/run/carlos/.ha-drain/drain.sock, agent-user only, existing) is now also served on a fixed box with the drain configured (was group members only), routing /v1/ingress/* to the ingress drain and the group drain verbs to 404 there. armHADepartures now takes fixtureDepartureGetenv() and MakeQueue fixtureDepartureQueue(), which in a production (non-rootrunner) build are os.Getenv and nil, as before. Read sites unchanged (9).;rev3=census-ruling-stateless-replicas-4-task1;basis=Arms the fleet-only replica swap worker next to the placement worker: same console URL and fleet token as the existing replicaCoordinatorAPI, the existing activator Service; stops and joins at shutdown. No new read site, credential or bucket reader.;rev3=census-ruling-stateless-replicas-4-task2;basis=Task 2: sets deployWorker.step to the rollout scheduler answer for the record permit (replicaStepOf over armedRollout), an in-memory callback; no read site, credential or bucket reader added.;rev3=census-ruling-stateless-replicas-4-task2-fix2;basis=Task 2 fix round 2: the swap worker step is armedReplicaStep, the same lazy scheduler lookup as before as a named function; no read site added.;rev3=census-ruling-stateless-replicas-4-merge-main;basis=Merge of main 5fac2ff1: both sides changed it. Main (01d6ca78, linked-deployments-slice1) starts linkLoop beside tunnelLoop; this branch keeps its replica coordinator wiring. Both kept as-is; no read added.;rev3=census-ruling-stateless-replicas-4-final;basis=#511 final wave item 2: wires the swap worker's drive (armedReplicaDrive, the armed rollout manager's DriveReplicaRelease); no read added;rev3=census-ruling-stateless-replicas-4-merge-main2;basis=Merge of main af871da0 (v0.34.49): both sides changed it. Main (178dcfe5, member-backups-2a) moves the inline duty-view closure into armDutyView/dutyView and starts verifyAssignLoop; its sites drop by registry:Host and whole:Route x2 as main recorded them. This branch keeps its replica coordinator, swap worker and drive wiring. Both kept as-is; no read added.;rev3=census-ruling-stateless-replicas-4-drill3;basis=drill 3 R24: makes one in-memory channel, closes it (once) inside the edge's existing shutdown-started callback after ingress.shutdownStarted, and passes it to tunnelLoop, which drains only a fleet channel name; no read added, same six sites; touches no admission, lease, ingress drain, listener or file; the agent process, no root decision;rev3=census-ruling-edge-ppv2;basis=Agent (uid carlos), not root. memwatchLoop now gets edgeProxyCounters(&demoEdge) (in-process counters, no read). The drain socket's driver is newAgentDrainSocket(ingress, e, os.Getenv), which attaches the edge trust handler only when CARLOS_INGRESS_PROXY_SOURCES in the agent's environment (from the root-owned host.env) parses to a non-empty list; the socket is served when drainSocketServed: a group member or a configured ingress drain (both as before), or a box armed for PROXY protocol (new). The socket's path and agent-user-only permissions are unchanged. Read sites unchanged (6).
+- `internal/host/claimunit.go` `claimUnitContent`: authority, task E1,E3. Basis: rev3=PROPOSED-p3;identity=root claim/adoption controller uid 0;basis=adds write permission for exactly the public retry directory only when the root settings reader has verified a complete census and prepared that directory;rev3=census-ruling-agent-start-demo-1;basis=Demo-only ReadWritePaths for instance data/runtime, staged files and root release lock; ordinary rendering unchanged.;rev3=census-ruling-agent-start-demo-1-followups;basis=In demo box mode, declare StateDirectory=carlos-release/private with mode 0700 so systemd creates root-owned release state before namespace setup and keeps it writable. Existing ReadWritePaths and ordinary/claims rendering stay unchanged. No new read site or caller-controlled path.;rev3=census-ruling-agent-start-demo-3;basis=Declare /var/lib/carlos-demo-snapshots as root-owned StateDirectory with mode 0700 only for configured demo boxes, including recovery with admission off. Ordinary claims units retain their original directories. The shared unit template is unchanged from main; no file read is added.;rev3=census-ruling-gvisor-demos;basis=Mark only claim/demo renderings explicitly; common host.env remains loaded. Ordinary rendering masks CARLOS_HOST_CLAIM with UnsetEnvironment, removed only for a successfully parsed enabled claim rendering. Existing template read unchanged. Task 7: render aggregate build slice through SlicePropertiesFor using the resolved host mode, with 32 MiB and 64-task gVisor overhead per slot. Existing control permissions unchanged.
+- `internal/host/layoutleg.go` `layoutStatusReport`: diagnostic, task H3. Basis: no-effect;rev3=census-ruling-instance-egress-sizes-328-329;basis=#329 plan 3 Task 7: each activator-managed instance row gains a Size cell, rowSizeCell(armedSizeSource.Load(), rt.Host, word) (the added registry:Host site), which for an awake nested row reads that host's cgroup memory.max through readSizeInForce (a decision row, in the agent); still a status report with no effect on any decision.;rev3=census-ruling-alias-socket-follow-338;basis=#338: a platform socket row reports alias (aliasLayout) instead of external; reads Platform;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Task 5: Pass.Held takes the whole route (so a row with a runtime is never reported as held); status display only;rev3=census-ruling-gvisor-demos;basis=Task 8: add root-reported configured/effective mode, runtime pin and readiness through Client.SandboxStatus, plus observed per-row family from the activator handle. Missing/stale root builds remain unknown. Presentation only, no root decision.
+- `internal/host/units/carlos-instance-control.service` `external`: authority, task B3,C,D,E1,J4. Basis: root-input;kept=B3,C,D,E1;scope=protected-decision-only;rev3=census-ruling-agent-start-demo-3;basis=Correct the runtime-write comment to include escaped demo snapshot .mount units alongside per-generation drop-ins; service directives are unchanged.;rev3=census-ruling-region-ha-graceful-terminate-t1;basis=Region HA T1/DR-4 final fix: retain After=nftables.service without Wants or Requires; add Restart=on-failure and RestartSec=1 so a crashed control restarts before a later edge stop can block socket activation and shutdown proofs; rewrap the header and explain this ordering. Same ExecStart and protections; no new root read, input, path, command or capability.;rev3=census-ruling-gvisor-demos;basis=Add Wants/After installer and narrowly writable rootfs parent. Keep one host.env EnvironmentFile and other hardening.;rev3=census-ruling-gvisor-update-dirs;basis=Make the existing /var/lib/carlos/oci-rootfs writable-path entry optional when absent so old updaters can start the new control unit; retain ProtectSystem=strict and the same path and environment. No new root read.
+- `internal/host/units/carlos-instances.slice` `external`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J4;basis=root-input
+- `internal/host/units/carlos.slice` `external`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J4;basis=root-input
+- `internal/instancectl/server.go` `type Server`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-carlos-run;basis=Re-digested at the pre-land merge: the body includes main's own change under census ruling 292, with no further change from this branch. Census ruling 292 reclassified this declaration accepted-legacy (J2,J4) for root's per-host ordering of legacy run starts against stops; this ruling kept the row as main classed it. Its own addition is the cmd start's poll and wait bounds and its per-host lock map: field declarations only;rev3=census-ruling-rootfs-apps-2;basis=new fields: HostRuntime, ProbeImage, ProbeImageFile, RootfsProbeOut, DenyEvery, the deny's lastDeny and denyMu, the rootfs probe's report and lock, the jit reload counters and imageDigests; genStarting counts binary generation starts per unit; rootfsLocksMu and rootfsLocks, one lock entry per rootfs unit name being started or removed right now, held by a start from its layout through systemctl start and its own cleanup and by a removal from its proof through the raw removal, a removal refusing while it is taken, a waiting start giving up when its request ends, an entry dropped with its last holder or waiter (fixes E6, L2, L3); rootfsProvenHook, a test hook run between the proof and the raw removal; field declarations only; no read added;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328 plan 2 and #329 plan 3 Task 5: the declaration gains sliceLocks (one mutex per host slice, taken by /size and /parent) and Egress (the asserter every start path calls), and its comment names the egress allow (plan 3's ControlDropInDir field was deleted in ef38e13b, the P1 EROFS fix); the same one site, the Statfs field, offset moved; no read added.;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 6: comments only: the one-shot pacing fields cover /cmd and /tty, and cmdLocks is now keyed by (role, host) (oneShotKey, PF-7) so a session's start never waits behind a command's; field declarations unchanged; the same one site, no read added;rev3=census-ruling-agent-start-demo-1;basis=Adds fixed demo configuration, registry views, derived runtime root, synchronization and purge guard.;rev3=census-ruling-region-ha-p3b;basis=Add hairpinActive boolean alongside lastDeny under existing deny synchronization. Field declaration only; existing Statfs selector unchanged, no new read or externally supplied authority.;rev3=census-ruling-region-ha-p3b2-rolls;basis=adds one field holding the current hairpin exit watcher, guarded by the root hairpin flock; no new read;rev3=census-ruling-agent-start-demo-3;basis=Retain the snapshot supervisor in instance-control state; no new request-selected path. Census read-site delta: unchanged (1).;rev3=census-ruling-gvisor-demos;basis=Retain Task 1 mode/error/readiness fields, baseline/runtime callbacks, Task 4 per-host validated staged descriptors and root-selected probe nonce. Fix round 1 adds a private writer-operation seam assigned only in package tests, after the unchanged GVisorID admission check; production defaults still call the same checked constructor, WriteRootfs, WriteBundle and verifier. No new direct read or request-controlled callback. Task 5: private injected removal seam for unprivileged tests; production default removes only root-derived bundle and skeleton after both-family proof inside existing start fence. No new request field or agent-selected unit. Task 6: Retain serialized probe nonce, runtime-set identity verifier/token, fixed claims flag, bundle discovery root, and private unprivileged identity seam. No request-controlled callback or path; existing declaration read-site classification unchanged. Task 6 fix round 1: private gvisorProbeTestOps is set only in package tests; production defaults retain all fixed paths and the checked root output opener. No externally supplied callback or new direct read. Final R1 P2: retain fixed skeleton parent and concurrent per-instance cleanup refusals; no direct read or external configuration field. Carry the root-only host.env validation callback into Ready; no agent read or caller-selected path.
+- `internal/instanceexec/probe_hardening.go` `networkAndIPCChecks`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-rootfs-apps-2;identity=both isolation probes (carlos instance-probe in carlos-instance-probe.service and instance-probe --rootfs in carlos-instance-rootfs-probe.service, both started by instance control, user carlos inside the unit's own namespace; no tenant code runs there);basis=root-input (J4, as hardeningChecks, whose body this is): new (rootfs Plan 2 Tasks 7 and 7a): hardeningChecks' network, IPC and resource lines, shared by both probes, with the box-addr (boxAddrClosed) and mdwe lines added; its two sites are hardeningChecks': ReadFile of the unit's resolv.conf and of its own cgroup's io.weight; no root process runs it; decides nothing for root;rev3=census-ruling-instance-syscall-filter;basis=one more verdict line, syscall-filter (syscallFilterHeld: both calls must answer ENOSYS; unverified when the unit does not advertise the filter); inside the probe units as carlos; decides nothing for root beyond one more probe line that can fail readiness
+- `status_instances.go` `printStatusLayout`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328 plan 2 Task 12 and #329 plan 3 Task 10: carlos status --layout, in the operator's carlos CLI on the operator's own machine, prints SIZE and EGRESS columns from the console's JSON (statusLayoutRow.Size and Egress), joins the egress reason into REASON and prints one note when a size is pending; the same one site (the /data literal in the mixed-box warning), no read added.;rev3=census-ruling-region-labels;basis=a REGION column (statusRegionCell) from the console's answer; no read added;rev3=census-ruling-gvisor-demos;basis=Task 8: print draft SANDBOX column and one exec-sandbox summary per reported box from the existing operator API. Missing/stale reports display unknown; no new file read or authority.
+
+New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff:
+
+- new `internal/edgefence/edgefence.go:Exec`: reads +file:CommandContext, +file:Exec; written legacy, accepted-legacy, frozen
+- new `internal/instanceexec/probe_hardening.go:readBoxAddrs`: reads +file:ReadFile; written legacy, accepted-legacy, frozen
+- quiet `internal/instanceexec/probe_hardening.go:boxAddrClosed`: reads nothing now; retired while it reads nothing (or its row keeps no sites)
+- reads `internal/instancectl/server.go:runWithClaim`: +file:Exec; keeps authority, task C,D,G
+
+Seal: `19c9f395547d998f4b5e87e89c0dfa3b5f012d177a87eb5010a8c4defac305dc` โ†’ `76c986ad534d23071100a9a573ffb38afc60b26c8942baf218436bf6a3ff03b3`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-same-box-edge-fence.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/plans/2026-11-13-same-box-calls-edge-fence.md b/docs/superpowers/plans/2026-11-13-same-box-calls-edge-fence.md
new file mode 100644
index 000000000..2e9a29a4c
--- /dev/null
+++ b/docs/superpowers/plans/2026-11-13-same-box-calls-edge-fence.md
@@ -0,0 +1,475 @@
+# Same-box calls through the edge (edge fence) Implementation Plan
+
+> **For agentic workers:** steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** A nested instance can call another app on its own box by the
+app's public hostname, exactly as it can call an app on any other box.
+From an instance, the box's own global addresses answer on TCP 80 and
+443 (the edge) and on nothing else. Everything else #367 closed stays
+closed.
+
+**Why:** discussion #990. Since v0.28.17 (#367) `denyLocalAddrs` puts
+every box address on `carlos-instances.slice` as `IPAddressDeny=`. That
+list has no ports, so it also closes the edge. Jelly on
+console.carlos.exciting.io (one box, `leo-bookbinding`) is held at
+v0.28.11 because its manager and team instances call each other by
+hostname. #367's intent, restated on that discussion: traffic from an
+instance to the box's own address sees what the outside sees, and no
+more.
+
+**Architecture:** one new package, `internal/edgefence`, renders, loads
+and reads back an nft table that is scoped by cgroup to
+`carlos.slice/carlos-instances.slice`. The control service (root)
+removes a box address from the slice deny only while that table is
+loaded and reads back exactly as rendered. Every failure puts the full
+#367 deny back. Group-mode boxes are untouched: the region HA hairpin
+(`internal/hairpin`) owns them, and this plan does not change that
+package (stopping rule 4).
+
+**Tech stack:** Go 1.26, `nft` (nftables), systemd cgroup v2 slices.
+
+**Plan review history (stopping rules apply):**
+- **Round 1** (2026-11-13, an agent reviewing for James against
+ `internal/instancectl` and the units): no P1 as such. It answered the
+ three open questions and made seven corrections (lock, ingress,
+ refresh condition, control downtime, the parent slice, the reject
+ rule untested, module preload). **Rev 2** (this revision) applies all
+ of them; the experiment was rerun for every point the review marked
+ untested (Evidence, run 2). A round 2 is the Task 7 review of the
+ code, not of this plan.
+
+**Branch review history (stopping rules apply):**
+- **Round 1** (Codex `gpt-6-astra`, 2026-11-13, at `7aad44ce7`): NOT
+ READY, 1 P1, 1 P2, no P3; census: every unit approved, the
+ `internal/instancectl` envelope rejected for the two findings.
+ - P1, family **"fail-closed enforcement of the box-address
+ boundary"** (first round in it): with the fence exempting and the
+ box's addresses unreadable, the refresh skipped the fence check, so
+ a flush left running instances open for as long as the read failed.
+ Fixed: `fenceWithoutAddresses` checks the remembered addresses on
+ every tick and before every start, reloads the fence, or rebuilds
+ the whole deny from the last deny plus those addresses.
+ - P2, family **"status describes observed state"**: `not_needed`
+ asserted calls already worked. Fixed: the state is gone; a box with
+ no public address reports `off (no public address on this box)`.
+- **Round 2** (same reviewer, at `e467f44fe`): **READY**. Both round-1
+ findings resolved; no P1, no P2; census: `internal/instancectl`
+ approved, so every unit and envelope on the card is approved. The
+ review stops here (rule 1).
+- **P3 follow-ups** (never a round): the reason "no public address on
+ this box" also covers a public local prefix wider than /32 or /128,
+ which the fence never names; say "no eligible local address" instead
+ (round 2, diagnostic precision).
+
+## The invariant
+
+> An instance reaches an address of its own box only on TCP 80 or 443,
+> or the full #367 deny is in place.
+
+It is enforced in one place: the control service is the only writer of
+the slice's `IPAddressDeny=`. On a non-group box `hairpin.Acquire`
+returns nil (no group config), so `hairpinLocked` takes no cross-process
+lock there, and the in-process `denyMu` is what serialises the deny
+writes and the fence checks. That is enough because control is the only
+writer; the plan does not claim more.
+
+The bound on the invariant's one gap (an nft flush, below) holds **while
+control is running**. The exemption is a `set-property --runtime`
+drop-in and outlives the control process, so control verifies the fence
+or restores the full deny before it does anything else at startup.
+
+## Evidence
+
+Both runs on hal in a throwaway network namespace (`ip netns`), with
+systemd slices and units standing in for the box's (`fencetest.slice`,
+`fencetest.slice/fencetest-instances.slice`). Everything was removed
+afterwards, including the runtime deny drop-in, which outlived its
+slice.
+
+### Run 1
+
+1. With no fence, a process in the "instances" slice reached the box
+ address on 80, 443 and 5432, and sent UDP. That is #367.
+2. With a cgroup-scoped output table (accept 80/443, drop the rest),
+ the instance reached 80 and 443; 5432 timed out; UDP to port 9 got
+ `EPERM`, the existing `box-addr` probe line's contract. A process
+ outside the slice still reached every port.
+3. **nft resolves the cgroup path to an id when the rule loads.** A
+ slice that does not exist cannot be named (load fails). An empty
+ transient slice is garbage-collected; an explicitly started slice
+ stays active while empty.
+4. **The fence fails open if the slice is recreated.** After a
+ stop/start of the slice the rule still held the old id, matched
+ nothing, and the instance reached 5432 again. The readback shows it:
+ the path prints as a bare number (`socket cgroupv2 level 2 803329`)
+ instead of the quoted path.
+
+### Run 2 (the review's untested points)
+
+5. **Reject works in an output chain at priority -300.** With
+ `meta l4proto tcp reject with tcp reset` before the drop, 5432 fails
+ at once with `ECONNREFUSED`; 80/443 open; UDP still `EPERM`.
+6. **Modules autoload under `ProtectKernelModules=yes`.** With
+ `nft_socket` unloaded and `nft_reject_inet` never loaded, `nft -f`
+ from a unit with `ProtectKernelModules=yes` and
+ `RestrictAddressFamilies=AF_UNIX AF_NETLINK` loaded the table, and
+ both modules came up. The kernel's module helper runs outside the
+ unit's sandbox. No preload is needed; a missing module fails the
+ load, which keeps the full deny.
+7. **The readback** (`nft -s -nn -y list table inet <t>`), captured for
+ the whole table, v4 and v6:
+
+ table inet carlos_edge_fence {
+ chain output {
+ type filter hook output priority -300; policy accept;
+ socket cgroupv2 level 2 "carlos.slice/carlos-instances.slice" ip daddr A tcp dport { 80, 443 } accept
+ socket cgroupv2 level 2 "carlos.slice/carlos-instances.slice" ip daddr A meta l4proto 6 reject with tcp reset
+ socket cgroupv2 level 2 "carlos.slice/carlos-instances.slice" ip daddr A drop
+ socket cgroupv2 level 2 "carlos.slice/carlos-instances.slice" ip6 daddr B tcp dport { 80, 443 } accept
+ socket cgroupv2 level 2 "carlos.slice/carlos-instances.slice" ip6 daddr B meta l4proto 6 reject with tcp reset
+ socket cgroupv2 level 2 "carlos.slice/carlos-instances.slice" ip6 daddr B drop
+ }
+ }
+
+ (Captured with the test slice names; a single address prints
+ without braces; `tcp` prints as `meta l4proto 6`.)
+8. **Ingress through the box address.** Once the address leaves the
+ deny, a local process outside the slice connecting to an instance's
+ TCP listener through the box address is still refused in the normal
+ case: the instance's own packets to it have a non-web destination
+ port, and the output fence refuses them (the connect timed out).
+ **The residual case:** a process outside the slice whose *source*
+ port is 80 or 443. With the edge stopped, a root process bound to
+ source port 443 reached the instance's listener. Two attempts to
+ close it in nft failed: an input-chain `socket cgroupv2` match does
+ not attribute loopback SYNs to the instance's listener, and an
+ output `SYN|ACK` drop does not match, since the handshake packet is
+ not attributed to a full socket. Conntrack (`ct direction reply`)
+ would close it but brings box-wide connection tracking to the edge,
+ which this plan does not take on.
+ **Why it is ruled out on these boxes:** binding a port below 1024
+ needs `CAP_NET_BIND_SERVICE` or root. Legacy `carlos-app@` units have
+ an empty `CapabilityBoundingSet=`, nothing in the tree lowers
+ `net.ipv4.ip_unprivileged_port_start`, and the only non-root unit
+ with the capability is `carlos-edge.service`, which holds :80 and
+ :443 itself (`:443` is the dual-stack wildcard). So the residual
+ needs root or the edge, both already trusted with the instances.
+ Task 5 adds a guard test that keeps those three facts true.
+9. **A returning deny cuts open connections.** An instance held an
+ echo connection to the box address with no fence and no deny; when
+ `IPAddressDeny=` came back on the slice, the next exchange timed out
+ and every one after it. The deny filters per packet. So the exposure
+ from an nft flush is at most one refresh interval of reach, not a
+ connection that survives it.
+
+## Design
+
+### The table
+
+- `inet carlos_edge_fence`, one `output` chain, filter hook, priority
+ -300, policy accept. Output only: an instance originates the traffic;
+ replies from the edge come from a socket outside the slice and are
+ not matched. No input chain (evidence 8), so inbound traffic from
+ outside (ssh and the rest) is unaffected.
+- For each fenced address, v4 (`ip daddr`) and v6 (`ip6 daddr`):
+ 1. `tcp dport { 80, 443 } accept`
+ 2. `meta l4proto tcp reject with tcp reset`: a refused port fails
+ fast (James, 2026-11-13). It leaks nothing: every non-web port
+ answers the same whether or not something listens.
+ 3. `drop`: everything else. UDP keeps its `EPERM`.
+- Every rule carries the `socket cgroupv2 level 2
+ "carlos.slice/carlos-instances.slice"` match. Per-host slices
+ (`carlos-instances-<host>.slice`) sit below that level and are
+ matched. gVisor instances run with `--network=none` and never reach
+ the table.
+
+### Fenced addresses
+
+The single-address (`/32`, `/128`) local prefixes that are global
+unicast: the `probeBoxAddrs` set, minus anything in the templates'
+static `IPAddressDeny=` (loopback, RFC 1918, CGNAT, link-local, ULA and
+so on). Wider local ranges (127.0.0.0/8) stay denied. On a box with no
+global address (EC2 without IPv6) the set is empty, and the fence is not
+loaded at all.
+
+### Enable, refresh, fail
+
+In `denyLocalAddrs`, under `denyMu`, non-group boxes only:
+
+1. `systemctl start carlos-instances.slice` (idempotent).
+2. Render the table for the current fenced addresses. Load it with
+ `nft -f -` (`add table` + `delete table` + table, atomic in one
+ transaction, the same shape as `hairpin.Lease.Install`).
+3. Read it back with `nft -s -nn -y list table inet carlos_edge_fence`
+ and compare token for token with the expected readback (evidence
+ 7). A bare number where the cgroup path should be is a mismatch.
+4. Only then set `IPAddressDeny=` without the fenced addresses.
+
+Any error in 1โ€“3: set the full deny (every local prefix), record the
+reason, and leave the table loaded, since a loaded fence is harmless
+under a full deny.
+
+**At control startup**, synchronously, before `Serve` and beside
+`resumeGroupHairpin` (`server.go` `Run`): verify the fence against the
+current addresses, or restore the full deny. Today the first
+`denyLocalAddrs` runs inside the first probe, in a goroutine, while
+`Serve` is already accepting; a drop-in left by a previous control
+process must not stand unchecked in that window.
+
+**Check before start.** Every place the control service starts a unit
+under `carlos-instances.slice` (`server.go` start sites, `cmd.go`,
+`demo_snapshot.go`, the probe start) runs the readback first and, on a
+mismatch, restores the full deny before the start. Together with
+`Restart=no` on every instance template (confirmed: `carlos-instance@`,
+`-rootfs@`, `-gvisor@`, `-sidecar@`, `-gen@`, `-rootfs-gen@`,
+`-rootfs-worker@`; the rest default to no), so systemd never starts one
+behind control's back, **this is what closes the slice-recreation
+path**. (The activator's `systemctl start` is for legacy `carlos-app@`
+units, which are not nested.)
+
+**Refresh.** `denyLoopWith` today calls `denyLocalAddrs` only when the
+addresses changed or `hairpinActive` is set. It gains its own flag,
+`fenceActive`, in that condition, so every tick (10 s, `DenyEvery`)
+re-reads the fence while an exemption is applied, addresses changed or
+not.
+
+**Slices.** `RefuseManualStop=yes` on both `carlos-instances.slice` and
+`carlos.slice`: a stop of `carlos.slice` propagates to the child and
+recreates it, and a propagated stop is not a manual stop of the child.
+These refusals are **defence in depth**, covering an operator
+hand-starting a unit after a slice restart; check-before-start is the
+closing control. Nothing in the tree stops either slice today (Go,
+scripts and docs grepped). The slice unit comments name the remaining
+"stop every tenant now" levers: `systemctl stop
+'carlos-instances-*.slice'` or `systemctl kill carlos-instances.slice`.
+Shutdown is unaffected.
+
+### The nft-flush window
+
+`systemctl reload nftables` (`flush ruleset`) removes the table while
+the exemption stands. Accepted (James, 2026-11-13), stated precisely:
+
+- **Bound:** at most one refresh interval (10 s) per flush, **while
+ control is running**. Startup verification covers the restart case;
+ while control is stopped or crash-looping nothing re-verifies.
+- **Not luck-dependent:** an instance can loop connect attempts to the
+ box's other ports forever, so it catches any flush. The exposure is
+ up to 10 s of reach to all-address listeners per flush; open
+ connections die when the deny returns (evidence 9).
+- A faster tick narrows it but does not change its shape.
+
+**Follow-up (not this plan):** a port-aware cgroup-skb filter attached
+by systemd to the slice (`IPEgressFilterPath=`, a pinned BPF program).
+It would survive both slice recreation and an nft flush, making the
+refuse and the window moot. A bigger build, with a BPF loader in the
+root binary.
+
+### Group mode
+
+When `hairpin.GroupPresent()`, the edge fence is never loaded. The
+group hairpin keeps its own fence and exemption as now. A follow-up,
+after region HA merges, can make the group hairpin one user of the
+edge fence.
+
+### The edge
+
+No change expected. A same-box call arrives from the box's public
+address as a visitor's peer would, and the forwarded-header trust is
+MAC-proven (`forwardproof.go`, `homemap.go`), not peer-address based.
+`localhold.go:47` trusts loopback only. Task 1 confirms this before any
+root code changes.
+
+## Tasks
+
+### Task 1: audit the edge for peer-address trust (no code)
+
+- [x] Grep `internal/edge` and `internal/activator` for any decision
+ keyed on the peer being a box address (rate-limit exemptions, admin
+ paths, `/.carlos/` handlers, forwarded-header trust). Record the
+ result in this plan. Any hit becomes a task before Task 3.
+
+**Result (2026-11-13): no hit; no edge task.** Every `RemoteAddr` use in
+`internal/edge` and `internal/activator` was read:
+
+- Forwarded-header trust is proof-based: `clientIP` (`analytics.go`)
+ reads `X-Forwarded-For` only under a MAC-proven hop; mesh, homemap
+ and HA drain requests are signature-checked (`hadrain.go`,
+ `burst_notice.go`). A peer address grants nothing.
+- PROXY protocol sources must be private IPv4 (`hostenv.ParseProxySources`,
+ `hostenv.go:322`), so the box's public address can never be one.
+- The devbox front treats a request from the box's own address as
+ anonymous (`anonymousSource`, `visitor.go:129`).
+- `isLocalUpstream` (`localhold.go`) is about upstream dials, loopback
+ only.
+- The edge-local door (#175 P7, `door.go`) is marked by a context value
+ after a door-key check, never by peer. Its security model is this
+ plan's: "a request from this box โ€ฆ grants nothing a public request
+ from this box lacks", and it already presents the box's public
+ address as the peer, which is what a fenced same-box call will
+ present. The door is also prior art for #990's grant-and-proxy
+ alternative, limited to an app's own instances; it does not cover
+ Jelly's calls between different apps.
+
+Rate limits and protection key on the peer as for any visitor; there is
+no self-address exemption.
+
+### Task 2: `internal/edgefence`
+
+- [x] `Rules(addrs []netip.Addr) (string, error)`: the table above,
+ addresses sorted and validated (global unicast, single IP).
+- [x] `Expected(addrs) string`: the readback `nft -s -nn -y` prints for
+ that table, from evidence 7's capture.
+- [x] Linux: `Install(ctx)`, `Verify(ctx)` and `Present(ctx)`, running
+ `nft` the way `hairpin/native_linux.go` does. Other OS: an
+ `ErrUnsupported` stub, so the CLI still cross-compiles.
+- [x] Tests: render; readback matches; a numeric cgroup id is a
+ mismatch; a missing table is a mismatch; the reject line's
+ `meta l4proto 6` form; no address renders no table.
+
+### Task 3: control service integration
+
+- [x] `denyLocalAddrs`: on non-group boxes, enable/refresh/fail as
+ above; `applyLocalDeny` gets the exempted set.
+- [x] Startup verification in `Run`, before `Serve`.
+- [x] Check-before-start at every start site under the slice.
+- [x] `fenceActive` in `denyLoopWith`'s condition.
+- [x] Remember the state and the reason (`fenceActive`, `fenceReason`)
+ for reporting.
+- [x] An operator off switch: `CARLOS_EDGE_FENCE=off` in host.env keeps
+ the full deny (the rollback path without a release).
+- [x] Tests, with fakes for systemctl and nft: the exemption only after
+ a verified readback; a failed install, a failed readback and a stale
+ cgroup id each restore the full deny; startup with a leftover
+ exemption and a missing table restores the full deny before `Serve`;
+ **a tick with unchanged addresses still runs the readback**; a start
+ after a stale readback restores the full deny before the start; group
+ mode never loads the table; the off switch holds.
+
+### Task 4: units
+
+- [x] `carlos-instance-control.service`: `RestrictAddressFamilies=AF_UNIX
+ AF_NETLINK` (nft talks netlink; the group drop-in already does this
+ on group boxes).
+- [x] `carlos-instances.slice` and `carlos.slice`: `RefuseManualStop=yes`,
+ with the comment naming the remaining levers. The control service
+ starts `carlos-instances.slice`.
+- [x] Missing `nft` binary or a failed load: full deny, reported.
+
+### Task 5: the probe and the guard
+
+- [x] `box-addr` stays as it is (UDP `EPERM` on every box address).
+- [x] New `box-addr-ports`: TCP to a non-web port on each box address
+ is refused (reset or `EPERM`, not a connect).
+- [x] New `box-addr-edge`: TCP 443 on each box address connects when
+ the fence is active; `unverified` when it is off, with the reason.
+- [x] Guard test for evidence 8's three facts: `carlos-app@` keeps an
+ empty `CapabilityBoundingSet=`; no unit outside the instances slice
+ other than `carlos-edge.service` grants `CAP_NET_BIND_SERVICE`;
+ nothing the tree installs sets `ip_unprivileged_port_start`.
+
+### Build notes (Tasks 2โ€“5, 2026-11-13)
+
+Where the build departed from the text above, and why:
+
+- **One choke point for starts.** Instead of a check at each of the 13
+ start sites, `guardStarts` wraps the service's `Systemctl` once in
+ `runWithClaim`; `TestEveryStartIsSeenByTheFenceCheck` fails on a start
+ through any other systemctl. Two such paths exist and are covered:
+ the egress asserter's `try-restart` (through `RestartAllowed`,
+ `bindEgressFence`) and claim units' own systemctl (the fence stays
+ **off in claims mode**, reason "host claims mode"; claims are
+ shelved).
+- **A flushed or stale fence is reloaded**, not just reported: the
+ refresh and the pre-start check reinstall and re-verify, and fall
+ back to the whole deny only if that fails. The invariant holds either
+ way; a reload keeps same-box calls working through an nftables
+ reload.
+- **The refresh does not re-set an unchanged deny** (`set-property`
+ re-attaches the slice's BPF filters under every instance); the probe
+ path still re-applies as before.
+- **A start is refused** until this service has applied a deny
+ (`errFenceUnknown`), so a failed startup check cannot leave an
+ unchecked leftover exemption in force for new instances.
+- **Units**: the claims-mode control unit rewrite matched the old
+ `RestrictAddressFamilies=AF_UNIX` line exactly; it now matches the new
+ line (it would have silently dropped `AF_INET`/`AF_INET6`).
+- **Probe**: the fenced addresses are marked in the existing
+ `box-addrs` file (`<addr> edge`) rather than a second file, so the
+ probes' exact `/opt/carlos` listings and bind mounts are unchanged.
+ `box-addr-ports` dials TCP 22 (ssh, the listener a box most often
+ has); `box-addr-edge` is never `fail`, so an edge restart does not
+ take the box out of service.
+- **Policy point for review:** `adopt_advice.go` says the platform never
+ writes the firewall on fixed boxes (spec ยง4b, ยง5a, the IMDS role
+ gate). The fence is a platform-owned table that only restricts the
+ instances slice's own traffic and opens nothing, as the group hairpin
+ already is on group boxes; the reviewer should confirm that reading.
+
+### Task 6: reporting
+
+- [x] The box report carries the fence state and reason, and the CLI
+ shows it per box (UX pass first, per AGENTS.md). James chose the
+ placement on 2026-11-13: one line per box in `carlos status --layout`,
+ after `exec-sandbox:`. States: `on`, `off (reason)`, `unknown`
+ (`not needed` was cut in review round 1, P2).
+
+**Where (traced 2026-11-13):** `carlos instances list` has one row per
+instance, not per box, and shows nothing from the probe today. The
+per-box pattern is `carlos status --layout`'s `exec-sandbox:` line
+(`status_instances.go` `printExecSandboxStatus`, fed by
+`status.LayoutReport.ExecSandbox`, filled in `internal/host/layoutleg.go`
+from the control service's `/ready` report). The fence state would take
+the same path: a field on `ProbeReport`, then `LayoutReport`, then
+`apiStatusLayoutBox`, then one line per box.
+
+### Task 7: census, review, drill
+
+- [x] `make census-card`, CLAIMS, `make census-propose` (root binary
+ and units change): `docs/superpowers/notes/census-proposal-same-box-edge-fence.md`.
+- [ ] Opus or Fable review of Tasks 2โ€“5 (security gate, root; stopping
+ rule 3), with this plan, its round history and #990 in the brief.
+- [ ] Drill on a single-address non-group box (the letsjelly.dev
+ testbed or the load-test box, with scoped approval):
+ - an instance reaches another app on the box by hostname;
+ - 22, 5432 and a console port are refused at once;
+ - with the refuse lifted, restarting `carlos-instances.slice`, and
+ separately `carlos.slice`, leaves the full deny in place before the
+ next instance start;
+ - `systemctl reload nftables` restores the full deny within one tick,
+ and an open connection to a non-web port dies when it does;
+ - stopping control, flushing nft, starting control: the full deny is
+ back before control answers its socket.
+
+## Drill (2026-11-13, carlos-jelly-load-test, 178.104.232.12)
+
+Approved by James for this box. Debian 13, kernel 6.12, public IPv4 as
+a /32 on eth0 plus a global IPv6, sshd on all addresses, plain-HTTP
+edge on :80, 100 jam instances. The box ran a patched `wakeburst3`
+build; the drill swapped in this branch's build (`edgefence-drill1`,
+then `-drill2` with the two fixes below), put the unit changes in as
+drop-ins, and restored everything afterwards (binary, drop-ins removed,
+no fence table, the #367 deny back, the baseline re-run). Checks ran as
+uid carlos in a transient unit under `carlos-instances-c1.apps.test.slice`.
+
+| step | result |
+|---|---|
+| baseline (#367 deny) | edge on the box's own v4 and v6 address: **timeout**. :22 not reachable, UDP EPERM |
+| fence on | `edge fence: on for [178.104.232.12 2a01:4f8:1c1c:f9ce::1]`; edge **HTTP 303** on v4 and v6 (c2's gate); :22 **refused at once** on both; UDP EPERM; deny keeps loopback and link-local only. Verify passed against Debian 13's nft. Probe: box-addr ok, box-addr-ports ok, box ready |
+| manual stop of either slice | refused by `RefuseManualStop` |
+| slice recreated, wake through control | `edge fence before a start: ... recreated` โ†’ reloaded before c2 started |
+| slice recreated, unit started by hand (refuse lifted) | :22 reachable for **~7 s**, until the refresh tick reloaded the fence: the documented residual, bounded by one tick |
+| carlos.slice stopped (refuse lifted) | a refresh raced the stop, the load failed (`cgroupv2 path fails`), the **whole deny applied** (fail closed) โ€” and stayed until the next probe. **Fixed in drill2**: a failed fence is retried every tick. Rerun: reloaded within 4 s of the edge coming back |
+| fence table deleted (as an nftables reload) | an instance opened a connection to :5555 in the gap; **reset after 8 s** when the tick reloaded the fence (`table not loaded; reloaded`) |
+| control stopped + table deleted | control is socket-activated: the next request restarted it, and it reloaded the fence before serving |
+| box-addr-edge | `unverified` on this plain-HTTP box (nothing on 443). **Fixed in drill2**: 80 counts too |
+
+CI on the first push: the census (expected before the overlay) and
+`TestHALostLeaseRecoversOnlyAfterFreshAcquire` (activator; the known
+leak in #963, nothing on this branch touches the activator).
+
+## Switch-on
+
+On by default in the release that carries it (stopping rule 5: Jelly is
+the user, and rolling console.carlos.exciting.io to it is the
+switch-on). The first observable change (rule 6): from a Jelly team
+instance, `curl https://join.letsjelly.com` answers.
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-same-box-edge-fence-R2.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-same-box-edge-fence-R2.md
new file mode 100644
index 000000000..fdceaa140
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-same-box-edge-fence-R2.md
@@ -0,0 +1,57 @@
+# Review brief: branch same-box-edge-fence (the edge fence, #990), round 2 of 3
+
+Repo carlos/platform, branch `same-box-edge-fence` on amadan.net.
+Under review: the diff `4f95eb302..<tip named in the prompt>`; the fixes
+since round 1 are `7aad44ce7..<tip>` (commit `cbf450cc3` and this brief).
+Authorities, plan and census card: as in round 1
+(`docs/superpowers/reviews/CODEX-REVIEW-BRIEF-same-box-edge-fence.md`);
+the census card is unchanged except the `internal/instancectl` envelope,
+re-pinned for the fixes.
+
+## Round 2
+
+Earlier rounds: round 1 (you, at `7aad44ce7`): NOT READY, P1
+"address-discovery failure leaves an unchecked exemption active"
+(family: fail-closed enforcement of the box-address boundary), P2
+"`not_needed` asserts connectivity that was never established" (family:
+status describes observed state); census: all units approved, the
+`internal/instancectl` envelope rejected for those two findings.
+
+First give one line per round-1 finding: resolved, partly, or not.
+Carry every unresolved or partly resolved finding forward at its
+current severity, then add new findings. The verdict covers everything
+outstanding.
+
+What changed:
+
+- `internal/instancectl/edgefence.go` `fenceWithoutAddresses`: with the
+ address read failing and the fence exempting, the remembered
+ addresses' fence must read back, or is reloaded, or the whole deny is
+ rebuilt (`lastDeny` plus the remembered addresses as /32 and /128)
+ and applied, and the fence is recorded off with reason
+ `fenceOffUnread` (retried every tick, since it is not a settled
+ reason).
+- `hardening.go`: `denyLocalAddrsLocked` calls it on an address-read
+ error (so RunProbe, the refresh and the pre-start check all do);
+ `denyLoopWith` now calls `denyLocalAddrsWith` on a read error while
+ the fence exempts (before, a read error skipped the tick).
+- `not_needed` is removed everywhere (report, status, CLI); a box with
+ no public address reports `off (no public address on this box)`.
+- Tests: `TestFenceIsCheckedWhenAddressesCannotBeRead` (reloaded, whole
+ deny over repeated ticks then recovery, before a start), mutation-
+ checked against the old tick.
+
+Also re-give the census verdict for the `internal/instancectl`
+envelope.
+
+Stopping rules: this is round 2. A P1 in the same family as round 1's
+P1 means rule 2 applies (two rounds in one family): say so, and say
+whether stating the invariant in one place and checking it with a
+guard test or a randomized simulation would remove it.
+
+## Severity, output
+
+As in round 1's brief: P1/P2/P3 with evidence and fault family, then
+the census verdict, then exactly one of READY, READY AFTER FIXES,
+NOT READY. Do not edit files (shared worktree); reply with findings.
+Targeted `go test -run` only.
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-same-box-edge-fence.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-same-box-edge-fence.md
new file mode 100644
index 000000000..1e6dfa245
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-same-box-edge-fence.md
@@ -0,0 +1,117 @@
+# Review brief: branch same-box-edge-fence (the edge fence, #990), round 1 of 3
+
+Repo carlos/platform, branch `same-box-edge-fence` on amadan.net (the
+local worktree branch is `app-call-grant-edge-proxy`, same commits).
+Under review: the diff `4f95eb302..<tip named in the prompt>`.
+Authorities: none merged beyond `main`. The plan this branch implements
+is on the branch itself:
+`docs/superpowers/plans/2026-11-13-same-box-calls-edge-fence.md` (read
+it first: the invariant, the evidence from two namespace experiments,
+the design, the build notes, the drill table). Background: amadan
+discussions #990 (the problem) and #367 (the deny it narrows).
+
+You are an independent reviewer. Read the plan, then the code it names,
+and check every claim against that code. This review is also the census
+review: `docs/superpowers/notes/census-proposal-same-box-edge-fence.md`
+is the card; give a verdict for every unit and every re-pinned envelope
+on it, as AGENTS.md "The census: the reviewer decides" describes.
+
+## Round history
+
+The plan had one review round (an agent reviewing for James, recorded
+in the plan's "Plan review history"): no P1; seven corrections applied.
+This is the first review of the code. Stopping rules 1 and 2 apply.
+
+## Fixed: do not re-argue
+
+- James's rulings of 2026-11-13, recorded in the plan: refuse manual
+ stop on both slices (defence in depth); reset, not silent drop, for
+ refused TCP ports; accept the nftables-flush window (one refresh
+ tick while control runs); the reporting goes in `carlos status
+ --layout`, one line per box.
+- The choice of a cgroup-scoped output-only nft table over the
+ grant-and-proxy alternative (#990), and over a BPF filter attached
+ by systemd (`IPEgressFilterPath=`, recorded as a follow-up).
+- The fence is off in claims mode and on group boxes.
+
+## What to check
+
+1. **The invariant** (plan, "The invariant"): an instance reaches an
+ address of its own box only on TCP 80 or 443, or the whole #367 deny
+ is in place. Find any path where an address leaves the slice's
+ `IPAddressDeny=` without a verified fence for it: in
+ `internal/instancectl/edgefence.go` (`edgeFenceDeny`,
+ `fenceBeforeStart`, `guardStarts`, `recordFence`),
+ `hardening.go` (`denyLocalAddrsLocked`, the refresh skip,
+ `denyLoopWith`), and `server.go` (`runWithClaim`: the wrap, the
+ startup check before `Serve`).
+2. **Every start sees the check.** `guardStarts` wraps `s.Systemctl`
+ once; `TestEveryStartIsSeenByTheFenceCheck` scans the package. Is
+ there a start of a unit under `carlos-instances.slice` it misses (in
+ this package or any other process on the box), and is the egress
+ asserter's `RestartAllowed` hook (`bindEgressFence`) really in front
+ of every restart it makes?
+3. **The readback.** `internal/edgefence`: `Rules` renders exactly what
+ `nft -s -nn -y` prints back (fixture
+ `internal/edgefence/testdata/readback-v4-v6.txt`, captured from a real
+ kernel; the drill's Debian 13 nft also verified). Can a readback that
+ compares equal still fail to enforce the rule set (a stale cgroup id
+ printed as a path, another table at an earlier priority that accepts
+ first, a chain policy elsewhere)? Can `Verify` pass while the
+ instances' traffic bypasses the output hook?
+4. **The residual** (plan evidence 8): a process outside the slice with
+ source port 80/443 can reach an instance's TCP listener through the
+ box address. The plan rules it out because only root and the edge can
+ bind those ports, pinned by `TestOnlyTheEdgeBindsAPrivilegedPort`.
+ Is that argument sound and is the guard complete?
+5. **Fail-closed under failure and concurrency.** `denyMu`, `mu`, the
+ fence fields, the retry flag (`fenceRetry`, added after the drill
+ found a refresh racing `systemctl stop carlos.slice`). Deadlocks
+ (`fenceBeforeStart` takes `denyMu`; is any start made while holding
+ it?), lost updates, a refresh that skips an apply it needed.
+6. **Units.** `AF_NETLINK` on the control unit; `RefuseManualStop` on
+ both slices; the claims-mode rewrite in `internal/host/claimunit.go`.
+ Any boot, update or shutdown path that stops either slice and is now
+ refused?
+7. **The firewall boundary.** `internal/host/adopt_advice.go` says the
+ platform never writes the firewall on fixed boxes (spec ยง4b, ยง5a,
+ about the IMDS role gate). The fence is a platform-owned table that
+ only restricts the instances slice's own traffic. Does it conflict
+ with that rule or with an operator's nftables configuration (for
+ example `flush ruleset` at boot ordering, `After=nftables.service`)?
+8. **Reporting.** `/ready`'s `edge_fence`, the agent's read
+ (`internal/host/execsandboxstatus.go`), `status.LayoutReport`, the
+ console passthrough and `printEdgeFenceStatus`. Wrong or misleading
+ states, especially `not_needed`.
+9. **The census card**: a verdict per unit and envelope.
+
+## 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 verdicts. 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: you share this worktree with the author. Write your
+findings as your reply, not to a file. Do not spawn Anthropic-model
+reviewers or subagents of your own. Do not run the full test suites;
+targeted `go test -run` of the packages named here is fine.
diff --git a/internal/console/apistatuslayout.go b/internal/console/apistatuslayout.go
index b52d04258..e78c69aa7 100644
--- a/internal/console/apistatuslayout.go
+++ b/internal/console/apistatuslayout.go
@@ -73,6 +73,7 @@ func egressView(h status.HostEgress, ok bool, conflicts map[string]string) *apiE
// other private reader of status/boxes/ uses), and its rows.
type apiStatusLayoutBox struct {
ExecSandbox *status.ExecSandbox `json:"exec_sandbox,omitempty"`
+ EdgeFence *status.EdgeFence `json:"edge_fence,omitempty"`
Box string `json:"box"`
Mode string `json:"mode"`
// Region and RegionName are the box's placement code and label from
@@ -163,6 +164,7 @@ func (s *Server) handleAPIStatusLayout(w http.ResponseWriter, r *http.Request) {
out = append(out, apiStatusLayoutBox{
Box: b.Label,
ExecSandbox: b.Metrics.Layout.ExecSandbox,
+ EdgeFence: b.Metrics.Layout.EdgeFence,
Region: region,
RegionName: regionName,
Mode: b.Metrics.Layout.Mode,
diff --git a/internal/console/apistatuslayout_test.go b/internal/console/apistatuslayout_test.go
index 549f97ba1..402ee7364 100644
--- a/internal/console/apistatuslayout_test.go
+++ b/internal/console/apistatuslayout_test.go
@@ -340,7 +340,7 @@ func TestStatusLayoutSandbox(t *testing.T) {
if err := fx.st.SetOperator("paul@keymail.dev", true); err != nil {
t.Fatal(err)
}
- report := &status.LayoutReport{Mode: "nested", ExecSandbox: &status.ExecSandbox{Configured: "auto", Effective: "gvisor", Runsc: &status.RunscStatus{Version: "release-20261102.0", SHA256: "pin"}, Ready: false, Blocked: "probe-blocked"}, Rows: map[string]status.RowLayout{"demo.example.com": {Layout: "nested", Sandbox: "gvisor"}, "sleep.example.com": {Layout: "nested"}}}
+ report := &status.LayoutReport{Mode: "nested", ExecSandbox: &status.ExecSandbox{Configured: "auto", Effective: "gvisor", Runsc: &status.RunscStatus{Version: "release-20261102.0", SHA256: "pin"}, Ready: false, Blocked: "probe-blocked"}, EdgeFence: &status.EdgeFence{State: "off", Reason: "host claims mode"}, Rows: map[string]status.RowLayout{"demo.example.com": {Layout: "nested", Sandbox: "gvisor"}, "sleep.example.com": {Layout: "nested"}}}
seedLayoutBox(t, fx.rel, "fresh", time.Now(), report)
seedLayoutBox(t, fx.rel, "old", time.Now(), &status.LayoutReport{Mode: "nested"})
seedLayoutBox(t, fx.rel, "stale", time.Now().Add(-time.Hour), report)
@@ -359,7 +359,7 @@ func TestStatusLayoutSandbox(t *testing.T) {
}
for _, b := range out.Boxes {
if b.Box == "old" {
- if b.ExecSandbox != nil {
+ if b.ExecSandbox != nil || b.EdgeFence != nil {
t.Fatal("old box has guessed status")
}
continue
@@ -367,5 +367,9 @@ func TestStatusLayoutSandbox(t *testing.T) {
if b.ExecSandbox == nil || b.ExecSandbox.Ready || b.ExecSandbox.Runsc.SHA256 != "pin" || b.ExecSandbox.Blocked != "probe-blocked" || b.Rows[0].Sandbox != "gvisor" || b.Rows[1].Sandbox != "" || b.Stale != (b.Box == "stale") {
t.Fatalf("projection: %+v", b)
}
+ // #990: the edge fence report passes through as the box sent it.
+ if b.EdgeFence == nil || b.EdgeFence.State != "off" || b.EdgeFence.Reason != "host claims mode" {
+ t.Fatalf("edge fence projection: %+v", b.EdgeFence)
+ }
}
}
diff --git a/internal/edgefence/edgefence.go b/internal/edgefence/edgefence.go
new file mode 100644
index 000000000..df05704a1
--- /dev/null
+++ b/internal/edgefence/edgefence.go
@@ -0,0 +1,220 @@
+// Package edgefence owns the nft table that lets nested instances reach
+// the edge on the box's own addresses, and nothing else there (#990).
+//
+// #367 denies every address of the box on carlos-instances.slice, because
+// traffic to a local address never leaves the box: through one, an
+// instance reaches every listener bound to all addresses, past any
+// inbound firewall. systemd's IPAddressDeny= has no ports, so that deny
+// also closes the edge on 80 and 443, and an app cannot call another app
+// on its own box by hostname, though it can call one on any other box.
+//
+// The fence restores the edge and only the edge. Its rules match sockets
+// in carlos.slice/carlos-instances.slice and, for each fenced address,
+// accept TCP 80 and 443, reset any other TCP port and drop everything
+// else (UDP keeps the synchronous EPERM the box-addr probe line reads).
+// The control service removes an address from the slice deny only while
+// Verify passes for it; any failure puts the full deny back. That
+// invariant is instancectl's to keep; this package renders, loads and
+// reads back the table and decides nothing else.
+//
+// nft resolves the cgroup path to the cgroup's id when the rule loads. If
+// the slice is later recreated, the rule keeps the old id and matches
+// nothing, and the readback prints that id as a bare number where the
+// quoted path should be. Verify refuses that readback (ErrStale), which
+// is why the control service runs it before every start under the slice
+// (plan 2026-11-13-same-box-calls-edge-fence, evidence 3 and 4).
+package edgefence
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "net/netip"
+ "os/exec"
+ "regexp"
+ "slices"
+ "strings"
+)
+
+// Table is the nft table the fence owns, in the inet family.
+const Table = "carlos_edge_fence"
+
+// Cgroup is the slice every nested unit runs under, as nft names it: the
+// cgroup v2 path at level 2 (carlos.slice is level 1). The per-host slices
+// (carlos-instances-<host>.slice) sit below it and are matched with it.
+const Cgroup = "carlos.slice/carlos-instances.slice"
+
+// cgroupLevel is Cgroup's depth below the cgroup root.
+const cgroupLevel = 2
+
+var (
+ // ErrNoAddress is Rules with nothing to fence: the box has no global
+ // address of its own, so there is no table to load and nothing to
+ // exempt.
+ ErrNoAddress = errors.New("edge fence: no address to fence")
+ // ErrAddress is an address the fence refuses to name.
+ ErrAddress = errors.New("edge fence: address refused")
+ // ErrMissing is a readback with no fence table.
+ ErrMissing = errors.New("edge fence: table not loaded")
+ // ErrStale is a readback whose rules name the slice by a bare cgroup
+ // id: the slice was recreated after the table loaded, and the rules
+ // match nothing.
+ ErrStale = errors.New("edge fence: the instances slice was recreated after the fence loaded")
+ // ErrMismatch is any other readback that differs from the render.
+ ErrMismatch = errors.New("edge fence: table differs from what was loaded")
+)
+
+// Runner runs a command with input on stdin and returns its combined
+// output. Exec is the real one; tests pass their own.
+type Runner func(ctx context.Context, input string, args ...string) ([]byte, error)
+
+// Exec runs the command. A failure carries the command's own words.
+func Exec(ctx context.Context, input string, args ...string) ([]byte, error) {
+ c := exec.CommandContext(ctx, args[0], args[1:]...)
+ if input != "" {
+ c.Stdin = strings.NewReader(input)
+ }
+ out, err := c.CombinedOutput()
+ if err != nil {
+ return out, fmt.Errorf("%s: %w: %s", args[0], err, strings.TrimSpace(string(out)))
+ }
+ return out, nil
+}
+
+// staticDeny is the IPAddressDeny= every carlos-instance*.service
+// template carries ("localhost" and "multicast" spelled out). An address
+// inside it is closed by the template whatever the slice says, so it is
+// never fenced: exempting it from the slice deny would open nothing, and
+// naming it in the fence would suggest otherwise. TestStaticDenyMatchesTemplates
+// keeps this list and the templates in step.
+var staticDeny = []netip.Prefix{
+ netip.MustParsePrefix("127.0.0.0/8"), netip.MustParsePrefix("::1/128"),
+ netip.MustParsePrefix("224.0.0.0/4"), netip.MustParsePrefix("ff00::/8"),
+ netip.MustParsePrefix("0.0.0.0/8"), netip.MustParsePrefix("10.0.0.0/8"),
+ netip.MustParsePrefix("100.64.0.0/10"), netip.MustParsePrefix("169.254.0.0/16"),
+ netip.MustParsePrefix("169.254.169.254/32"), netip.MustParsePrefix("172.16.0.0/12"),
+ netip.MustParsePrefix("192.0.0.0/24"), netip.MustParsePrefix("192.168.0.0/16"),
+ netip.MustParsePrefix("198.18.0.0/15"), netip.MustParsePrefix("240.0.0.0/4"),
+ netip.MustParsePrefix("64:ff9b::/96"), netip.MustParsePrefix("fc00::/7"),
+ netip.MustParsePrefix("fd00:ec2::254/128"), netip.MustParsePrefix("fe80::/10"),
+ netip.MustParsePrefix("fec0::/10"),
+}
+
+// Fenceable reports whether a may be named by the fence: one global
+// unicast address, IPv4 or IPv6 (never IPv4-mapped), outside the
+// templates' static deny.
+func Fenceable(a netip.Addr) bool {
+ if !a.IsValid() || a.Is4In6() || a.Zone() != "" || !a.IsGlobalUnicast() {
+ return false
+ }
+ for _, p := range staticDeny {
+ if p.Contains(a) {
+ return false
+ }
+ }
+ return true
+}
+
+// Addresses is the fence's address set for the box's local prefixes: the
+// address of every single-address prefix (/32, /128) that is Fenceable,
+// each once, sorted. A wider local range (127.0.0.0/8, a whole routed
+// block) is never fenced and stays in the deny.
+func Addresses(local []netip.Prefix) []netip.Addr {
+ var out []netip.Addr
+ for _, p := range local {
+ if !p.IsSingleIP() {
+ continue
+ }
+ a := p.Addr()
+ if Fenceable(a) && !slices.Contains(out, a) {
+ out = append(out, a)
+ }
+ }
+ slices.SortFunc(out, netip.Addr.Compare)
+ return out
+}
+
+// Rules is the table for addrs, written exactly as `nft -s -nn -y list
+// table inet carlos_edge_fence` prints it back (evidence 7), so the one
+// text is both what Install loads and what Verify compares against.
+//
+// One output chain, nothing on input: an instance originates the traffic,
+// and the edge's replies come from a socket outside the slice, which the
+// rules do not match. Inbound traffic from outside the box is untouched.
+func Rules(addrs []netip.Addr) (string, error) {
+ if len(addrs) == 0 {
+ return "", ErrNoAddress
+ }
+ sorted := slices.Clone(addrs)
+ slices.SortFunc(sorted, netip.Addr.Compare)
+ var b strings.Builder
+ fmt.Fprintf(&b, "table inet %s {\n", Table)
+ b.WriteString("\tchain output {\n")
+ b.WriteString("\t\ttype filter hook output priority -300; policy accept;\n")
+ for i, a := range sorted {
+ if !Fenceable(a) {
+ return "", fmt.Errorf("%w: %s is not a global address of this box", ErrAddress, a)
+ }
+ if i > 0 && a == sorted[i-1] {
+ return "", fmt.Errorf("%w: %s named twice", ErrAddress, a)
+ }
+ family := "ip"
+ if a.Is6() {
+ family = "ip6"
+ }
+ match := fmt.Sprintf("\t\tsocket cgroupv2 level %d %q %s daddr %s", cgroupLevel, Cgroup, family, a)
+ b.WriteString(match + " tcp dport { 80, 443 } accept\n")
+ b.WriteString(match + " meta l4proto 6 reject with tcp reset\n")
+ b.WriteString(match + " drop\n")
+ }
+ b.WriteString("\t}\n}\n")
+ return b.String(), nil
+}
+
+// Install loads the table for addrs, replacing any earlier one in the
+// same transaction. `add table` makes the delete safe when there is none;
+// nothing outside this table is touched.
+func Install(ctx context.Context, run Runner, addrs []netip.Addr) error {
+ rules, err := Rules(addrs)
+ if err != nil {
+ return err
+ }
+ script := fmt.Sprintf("add table inet %s\ndelete table inet %s\n%s", Table, Table, rules)
+ if _, err := run(ctx, script, "nft", "-f", "-"); err != nil {
+ return fmt.Errorf("edge fence: load: %w", err)
+ }
+ return nil
+}
+
+// staleCgroup is a rule naming the slice by a bare cgroup id.
+var staleCgroup = regexp.MustCompile(`socket cgroupv2 level \d+ \d+ `)
+
+// Verify reads the table back and compares it, whitespace aside, with
+// Rules(addrs). Anything else, an extra rule, a missing one, another
+// address, a port, a bare cgroup id, is refused.
+func Verify(ctx context.Context, run Runner, addrs []netip.Addr) error {
+ want, err := Rules(addrs)
+ if err != nil {
+ return err
+ }
+ got, err := run(ctx, "", "nft", "-s", "-nn", "-y", "list", "table", "inet", Table)
+ if err != nil {
+ if strings.Contains(string(got), "No such file or directory") {
+ return ErrMissing
+ }
+ return fmt.Errorf("edge fence: read back: %w", err)
+ }
+ return compare(string(got), want)
+}
+
+func compare(got, want string) error {
+ if compact(got) == compact(want) {
+ return nil
+ }
+ if staleCgroup.MatchString(got) {
+ return ErrStale
+ }
+ return fmt.Errorf("%w: got %q", ErrMismatch, got[:min(len(got), 4096)])
+}
+
+func compact(s string) string { return strings.Join(strings.Fields(s), "") }
diff --git a/internal/edgefence/edgefence_test.go b/internal/edgefence/edgefence_test.go
new file mode 100644
index 000000000..8acf07716
--- /dev/null
+++ b/internal/edgefence/edgefence_test.go
@@ -0,0 +1,272 @@
+package edgefence
+
+import (
+ "context"
+ "errors"
+ "net/netip"
+ "os"
+ "path/filepath"
+ "slices"
+ "strings"
+ "testing"
+)
+
+var (
+ v4 = netip.MustParseAddr("198.51.100.7")
+ v6 = netip.MustParseAddr("2001:db8::7")
+)
+
+// readback is what nft printed for this table on a real kernel (6.8,
+// nftables 1.0.9), captured in the plan's run 2 with only the test
+// slice and table names swapped for the real ones.
+func readback(t *testing.T) string {
+ t.Helper()
+ b, err := os.ReadFile(filepath.Join("testdata", "readback-v4-v6.txt"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ return string(b)
+}
+
+func TestRulesIsTheReadback(t *testing.T) {
+ got, err := Rules([]netip.Addr{v6, v4})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got != readback(t) {
+ t.Fatalf("render differs from nft's own readback:\n got: %q\nwant: %q", got, readback(t))
+ }
+}
+
+func TestRulesRefuses(t *testing.T) {
+ if _, err := Rules(nil); !errors.Is(err, ErrNoAddress) {
+ t.Fatalf("no address: %v", err)
+ }
+ for _, s := range []string{"10.0.0.5", "127.0.0.1", "100.64.1.1", "169.254.169.254", "fd00::1", "fe80::1", "::1", "224.0.0.1", "0.0.0.0", "::ffff:198.51.100.7"} {
+ if _, err := Rules([]netip.Addr{netip.MustParseAddr(s)}); !errors.Is(err, ErrAddress) {
+ t.Errorf("%s: %v, want ErrAddress", s, err)
+ }
+ }
+ if _, err := Rules([]netip.Addr{v4, v4}); !errors.Is(err, ErrAddress) {
+ t.Fatalf("duplicate: %v", err)
+ }
+ if _, err := Rules([]netip.Addr{{}}); !errors.Is(err, ErrAddress) {
+ t.Fatalf("zero address: %v", err)
+ }
+}
+
+func TestAddresses(t *testing.T) {
+ local := []netip.Prefix{
+ netip.MustParsePrefix("127.0.0.0/8"), // wide local range: stays denied
+ netip.MustParsePrefix("127.0.0.1/32"), // loopback
+ netip.MustParsePrefix("10.0.1.4/32"), // private: the template denies it
+ netip.MustParsePrefix("198.51.100.7/32"), // the public address
+ netip.MustParsePrefix("198.51.100.7/32"), // listed twice
+ netip.MustParsePrefix("203.0.113.0/24"), // a routed local block, not an address
+ netip.MustParsePrefix("2001:db8::7/128"),
+ netip.MustParsePrefix("fe80::1/128"),
+ netip.MustParsePrefix("::1/128"),
+ }
+ got := Addresses(local)
+ want := []netip.Addr{v4, v6}
+ if !slices.Equal(got, want) {
+ t.Fatalf("Addresses = %v, want %v", got, want)
+ }
+ if got := Addresses([]netip.Prefix{netip.MustParsePrefix("10.0.1.4/32")}); len(got) != 0 {
+ t.Fatalf("EC2 without IPv6 fences nothing, got %v", got)
+ }
+}
+
+// fakeNFT records what it was asked and answers a list with out.
+type fakeNFT struct {
+ calls [][]string
+ input []string
+ out string
+ err error
+}
+
+func (f *fakeNFT) run(_ context.Context, input string, args ...string) ([]byte, error) {
+ f.calls = append(f.calls, args)
+ f.input = append(f.input, input)
+ return []byte(f.out), f.err
+}
+
+func TestInstallReplacesOnlyItsTable(t *testing.T) {
+ f := &fakeNFT{}
+ if err := Install(context.Background(), f.run, []netip.Addr{v4, v6}); err != nil {
+ t.Fatal(err)
+ }
+ if len(f.calls) != 1 || strings.Join(f.calls[0], " ") != "nft -f -" {
+ t.Fatalf("calls = %v", f.calls)
+ }
+ want := "add table inet carlos_edge_fence\ndelete table inet carlos_edge_fence\n" + readback(t)
+ if f.input[0] != want {
+ t.Fatalf("script:\n%s\nwant:\n%s", f.input[0], want)
+ }
+}
+
+func TestInstallFailure(t *testing.T) {
+ f := &fakeNFT{err: errors.New("exit status 1")}
+ if err := Install(context.Background(), f.run, []netip.Addr{v4}); err == nil {
+ t.Fatal("a failed load must be an error")
+ }
+ if err := Install(context.Background(), f.run, nil); !errors.Is(err, ErrNoAddress) {
+ t.Fatalf("no address: %v", err)
+ }
+}
+
+func TestVerify(t *testing.T) {
+ ctx := context.Background()
+ addrs := []netip.Addr{v4, v6}
+ good := readback(t)
+ for _, tc := range []struct {
+ name string
+ out string
+ err error
+ want error
+ }{
+ {name: "exact", out: good},
+ {name: "spacing aside", out: strings.ReplaceAll(good, "\t", " ")},
+ // Evidence 4: after the slice was stopped and started, nft printed
+ // the old cgroup id where the path had been.
+ {name: "slice recreated", out: strings.ReplaceAll(good, `"carlos.slice/carlos-instances.slice"`, "803329"), want: ErrStale},
+ {name: "missing table", out: "Error: No such file or directory\nlist table inet carlos_edge_fence\n", err: errors.New("exit status 1"), want: ErrMissing},
+ {name: "extra port", out: strings.Replace(good, "{ 80, 443 }", "{ 22, 80, 443 }", 1), want: ErrMismatch},
+ {name: "rule removed", out: strings.Replace(good, "\t\tsocket cgroupv2 level 2 \"carlos.slice/carlos-instances.slice\" ip daddr 198.51.100.7 drop\n", "", 1), want: ErrMismatch},
+ {name: "another address", out: strings.ReplaceAll(good, "198.51.100.7", "198.51.100.8"), want: ErrMismatch},
+ {name: "accept policy rule appended", out: strings.Replace(good, "\t}\n}", "\t\taccept\n\t}\n}", 1), want: ErrMismatch},
+ {name: "another level", out: strings.ReplaceAll(good, "level 2", "level 1"), want: ErrMismatch},
+ {name: "empty", out: "", want: ErrMismatch},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ f := &fakeNFT{out: tc.out, err: tc.err}
+ err := Verify(ctx, f.run, addrs)
+ switch {
+ case tc.want == nil && err != nil:
+ t.Fatalf("Verify = %v, want nil", err)
+ case tc.want != nil && !errors.Is(err, tc.want):
+ t.Fatalf("Verify = %v, want %v", err, tc.want)
+ }
+ if got := strings.Join(f.calls[0], " "); got != "nft -s -nn -y list table inet carlos_edge_fence" {
+ t.Fatalf("read back with %q", got)
+ }
+ })
+ }
+}
+
+func TestVerifyOtherFailure(t *testing.T) {
+ f := &fakeNFT{out: "", err: errors.New("exec: \"nft\": executable file not found in $PATH")}
+ err := Verify(context.Background(), f.run, []netip.Addr{v4})
+ if err == nil || errors.Is(err, ErrMissing) {
+ t.Fatalf("Verify = %v, want a read-back failure that is not ErrMissing", err)
+ }
+}
+
+// TestStaticDenyMatchesTemplates keeps staticDeny equal to the
+// IPAddressDeny= every nested template carries. If a template's list
+// changes, Fenceable must change with it: an address the template denies
+// is never fenced, and one it stops denying may need to be.
+func TestStaticDenyMatchesTemplates(t *testing.T) {
+ paths, err := filepath.Glob(filepath.Join("..", "host", "units", "carlos-instance*.service"))
+ if err != nil || len(paths) == 0 {
+ t.Fatalf("templates: %v %v", paths, err)
+ }
+ expand := map[string][]string{
+ "localhost": {"127.0.0.0/8", "::1/128"},
+ "multicast": {"224.0.0.0/4", "ff00::/8"},
+ }
+ var want []string
+ for _, p := range staticDeny {
+ want = append(want, p.String())
+ }
+ slices.Sort(want)
+ seen := 0
+ for _, path := range paths {
+ b, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, line := range strings.Split(string(b), "\n") {
+ v, ok := strings.CutPrefix(line, "IPAddressDeny=")
+ if !ok || v == "" {
+ continue
+ }
+ seen++
+ var got []string
+ for _, f := range strings.Fields(v) {
+ if e, ok := expand[f]; ok {
+ got = append(got, e...)
+ continue
+ }
+ got = append(got, netip.MustParsePrefix(f).String())
+ }
+ slices.Sort(got)
+ if !slices.Equal(got, want) {
+ t.Errorf("%s: IPAddressDeny=%s\n differs from staticDeny %v", filepath.Base(path), v, want)
+ }
+ }
+ }
+ if seen == 0 {
+ t.Fatal("no IPAddressDeny= line in any template")
+ }
+}
+
+// TestOnlyTheEdgeBindsAPrivilegedPort keeps true the three facts the plan
+// (evidence 8) rests on to rule out the fence's one residual: a process
+// outside the instances slice, bound to source port 80 or 443 on a box
+// address, can talk to an instance's TCP listener through it. Binding
+// below 1024 needs root or CAP_NET_BIND_SERVICE, so:
+//
+// 1. carlos-app@ (the legacy tenants outside the slice) has an empty
+// CapabilityBoundingSet=;
+// 2. the only unit the platform installs that grants CAP_NET_BIND_SERVICE
+// is carlos-edge.service, which holds :80 and :443 itself; the
+// capability renderer (internal/caps) grants no capability at all;
+// 3. nothing the tree installs lowers net.ipv4.ip_unprivileged_port_start.
+//
+// If one of these has to change, the residual has to be closed some other
+// way first (conntrack, or a BPF filter on the slice).
+func TestOnlyTheEdgeBindsAPrivilegedPort(t *testing.T) {
+ units := filepath.Join("..", "host", "units")
+ app, err := os.ReadFile(filepath.Join(units, "carlos-app@.service"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !strings.Contains("\n"+string(app), "\nCapabilityBoundingSet=\n") {
+ t.Error("carlos-app@.service must keep an empty CapabilityBoundingSet=")
+ }
+ paths, _ := filepath.Glob(filepath.Join(units, "*"))
+ for _, p := range paths {
+ b, err := os.ReadFile(p)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, line := range strings.Split(string(b), "\n") {
+ if strings.HasPrefix(line, "AmbientCapabilities=") && strings.Contains(line, "CAP_NET_BIND_SERVICE") && filepath.Base(p) != "carlos-edge.service" {
+ t.Errorf("%s grants CAP_NET_BIND_SERVICE: %s", filepath.Base(p), line)
+ }
+ }
+ }
+ renderers, _ := filepath.Glob(filepath.Join("..", "caps", "*.go"))
+ for _, p := range renderers {
+ if strings.HasSuffix(p, "_test.go") {
+ continue
+ }
+ b, _ := os.ReadFile(p)
+ if strings.Contains(string(b), "AmbientCapabilities") || strings.Contains(string(b), "CAP_NET_BIND_SERVICE") {
+ t.Errorf("%s renders a capability grant", p)
+ }
+ }
+ for _, root := range []string{filepath.Join("..", "host"), filepath.Join("..", "provision"), filepath.Join("..", "..", "infra")} {
+ _ = filepath.WalkDir(root, func(p string, d os.DirEntry, err error) error {
+ if err != nil || d.IsDir() || strings.HasSuffix(p, "_test.go") || strings.Contains(p, "testdata") {
+ return nil
+ }
+ b, _ := os.ReadFile(p)
+ if strings.Contains(string(b), "ip_unprivileged_port_start") {
+ t.Errorf("%s sets ip_unprivileged_port_start", p)
+ }
+ return nil
+ })
+ }
+}
diff --git a/internal/edgefence/testdata/readback-v4-v6.txt b/internal/edgefence/testdata/readback-v4-v6.txt
new file mode 100644
index 000000000..2436e344a
--- /dev/null
+++ b/internal/edgefence/testdata/readback-v4-v6.txt
@@ -0,0 +1,11 @@
+table inet carlos_edge_fence {
+ chain output {
+ type filter hook output priority -300; policy accept;
+ socket cgroupv2 level 2 "carlos.slice/carlos-instances.slice" ip daddr 198.51.100.7 tcp dport { 80, 443 } accept
+ socket cgroupv2 level 2 "carlos.slice/carlos-instances.slice" ip daddr 198.51.100.7 meta l4proto 6 reject with tcp reset
+ socket cgroupv2 level 2 "carlos.slice/carlos-instances.slice" ip daddr 198.51.100.7 drop
+ socket cgroupv2 level 2 "carlos.slice/carlos-instances.slice" ip6 daddr 2001:db8::7 tcp dport { 80, 443 } accept
+ socket cgroupv2 level 2 "carlos.slice/carlos-instances.slice" ip6 daddr 2001:db8::7 meta l4proto 6 reject with tcp reset
+ socket cgroupv2 level 2 "carlos.slice/carlos-instances.slice" ip6 daddr 2001:db8::7 drop
+ }
+}
diff --git a/internal/host/agent.go b/internal/host/agent.go
index b77c3e24b..50a5c1d02 100644
--- a/internal/host/agent.go
+++ b/internal/host/agent.go
@@ -604,6 +604,7 @@ func runAgent(args []string, buildClaims ClaimFactory) {
eb.Control = ctl
egressStatus = ctl
armExecSandboxStatus(ctl.SandboxStatus)
+ armEdgeFenceStatus(ctl.EdgeFence)
// A grant or revoke the agent converged into the registry reaches
// root on the next 2 s beat rather than root's 30 s loop (#328).
go egressNudgeLoop(agentCtx, reg, ctl)
diff --git a/internal/host/claimunit.go b/internal/host/claimunit.go
index b84640416..8eba28c5d 100644
--- a/internal/host/claimunit.go
+++ b/internal/host/claimunit.go
@@ -184,7 +184,9 @@ func claimUnitContent(name string, content []byte, cfg claimUnitSettings) []byte
}
content = bytes.Replace(content, []byte("[Service]\n"), []byte("[Service]\nStateDirectory=carlos-claims\nStateDirectoryMode=0700\n"), 1)
content = bytes.Replace(content, []byte("ReadWritePaths=/run/carlos-control /run/systemd/system\n"), []byte("ReadWritePaths="+strings.Join(roots, " ")+"\n"), 1)
- content = bytes.Replace(content, []byte("RestrictAddressFamilies=AF_UNIX\n"), []byte("RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6\n"), 1)
+ // The base unit's families carry AF_NETLINK for the edge fence (#990);
+ // claim mode keeps it (the fence is off in claim mode) and adds IP.
+ content = bytes.Replace(content, []byte("RestrictAddressFamilies=AF_UNIX AF_NETLINK\n"), []byte("RestrictAddressFamilies=AF_UNIX AF_NETLINK AF_INET AF_INET6\n"), 1)
// Claim mode adds the root journal service, the offline legacy migration
// (up to 16 MiB of decoded, validated and re-marshalled rows) and the AWS
// fence pass to this process. 64M leaves no headroom over the Go runtime
diff --git a/internal/host/claimunit_test.go b/internal/host/claimunit_test.go
index 9015c23d4..f03ad4e91 100644
--- a/internal/host/claimunit_test.go
+++ b/internal/host/claimunit_test.go
@@ -82,7 +82,7 @@ func TestClaimControlUnitInstallers(t *testing.T) {
"StateDirectory": {"carlos-claims"},
"StateDirectoryMode": {"0700"},
"ReadWritePaths": {"/run/carlos-control /run/carlos /var/lib/carlos-claims /var/lib/carlos-release/private /run/systemd/system /data /opt/carlos /etc/systemd/system /sys/fs/cgroup", "-/var/lib/carlos/oci-rootfs"},
- "RestrictAddressFamilies": {"AF_UNIX AF_INET AF_INET6"},
+ "RestrictAddressFamilies": {"AF_UNIX AF_NETLINK AF_INET AF_INET6"},
"ProtectSystem": {"strict"},
"ProtectHome": {"yes"},
} {
@@ -294,7 +294,7 @@ func TestClaimBadUnitSettingsStillRepairSystemUnits(t *testing.T) {
}
func TestPlan14RootRetryUnitDirectoryScope(t *testing.T) {
- raw := []byte("[Service]\nReadWritePaths=/run/carlos-control /run/systemd/system\nRestrictAddressFamilies=AF_UNIX\nMemoryMax=64M\n")
+ raw := []byte("[Service]\nReadWritePaths=/run/carlos-control /run/systemd/system\nRestrictAddressFamilies=AF_UNIX AF_NETLINK\nMemoryMax=64M\n")
legacy := claimUnitContent(claimControlUnit, raw, claimUnitSettings{enabled: true, data: "/data", opt: "/opt/carlos"})
if bytes.Contains(legacy, []byte(rootRetryProjection)) {
t.Fatal("no-census unit received E3 write access")
diff --git a/internal/host/execsandboxstatus.go b/internal/host/execsandboxstatus.go
index 04ad61a47..9a6cef23f 100644
--- a/internal/host/execsandboxstatus.go
+++ b/internal/host/execsandboxstatus.go
@@ -39,3 +39,27 @@ func execSandboxStatusReport() *status.ExecSandbox {
}
return report
}
+
+type edgeFenceStatusReader func(context.Context) (*instancectl.EdgeFenceReport, error)
+
+var armedEdgeFenceStatus atomic.Pointer[edgeFenceStatusReader]
+
+func armEdgeFenceStatus(read edgeFenceStatusReader) {
+ armedEdgeFenceStatus.Store(&read)
+}
+
+// edgeFenceStatusReport is root's edge fence state (#990) for the layout
+// report; nil (unknown) when root cannot be asked or does not say.
+func edgeFenceStatusReport() *status.EdgeFence {
+ read := armedEdgeFenceStatus.Load()
+ if read == nil {
+ return nil
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), instancectl.DeadlineReady)
+ defer cancel()
+ rep, err := (*read)(ctx)
+ if err != nil || rep == nil {
+ return nil
+ }
+ return &status.EdgeFence{State: rep.State, Reason: rep.Reason}
+}
diff --git a/internal/host/group_hairpin_test.go b/internal/host/group_hairpin_test.go
index 34d9278a3..19f69d306 100644
--- a/internal/host/group_hairpin_test.go
+++ b/internal/host/group_hairpin_test.go
@@ -108,7 +108,12 @@ func TestHairpinControlGroupDropIn(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- if strings.Contains(string(base), "carlos-hairpin") || strings.Contains(string(base), "AF_NETLINK") {
+ // AF_NETLINK is in the fixed unit too since #990 (the edge fence runs
+ // nft on every non-group box); the hairpin's runtime directory is not.
+ if strings.Contains(string(base), "carlos-hairpin") {
t.Fatal("group hairpin hardening escaped into fixed unit")
}
+ if !strings.Contains(string(base), "\nRestrictAddressFamilies=AF_UNIX AF_NETLINK\n") {
+ t.Fatal("the fixed control unit must allow netlink for the edge fence (#990)")
+ }
}
diff --git a/internal/host/layoutleg.go b/internal/host/layoutleg.go
index 497c93be7..909082b7d 100644
--- a/internal/host/layoutleg.go
+++ b/internal/host/layoutleg.go
@@ -187,6 +187,7 @@ func layoutStatusReport(routes []registry.Route) *status.LayoutReport {
if pass == nil {
report := unmanagedLayoutReport(routes)
report.ExecSandbox = execSandboxStatusReport()
+ report.EdgeFence = edgeFenceStatusReport()
return report
}
mode := lastLayoutIntent()
@@ -224,7 +225,7 @@ func layoutStatusReport(routes []registry.Route) *status.LayoutReport {
rows[rt.Host] = status.RowLayout{Layout: "external"}
}
}
- return &status.LayoutReport{Mode: mode, Rows: rows, Default: def.Applied, DefaultBlocked: def.Blocked, ExecSandbox: execSandboxStatusReport()}
+ return &status.LayoutReport{Mode: mode, Rows: rows, Default: def.Applied, DefaultBlocked: def.Blocked, ExecSandbox: execSandboxStatusReport(), EdgeFence: edgeFenceStatusReport()}
}
// Copy for a platform alias's row in `carlos status --layout` (#338,
diff --git a/internal/host/units/carlos-instance-control.service b/internal/host/units/carlos-instance-control.service
index dc47099a4..e5bb95044 100644
--- a/internal/host/units/carlos-instance-control.service
+++ b/internal/host/units/carlos-instance-control.service
@@ -52,6 +52,12 @@ PrivateDevices=yes
ProtectKernelTunables=yes
ProtectKernelModules=yes
ProtectKernelLogs=yes
-RestrictAddressFamilies=AF_UNIX
+# AF_NETLINK is nft's (#990, the edge fence): this service loads and reads
+# back the carlos_edge_fence table before it lets an instance reach the
+# edge on the box's own address. Without it nft fails and the whole #367
+# deny stays. The group drop-in (60-hairpin.conf) already adds it on group
+# boxes. nft's modules (nft_socket, nft_reject_inet) autoload despite
+# ProtectKernelModules=: the kernel's helper loads them outside this unit.
+RestrictAddressFamilies=AF_UNIX AF_NETLINK
MemoryDenyWriteExecute=yes
MemoryMax=64M
diff --git a/internal/host/units/carlos-instances.slice b/internal/host/units/carlos-instances.slice
index 2930ac8bc..b6d9b2c26 100644
--- a/internal/host/units/carlos-instances.slice
+++ b/internal/host/units/carlos-instances.slice
@@ -4,7 +4,18 @@
# walls are the per-host slices the control service sets the tier on. This
# level exists so the sampler has one root to scan and so an operator can
# `systemctl status carlos-instances.slice`.
+#
+# RefuseManualStop (#990, the edge fence): the fence's nft rules name this
+# slice by the cgroup id it had when they loaded, so a stop and a fresh
+# start leave them matching nothing. instance-control checks the fence
+# before every start it makes, and that check is what closes the gap; the
+# refusal is defence in depth against a unit started by hand after a
+# slice restart. Shutdown is unaffected. To stop every tenant at once:
+# systemctl stop 'carlos-instances-*.slice'
+# or, to signal them without stopping the units:
+# systemctl kill carlos-instances.slice
[Unit]
Description=carlos exec-backed instances
+RefuseManualStop=yes
[Slice]
diff --git a/internal/host/units/carlos.slice b/internal/host/units/carlos.slice
index 6f78ac1a9..ac5bb32fe 100644
--- a/internal/host/units/carlos.slice
+++ b/internal/host/units/carlos.slice
@@ -10,8 +10,14 @@
#
# Percentages so one file fits a t4g.micro and a t4g.medium; 80% leaves what
# the box's other units (keymail, console, ssm, litestream, journald) use.
+#
+# RefuseManualStop (#990): a stop here propagates to carlos-instances.slice
+# and recreates it, which a refusal on that slice alone does not catch (a
+# propagated stop is not a manual one). See carlos-instances.slice. Stop
+# the edge with `systemctl stop carlos-edge.service`, as before.
[Unit]
Description=carlos (edge, activator and every exec-backed instance)
+RefuseManualStop=yes
[Slice]
MemoryHigh=70%
diff --git a/internal/instancectl/client.go b/internal/instancectl/client.go
index 6120c8245..29f4ddb6b 100644
--- a/internal/instancectl/client.go
+++ b/internal/instancectl/client.go
@@ -479,6 +479,19 @@ func (c *Client) SandboxStatus(ctx context.Context) (execsandbox.State, error) {
return state, err
}
+// EdgeFence is the control service's edge fence state (#990), from its
+// /ready answer whether or not the box is ready. Nil, with no error, from
+// a control service too old to report it or one that has applied no deny
+// yet.
+func (c *Client) EdgeFence(ctx context.Context) (*EdgeFenceReport, error) {
+ rep, err := c.readyReport(ctx, "/ready", false)
+ var notReady *NotReadyError
+ if err != nil && !errors.As(err, &notReady) {
+ return nil, err
+ }
+ return rep.EdgeFence, nil
+}
+
// Egress asks root to re-assert host's egress allow now (#328), after
// the agent changed the host's registry column. The request names only
// the host: root reads the addresses from its own source. A 502 carries
diff --git a/internal/instancectl/edgefence.go b/internal/instancectl/edgefence.go
new file mode 100644
index 000000000..49cc599ae
--- /dev/null
+++ b/internal/instancectl/edgefence.go
@@ -0,0 +1,292 @@
+package instancectl
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "net/netip"
+ "slices"
+ "strings"
+
+ "github.com/carlosframework/platform/internal/edgefence"
+)
+
+// The edge fence (#990, plan 2026-11-13-same-box-calls-edge-fence): a
+// nested instance reaches the box's own global addresses on TCP 80 and
+// 443, the edge, and on nothing else, so an app can call another app on
+// its own box by hostname as it can call one on any other box.
+//
+// The invariant, kept here and nowhere else:
+//
+// An instance reaches an address of its own box only on TCP 80 or 443,
+// or the full #367 deny is in place.
+//
+// An address leaves the slice's IPAddressDeny= only while
+// edgefence.Verify passes for it, checked under denyMu after the fence
+// was (re)loaded. Every failure applies the full deny. Because nft names
+// the slice by the cgroup id it had when the table loaded, a recreated
+// slice leaves the rules matching nothing; guardStarts therefore runs the
+// readback before every unit start the service asks for, and the slice
+// is recreated only by a start (every instance template is Restart=no).
+// denyLoop re-reads the fence every tick while it exempts, which bounds
+// the one gap left, an nft flush while instances run, to one tick while
+// this service is up; Run checks the fence before it serves, because the
+// runtime deny drop-in outlives this process.
+//
+// Group-mode boxes never load the fence: the region HA hairpin owns their
+// box-address exemption (internal/hairpin).
+
+// EdgeFenceEnv is the host.env switch: "off" keeps the full #367 deny on
+// this box (the operator's rollback without a release).
+const EdgeFenceEnv = "CARLOS_EDGE_FENCE"
+
+// edgeFenceGroupBox reports a group-mode box; a var so tests can say.
+var edgeFenceGroupBox = groupHairpinMarker
+
+// fenceInternalKey marks the fence's own systemctl calls, which
+// guardStarts lets through: checking the fence before the slice start the
+// fence itself asks for would wait on denyMu, which the caller holds.
+type fenceInternalKey struct{}
+
+// Reasons the fence is not exempting, as the box reports them.
+const (
+ fenceOffSwitch = "turned off with " + EdgeFenceEnv + "=off"
+ fenceOffGroup = "a region group box: the group hairpin decides"
+ fenceOffNoAddr = "no public address on this box"
+ fenceOffUnwired = "not wired"
+ fenceOffClaims = "host claims mode"
+)
+
+// EdgeFenceState is what the box reports: whether same-box calls are on,
+// for which addresses, and why not when they are off.
+type EdgeFenceState struct {
+ On bool
+ Addresses []netip.Addr
+ Reason string
+}
+
+// EdgeFence is the fence's state as last applied.
+func (s *Server) EdgeFence() EdgeFenceState {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return EdgeFenceState{On: len(s.fenceAddrs) > 0, Addresses: slices.Clone(s.fenceAddrs), Reason: s.fenceReason}
+}
+
+// edgeFenceDeny is the deny for local and the addresses it exempts. The
+// exemption is non-empty only when the fence for exactly those addresses
+// has just read back as loaded; otherwise deny is local, whole, and
+// reason says why. The caller holds denyMu.
+func (s *Server) edgeFenceDeny(ctx context.Context, local []netip.Prefix) (deny []netip.Prefix, exempt []netip.Addr, reason string) {
+ switch {
+ case edgeFenceGroupBox():
+ return local, nil, fenceOffGroup
+ case s.EdgeFenceOff:
+ return local, nil, fenceOffSwitch
+ case s.NFT == nil:
+ return local, nil, fenceOffUnwired
+ case s.ClaimStop != nil:
+ // Claim launches start their units with their own systemctl
+ // (ClaimUnits), which guardStarts does not see. Host claims are
+ // shelved (2026-10-25); until a claim start checks the fence, a
+ // claims-mode box keeps the whole deny.
+ return local, nil, fenceOffClaims
+ }
+ addrs := edgefence.Addresses(local)
+ if len(addrs) == 0 {
+ return local, nil, fenceOffNoAddr
+ }
+ // nft resolves the slice's path when the table loads, and an empty
+ // slice may not exist: start it (a no-op when it runs) so the path
+ // names the cgroup the next instance will join.
+ internal := context.WithValue(ctx, fenceInternalKey{}, true)
+ if out, err := s.Systemctl(internal, "start", InstancesSlice); err != nil {
+ return local, nil, fmt.Sprintf("start %s: %s", InstancesSlice, strings.TrimSpace(out+" "+err.Error()))
+ }
+ if err := edgefence.Verify(ctx, s.NFT, addrs); err != nil {
+ if !s.fenceWasLoaded(addrs) {
+ err = nil // the first load, or a new address set: nothing to report
+ }
+ if ierr := edgefence.Install(ctx, s.NFT, addrs); ierr != nil {
+ return local, nil, ierr.Error()
+ }
+ if verr := edgefence.Verify(ctx, s.NFT, addrs); verr != nil {
+ return local, nil, verr.Error()
+ }
+ if err != nil {
+ s.logf("instance-control: edge fence: %v; reloaded", err)
+ }
+ }
+ deny = make([]netip.Prefix, 0, len(local))
+ for _, p := range local {
+ if p.IsSingleIP() && slices.Contains(addrs, p.Addr()) {
+ continue
+ }
+ deny = append(deny, p)
+ }
+ return deny, addrs, ""
+}
+
+// fenceWasLoaded reports whether the fence last applied was for addrs, so
+// a readback failure means it went away rather than was never there.
+func (s *Server) fenceWasLoaded(addrs []netip.Addr) bool {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return slices.Equal(s.fenceAddrs, addrs)
+}
+
+// recordFence remembers what the deny just applied exempts. The caller
+// holds denyMu and has applied the deny.
+func (s *Server) recordFence(exempt []netip.Addr, reason string) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if len(s.fenceAddrs) > 0 && len(exempt) == 0 {
+ s.logf("instance-control: edge fence: off, the full box-address deny applies: %s", reason)
+ }
+ if len(s.fenceAddrs) == 0 && len(exempt) > 0 {
+ s.logf("instance-control: edge fence: on for %v", exempt)
+ }
+ s.fenceAddrs = slices.Clone(exempt)
+ s.fenceReason = reason
+ s.fenceRetry = len(exempt) == 0 && !fenceOffSettled(reason)
+ s.denyApplied = true
+}
+
+// fenceOffSettled reports a reason the fence stays off for until the box
+// itself changes: the switch, a group box, claims mode, no public address,
+// no nft wired. Any other reason is a failure (a load, a readback, the
+// slice's start), which denyLoop retries every tick: the deny is whole
+// meanwhile, and same-box calls come back without waiting for a probe.
+// (Drill 2026-11-13: a refresh racing `systemctl stop carlos.slice` found
+// no slice to load against and stayed off until the next probe.)
+func fenceOffSettled(reason string) bool {
+ switch reason {
+ case fenceOffSwitch, fenceOffGroup, fenceOffNoAddr, fenceOffUnwired, fenceOffClaims:
+ return true
+ }
+ return false
+}
+
+// errFenceUnknown refuses a start before this service has applied any
+// deny: a deny drop-in left by an earlier process may exempt an address
+// whose fence nobody has checked.
+var errFenceUnknown = errors.New("edge fence: the box-address deny has not been applied since this service started; refusing the start")
+
+// fenceBeforeStart is guardStarts' check: when the applied deny exempts
+// an address, the fence must still read back as loaded, or the deny is
+// worked out again (reloading the fence, or the full deny) before the
+// start goes ahead. A service with no NFT, and a group box, never exempt
+// here and check nothing; a group box's starts stay off the hairpin lock.
+// Elsewhere hairpinLocked takes no lock (no group config), so denyMu is
+// what serialises this with the deny refresh.
+func (s *Server) fenceBeforeStart(ctx context.Context) error {
+ if s.NFT == nil || edgeFenceGroupBox() {
+ return nil
+ }
+ s.denyMu.Lock()
+ defer s.denyMu.Unlock()
+ s.mu.Lock()
+ addrs, applied := slices.Clone(s.fenceAddrs), s.denyApplied
+ s.mu.Unlock()
+ if !applied {
+ return errFenceUnknown
+ }
+ if len(addrs) == 0 {
+ return nil
+ }
+ err := edgefence.Verify(ctx, s.NFT, addrs)
+ if err == nil {
+ return nil
+ }
+ s.logf("instance-control: edge fence before a start: %v", err)
+ return s.denyLocalAddrsLocked(ctx, false)
+}
+
+// startVerbs are the systemctl verbs that can start a unit.
+var startVerbs = map[string]bool{"start": true, "restart": true, "try-restart": true, "reload-or-restart": true, "try-reload-or-restart": true}
+
+// guardStarts wraps systemctl so that every start the service asks for
+// runs fenceBeforeStart first, whatever the unit: one choke point rather
+// than a check at each start site, so a new start site is covered too.
+// The fence's own calls (fenceInternalKey) pass straight through.
+func (s *Server) guardStarts(raw func(context.Context, ...string) (string, error)) func(context.Context, ...string) (string, error) {
+ return func(ctx context.Context, args ...string) (string, error) {
+ if len(args) > 0 && startVerbs[args[0]] && ctx.Value(fenceInternalKey{}) == nil {
+ if err := s.fenceBeforeStart(ctx); err != nil {
+ return "", err
+ }
+ }
+ return raw(ctx, args...)
+ }
+}
+
+// bindEgressFence puts fenceBeforeStart in front of the egress asserter's
+// restarts (#328): it restarts instance units with a systemctl of its own,
+// which guardStarts does not wrap, after asking RestartAllowed.
+func (s *Server) bindEgressFence() {
+ if s.Egress == nil {
+ return
+ }
+ previous := s.Egress.RestartAllowed
+ s.Egress.RestartAllowed = func(ctx context.Context) error {
+ if err := s.fenceBeforeStart(ctx); err != nil {
+ return err
+ }
+ if previous != nil {
+ return previous(ctx)
+ }
+ return nil
+ }
+}
+
+// edgeFenceReport is the fence's state for /ready, or nil before this
+// service has applied any deny (nothing to report yet).
+func (s *Server) edgeFenceReport() *EdgeFenceReport {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if !s.denyApplied {
+ return nil
+ }
+ if len(s.fenceAddrs) > 0 {
+ return &EdgeFenceReport{State: EdgeFenceOn}
+ }
+ return &EdgeFenceReport{State: EdgeFenceOff, Reason: s.fenceReason}
+}
+
+// fenceOffUnread is the reason when the box's addresses could not be read
+// and the remembered fence did not read back or reload.
+const fenceOffUnread = "the box's addresses could not be read and the fence did not read back"
+
+// fenceWithoutAddresses keeps the invariant when the box's addresses
+// cannot be read while the applied deny exempts some for the edge fence
+// (review round 1, P1): the fence for the remembered addresses must read
+// back, or reload, or the whole deny is rebuilt from what was last
+// applied plus those addresses and applied. whole reports that last case.
+// The caller holds denyMu.
+func (s *Server) fenceWithoutAddresses(ctx context.Context) (whole bool, err error) {
+ s.mu.Lock()
+ addrs, last := slices.Clone(s.fenceAddrs), slices.Clone(s.lastDeny)
+ s.mu.Unlock()
+ if len(addrs) == 0 || s.NFT == nil {
+ return false, nil
+ }
+ verr := edgefence.Verify(ctx, s.NFT, addrs)
+ if verr == nil {
+ return false, nil
+ }
+ internal := context.WithValue(ctx, fenceInternalKey{}, true)
+ if _, serr := s.Systemctl(internal, "start", InstancesSlice); serr == nil {
+ if edgefence.Install(ctx, s.NFT, addrs) == nil && edgefence.Verify(ctx, s.NFT, addrs) == nil {
+ s.logf("instance-control: edge fence: %v; reloaded (the box's addresses could not be read)", verr)
+ return false, nil
+ }
+ }
+ rebuilt := last
+ for _, a := range addrs {
+ rebuilt = append(rebuilt, netip.PrefixFrom(a, a.BitLen()))
+ }
+ if err := s.applyLocalDeny(ctx, rebuilt, true); err != nil {
+ return false, fmt.Errorf("edge fence: %v; the whole deny could not be applied: %w", verr, err)
+ }
+ s.recordFence(nil, fenceOffUnread)
+ return true, verr
+}
diff --git a/internal/instancectl/edgefence_test.go b/internal/instancectl/edgefence_test.go
new file mode 100644
index 000000000..a397666e0
--- /dev/null
+++ b/internal/instancectl/edgefence_test.go
@@ -0,0 +1,567 @@
+package instancectl
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "net/http"
+ "net/netip"
+ "os"
+ "path/filepath"
+ "regexp"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/edgefence"
+)
+
+// fakeNFT models the one table the fence owns: loaded or not, and, once
+// the slice is recreated (stale), printed with a bare cgroup id as nft
+// does (plan evidence 4).
+type fakeNFT struct {
+ mu sync.Mutex
+ loaded string // the table's text as nft would print it; "" when not loaded
+ stale bool
+ failLoad error
+ loads int
+ readbacks int
+ log []string
+}
+
+var tableBody = regexp.MustCompile(`(?s)table inet ` + edgefence.Table + ` \{.*`)
+
+func (f *fakeNFT) run(_ context.Context, input string, args ...string) ([]byte, error) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ line := strings.Join(args, " ")
+ f.log = append(f.log, line)
+ switch line {
+ case "nft -f -":
+ f.loads++
+ if f.failLoad != nil {
+ return []byte("Error: Could not process rule"), f.failLoad
+ }
+ f.loaded, f.stale = tableBody.FindString(input), false
+ return nil, nil
+ case "nft -s -nn -y list table inet " + edgefence.Table:
+ f.readbacks++
+ if f.loaded == "" {
+ return []byte("Error: No such file or directory"), errors.New("exit status 1")
+ }
+ if f.stale {
+ return []byte(strings.ReplaceAll(f.loaded, fmt.Sprintf("%q", edgefence.Cgroup), "803329")), nil
+ }
+ return []byte(f.loaded), nil
+ }
+ return nil, fmt.Errorf("unexpected nft call %q", line)
+}
+
+func (f *fakeNFT) set(fn func(*fakeNFT)) { f.mu.Lock(); defer f.mu.Unlock(); fn(f) }
+func (f *fakeNFT) counts() (loads, readbacks int) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return f.loads, f.readbacks
+}
+
+// A box like leo-bookbinding: one public IPv4 on its interface, plus a
+// private one and a global IPv6 for coverage.
+var fenceLocal = func() ([]netip.Prefix, error) {
+ return parsePrefixes("127.0.0.0/8", "172.31.7.19/32", "203.0.113.7/32", "2001:db8::7/128", "fe80::1/128"), nil
+}
+
+const (
+ wholeDeny = "IPAddressDeny=127.0.0.0/8 172.31.7.19/32 2001:db8::7/128 203.0.113.7/32 fe80::1/128"
+ fencedDeny = "IPAddressDeny=127.0.0.0/8 172.31.7.19/32 fe80::1/128"
+)
+
+func notGroup(t *testing.T) {
+ t.Helper()
+ old := edgeFenceGroupBox
+ edgeFenceGroupBox = func() bool { return false }
+ t.Cleanup(func() { edgeFenceGroupBox = old })
+}
+
+func fenceServer(t *testing.T) (*Server, *fakeCtl, *fakeNFT) {
+ t.Helper()
+ notGroup(t)
+ ctl, nft := &fakeCtl{}, &fakeNFT{}
+ s := &Server{Systemctl: ctl.run, Logf: t.Logf, LocalAddrs: fenceLocal, NFT: nft.run}
+ return s, ctl, nft
+}
+
+// #990: the box's global addresses leave the deny only after the fence for
+// exactly those addresses reads back as loaded, and the slice is started
+// before the load so the rules name the cgroup instances will join.
+func TestEdgeFenceExemptsOnlyAfterTheReadback(t *testing.T) {
+ s, ctl, nft := fenceServer(t)
+ if err := s.denyLocalAddrs(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ ctl.mustHaveCallsInOrder(t, "start "+InstancesSlice, "set-property --runtime "+InstancesSlice+" IPAddressDeny= "+fencedDeny)
+ if got := strings.Join(nft.log, "; "); got != "nft -s -nn -y list table inet carlos_edge_fence; nft -f -; nft -s -nn -y list table inet carlos_edge_fence" {
+ t.Fatalf("nft calls: %s", got)
+ }
+ want, _ := edgefence.Rules([]netip.Addr{netip.MustParseAddr("203.0.113.7"), netip.MustParseAddr("2001:db8::7")})
+ if nft.loaded != want {
+ t.Fatalf("loaded %q, want %q", nft.loaded, want)
+ }
+ st := s.EdgeFence()
+ if !st.On || len(st.Addresses) != 2 || st.Reason != "" {
+ t.Fatalf("state = %+v", st)
+ }
+}
+
+// Every way the fence can fail leaves the deny whole and says why.
+func TestEdgeFenceFailuresKeepTheWholeDeny(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ setup func(*fakeCtl, *fakeNFT)
+ reason string
+ }{
+ {"the load fails", func(_ *fakeCtl, n *fakeNFT) { n.failLoad = errors.New("exit status 1") }, "load"},
+ {"the slice cannot start", func(c *fakeCtl, _ *fakeNFT) {
+ c.fail = map[string]error{"start": errors.New("exit status 5")}
+ }, "start " + InstancesSlice},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ s, ctl, nft := fenceServer(t)
+ tc.setup(ctl, nft)
+ if err := s.denyLocalAddrs(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ if n := ctl.count(wholeDeny); n != 1 {
+ t.Fatalf("whole deny applied %d times; calls %q", n, ctl.joined())
+ }
+ st := s.EdgeFence()
+ if st.On || !strings.Contains(st.Reason, tc.reason) {
+ t.Fatalf("state = %+v, want off naming %q", st, tc.reason)
+ }
+ })
+ }
+}
+
+// A readback that differs after a load (here: the slice recreated between
+// the load and the readback) is a failure too.
+func TestEdgeFenceRefusesAReadbackThatDiffersAfterTheLoad(t *testing.T) {
+ s, ctl, _ := fenceServer(t)
+ stale := &fakeNFT{}
+ s.NFT = func(ctx context.Context, input string, args ...string) ([]byte, error) {
+ out, err := stale.run(ctx, input, args...)
+ if args[1] == "-f" {
+ stale.set(func(f *fakeNFT) { f.stale = true })
+ }
+ return out, err
+ }
+ if err := s.denyLocalAddrs(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ if n := ctl.count(wholeDeny); n != 1 {
+ t.Fatalf("whole deny applied %d times; calls %q", n, ctl.joined())
+ }
+ if st := s.EdgeFence(); st.On || !strings.Contains(st.Reason, "recreated") {
+ t.Fatalf("state = %+v", st)
+ }
+}
+
+// The off switch, a group box, a claims-mode box, a box with no public
+// address and a service with no NFT never touch nft or the slice, and
+// keep the deny whole.
+func TestEdgeFenceOffCases(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ setup func(*Server)
+ reason string
+ }{
+ {"off switch", func(s *Server) { s.EdgeFenceOff = true }, fenceOffSwitch},
+ {"group box", func(*Server) { edgeFenceGroupBox = func() bool { return true } }, fenceOffGroup},
+ {"claims mode", func(s *Server) { s.ClaimStop = http.NotFoundHandler() }, fenceOffClaims},
+ {"no public address", func(s *Server) {
+ s.LocalAddrs = func() ([]netip.Prefix, error) { return parsePrefixes("127.0.0.0/8", "172.31.7.19/32"), nil }
+ }, fenceOffNoAddr},
+ {"no nft", func(s *Server) { s.NFT = nil }, fenceOffUnwired},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ s, ctl, nft := fenceServer(t)
+ tc.setup(s)
+ if err := s.denyLocalAddrs(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ if len(nft.log) != 0 {
+ t.Fatalf("nft ran: %v", nft.log)
+ }
+ if ctl.count("start") != 0 {
+ t.Fatalf("the slice was started: %q", ctl.joined())
+ }
+ if ctl.count("set-property") != 1 || ctl.count(fencedDeny) != 0 {
+ t.Fatalf("calls %q", ctl.joined())
+ }
+ if st := s.EdgeFence(); st.On || st.Reason != tc.reason {
+ t.Fatalf("state = %+v, want reason %q", st, tc.reason)
+ }
+ })
+ }
+}
+
+// While the fence exempts, every tick reads it back, addresses changed or
+// not, without setting an unchanged deny again. A flushed table is
+// reloaded on the next tick; one that cannot be reloaded puts the whole
+// deny back.
+func TestDenyLoopRereadsTheFenceEveryTick(t *testing.T) {
+ s, ctl, nft := fenceServer(t)
+ ticks, handled := make(chan time.Time), make(chan struct{})
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ go s.denyLoopWith(ctx, ticks, func() { handled <- struct{}{} })
+ tick := func() { ticks <- time.Time{}; <-handled }
+
+ tick()
+ if n := ctl.count(fencedDeny); n != 1 {
+ t.Fatalf("first tick: fenced deny applied %d times; %q", n, ctl.joined())
+ }
+ _, before := nft.counts()
+ for i := 0; i < 3; i++ {
+ tick()
+ }
+ if _, after := nft.counts(); after != before+3 {
+ t.Fatalf("3 ticks with unchanged addresses read the fence back %d times, want 3", after-before)
+ }
+ if n := ctl.count("set-property"); n != 1 {
+ t.Fatalf("an unchanged deny was set again: %d set-property calls", n)
+ }
+
+ // `systemctl reload nftables` flushed the ruleset.
+ nft.set(func(f *fakeNFT) { f.loaded = "" })
+ loads, _ := nft.counts()
+ tick()
+ if l, _ := nft.counts(); l != loads+1 {
+ t.Fatalf("a flushed fence was not reloaded on the next tick")
+ }
+ if !s.EdgeFence().On || ctl.count("set-property") != 1 {
+ t.Fatalf("a reloaded fence changed the deny: %q", ctl.joined())
+ }
+
+ // Flushed again, and now it cannot load: the whole deny returns.
+ nft.set(func(f *fakeNFT) { f.loaded, f.failLoad = "", errors.New("exit status 1") })
+ tick()
+ if n := ctl.count(wholeDeny); n != 1 {
+ t.Fatalf("whole deny applied %d times after a failed reload; %q", n, ctl.joined())
+ }
+ if s.EdgeFence().On {
+ t.Fatal("the fence still reads as on")
+ }
+}
+
+// guardStarts refuses a start before this service has applied a deny, and
+// otherwise checks the fence before every start: a slice recreated under a
+// loaded fence (bare cgroup id) gets a fresh fence, or the whole deny,
+// before the unit starts.
+func TestGuardStartsChecksTheFenceBeforeEveryStart(t *testing.T) {
+ s, ctl, nft := fenceServer(t)
+ s.Systemctl = s.guardStarts(ctl.run)
+ ctx := context.Background()
+
+ if _, err := s.Systemctl(ctx, "start", "carlos-instance@a.service"); !errors.Is(err, errFenceUnknown) {
+ t.Fatalf("start before any deny: %v", err)
+ }
+ if ctl.count("carlos-instance@a.service") != 0 {
+ t.Fatal("the unit started")
+ }
+ if err := s.denyLocalAddrs(ctx); err != nil {
+ t.Fatal(err)
+ }
+
+ _, before := nft.counts()
+ if _, err := s.Systemctl(ctx, "start", "carlos-instance@a.service"); err != nil {
+ t.Fatal(err)
+ }
+ if _, after := nft.counts(); after != before+1 {
+ t.Fatalf("the start read the fence back %d times, want 1", after-before)
+ }
+ // Verbs that start nothing are not checked.
+ if _, err := s.Systemctl(ctx, "stop", "carlos-instance@a.service"); err != nil {
+ t.Fatal(err)
+ }
+ if _, after := nft.counts(); after != before+1 {
+ t.Fatal("a stop read the fence back")
+ }
+
+ // The slice was stopped and is about to be recreated by this start.
+ nft.set(func(f *fakeNFT) { f.stale = true })
+ loads, _ := nft.counts()
+ if _, err := s.Systemctl(ctx, "restart", "carlos-instance@a.service"); err != nil {
+ t.Fatal(err)
+ }
+ if l, _ := nft.counts(); l != loads+1 {
+ t.Fatal("a stale fence was not reloaded before the restart")
+ }
+ ctl.mustHaveCallsInOrder(t, "start "+InstancesSlice, "restart carlos-instance@a.service")
+
+ // Stale again, and the reload fails: the whole deny is set before the
+ // unit starts.
+ nft.set(func(f *fakeNFT) { f.stale, f.failLoad = true, errors.New("exit status 1") })
+ if _, err := s.Systemctl(ctx, "start", "carlos-instance@b.service"); err != nil {
+ t.Fatal(err)
+ }
+ ctl.mustHaveCallsInOrder(t, "set-property --runtime "+InstancesSlice+" IPAddressDeny= "+wholeDeny, "start carlos-instance@b.service")
+}
+
+// A whole deny that cannot be set when the fence fails before a start
+// refuses the start: the last deny may exempt an address nothing fences.
+func TestGuardStartsRefusesWhenTheWholeDenyCannotBeSet(t *testing.T) {
+ s, ctl, nft := fenceServer(t)
+ s.Systemctl = s.guardStarts(ctl.run)
+ ctx := context.Background()
+ if err := s.denyLocalAddrs(ctx); err != nil {
+ t.Fatal(err)
+ }
+ nft.set(func(f *fakeNFT) { f.loaded, f.failLoad = "", errors.New("exit status 1") })
+ ctl.mu.Lock()
+ ctl.fail = map[string]error{"set-property": errors.New("exit status 1")}
+ ctl.mu.Unlock()
+ if _, err := s.Systemctl(ctx, "start", "carlos-instance@a.service"); err == nil {
+ t.Fatal("the start went ahead")
+ }
+ if ctl.count("start carlos-instance@a.service") != 0 {
+ t.Fatal("the unit started")
+ }
+}
+
+// The egress asserter restarts instance units with a systemctl of its own;
+// its RestartAllowed runs the fence check first.
+func TestEgressRestartsCheckTheFence(t *testing.T) {
+ s, _, _ := fenceServer(t)
+ called := false
+ s.Egress = &EgressAsserter{RestartAllowed: func(context.Context) error { called = true; return nil }}
+ s.bindEgressFence()
+ if err := s.Egress.RestartAllowed(context.Background()); !errors.Is(err, errFenceUnknown) {
+ t.Fatalf("restart before any deny: %v", err)
+ }
+ if called {
+ t.Fatal("the earlier hook ran after the fence refused")
+ }
+ if err := s.denyLocalAddrs(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ if err := s.Egress.RestartAllowed(context.Background()); err != nil || !called {
+ t.Fatalf("after the deny: %v, earlier hook ran %v", err, called)
+ }
+}
+
+// Every start the package asks systemd for goes through a systemctl the
+// fence check sees: the Server's (guardStarts), the egress asserter's
+// (RestartAllowed, bindEgressFence), or a claim unit's (the fence stays
+// off in claims mode). A start site on any other systemctl, or on exec
+// directly, would start a unit behind the fence check; this test names
+// it.
+func TestEveryStartIsSeenByTheFenceCheck(t *testing.T) {
+ paths, err := filepath.Glob("*.go")
+ if err != nil {
+ t.Fatal(err)
+ }
+ call := regexp.MustCompile(`([\w.]+)\.Systemctl\(\w+, "(start|restart|try-restart|reload-or-restart|try-reload-or-restart)"`)
+ direct := regexp.MustCompile(`"systemctl", "(start|restart|try-restart)"`)
+ allowed := map[string]bool{"s": true, "p.s": true, "e": true, "u": true}
+ seen := 0
+ for _, path := range paths {
+ if strings.HasSuffix(path, "_test.go") {
+ continue
+ }
+ b, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for i, line := range strings.Split(string(b), "\n") {
+ if m := call.FindStringSubmatch(line); m != nil {
+ seen++
+ if !allowed[m[1]] {
+ t.Errorf("%s:%d: %s starts a unit through %s.Systemctl, which the fence check does not see", path, i+1, m[2], m[1])
+ }
+ }
+ if direct.MatchString(line) {
+ t.Errorf("%s:%d: a unit started by exec, not through a fenced systemctl", path, i+1)
+ }
+ }
+ }
+ if seen < 10 {
+ t.Fatalf("found %d start sites; the pattern has stopped matching them", seen)
+ }
+}
+
+// /ready carries the fence's state once a deny has been applied: on, or
+// off with the reason (a box with no public address is off, saying so,
+// never "not needed": review round 1, P2).
+func TestEdgeFenceReport(t *testing.T) {
+ s, _, _ := fenceServer(t)
+ if r := s.edgeFenceReport(); r != nil {
+ t.Fatalf("before any deny: %+v", r)
+ }
+ if err := s.denyLocalAddrs(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ if r := s.edgeFenceReport(); r == nil || r.State != EdgeFenceOn || r.Reason != "" {
+ t.Fatalf("fence on: %+v", r)
+ }
+ s.EdgeFenceOff = true
+ if err := s.denyLocalAddrs(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ if r := s.edgeFenceReport(); r == nil || r.State != EdgeFenceOff || r.Reason != fenceOffSwitch {
+ t.Fatalf("switched off: %+v", r)
+ }
+ s.EdgeFenceOff = false
+ s.LocalAddrs = func() ([]netip.Prefix, error) { return parsePrefixes("127.0.0.0/8", "172.31.7.19/32"), nil }
+ if err := s.denyLocalAddrs(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ if r := s.edgeFenceReport(); r == nil || r.State != EdgeFenceOff || r.Reason != fenceOffNoAddr {
+ t.Fatalf("no public address on the box: %+v", r)
+ }
+}
+
+// The agent reads the state from /ready whether or not the box is ready.
+func TestClientReadsTheEdgeFenceFromANotReadyBox(t *testing.T) {
+ notGroup(t)
+ nft := &fakeNFT{}
+ ctl := &fakeCtl{}
+ s, sock := serveOnSocket(t, ctl, func(s *Server) { s.LocalAddrs, s.NFT = fenceLocal, nft.run })
+ if err := s.denyLocalAddrs(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ s.mu.Lock()
+ s.report, s.probed = ProbeReport{Ready: false, Lines: []VerdictLine{{Check: "x", Verdict: "fail"}}}, true
+ s.mu.Unlock()
+ c := &Client{Path: sock}
+ got, err := c.EdgeFence(context.Background())
+ if err != nil || got == nil || got.State != EdgeFenceOn {
+ t.Fatalf("EdgeFence = %+v, %v", got, err)
+ }
+}
+
+// A fence that failed to load is tried again on every tick, with the
+// whole deny standing meanwhile and set only once, and comes back on
+// without waiting for the next probe. A settled reason (the off switch)
+// is not retried.
+func TestDenyLoopRetriesAFailedFence(t *testing.T) {
+ s, ctl, nft := fenceServer(t)
+ nft.set(func(f *fakeNFT) { f.failLoad = errors.New("exit status 1") })
+ ticks, handled := make(chan time.Time), make(chan struct{})
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ go s.denyLoopWith(ctx, ticks, func() { handled <- struct{}{} })
+ tick := func() { ticks <- time.Time{}; <-handled }
+
+ tick()
+ tick()
+ tick()
+ if n := ctl.count(wholeDeny); n != 1 {
+ t.Fatalf("whole deny set %d times over 3 failing ticks, want 1; %q", n, ctl.joined())
+ }
+ if loads, _ := nft.counts(); loads != 3 {
+ t.Fatalf("%d loads over 3 failing ticks, want 3", loads)
+ }
+ nft.set(func(f *fakeNFT) { f.failLoad = nil })
+ tick()
+ if !s.EdgeFence().On || ctl.count(fencedDeny) != 1 {
+ t.Fatalf("the fence did not come back on the next tick: %+v %q", s.EdgeFence(), ctl.joined())
+ }
+
+ s.EdgeFenceOff = true
+ tick()
+ loads, _ := nft.counts()
+ tick()
+ tick()
+ if l, _ := nft.counts(); l != loads {
+ t.Fatal("a fence switched off was retried")
+ }
+}
+
+// Review round 1, P1: with the fence exempting and the box's addresses
+// unreadable, a flushed fence is still checked every tick: reloaded for
+// the remembered addresses, or the whole deny rebuilt from the last deny
+// plus those addresses. The pre-start check does the same and refuses the
+// start.
+func TestFenceIsCheckedWhenAddressesCannotBeRead(t *testing.T) {
+ unreadable := func() ([]netip.Prefix, error) { return nil, errors.New("fib_trie: permission denied") }
+ loop := func(t *testing.T, s *Server) func() {
+ ticks, handled := make(chan time.Time), make(chan struct{})
+ ctx, cancel := context.WithCancel(context.Background())
+ t.Cleanup(cancel)
+ go s.denyLoopWith(ctx, ticks, func() { handled <- struct{}{} })
+ return func() { ticks <- time.Time{}; <-handled }
+ }
+
+ t.Run("reloaded", func(t *testing.T) {
+ s, ctl, nft := fenceServer(t)
+ tick := loop(t, s)
+ tick()
+ s.mu.Lock()
+ s.LocalAddrs = unreadable
+ s.mu.Unlock()
+ nft.set(func(f *fakeNFT) { f.loaded = "" })
+ _, before := nft.counts()
+ for i := 0; i < 3; i++ {
+ tick()
+ }
+ if _, after := nft.counts(); after-before < 3 {
+ t.Fatalf("%d readbacks over 3 ticks with unreadable addresses", after-before)
+ }
+ if loads, _ := nft.counts(); loads != 2 {
+ t.Fatalf("loads = %d, want the first and one reload", loads)
+ }
+ if !s.EdgeFence().On || ctl.count("set-property") != 1 {
+ t.Fatalf("a reloaded fence changed the deny: %+v %q", s.EdgeFence(), ctl.joined())
+ }
+ })
+
+ t.Run("whole deny", func(t *testing.T) {
+ s, ctl, nft := fenceServer(t)
+ tick := loop(t, s)
+ tick()
+ s.mu.Lock()
+ s.LocalAddrs = unreadable
+ s.mu.Unlock()
+ nft.set(func(f *fakeNFT) { f.loaded, f.failLoad = "", errors.New("exit status 1") })
+ tick()
+ if n := ctl.count(wholeDeny); n != 1 {
+ t.Fatalf("whole deny applied %d times; %q", n, ctl.joined())
+ }
+ if r := s.edgeFenceReport(); r == nil || r.State != EdgeFenceOff || r.Reason != fenceOffUnread {
+ t.Fatalf("/ready = %+v", r)
+ }
+ tick()
+ tick()
+ if n := ctl.count("set-property"); n != 2 {
+ t.Fatalf("set-property %d times, want the fenced deny then the whole one", n)
+ }
+ // Addresses readable and nft working again: the fence comes back.
+ s.mu.Lock()
+ s.LocalAddrs = fenceLocal
+ s.mu.Unlock()
+ nft.set(func(f *fakeNFT) { f.failLoad = nil })
+ tick()
+ if !s.EdgeFence().On || ctl.count(fencedDeny) != 2 {
+ t.Fatalf("the fence did not come back: %+v %q", s.EdgeFence(), ctl.joined())
+ }
+ })
+
+ t.Run("before a start", func(t *testing.T) {
+ s, ctl, nft := fenceServer(t)
+ s.Systemctl = s.guardStarts(ctl.run)
+ if err := s.denyLocalAddrs(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ s.LocalAddrs = unreadable
+ nft.set(func(f *fakeNFT) { f.stale, f.failLoad = true, errors.New("exit status 1") })
+ if _, err := s.Systemctl(context.Background(), "start", "carlos-instance@a.service"); err == nil {
+ t.Fatal("the start went ahead")
+ }
+ if ctl.count("start carlos-instance@a.service") != 0 {
+ t.Fatal("the unit started")
+ }
+ if n := ctl.count(wholeDeny); n != 1 {
+ t.Fatalf("whole deny applied %d times before the refusal; %q", n, ctl.joined())
+ }
+ })
+}
diff --git a/internal/instancectl/hardening.go b/internal/instancectl/hardening.go
index 2e4eb43dd..0738cb663 100644
--- a/internal/instancectl/hardening.go
+++ b/internal/instancectl/hardening.go
@@ -290,7 +290,18 @@ func (s *Server) allowResolvers(ctx context.Context) (refused []string, err erro
// (the last deny stands) and returns the error. What it applied is
// remembered in lastDeny, for denyLoop. denyMu runs one call at a time, so
// an older read can never be applied over a newer one.
+//
+// The edge fence (#990, edgefence.go) may exempt the box's global
+// addresses from the deny, and only after its table reads back as loaded
+// for exactly those addresses; every failure leaves the deny whole.
func (s *Server) denyLocalAddrs(ctx context.Context) error {
+ return s.denyLocalAddrsWith(ctx, false)
+}
+
+// denyLocalAddrsWith is denyLocalAddrs; refresh is denyLoop's tick, which
+// re-checks the fence but does not set an unchanged deny again (setting
+// it re-attaches the slice's address filters under every instance).
+func (s *Server) denyLocalAddrsWith(ctx context.Context, refresh bool) error {
ctx, unlock, lockErr := hairpinLocked(ctx)
if lockErr != nil {
return lockErr
@@ -298,15 +309,42 @@ func (s *Server) denyLocalAddrs(ctx context.Context) error {
defer unlock()
s.denyMu.Lock()
defer s.denyMu.Unlock()
+ return s.denyLocalAddrsLocked(ctx, refresh)
+}
+
+// denyLocalAddrsLocked is denyLocalAddrsWith under denyMu (and the hairpin
+// lock, where there is one).
+func (s *Server) denyLocalAddrsLocked(ctx context.Context, refresh bool) error {
local, err := s.localPrefixes()
if err != nil {
- return fmt.Errorf("this box's addresses: %v; the last deny stands", err)
+ // #990: the last deny stands, but if it exempts addresses for the
+ // edge fence, that fence is checked from what was remembered:
+ // reloaded, or the whole deny rebuilt (review round 1, P1).
+ whole, fenceErr := s.fenceWithoutAddresses(ctx)
+ if whole {
+ return errors.Join(fmt.Errorf("this box's addresses: %v; the whole box-address deny applies", err), fenceErr)
+ }
+ return errors.Join(fmt.Errorf("this box's addresses: %v; the last deny stands", err), fenceErr)
}
local, hairpinErr := s.hairpinDeny(ctx, local)
if hairpinErr != nil {
return hairpinErr
}
- return s.applyLocalDeny(ctx, local, false)
+ deny, exempt, reason := s.edgeFenceDeny(ctx, local)
+ if refresh {
+ s.mu.Lock()
+ unchanged := slices.Equal(denySet(deny), s.lastDeny)
+ s.mu.Unlock()
+ if unchanged {
+ s.recordFence(exempt, reason)
+ return nil
+ }
+ }
+ if err := s.applyLocalDeny(ctx, deny, false); err != nil {
+ return err
+ }
+ s.recordFence(exempt, reason)
+ return nil
}
// The caller holds denyMu. A failed hairpin readback forces a full deny even
@@ -394,15 +432,29 @@ func (s *Server) denyLoopWith(ctx context.Context, ticks <-chan time.Time, done
case <-ticks:
}
local, err := s.localPrefixes()
+ if err != nil {
+ // #990: an exempting fence is still checked when the addresses
+ // cannot be read (fenceWithoutAddresses).
+ s.mu.Lock()
+ fence := len(s.fenceAddrs) > 0
+ s.mu.Unlock()
+ if fence {
+ err = s.denyLocalAddrsWith(ctx, true)
+ }
+ }
logErr(err)
if err == nil {
s.mu.Lock()
previous := slices.Clone(s.lastDeny)
unchanged := slices.Equal(denySet(local), previous)
active := s.hairpinActive
+ // #990: while the edge fence exempts, every tick re-reads it,
+ // addresses changed or not; while it is off after a failure,
+ // every tick tries it again.
+ fence := len(s.fenceAddrs) > 0 || s.fenceRetry
s.mu.Unlock()
- if !unchanged || active {
- err := s.denyLocalAddrs(ctx)
+ if !unchanged || active || fence {
+ err := s.denyLocalAddrsWith(ctx, fence)
logErr(err)
if err == nil {
s.mu.Lock()
@@ -453,7 +505,8 @@ func probeBoxAddrs(local []netip.Prefix) []netip.Addr {
}
// writeProbeBoxAddrs writes probeBoxAddrs of the box's addresses to
-// dir/ProbeBoxAddrsName, one address a line, 0644, through a temp file
+// dir/ProbeBoxAddrsName, one address a line, followed by " edge" where
+// the edge fence exempts it (#990), 0644, through a temp file
// renamed into place (root's file; the probe binds it read-only). When
// the addresses cannot be read it writes nothing and returns the error.
func (s *Server) writeProbeBoxAddrs(dir string) error {
@@ -461,9 +514,14 @@ func (s *Server) writeProbeBoxAddrs(dir string) error {
if err != nil {
return fmt.Errorf("this box's addresses: %w", err)
}
+ fenced := s.EdgeFence().Addresses
var b strings.Builder
for _, a := range probeBoxAddrs(local) {
- b.WriteString(a.String() + "\n")
+ b.WriteString(a.String())
+ if slices.Contains(fenced, a) {
+ b.WriteString(" " + BoxAddrFenceMark)
+ }
+ b.WriteString("\n")
}
return writeFileExcl(filepath.Join(dir, ProbeBoxAddrsName), []byte(b.String()), 0o644)
}
diff --git a/internal/instancectl/names.go b/internal/instancectl/names.go
index f151c68cf..08b95453f 100644
--- a/internal/instancectl/names.go
+++ b/internal/instancectl/names.go
@@ -565,6 +565,9 @@ const RootfsReadyPath = "/ready/rootfs"
const (
BoxAddrsPath = "/opt/carlos/box-addrs"
ProbeBoxAddrsName = "box-addrs"
+ // BoxAddrFenceMark follows an address in box-addrs when the edge fence
+ // exempts it (#990): the probe then expects the edge to answer there.
+ BoxAddrFenceMark = "edge"
)
// ProbePtsPrivateEnv is the binary probe unit's advertisement that its
@@ -652,8 +655,27 @@ type ProbeReport struct {
Ready bool `json:"ready"`
Lines []VerdictLine `json:"lines"`
Nonce string `json:"nonce,omitempty"`
+ // EdgeFence is the edge fence's state (#990), added by /ready from the
+ // deny last applied; the probe never sets it. Absent from an older
+ // control service.
+ EdgeFence *EdgeFenceReport `json:"edge_fence,omitempty"`
}
+// EdgeFenceReport is whether instances on this box can call other apps on
+// it through the edge (#990): State is EdgeFenceOn or EdgeFenceOff, and
+// Reason says why when it is off. It reports what root applied, never a
+// routing outcome root did not observe (review round 1, P2).
+type EdgeFenceReport struct {
+ State string `json:"state"`
+ Reason string `json:"reason,omitempty"`
+}
+
+// The edge fence report's states.
+const (
+ EdgeFenceOn = "on"
+ EdgeFenceOff = "off"
+)
+
// BuildHeader carries the control service's version.Build on every /ready
// answer (#256). The agent compares it with its own: both are meant to be
// /opt/carlos/carlos, and a service that reports another build, or none
diff --git a/internal/instancectl/server.go b/internal/instancectl/server.go
index 29353c073..a0e487a55 100644
--- a/internal/instancectl/server.go
+++ b/internal/instancectl/server.go
@@ -27,6 +27,7 @@ import (
"github.com/carlosframework/platform/internal/controlsock"
"github.com/carlosframework/platform/internal/demo"
"github.com/carlosframework/platform/internal/demobuild"
+ "github.com/carlosframework/platform/internal/edgefence"
"github.com/carlosframework/platform/internal/execsandbox"
"github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/registry"
@@ -140,6 +141,12 @@ type Server struct {
// inside it is never opened (#126). Production reads procfs
// (localPrefixes); nil closes every resolver.
LocalAddrs func() ([]netip.Prefix, error)
+ // NFT runs nft for the edge fence (#990); nil never loads it and keeps
+ // the full #367 deny (tests of other verbs, the hairpin reset server).
+ NFT edgefence.Runner
+ // EdgeFenceOff is host.env's CARLOS_EDGE_FENCE=off: the full deny,
+ // whatever the box's addresses.
+ EdgeFenceOff bool
// DenyEvery is denyLoop's cadence: how often the box's addresses are
// re-read for a change, so a new one is denied to every nested unit
// (#367; 10 s in production). Zero runs no loop.
@@ -235,6 +242,15 @@ type Server struct {
lastDeny []netip.Prefix
hairpinActive bool
hairpinWatch groupHairpinWatch
+ // fenceAddrs is what the deny denyLocalAddrs last applied exempts for
+ // the edge fence (#990, edgefence.go), sorted; empty when the deny is
+ // whole. fenceReason says why it is whole. denyApplied is whether any
+ // deny has been applied since this service started (guardStarts
+ // refuses starts until one has).
+ fenceAddrs []netip.Addr
+ fenceReason string
+ fenceRetry bool
+ denyApplied bool
// denyMu runs one denyLocalAddrs at a time (RunProbe's and denyLoop's),
// so an older read of the addresses is never applied over a newer one.
denyMu sync.Mutex
@@ -345,6 +361,8 @@ func runWithClaim(args []string, claim, heldRelease http.Handler, view RegistryV
ResolvConf: "/etc/resolv.conf",
ResolvedConf: ResolvedConf,
LocalAddrs: func() ([]netip.Prefix, error) { return localPrefixes(fibTriePath, ifInet6Path) },
+ NFT: edgefence.Exec,
+ EdgeFenceOff: os.Getenv(EdgeFenceEnv) == "off",
DenyEvery: 10 * time.Second,
DataRoot: "/data/instances",
Statfs: statfsBytes,
@@ -353,7 +371,11 @@ func runWithClaim(args []string, claim, heldRelease http.Handler, view RegistryV
ExeCurrent: installedBinaryCurrent,
Egress: egress,
}
+ // #990: every start this service asks for checks the edge fence first
+ // (guardStarts, edgefence.go).
+ s.Systemctl = s.guardStarts(s.Systemctl)
s.bindSandboxEgress()
+ s.bindEgressFence()
ln, activated, err := activatedListener()
if err != nil {
log.Fatalf("instance-control: %v", err)
@@ -371,6 +393,13 @@ func runWithClaim(args []string, claim, heldRelease http.Handler, view RegistryV
if err := s.resumeGroupHairpin(ctx); err != nil {
log.Fatal(err)
}
+ // #990: the deny is a runtime drop-in that outlives this process, and
+ // may exempt an address whose fence an nft flush removed while it was
+ // down. Check the fence, or put the whole deny back, before serving.
+ // On a failure starts are refused (guardStarts) until a deny applies.
+ if err := s.denyLocalAddrs(ctx); err != nil {
+ log.Printf("instance-control: box-address deny at start: %v", err)
+ }
s.InspectMountpoints(ctx)
firstProbe := make(chan struct{})
builderEnv := os.Getenv
@@ -1411,6 +1440,7 @@ func (s *Server) handleReady(w http.ResponseWriter, r *http.Request) {
w.Header().Set(BuildHeader, s.Build)
}
rep, ready := s.Ready()
+ rep.EdgeFence = s.edgeFenceReport()
if ready {
writeJSON(w, http.StatusOK, rep)
return
diff --git a/internal/instanceexec/probe_hardening.go b/internal/instanceexec/probe_hardening.go
index 16ab95f04..8ccafb6b7 100644
--- a/internal/instanceexec/probe_hardening.go
+++ b/internal/instanceexec/probe_hardening.go
@@ -158,6 +158,12 @@ func networkAndIPCChecks(e probeEnv, add func(check, verdict, detail string), pa
// #367: the box's own addresses are closed, as the private ranges are.
bv, bd := boxAddrClosed(e)
add("box-addr", bv, bd)
+ // #990: no other TCP port opens on the box's addresses, and where the
+ // edge fence exempts one, the edge answers there.
+ pv, pd := boxAddrPorts(e)
+ add("box-addr-ports", pv, pd)
+ ev, ed := boxAddrEdge(e)
+ add("box-addr-edge", ev, ed)
// #178: an IPC namespace of its own, and no host mqueue mount.
ino, ierr := e.ipcInode()
@@ -245,35 +251,51 @@ func ptsPrivate(e probeEnv) (detail string, ok bool) {
return d, empty && perr != nil
}
-// boxAddrClosed is the box-addr line (#367): every address in root's list
-// of the box's own (e.boxAddrs, one per line) answers EPERM to a datagram,
-// as the private ranges do. An address that answers anything else fails
-// the line and is named. An IPv6 address the box has no route for is
-// unverified, as private-v6 is. A list that is missing, unreadable, holds
-// a line that is not an address, or holds no address at all fails: root
-// writes it before every run, so its absence is a fault, never a pass.
-func boxAddrClosed(e probeEnv) (verdict, detail string) {
+// boxAddr is one line of root's box-addrs file: an address of the box,
+// and whether the edge fence (#990) exempts it, so that an instance
+// reaches the edge there on TCP 80 and 443.
+type boxAddr struct {
+ addr netip.Addr
+ fence bool
+}
+
+// readBoxAddrs reads root's box-addrs file: one address a line, followed
+// by " edge" when the edge fence exempts it.
+func readBoxAddrs(e probeEnv) ([]boxAddr, error) {
b, err := os.ReadFile(e.boxAddrs)
if err != nil {
- return "fail", err.Error()
+ return nil, err
}
- var addrs []netip.Addr
+ var out []boxAddr
for _, line := range strings.Split(string(b), "\n") {
- line = strings.TrimSpace(line)
- if line == "" {
+ fields := strings.Fields(line)
+ if len(fields) == 0 {
continue
}
- a, err := netip.ParseAddr(line)
- if err != nil {
- return "fail", fmt.Sprintf("%s: %q is not an address", e.boxAddrs, line)
+ a, err := netip.ParseAddr(fields[0])
+ if err != nil || len(fields) > 2 || (len(fields) == 2 && fields[1] != instancectl.BoxAddrFenceMark) {
+ return nil, fmt.Errorf("%s: %q is not an address line", e.boxAddrs, line)
}
- addrs = append(addrs, a)
+ out = append(out, boxAddr{addr: a, fence: len(fields) == 2})
}
- if len(addrs) == 0 {
- return "fail", "no address in " + e.boxAddrs
+ if len(out) == 0 {
+ return nil, fmt.Errorf("no address in %s", e.boxAddrs)
+ }
+ return out, nil
+}
+
+// boxAddrClosed is the #367 line: a datagram to every address of the box
+// is refused (EPERM), fenced or not. Under the edge fence the refusal is
+// the fence's drop rule rather than the slice deny, so this line also
+// shows the fence's cgroup match is live.
+func boxAddrClosed(e probeEnv) (verdict, detail string) {
+ addrs, err := readBoxAddrs(e)
+ if err != nil {
+ return "fail", err.Error()
}
var failed, unrouted []string
- for _, a := range addrs {
+ for _, b := range addrs {
+ a := b.addr
network := "udp4"
if a.Is6() {
network = "udp6"
@@ -296,6 +318,68 @@ func boxAddrClosed(e probeEnv) (verdict, detail string) {
return "ok", ""
}
+// boxAddrPortsProbe is the TCP port box-addr-ports dials: ssh's, the
+// listener a box most often has on all its addresses.
+const boxAddrPortsProbe = 22
+
+// boxAddrPorts (#990): a TCP connection to a port other than the edge's
+// on any address of the box does not open, fenced or not. A refusal, an
+// EPERM or a timeout all pass; only a connection fails.
+func boxAddrPorts(e probeEnv) (verdict, detail string) {
+ addrs, err := readBoxAddrs(e)
+ if err != nil {
+ return "fail", err.Error()
+ }
+ var failed []string
+ for _, b := range addrs {
+ target := netip.AddrPortFrom(b.addr, boxAddrPortsProbe).String()
+ if err := e.connectTCP(target, 2*time.Second); err == nil {
+ failed = append(failed, target+": connected")
+ }
+ }
+ if len(failed) > 0 {
+ return "fail", strings.Join(failed, "; ")
+ }
+ return "ok", ""
+}
+
+// boxAddrEdge (#990): on every address the edge fence exempts, the edge
+// answers on TCP 443 or 80 (a box may serve only one). It never fails
+// the probe: an edge that is down or restarting is not an isolation
+// fault. It says "unverified" when the fence is off on this box or the
+// edge did not answer.
+func boxAddrEdge(e probeEnv) (verdict, detail string) {
+ addrs, err := readBoxAddrs(e)
+ if err != nil {
+ return "unverified", err.Error()
+ }
+ var fenced, missed []string
+ for _, b := range addrs {
+ if !b.fence {
+ continue
+ }
+ fenced = append(fenced, b.addr.String())
+ var errs []string
+ for _, port := range []uint16{443, 80} {
+ target := netip.AddrPortFrom(b.addr, port).String()
+ err := e.connectTCP(target, 2*time.Second)
+ if err == nil {
+ errs = nil
+ break
+ }
+ errs = append(errs, fmt.Sprintf("%s: %v", target, err))
+ }
+ missed = append(missed, errs...)
+ }
+ switch {
+ case len(fenced) == 0:
+ return "unverified", "same-box calls are off on this box"
+ case len(missed) > 0:
+ return "unverified", "the edge did not answer: " + strings.Join(missed, "; ")
+ }
+ return "ok", ""
+}
+
// noV6 is an answer that means the box has no IPv6 path for that
// address, so the fence was never asked.
func noV6(err error) bool {
diff --git a/internal/instanceexec/probe_hardening_test.go b/internal/instanceexec/probe_hardening_test.go
index 2f4b54d5a..2c866e227 100644
--- a/internal/instanceexec/probe_hardening_test.go
+++ b/internal/instanceexec/probe_hardening_test.go
@@ -8,6 +8,7 @@ import (
"os"
"path/filepath"
"runtime"
+ "slices"
"strings"
"syscall"
"testing"
@@ -274,3 +275,96 @@ func countLines(r instancectl.ProbeReport, check string) int {
}
return n
}
+
+// #990: box-addr-ports fails only when a non-edge TCP port connects on a
+// box address; box-addr-edge reads the " edge" mark root writes beside an
+// address the edge fence exempts, and never fails the probe.
+func TestProbeEdgeFenceLines(t *testing.T) {
+ fenced := func(t *testing.T) probeEnv {
+ e := goodEnv(t)
+ if err := os.WriteFile(e.boxAddrs, []byte("10.0.3.17\n203.0.113.7 edge\n2001:db8::7 edge\n"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ return e
+ }
+ refused := errors.New("connect: connection refused")
+
+ // Fence on, edge answering on 443, every other port refused.
+ e := fenced(t)
+ var dialled []string
+ e.connectTCP = func(addr string, _ time.Duration) error {
+ dialled = append(dialled, addr)
+ if strings.HasSuffix(addr, ":443") {
+ return nil
+ }
+ return refused
+ }
+ r := runChecks(e)
+ for _, line := range []string{"box-addr", "box-addr-ports", "box-addr-edge"} {
+ if verdict(r, line) != "ok" {
+ t.Errorf("%s = %s: %s", line, verdict(r, line), detail(r, line))
+ }
+ }
+ for _, want := range []string{"10.0.3.17:22", "203.0.113.7:22", "[2001:db8::7]:22", "203.0.113.7:443", "[2001:db8::7]:443"} {
+ if !slices.Contains(dialled, want) {
+ t.Errorf("did not dial %s: %v", want, dialled)
+ }
+ }
+ if slices.Contains(dialled, "10.0.3.17:443") || slices.Contains(dialled, "203.0.113.7:80") {
+ t.Error("dialled the edge on an address the fence does not exempt")
+ }
+
+ // Port 22 connects on a fenced address: the fence is not holding.
+ e = fenced(t)
+ e.connectTCP = func(addr string, _ time.Duration) error {
+ if strings.HasPrefix(addr, "203.0.113.7:") {
+ return nil
+ }
+ return refused
+ }
+ if r := runChecks(e); r.Ready || verdict(r, "box-addr-ports") != "fail" || !strings.Contains(detail(r, "box-addr-ports"), "203.0.113.7:22") {
+ t.Errorf("a connected port 22 passed: %s %s", verdict(r, "box-addr-ports"), detail(r, "box-addr-ports"))
+ }
+
+ // An edge serving only plain HTTP answers on 80: ok.
+ e = fenced(t)
+ e.connectTCP = func(addr string, _ time.Duration) error {
+ if strings.HasSuffix(addr, ":80") {
+ return nil
+ }
+ return refused
+ }
+ if r := runChecks(e); verdict(r, "box-addr-edge") != "ok" {
+ t.Errorf("edge on 80 only: %s %s", verdict(r, "box-addr-edge"), detail(r, "box-addr-edge"))
+ }
+
+ // The edge is down: unverified, and the box stays ready.
+ e = fenced(t)
+ e.connectTCP = func(string, time.Duration) error { return refused }
+ if r := runChecks(e); !r.Ready || verdict(r, "box-addr-edge") != "unverified" {
+ t.Errorf("edge down: ready=%v box-addr-edge=%s %s", r.Ready, verdict(r, "box-addr-edge"), detail(r, "box-addr-edge"))
+ }
+
+ // The fence is off: no edge dial, unverified, ready.
+ e = goodEnv(t)
+ dialled = nil
+ e.connectTCP = func(addr string, _ time.Duration) error { dialled = append(dialled, addr); return refused }
+ if r := runChecks(e); !r.Ready || verdict(r, "box-addr-edge") != "unverified" || !strings.Contains(detail(r, "box-addr-edge"), "off") {
+ t.Errorf("fence off: ready=%v box-addr-edge=%s %s", r.Ready, verdict(r, "box-addr-edge"), detail(r, "box-addr-edge"))
+ }
+ for _, d := range dialled {
+ box := strings.HasPrefix(d, "10.0.3.17:") || strings.HasPrefix(d, "[2001:db8::7]:")
+ if box && (strings.HasSuffix(d, ":443") || strings.HasSuffix(d, ":80")) {
+ t.Errorf("dialled the edge with the fence off: %s", d)
+ }
+ }
+
+ // A mark root never writes is refused, failing box-addr.
+ e = goodEnv(t)
+ if err := os.WriteFile(e.boxAddrs, []byte("203.0.113.7 open\n"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if r := runChecks(e); r.Ready || verdict(r, "box-addr") != "fail" {
+ t.Errorf("an unknown mark passed: %s %s", verdict(r, "box-addr"), detail(r, "box-addr"))
+ }
+}
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index fb8a47b1c..a4d540ef9 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -206,3 +206,4 @@ plan14-root-reads-spread-every-schedule-ticks.tsv 07b748a749084fdaf61c5087a6edfc
plan14-root-reads-member-backups-2b.tsv 07b748a749084fdaf61c5087a6edfca8a79273962822ce551dd4d42b0d20c063
plan14-root-reads-instance-gomemlimit-991.tsv 19c9f395547d998f4b5e87e89c0dfa3b5f012d177a87eb5010a8c4defac305dc
plan14-root-reads-ppv2-operator-copy.tsv 19c9f395547d998f4b5e87e89c0dfa3b5f012d177a87eb5010a8c4defac305dc
+plan14-root-reads-same-box-edge-fence.tsv 76c986ad534d23071100a9a573ffb38afc60b26c8942baf218436bf6a3ff03b3
diff --git a/internal/provision/testdata/plan14-root-reads-same-box-edge-fence.tsv b/internal/provision/testdata/plan14-root-reads-same-box-edge-fence.tsv
new file mode 100644
index 000000000..2c86bef9f
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-same-box-edge-fence.tsv
@@ -0,0 +1,31 @@
+# Census overlay same-box-edge-fence, written by census-propose (#369). census-ruling-same-box-edge-fence, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-same-box-edge-fence.md.
+# 9 body, 0 sites, 7 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+# 4 new dispositions: 1 reads re-frozen at their disposition with the claim, 2 new units frozen accepted-legacy, 1 quiet units retired while they read nothing, 0 other.
+@legacy ee431ed805a1a814746f0cc4857711c39b5cb1cb41ae8316331e2bcc9e3ace7e internal/host/units/carlos-instances.slice external legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-same-box-edge-fence;basis=RefuseManualStop=yes, with a comment naming the remaining stop levers (stop 'carlos-instances-*.slice', kill carlos-instances.slice). Defence in depth for the fence (a recreated slice leaves nft's rules matching an old cgroup id); no read, no other directive. file:external@0 09de7ed1ab8fa8dca0d150490a453a680f63cc0826b94c5836923a4b4f1796f9
+@legacy 65dac182eb611a1c3681a3c814ed6bc24e63d20be5bdf3e02f1c50b9835ad831 internal/host/units/carlos.slice external legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-same-box-edge-fence;basis=RefuseManualStop=yes, with a comment: a stop of carlos.slice propagates to carlos-instances.slice and recreates it. Memory limits unchanged; no read. file:external@0 c431d5b06875f361532c80afaa69bf3c8a4a40fb8b09a0761164f0f85aaf7890
+@legacy ec26ab2ee1ff76e5c3ac831ce211895b0a557bdf03752575c4f3f79821d310e3 internal/instancectl/server.go type Server legacy accepted-legacy accepted-legacy;rev3=census-ruling-carlos-run;basis=Re-digested at the pre-land merge: the body includes main's own change under census ruling 292, with no further change from this branch. Census ruling 292 reclassified this declaration accepted-legacy (J2,J4) for root's per-host ordering of legacy run starts against stops; this ruling kept the row as main classed it. Its own addition is the cmd start's poll and wait bounds and its per-host lock map: field declarations only;rev3=census-ruling-rootfs-apps-2;basis=new fields: HostRuntime, ProbeImage, ProbeImageFile, RootfsProbeOut, DenyEvery, the deny's lastDeny and denyMu, the rootfs probe's report and lock, the jit reload counters and imageDigests; genStarting counts binary generation starts per unit; rootfsLocksMu and rootfsLocks, one lock entry per rootfs unit name being started or removed right now, held by a start from its layout through systemctl start and its own cleanup and by a removal from its proof through the raw removal, a removal refusing while it is taken, a waiting start giving up when its request ends, an entry dropped with its last holder or waiter (fixes E6, L2, L3); rootfsProvenHook, a test hook run between the proof and the raw removal; field declarations only; no read added;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328 plan 2 and #329 plan 3 Task 5: the declaration gains sliceLocks (one mutex per host slice, taken by /size and /parent) and Egress (the asserter every start path calls), and its comment names the egress allow (plan 3's ControlDropInDir field was deleted in ef38e13b, the P1 EROFS fix); the same one site, the Statfs field, offset moved; no read added.;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 6: comments only: the one-shot pacing fields cover /cmd and /tty, and cmdLocks is now keyed by (role, host) (oneShotKey, PF-7) so a session's start never waits behind a command's; field declarations unchanged; the same one site, no read added;rev3=census-ruling-agent-start-demo-1;basis=Adds fixed demo configuration, registry views, derived runtime root, synchronization and purge guard.;rev3=census-ruling-region-ha-p3b;basis=Add hairpinActive boolean alongside lastDeny under existing deny synchronization. Field declaration only; existing Statfs selector unchanged, no new read or externally supplied authority.;rev3=census-ruling-region-ha-p3b2-rolls;basis=adds one field holding the current hairpin exit watcher, guarded by the root hairpin flock; no new read;rev3=census-ruling-agent-start-demo-3;basis=Retain the snapshot supervisor in instance-control state; no new request-selected path. Census read-site delta: unchanged (1).;rev3=census-ruling-gvisor-demos;basis=Retain Task 1 mode/error/readiness fields, baseline/runtime callbacks, Task 4 per-host validated staged descriptors and root-selected probe nonce. Fix round 1 adds a private writer-operation seam assigned only in package tests, after the unchanged GVisorID admission check; production defaults still call the same checked constructor, WriteRootfs, WriteBundle and verifier. No new direct read or request-controlled callback. Task 5: private injected removal seam for unprivileged tests; production default removes only root-derived bundle and skeleton after both-family proof inside existing start fence. No new request field or agent-selected unit. Task 6: Retain serialized probe nonce, runtime-set identity verifier/token, fixed claims flag, bundle discovery root, and private unprivileged identity seam. No request-controlled callback or path; existing declaration read-site classification unchanged. Task 6 fix round 1: private gvisorProbeTestOps is set only in package tests; production defaults retain all fixed paths and the checked root output opener. No externally supplied callback or new direct read. Final R1 P2: retain fixed skeleton parent and concurrent per-instance cleanup refusals; no direct read or external configuration field. Carry the root-only host.env validation callback into Ready; no agent read or caller-selected path.;rev3=census-ruling-same-box-edge-fence;basis=Field declarations only: NFT (the nft runner; nil never loads the fence), EdgeFenceOff (host.env CARLOS_EDGE_FENCE=off), and under the existing denyMu/mu: fenceAddrs, fenceReason, fenceRetry, denyApplied. No read added. file:Statfs@5239 8a1320185105abfc7c531195a9b83836137e1fe7c627b66e056b484a92167665
+@legacy 520fc2cb25b96d791b76f5f70ec0968550f7c8c8dbb6c204ed9a7fa8870dce4e internal/instanceexec/probe_hardening.go networkAndIPCChecks legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-2;identity=both isolation probes (carlos instance-probe in carlos-instance-probe.service and instance-probe --rootfs in carlos-instance-rootfs-probe.service, both started by instance control, user carlos inside the unit's own namespace; no tenant code runs there);basis=root-input (J4, as hardeningChecks, whose body this is): new (rootfs Plan 2 Tasks 7 and 7a): hardeningChecks' network, IPC and resource lines, shared by both probes, with the box-addr (boxAddrClosed) and mdwe lines added; its two sites are hardeningChecks': ReadFile of the unit's resolv.conf and of its own cgroup's io.weight; no root process runs it; decides nothing for root;rev3=census-ruling-instance-syscall-filter;basis=one more verdict line, syscall-filter (syscallFilterHeld: both calls must answer ENOSYS; unverified when the unit does not advertise the filter); inside the probe units as carlos; decides nothing for root beyond one more probe line that can fail readiness;rev3=census-ruling-same-box-edge-fence;basis=Probe (uid carlos inside the probe units; no root). Two more verdict lines after box-addr: box-addr-ports (TCP connect to port 22 on each address in root's box-addrs must not succeed) and box-addr-edge (TCP 443 or 80 on fenced addresses; ok or unverified, never fail). Decides nothing for root beyond one more line that can fail readiness. file:ReadFile@352,file:ReadFile@5123 90b1368d3375768ccfb8218596c864395ed3d1b00f1c971a722d9cdb0bef4acb
+@legacy 05119e7d66a98320afae77d703622647a1d4444fd4da6f6f67541e198c2bd5a9 status_instances.go printStatusLayout legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328 plan 2 Task 12 and #329 plan 3 Task 10: carlos status --layout, in the operator's carlos CLI on the operator's own machine, prints SIZE and EGRESS columns from the console's JSON (statusLayoutRow.Size and Egress), joins the egress reason into REASON and prints one note when a size is pending; the same one site (the /data literal in the mixed-box warning), no read added.;rev3=census-ruling-region-labels;basis=a REGION column (statusRegionCell) from the console's answer; no read added;rev3=census-ruling-gvisor-demos;basis=Task 8: print draft SANDBOX column and one exec-sandbox summary per reported box from the existing operator API. Missing/stale reports display unknown; no new file read or authority.;rev3=census-ruling-same-box-edge-fence;basis=CLI (operator's machine), not on a box. One more call, printEdgeFenceStatus, printing one line per box from the console's JSON: same-box calls: on / off (reason) / not needed (reason) / unknown. No read. data-literal@2445 8c7f8f30a88506ad8640d4642cdefaef9e31772588d0e1ccc0f1b5f76ba191a3
+@legacy 2cf76e79a4ee20b0705ebf6d4783cc928945a1da78feee97ab25648e3d0c55d8 internal/edgefence/edgefence.go Exec legacy accepted-legacy accepted-legacy;rev3=census-ruling-same-box-edge-fence;basis=Root (called from instance-control only through Server.NFT). Runs args[0] with fixed arguments; every caller in this package passes "nft" and text rendered from root-read addresses. Output returned to the caller for comparison only. file:CommandContext@85,file:Exec@5 c1d5e35bf2fc09fbb0f0d38f28e995959ac8a1ccd2fbd12f3974ffffc975ff82
+@legacy 7ac7b2816ec33f1db25a028ae0aa5039113ff2ce89871704eb617981dd704a28 internal/instanceexec/probe_hardening.go readBoxAddrs legacy accepted-legacy accepted-legacy;rev3=census-ruling-same-box-edge-fence;basis=Probe (uid carlos). New: reads root's box-addrs (the same fixed BoxAddrsPath boxAddrClosed read before) and parses `<addr>` or `<addr> edge`; any other line is refused. boxAddrClosed, boxAddrPorts and boxAddrEdge call it. file:ReadFile@62 0bb7ba196291c3e6b0df3284319426025b3448692249b9a307695bebba690593
+internal/host/agent.go runAgent authority B,C,D,F rev3=census-ruling-self-serve-moves-1;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): builds the box's lifetime judge once (newBoxJudge, nil with host claims on) and hands it to the seed placement, the moves and runs workers and every loop it starts; read sites unchanged, offsets moved; B,C,D,F authority retained; self-serve moves 1 Task 8: derives the box's lifetimes switch from the judge once (lifetimes := boxJudge != nil) and hands it to the edges file loop; read sites unchanged, offsets moved;rev3=census-ruling-plans-4d-lapse;basis=arms two more plans hooks from the same snapshot: e.SetPlanDisabledFor(planDisabledFor) beside SetPlanGovernedFor, and svc.SetDisabledFor(planDisabledRoute) beside SetMaxRunFor (plans 4d); the reads live in those units (plans-4d-units decision); read sites unchanged, offsets moved;rev3=census-ruling-rootfs-apps-2;basis=main's body as of the merge of origin/main 9b81d97b (with main's plan rate ceiling, edge request records, regional box names, self-serve moves plan 1, plans 4d-1 lapse and its other later changes under main's own census rulings) plus the rootfs placement wiring in the activator start: an agentRootfs built from eb.NestedOK, CARLOS_DEPLOYMENT_SINGLE_TENANT, CARLOS_POOLS, the claim flag, swapArming's answer, the control client's /ready/rootfs and, on a fleet box whose identity resolved, fleetOwnerCheck over the deploy store main already opens for the fleet label (fleetStore), then arm and armedRootfs.Store; this body reads nothing new itself; the closures it wires read later, at a rootfs wake and each status tick: GET /ready/rootfs over the control socket, NestedOK's checks, and release.FleetOwnerKey for the judged row's own account and this box's fleet from the deploy store;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328 plan 2 Tasks 7 and 11, #329 plan 3 Task 7 and plan 1 Task 7's policy cache: the control client is built once and handed to eb.Control, to the status tick (egressStatus) and to a new egressNudgeLoop goroutine; armSizeSource(svc, "/sys/fs/cgroup") after the activator Service; armPolicyCache() after armChangeIndex; statusLoop takes egressStatus. The reads are those units' own (decision rows); this body reads nothing new: the same five sites, offsets moved, in the agent; B,C,D,F authority retained.;rev3=census-ruling-remote-instance-metrics;basis=builds the metrics loop's owners closure (metricsOwners over the agent's registry, the activator and cgm.Leftover) when an activator exists and hands it to metricsLoop; reads nothing new itself;rev3=census-ruling-edge-asset-cache-3;basis=adds file:Statfs. runAgent keeps its authority (B,C,D,F). The new site is assetcache.Statfs, an exported assetcache.FS interface value (var Statfs FS = statfsFS{}), not a function value and not a call in runAgent: the ready hook passes it to armEdgeAssetCache as the store's filesystem, and armEdgeAssetCache calls its Space method on the configured data directory (dataDir(): $CARLOS_DATA_DIR, else /data), which calls unix.Statfs there (statfsFS.Space, accepted legacy at census-ruling-edge-asset-cache-2). No request-supplied pathname reaches it.;rev3=census-ruling-remote-metrics-nested;basis=main's body (merged origin/main acfa4f80, under main's own census rulings) plus: snapshots the nested layout (snapshotNestedUnits over /sys/fs/cgroup/carlos.slice/carlos-instances.slice) once at start, before the activator, and hands the metrics loop a unitSources struct (stamped units, routeHostNames, that root and the snapshot); reads nothing new itself;rev3=census-ruling-region-ha-p1a;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): wires region HA P1a into the activator: cfg.Record = haRecordFacts(openDeployStore, boxJudge) (the box's lifetime judge this body already builds with newBoxJudge, nil with host claims on; CI fix) and cfg.Self = lease.CurrentSelf; eb.Lifetimes (the process's lifetime index), eb.Registry, eb.StartupSwept (seedSweptAtStart.Load), eb.FilesStore from newProductionFilesStore (now lease.NewFilesStore, rootaws-loaded, a log line on failure) and lease.SetObligationDir(<data>/.ha-owed) (logged on failure; HA acquires then refuse); this body reads nothing new itself, the same five sites; the reads are those units' own (haRecordFacts and lease's SetObligationDir are new rows on this card); merge of origin/main d7ae1d76: main's own later changes to this body are kept as main has them, under main's rulings (census-ruling-remote-instance-metrics: the metricsOwners closure for metricsLoop; census-ruling-edge-asset-cache-3: the +file:Statfs site, assetcache.Statfs handed to the asset ready hook); this branch's change is the same as above;rev3=census-ruling-region-ha-p1b1;basis=region HA P1b-1: builds one termfence.Confirmer (Self from lease.CurrentSelf at each call, EC2 DescribeInstances method only, client from rootaws.LoadDefaultConfig with retries off, built lazily on first use) and sets eb.OwnerTerminated; this body reads nothing new itself, the same six sites;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Task 7: the startup Sweep literal hands its answer to startupSwept, which logs as before and, only on a clean sweep, marks rootfs admission swept (MarkRootfsSwept); same Sweep call, no read added;rev3=census-ruling-managed-fleets-1b;basis=managed fleets 1b (controller ruling after branch review R1, and Paul's R2 ruling): sets svc.Fleet = fleetWakeFor(os.Getenv, identity, identErr, fleetStore) from the identity it already resolves once and the deployment store the fleet loops already opened, and logs an ERROR naming the identity error when the box is on a fleet with an invalid identity. fleetWakeFor reads CARLOS_REGION and CARLOS_FLEET from the same environment. Read sites unchanged (6). Agent, not root; a platform box is unchanged.;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 12: one call more beside armRunsPass, armInteractivePass(svc, reg, rolloutSink, boxJudge), in the same activator Configure hook, handing it the same box judge; fix round 1 (Astra P2, shutdown): after svc.Shutdown(ctx), shutdownInteractive(ctx) ends and joins every interactive session under the same shutdown budget; the worker's own reads are its units' (interactive.go); this body reads nothing new, the same six sites; merge of origin/main 6f1f6ca6: main's svc.Fleet = fleetWakeFor(...) and its invalid-identity ERROR line are kept as main has them (census-ruling-managed-fleets-1b); this branch's change is the same as above; read sites unchanged (6);rev3=census-ruling-fix-set-aside-exdev;basis=set-aside EXDEV fix: one field more on the agent ExecBackend literal, RawInstanceDir: layout.RawInstanceDir (a pure path join: <dataDir>/.instances/<InstanceID(host)>), so the start rule set-aside moves a copy out through the raw directory instead of through the nosymfollow bind; this body reads nothing new, the same six sites;rev3=census-ruling-durability-3a-escrow;basis=durability 3a Task 3: one more assignment beside eb.FilesStore: eb.EscrowKey = haEscrowKey(os.Getenv("CARLOS_SECRETS_KEY")), the agent's own environment parsed by appconfig.ParsePrivateKey as the moves pass parses it (unset or unparseable: a log line and nil, and HA publication refuses on the box). No path is opened or read, no read site added; the same six sites, offsets moved; B,C,D,F authority retained. Durability 3a Task 4: one more goroutine beside configSyncLoop: go escrowLoop(agentCtx, reg, svc), the escrow sweep every 30 s over the same registry and Service. This body reads nothing new itself; the same six sites, offsets moved; B,C,D,F authority retained. Durability 3a Task 5: one more call beside eb.EscrowKey: wireRawSecretPages(eb, PageOperator, metricsBoxLabel(os.Getenv, readMachineID())), which sets eb.OnRawSecret to page an operator (alerting.Page through PageOperator, LevelIncident) on its own goroutine with a 20 s timeout; metricsBoxLabel and readMachineID are the reads this body already makes for the moves refusal log; no new read site; the same six sites, offsets moved; B,C,D,F authority retained. Merge of origin/main 90c4d3aa: main's own later changes to this body are kept as main has them, under main's rulings; this branch's change is the same as above. Merge of origin/main 00bf5b8c (fleet set-aside EXDEV fix): main's change to this body is kept as main has it, under its own census ruling; this branch's change is unchanged.;rev3=census-ruling-probe-burst-limit;basis=two more sink wirings beside setAnalyticsSink: setProtectionSink(e.SetProtectionRecordOnly) and setAssetOwnersSource(e.AssetOwners), function values the telemetry pass calls; this body reads nothing new, the same six sites; authority B,C,D,F retained; no new root read or write kind;rev3=census-ruling-region-ha-p1b3a;basis=Arm HA placement exactly once on the existing Service before activatorStart and edges publication, wiring AwakeApps and the PageOperator callback; existing six read sites unchanged, no new root authority.;rev3=census-ruling-stateless-replicas-1;basis=Final review I3: start the concrete coordinator's renewal worker with agent setup; existing closeReplicaCoordinator shutdown cancels and joins it before release. No new read sites or credentials. Merge origin/main c59715e7: retain main's armHAPlacement(svc, PageOperator) wiring beside the existing activator setup; stateless coordinator and shutdown wiring remain. Same read sites; no new root read or credential.;rev3=census-ruling-edge-held-streams;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): in the edge-ready callback, calls act.SetHeldWakeHook(e.HeldWake) when act is non-nil (installing the non-blocking wake callback) and stores e.HeldStreamsForStatus in heldStreamsSource. Wiring of in-memory callbacks only; no read added.;rev3=census-ruling-region-ha-p1b3b-t;basis=Wire Service.SetDutyView to the live edge DutySnapshot in the ready callback. No new read; no new loop or cloud operation. B2 wires the registry as the persistent DutyStore before service startup; no new cloud or filesystem path. B3b: arm one journal-backed termination consumer before service startup using agentCtx and the shared confirmer; expose edge tick and join at edge shutdown. No new direct read sites.;rev3=census-ruling-agent-start-demo-1;basis=Passes the existing registry, data store and hibernation prefix into the demo worker, and the existing instance-control client into the demo before-exec hook. No alternate data store or polling loop. Merge resolution against origin/main 9bd45488 retains main's HA departure controller, lifecycle and duty wiring alongside the demo data store and worker; no read site added by the resolution.;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: install closed fixed admission before every launch source, bind activator/backend and edge, wire the real termination Started lifecycle and role reader after the change index; close before cancellation/child shutdown. No new external reads or cloud authority. Fix R1: move bind/lifecycle/edge-option wiring into wireAgentAdmission and worker listing into runWorkerBootPassAfterAdmission. Worker boot waits for admission before listing then uses unchanged bounded wakes and per-host serialization; whole Route read moves to the helper. No new storage, cloud, or root execution authority. Preserve merged main's agent wiring and census basis; the branch removes one whole Route use by moving worker iteration to the helper, with no added read kind.;rev3=census-ruling-stateless-replicas-2;basis=Slice 3b: arms a fleet-only worker using the existing registry, activator, backend and authenticated console transport. Owned worker stops and joins at shutdown. No new bucket reader. merge of origin/main 9b8b2c50: retain HA duty/departure lifecycle, wake-slot and existing agent wiring alongside the replica placement worker; no new read introduced by resolution. merge of origin/main 6be08467: Retain main demo configuration, admission, build and expiry wiring alongside the replica worker; merge-only body change, no additional read. merge of origin/main 7920cccf: Retain main box-role/group admission wiring and boot publication beside the owned replica worker and shutdown; main moves the boot registry List into runWorkerBootPassAfterAdmission, removing its inline whole Route site. No new read introduced by conflict resolution.;rev3=census-ruling-stateless-replicas-3;basis=Task 1 fix round 1 M3: retain the private snapshot source and cancel/join ownership, but use the replica-health-specific retry loop. It logs its first failure only and retains the existing exponential backoff capped at 30 seconds; unsupported builds return nil. Existing five direct read sites unchanged; no new credentials, bucket reader or app lifecycle action. Fix round 1 Q20: publish Edge.ReplicaSnapshots as a separate in-memory status source, leaving the tenant-visible Upstreams source unchanged. No new external reader or authority.;rev3=census-ruling-region-ha-p3b;basis=Load root-written group marker/configuration, configure signed boot binding and agent receipt completer, wire cancellable admission into departure work and expose cached GroupReaderSnapshot. New indirect boot reads use protected root files; agent-owned receipt controls duplicate initial completion only, never root restart permission. Same five direct sites. Merge 45cebde4 retains the replica health socket lifecycle and setReplicaSource beside GroupReaderSnapshot; no extra read beyond main.;rev3=census-ruling-agent-start-demo-2;basis=agent.go:309-329 opens demo-traffic.db beside the operator-configured registry when a demo domain exists, closes it at shutdown and wires drain-before-purge; :1010-1019 shares the worker and write gate; :1164-1177 installs the fleet identity and closed-until-worker serving callback. One added whole Route pass; the new indirect filesystem/SQL reads are claimed in openDemoTraffic and worker/store units. No request chooses the database pathname.;rev3=census-ruling-region-ha-p1b3b-s;basis=Wire the service duty view to authoritative cached sidecar manifest placement in LifetimeIndex and the edge sidecar projection; missing policy denies duty. Existing instance duty wiring remains.;rev3=census-ruling-region-ha-g2-t3;basis=T3a: wire eb.Page = PageOperator beside OwnerTerminated before departures arm, so suspect-holder pages work if departure setup fails; no new read; existing nine sites and authority unchanged; pages through the existing sink. T3b: publish the same backend through an atomic pointer for the metrics observer, and clear it on return; no new external read or authority.;rev3=census-ruling-agent-start-demo-3;basis=Wire the claim activator and root snapshot client into the demo worker; pass moved readiness to status reporting. Census read-site delta: unchanged (9).;rev3=census-ruling-region-ha-g2-fixes;basis=Wire local pool evidence, live withdrawal activator, startup ingress scan and alias publication, and edge lookup; no new direct sites; new indirect record/claim reads use existing store/judge paths described in ingress helpers.;rev3=census-ruling-region-ha-g2r-fixes;basis=W3: starts the existing record-view backstop loop with a departure-inventory listener (non-blocking, coalesced signal) even without an armed RecordView; it requests the existing full pass (backstopFullDue) there. Same nine read sites; no new read or authority.;rev3=census-ruling-region-ha-graceful-terminate-t2;basis=Derive one signal-time deadline with a 90-second budget; cap departure stop and startup/seed/service shutdown joins by it. No read added.;rev3=census-ruling-static-sweep-periodic;basis=in the edge-ready callback, publishes e.LargestStaticTree in staticTreeSource for the disk alert line (diskAlertFrac in the metrics loop); in-memory wiring only, no read added; read sites unchanged (9);rev3=census-ruling-edge-page-cache-1;basis=wires the exec backend's CurrentInputs into the edge cache (wireCurrentInputs) and, in the ready hook after armEdgeAssetCache (whose returned store it now keeps), calls armEdgePageCache, which does nothing unless CARLOS_PAGE_CACHE=1; read sites unchanged (9); no read added;rev3=census-ruling-gvisor-demos;basis=Capture sandbox resolution and refusal once; log errors once; gate route admission and BeforeExec before process launch. No new root read. Task 5: pass the once-captured sandbox effective mode/config error into ExecBackend, UnitBackend and the immutable Client expectation. Same startup environment/registry reads; swapArming declines gVisor before placement. Task 8: arm read-only status projection with the existing Client.SandboxStatus callback. Agent status now queries the existing root /ready endpoint; no new root authority or guest-file input. Merge2 e8a1ddde: retain main wireCurrentInputs and armEdgePageCache through the existing asset-store ready hook alongside branch once-captured sandbox mode, wake gates and root status wiring. No new direct read; main page-cache helpers retain their own census overlays.;rev3=census-ruling-region-ha-held-build;basis=wires the drain state: svc.SetDrainingSource(boxDrain.IsDraining), svc.SetPeerDrainView(e.PeerDraining), e.SetPeerDrainedHook(svc.DropHoldersNaming); in-memory only; no read added; region HA held-requests Task 5: on group members, starts the drain driver over the activator, the edge and boxDrain, and serves its root-only drain socket; no read added beyond the socket's own Branch review r1: the drain state follows the root start fence on group members (the fence reader is the existing fenceLocation.read, a root-owned fixed path); e.SetPeerUndrainedHook(svc.AllowHoldersNaming) beside the drained hook (memory only); the drain socket serves only the agent's own user. No read added.;rev3=census-ruling-security-review-mitigations;basis=Wire the cached operator flat-layout choice into the exec backend's new-resident refusal; no read source added, existing authority retained.;rev3=census-ruling-w6-ingress-drain;basis=agent (user carlos), not root. Builds the ingress drain (newIngressDrain) with arming read at ask time from os.Getenv (CARLOS_REGION_HA, CARLOS_INGRESS_TARGET_GROUPS, both from the root-owned host.env), the fixed admission and lease.CurrentSelf (existing IMDS identity); its reader is awstg.Load, the box role's credentials calling ELB DescribeTargetHealth/DescribeTargetGroupAttributes (new AWS reads, by the agent). Wires admission.closeStartsForIngressDrain, the lbhealth drain condition, ingress.setEdge, and ingress.shutdownStarted in WithShutdownStarted. The drain socket (/run/carlos/.ha-drain/drain.sock, agent-user only, existing) is now also served on a fixed box with the drain configured (was group members only), routing /v1/ingress/* to the ingress drain and the group drain verbs to 404 there. armHADepartures now takes fixtureDepartureGetenv() and MakeQueue fixtureDepartureQueue(), which in a production (non-rootrunner) build are os.Getenv and nil, as before. Read sites unchanged (9).;rev3=census-ruling-stateless-replicas-4-task1;basis=Arms the fleet-only replica swap worker next to the placement worker: same console URL and fleet token as the existing replicaCoordinatorAPI, the existing activator Service; stops and joins at shutdown. No new read site, credential or bucket reader.;rev3=census-ruling-stateless-replicas-4-task2;basis=Task 2: sets deployWorker.step to the rollout scheduler answer for the record permit (replicaStepOf over armedRollout), an in-memory callback; no read site, credential or bucket reader added.;rev3=census-ruling-stateless-replicas-4-task2-fix2;basis=Task 2 fix round 2: the swap worker step is armedReplicaStep, the same lazy scheduler lookup as before as a named function; no read site added.;rev3=census-ruling-stateless-replicas-4-merge-main;basis=Merge of main 5fac2ff1: both sides changed it. Main (01d6ca78, linked-deployments-slice1) starts linkLoop beside tunnelLoop; this branch keeps its replica coordinator wiring. Both kept as-is; no read added.;rev3=census-ruling-stateless-replicas-4-final;basis=#511 final wave item 2: wires the swap worker's drive (armedReplicaDrive, the armed rollout manager's DriveReplicaRelease); no read added;rev3=census-ruling-stateless-replicas-4-merge-main2;basis=Merge of main af871da0 (v0.34.49): both sides changed it. Main (178dcfe5, member-backups-2a) moves the inline duty-view closure into armDutyView/dutyView and starts verifyAssignLoop; its sites drop by registry:Host and whole:Route x2 as main recorded them. This branch keeps its replica coordinator, swap worker and drive wiring. Both kept as-is; no read added.;rev3=census-ruling-stateless-replicas-4-drill3;basis=drill 3 R24: makes one in-memory channel, closes it (once) inside the edge's existing shutdown-started callback after ingress.shutdownStarted, and passes it to tunnelLoop, which drains only a fleet channel name; no read added, same six sites; touches no admission, lease, ingress drain, listener or file; the agent process, no root decision;rev3=census-ruling-edge-ppv2;basis=Agent (uid carlos), not root. memwatchLoop now gets edgeProxyCounters(&demoEdge) (in-process counters, no read). The drain socket's driver is newAgentDrainSocket(ingress, e, os.Getenv), which attaches the edge trust handler only when CARLOS_INGRESS_PROXY_SOURCES in the agent's environment (from the root-owned host.env) parses to a non-empty list; the socket is served when drainSocketServed: a group member or a configured ingress drain (both as before), or a box armed for PROXY protocol (new). The socket's path and agent-user-only permissions are unchanged. Read sites unchanged (6).;rev3=census-ruling-same-box-edge-fence;basis=Agent (uid carlos), not root. One added line: armEdgeFenceStatus(ctl.EdgeFence), beside the existing armExecSandboxStatus, so the layout report can ask root's /ready for the edge fence state over the control socket client the agent already holds. No read added. file:Exec@20444,file:Open@2191,file:Statfs@55968,registry:App@13287,whole:Route@13279,whole:Route@49446 a0b8d53d7ea0ecb026a3055a3c20e6845fcf93ac18f37c6ba97cd662343896e8
+internal/host/claimunit.go claimUnitContent authority E1,E3 rev3=PROPOSED-p3;identity=root claim/adoption controller uid 0;basis=adds write permission for exactly the public retry directory only when the root settings reader has verified a complete census and prepared that directory;rev3=census-ruling-agent-start-demo-1;basis=Demo-only ReadWritePaths for instance data/runtime, staged files and root release lock; ordinary rendering unchanged.;rev3=census-ruling-agent-start-demo-1-followups;basis=In demo box mode, declare StateDirectory=carlos-release/private with mode 0700 so systemd creates root-owned release state before namespace setup and keeps it writable. Existing ReadWritePaths and ordinary/claims rendering stay unchanged. No new read site or caller-controlled path.;rev3=census-ruling-agent-start-demo-3;basis=Declare /var/lib/carlos-demo-snapshots as root-owned StateDirectory with mode 0700 only for configured demo boxes, including recovery with admission off. Ordinary claims units retain their original directories. The shared unit template is unchanged from main; no file read is added.;rev3=census-ruling-gvisor-demos;basis=Mark only claim/demo renderings explicitly; common host.env remains loaded. Ordinary rendering masks CARLOS_HOST_CLAIM with UnsetEnvironment, removed only for a successfully parsed enabled claim rendering. Existing template read unchanged. Task 7: render aggregate build slice through SlicePropertiesFor using the resolved host mode, with 32 MiB and 64-task gVisor overhead per slot. Existing control permissions unchanged.;rev3=census-ruling-same-box-edge-fence;basis=Root unit rendering (claims mode). The control unit's families line is now `RestrictAddressFamilies=AF_UNIX AF_NETLINK`; the claims rewrite matches that line (it matched the old one exactly, and would otherwise have silently dropped AF_INET/AF_INET6) and renders `AF_UNIX AF_NETLINK AF_INET AF_INET6`. No read added; no other directive changed. data-literal@1504 b3b3bc5b3c60679ab11d13673626819f54d71a6f217c9ffddaccb184f1ef8997
+internal/host/layoutleg.go layoutStatusReport diagnostic H3 no-effect;rev3=census-ruling-instance-egress-sizes-328-329;basis=#329 plan 3 Task 7: each activator-managed instance row gains a Size cell, rowSizeCell(armedSizeSource.Load(), rt.Host, word) (the added registry:Host site), which for an awake nested row reads that host's cgroup memory.max through readSizeInForce (a decision row, in the agent); still a status report with no effect on any decision.;rev3=census-ruling-alias-socket-follow-338;basis=#338: a platform socket row reports alias (aliasLayout) instead of external; reads Platform;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Task 5: Pass.Held takes the whole route (so a row with a runtime is never reported as held); status display only;rev3=census-ruling-gvisor-demos;basis=Task 8: add root-reported configured/effective mode, runtime pin and readiness through Client.SandboxStatus, plus observed per-row family from the activator handle. Missing/stale root builds remain unknown. Presentation only, no root decision.;rev3=census-ruling-same-box-edge-fence;basis=Agent (uid carlos). Both returns set LayoutReport.EdgeFence from edgeFenceStatusReport() (root's /ready answer through the existing client, under DeadlineReady; nil when root cannot be asked). Its existing reads are unchanged. registry:Hibernate@1502,registry:Hibernate@1590,registry:Host@1315,registry:Host@1338,registry:Host@1420,registry:Host@1524,registry:Host@1740,registry:Kind@667,registry:Platform@1467,registry:Socket@1482,registry:Socket@1570,whole:Route@1014,whole:Route@1547,whole:Route@156,whole:Route@461,whole:Route@752,whole:Route@790,whole:Route@794 aadd22150d322bc482e51591f8b89699bfd37aa8a53b2ffff705266bfd23f345
+internal/host/units/carlos-instance-control.service external authority B3,C,D,E1,J4 root-input;kept=B3,C,D,E1;scope=protected-decision-only;rev3=census-ruling-agent-start-demo-3;basis=Correct the runtime-write comment to include escaped demo snapshot .mount units alongside per-generation drop-ins; service directives are unchanged.;rev3=census-ruling-region-ha-graceful-terminate-t1;basis=Region HA T1/DR-4 final fix: retain After=nftables.service without Wants or Requires; add Restart=on-failure and RestartSec=1 so a crashed control restarts before a later edge stop can block socket activation and shutdown proofs; rewrap the header and explain this ordering. Same ExecStart and protections; no new root read, input, path, command or capability.;rev3=census-ruling-gvisor-demos;basis=Add Wants/After installer and narrowly writable rootfs parent. Keep one host.env EnvironmentFile and other hardening.;rev3=census-ruling-gvisor-update-dirs;basis=Make the existing /var/lib/carlos/oci-rootfs writable-path entry optional when absent so old updaters can start the new control unit; retain ProtectSystem=strict and the same path and environment. No new root read.;rev3=census-ruling-same-box-edge-fence;basis=RestrictAddressFamilies gains AF_NETLINK (nft talks netlink), with a comment; the group drop-in already granted it on group boxes. No capability, path, environment or ExecStart change. Without it nft fails and the whole #367 deny stays. file:external@0 2807ef8f0e9950e65e425f931ef88326722183abddb554de82fcc0e054476985
+internal/host/units/carlos-instances.slice external legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-same-box-edge-fence;basis=RefuseManualStop=yes, with a comment naming the remaining stop levers (stop 'carlos-instances-*.slice', kill carlos-instances.slice). Defence in depth for the fence (a recreated slice leaves nft's rules matching an old cgroup id); no read, no other directive. file:external@0 09de7ed1ab8fa8dca0d150490a453a680f63cc0826b94c5836923a4b4f1796f9
+internal/host/units/carlos.slice external legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-same-box-edge-fence;basis=RefuseManualStop=yes, with a comment: a stop of carlos.slice propagates to carlos-instances.slice and recreates it. Memory limits unchanged; no read. file:external@0 c431d5b06875f361532c80afaa69bf3c8a4a40fb8b09a0761164f0f85aaf7890
+internal/instancectl/server.go type Server legacy accepted-legacy accepted-legacy;rev3=census-ruling-carlos-run;basis=Re-digested at the pre-land merge: the body includes main's own change under census ruling 292, with no further change from this branch. Census ruling 292 reclassified this declaration accepted-legacy (J2,J4) for root's per-host ordering of legacy run starts against stops; this ruling kept the row as main classed it. Its own addition is the cmd start's poll and wait bounds and its per-host lock map: field declarations only;rev3=census-ruling-rootfs-apps-2;basis=new fields: HostRuntime, ProbeImage, ProbeImageFile, RootfsProbeOut, DenyEvery, the deny's lastDeny and denyMu, the rootfs probe's report and lock, the jit reload counters and imageDigests; genStarting counts binary generation starts per unit; rootfsLocksMu and rootfsLocks, one lock entry per rootfs unit name being started or removed right now, held by a start from its layout through systemctl start and its own cleanup and by a removal from its proof through the raw removal, a removal refusing while it is taken, a waiting start giving up when its request ends, an entry dropped with its last holder or waiter (fixes E6, L2, L3); rootfsProvenHook, a test hook run between the proof and the raw removal; field declarations only; no read added;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328 plan 2 and #329 plan 3 Task 5: the declaration gains sliceLocks (one mutex per host slice, taken by /size and /parent) and Egress (the asserter every start path calls), and its comment names the egress allow (plan 3's ControlDropInDir field was deleted in ef38e13b, the P1 EROFS fix); the same one site, the Statfs field, offset moved; no read added.;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 6: comments only: the one-shot pacing fields cover /cmd and /tty, and cmdLocks is now keyed by (role, host) (oneShotKey, PF-7) so a session's start never waits behind a command's; field declarations unchanged; the same one site, no read added;rev3=census-ruling-agent-start-demo-1;basis=Adds fixed demo configuration, registry views, derived runtime root, synchronization and purge guard.;rev3=census-ruling-region-ha-p3b;basis=Add hairpinActive boolean alongside lastDeny under existing deny synchronization. Field declaration only; existing Statfs selector unchanged, no new read or externally supplied authority.;rev3=census-ruling-region-ha-p3b2-rolls;basis=adds one field holding the current hairpin exit watcher, guarded by the root hairpin flock; no new read;rev3=census-ruling-agent-start-demo-3;basis=Retain the snapshot supervisor in instance-control state; no new request-selected path. Census read-site delta: unchanged (1).;rev3=census-ruling-gvisor-demos;basis=Retain Task 1 mode/error/readiness fields, baseline/runtime callbacks, Task 4 per-host validated staged descriptors and root-selected probe nonce. Fix round 1 adds a private writer-operation seam assigned only in package tests, after the unchanged GVisorID admission check; production defaults still call the same checked constructor, WriteRootfs, WriteBundle and verifier. No new direct read or request-controlled callback. Task 5: private injected removal seam for unprivileged tests; production default removes only root-derived bundle and skeleton after both-family proof inside existing start fence. No new request field or agent-selected unit. Task 6: Retain serialized probe nonce, runtime-set identity verifier/token, fixed claims flag, bundle discovery root, and private unprivileged identity seam. No request-controlled callback or path; existing declaration read-site classification unchanged. Task 6 fix round 1: private gvisorProbeTestOps is set only in package tests; production defaults retain all fixed paths and the checked root output opener. No externally supplied callback or new direct read. Final R1 P2: retain fixed skeleton parent and concurrent per-instance cleanup refusals; no direct read or external configuration field. Carry the root-only host.env validation callback into Ready; no agent read or caller-selected path.;rev3=census-ruling-same-box-edge-fence;basis=Field declarations only: NFT (the nft runner; nil never loads the fence), EdgeFenceOff (host.env CARLOS_EDGE_FENCE=off), and under the existing denyMu/mu: fenceAddrs, fenceReason, fenceRetry, denyApplied. No read added. file:Statfs@5239 8a1320185105abfc7c531195a9b83836137e1fe7c627b66e056b484a92167665
+internal/instanceexec/probe_hardening.go networkAndIPCChecks legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-2;identity=both isolation probes (carlos instance-probe in carlos-instance-probe.service and instance-probe --rootfs in carlos-instance-rootfs-probe.service, both started by instance control, user carlos inside the unit's own namespace; no tenant code runs there);basis=root-input (J4, as hardeningChecks, whose body this is): new (rootfs Plan 2 Tasks 7 and 7a): hardeningChecks' network, IPC and resource lines, shared by both probes, with the box-addr (boxAddrClosed) and mdwe lines added; its two sites are hardeningChecks': ReadFile of the unit's resolv.conf and of its own cgroup's io.weight; no root process runs it; decides nothing for root;rev3=census-ruling-instance-syscall-filter;basis=one more verdict line, syscall-filter (syscallFilterHeld: both calls must answer ENOSYS; unverified when the unit does not advertise the filter); inside the probe units as carlos; decides nothing for root beyond one more probe line that can fail readiness;rev3=census-ruling-same-box-edge-fence;basis=Probe (uid carlos inside the probe units; no root). Two more verdict lines after box-addr: box-addr-ports (TCP connect to port 22 on each address in root's box-addrs must not succeed) and box-addr-edge (TCP 443 or 80 on fenced addresses; ok or unverified, never fail). Decides nothing for root beyond one more line that can fail readiness. file:ReadFile@352,file:ReadFile@5123 90b1368d3375768ccfb8218596c864395ed3d1b00f1c971a722d9cdb0bef4acb
+status_instances.go printStatusLayout legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328 plan 2 Task 12 and #329 plan 3 Task 10: carlos status --layout, in the operator's carlos CLI on the operator's own machine, prints SIZE and EGRESS columns from the console's JSON (statusLayoutRow.Size and Egress), joins the egress reason into REASON and prints one note when a size is pending; the same one site (the /data literal in the mixed-box warning), no read added.;rev3=census-ruling-region-labels;basis=a REGION column (statusRegionCell) from the console's answer; no read added;rev3=census-ruling-gvisor-demos;basis=Task 8: print draft SANDBOX column and one exec-sandbox summary per reported box from the existing operator API. Missing/stale reports display unknown; no new file read or authority.;rev3=census-ruling-same-box-edge-fence;basis=CLI (operator's machine), not on a box. One more call, printEdgeFenceStatus, printing one line per box from the console's JSON: same-box calls: on / off (reason) / not needed (reason) / unknown. No read. data-literal@2445 8c7f8f30a88506ad8640d4642cdefaef9e31772588d0e1ccc0f1b5f76ba191a3
+internal/edgefence/edgefence.go Exec legacy accepted-legacy accepted-legacy;rev3=census-ruling-same-box-edge-fence;basis=Root (called from instance-control only through Server.NFT). Runs args[0] with fixed arguments; every caller in this package passes "nft" and text rendered from root-read addresses. Output returned to the caller for comparison only. file:CommandContext@85,file:Exec@5 c1d5e35bf2fc09fbb0f0d38f28e995959ac8a1ccd2fbd12f3974ffffc975ff82
+internal/instanceexec/probe_hardening.go readBoxAddrs legacy accepted-legacy accepted-legacy;rev3=census-ruling-same-box-edge-fence;basis=Probe (uid carlos). New: reads root's box-addrs (the same fixed BoxAddrsPath boxAddrClosed read before) and parses `<addr>` or `<addr> edge`; any other line is refused. boxAddrClosed, boxAddrPorts and boxAddrEdge call it. file:ReadFile@62 0bb7ba196291c3e6b0df3284319426025b3448692249b9a307695bebba690593
+internal/instancectl/server.go runWithClaim authority C,D,G Claim instance controller adds held-release RPC dispatch within existing launch/participation execution boundary.;rev3=census-ruling-rootfs-apps-2;basis=takes a RegistryView (HostApp and HostRuntime) for the bare hostApp, and the production Server literal gains HostRuntime, ProbeImage: BuildProbeImage, ProbeImageFile: ProbeImagePath, RootfsProbeOut under /run/carlos-control and DenyEvery: 10s; this body reads nothing new itself; the readers it wires (instanceRegistryHostRuntime, BuildProbeImage, the rootfs probe's output) are decision rows;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328 plan 2 Task 4 and #329 plan 3 Task 5: takes the egress asserter as a parameter, sets it on the production Server literal (Egress) and starts its 30 s Loop beside probeLoop and diskLoop; the literal also names the fixture check ProbeFixturesOK (renamed in plan 2 Task 14). It sets no control drop-in directory: plan 3's ControlDropInDir default (/run/systemd/system.control) was deleted with removeGenControlDropIn in ef38e13b (the P1 EROFS fix), so instance control names systemd's control directory only to read it (TrustedDropinReader). The same four sites (the two exec.CommandContext closures, statfsBytes, the data literal), offsets moved; no read added.;rev3=census-ruling-agent-start-demo-1;basis=Wires root-owned demo config and existing fixed paths into the service.;rev3=census-ruling-region-ha-p3b;basis=Resume root-owned hairpin state before probes/control service work; verify current systemd agent identity and kernel fence/addresses, restore pidfd watch or revoke stale state. Same direct exec/statfs/data sites; indirect inputs are protected root snapshot/state and kernel evidence, never receipt data.;rev3=census-ruling-agent-start-demo-3;basis=Construct the demo snapshot supervisor for configured demo boxes; startup cleanup gates builder readiness. Census read-site delta: unchanged (4).;rev3=census-ruling-gvisor-demos;basis=Retain sandbox modes and error; bind host-provided baseline and runtime callbacks without importing host templates. Existing reads unchanged. Task 6: Capture HostClaims once from ControlConfig/hostwrite.Enabled and set the fixed root-owned bundle discovery directory. Existing command and configuration reads unchanged. Task 7: enable gVisor worker construction through fixed unitFamily(roleBuild); readiness proof rechecks sandbox admission and current Ready without reaching the constructor fatal path for transient refusals. Existing command/config reads unchanged. Final R1 P2: wire the fixed /var/lib/carlos/oci-rootfs parent for native readiness evidence; no request-supplied path. Carry the root-only host.env validation callback into Ready; no agent read or caller-selected path.;rev3=census-ruling-same-box-edge-fence;basis=Root. Sets NFT: edgefence.Exec (runs /usr/sbin/nft from PATH with fixed arguments and root-derived stdin, see the envelope) and EdgeFenceOff from os.Getenv; wraps s.Systemctl with guardStarts and calls bindEgressFence; calls denyLocalAddrs once before Serve so a leftover runtime exemption is checked or replaced by the whole deny before any request is served. No new file read; the exec is nft's. data-literal@2661,file:CommandContext@1151,file:CommandContext@1329,file:Exec@2530,file:Statfs@2682 c6779927278f6143036a9339b5dbcb1e09c2e887a888430068e3583b1222cf99
+@remove internal/instanceexec/probe_hardening.go boxAddrClosed
+@removed internal/instanceexec/probe_hardening.go boxAddrClosed H3 census-ruling-same-box-edge-fence;basis=Probe (uid carlos). Its ReadFile of box-addrs moved into readBoxAddrs, which it now calls; it reads nothing itself. The verdict rule is unchanged: a UDP datagram to every listed address must get EPERM (fenced addresses get it from the fence's drop rule).
+@coverage . 1b8f686b6f724152c6b93faedf9546ba26ea4236f27c7cc5082fc035533e0775
+@coverage internal/edgefence 115531fbda852d7ea66268f229f532f89c419f34b9d81670ec89012767389ee8
+@coverage internal/host 6515a8026cf0ae5430c31ed19fabe0ca8f3814a0d79d30b2bd5985d9831b9cc6
+@coverage internal/host/units 16617c256a62a706c691f42c7bed9c05d3fdd56cc1b4abb938b9c39eff0fefd7
+@coverage internal/instancectl e3308298508c556287cc104e871719f09f149ae6f5b71e2a0dd8bfe1e6be8bdf
+@coverage internal/instanceexec c6071fb5114f8512ac922f4a9c19d0b282a6a22b37894f742425806a2c26aef1
+@coverage internal/status 75501a65f2408dbf473e8f314769f3853aa966a93f4c3f44076d934b10a1e7e6
diff --git a/internal/status/snapshot.go b/internal/status/snapshot.go
index 222022e9d..f81d61f59 100644
--- a/internal/status/snapshot.go
+++ b/internal/status/snapshot.go
@@ -310,6 +310,13 @@ type ExecSandbox struct {
Blocked string `json:"blocked,omitempty"`
}
+// EdgeFence is root's edge fence report (#990): State is "on" or "off",
+// and Reason says why when it is off.
+type EdgeFence struct {
+ State string `json:"state"`
+ Reason string `json:"reason,omitempty"`
+}
+
type RunscStatus struct {
Version string `json:"version"`
SHA256 string `json:"sha256"`
@@ -322,9 +329,13 @@ type RunscStatus struct {
// the box, keyed by host. It carries real hostnames, so โ€” like RowLayout
// above โ€” it is private: BoxMetrics.Layout, never a field on Box itself.
type LayoutReport struct {
- ExecSandbox *ExecSandbox `json:"exec_sandbox,omitempty"`
- Mode string `json:"mode"`
- Rows map[string]RowLayout `json:"rows"`
+ ExecSandbox *ExecSandbox `json:"exec_sandbox,omitempty"`
+ // EdgeFence is whether instances here can call other apps on this box
+ // through the edge (#990). Absent when root did not say (an older
+ // control service, or none reachable): unknown.
+ EdgeFence *EdgeFence `json:"edge_fence,omitempty"`
+ Mode string `json:"mode"`
+ Rows map[string]RowLayout `json:"rows"`
// Default is set when Mode is nested by the deployment's default
// rather than by a recorded intent (design ยง8.6, "Nested by
// default"); DefaultBlocked is why the default is not in force on a
diff --git a/status_instances.go b/status_instances.go
index 366c15748..0e12a0e5c 100644
--- a/status_instances.go
+++ b/status_instances.go
@@ -188,6 +188,7 @@ const (
// statusLayoutBox is one box's layout report.
type statusLayoutBox struct {
ExecSandbox *statusExecSandbox `json:"exec_sandbox"`
+ EdgeFence *statusEdgeFence `json:"edge_fence"`
Box string `json:"box"`
Mode string `json:"mode"`
Stale bool `json:"stale"`
@@ -312,6 +313,7 @@ func printStatusLayout(w io.Writer, boxes []statusLayoutBox) {
fmt.Fprintf(w, "%s %s %s %s %s %s %s %s\n", l.box, l.region, l.host, l.layout, l.sandbox, l.size, l.egress, reason)
}
printExecSandboxStatus(w, boxes)
+ printEdgeFenceStatus(w, boxes)
// A size cell "in>want" is a new size waiting for a cold start (a
// populated slice is not shrunk live, and under host claims no size
// changes live). Said once, whatever the number of such rows.
@@ -353,6 +355,33 @@ type statusExecSandbox struct {
Blocked string `json:"blocked"`
}
+// statusEdgeFence is a box's edge fence report (#990).
+type statusEdgeFence struct {
+ State string `json:"state"`
+ Reason string `json:"reason"`
+}
+
+// printEdgeFenceStatus says, one line per box, whether instances there can
+// call other apps on the same box by hostname (#990): on, off with why,
+// or unknown.
+func printEdgeFenceStatus(w io.Writer, boxes []statusLayoutBox) {
+ sorted := append([]statusLayoutBox(nil), boxes...)
+ sort.Slice(sorted, func(i, j int) bool { return sorted[i].Box < sorted[j].Box })
+ for _, b := range sorted {
+ f := b.EdgeFence
+ switch {
+ case b.Stale:
+ fmt.Fprintf(w, "%s same-box calls: unknown (stale report)\n", b.Box)
+ case f == nil || f.State == "":
+ fmt.Fprintf(w, "%s same-box calls: unknown\n", b.Box)
+ case f.State == "on":
+ fmt.Fprintf(w, "%s same-box calls: on\n", b.Box)
+ default:
+ fmt.Fprintf(w, "%s same-box calls: %s (%s)\n", b.Box, f.State, sandboxWord(f.Reason))
+ }
+ }
+}
+
type statusRunsc struct {
Version string `json:"version"`
SHA256 string `json:"sha256"`
diff --git a/status_instances_test.go b/status_instances_test.go
index 5a0e9a254..41d8ec10d 100644
--- a/status_instances_test.go
+++ b/status_instances_test.go
@@ -318,3 +318,33 @@ func TestStatusLayoutSandbox(t *testing.T) {
t.Fatalf("expected one line per box: %s", &out)
}
}
+
+// #990: one line per box saying whether instances there can call another
+// app on the same box by hostname, from the console's JSON.
+func TestStatusLayoutSameBoxCalls(t *testing.T) {
+ var boxes []statusLayoutBox
+ raw := `[{"box":"leo","edge_fence":{"state":"on"},"rows":[]},` +
+ `{"box":"ec2","edge_fence":{"state":"off","reason":"no public address on this box"},"rows":[]},` +
+ `{"box":"held","edge_fence":{"state":"off","reason":"turned off with CARLOS_EDGE_FENCE=off"},"rows":[]},` +
+ `{"box":"old","rows":[]},` +
+ `{"box":"stale","stale":true,"edge_fence":{"state":"on"},"rows":[]}]`
+ if err := json.Unmarshal([]byte(raw), &boxes); err != nil {
+ t.Fatal(err)
+ }
+ var out bytes.Buffer
+ printStatusLayout(&out, boxes)
+ for _, want := range []string{
+ "leo same-box calls: on\n",
+ "ec2 same-box calls: off (no public address on this box)\n",
+ "held same-box calls: off (turned off with CARLOS_EDGE_FENCE=off)\n",
+ "old same-box calls: unknown\n",
+ "stale same-box calls: unknown (stale report)\n",
+ } {
+ if !strings.Contains(out.String(), want) {
+ t.Errorf("missing %q:\n%s", want, &out)
+ }
+ }
+ if n := strings.Count(out.String(), "same-box calls:"); n != 5 {
+ t.Fatalf("%d same-box lines, want one per box:\n%s", n, &out)
+ }
+}