carlos / platform Public

plan: same-box calls through the edge (edge fence, #990)

A cgroup-scoped nft fence lets nested instances reach the box's own
addresses on TCP 80/443 only, so an app can call another app on the
same box by hostname. Rev 2 applies review round 1 and James's answers;
the evidence section records two namespace experiments.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
James Adam pushed by james@keymail.dev 23b01bcde9ad24bd0cd204ed286392ce6f3fb9d7 parent 4f95eb3
1 file changed, +351 −0
  • docs/superpowers/plans/2026-11-13-same-box-calls-edge-fence.md +351 −0
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..d781b82ef
--- /dev/null
+++ b/docs/superpowers/plans/2026-11-13-same-box-calls-edge-fence.md
@@ -0,0 +1,351 @@
+# 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.
+
+## 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)
+
+- [ ] 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.
+
+### Task 2: `internal/edgefence`
+
+- [ ] `Rules(addrs []netip.Addr) (string, error)`: the table above,
+ addresses sorted and validated (global unicast, single IP).
+- [ ] `Expected(addrs) string`: the readback `nft -s -nn -y` prints for
+ that table, from evidence 7's capture.
+- [ ] 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.
+- [ ] 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
+
+- [ ] `denyLocalAddrs`: on non-group boxes, enable/refresh/fail as
+ above; `applyLocalDeny` gets the exempted set.
+- [ ] Startup verification in `Run`, before `Serve`.
+- [ ] Check-before-start at every start site under the slice.
+- [ ] `fenceActive` in `denyLoopWith`'s condition.
+- [ ] Remember the state and the reason (`fenceActive`, `fenceReason`)
+ for reporting.
+- [ ] An operator off switch: `CARLOS_EDGE_FENCE=off` in host.env keeps
+ the full deny (the rollback path without a release).
+- [ ] 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
+
+- [ ] `carlos-instance-control.service`: `RestrictAddressFamilies=AF_UNIX
+ AF_NETLINK` (nft talks netlink; the group drop-in already does this
+ on group boxes).
+- [ ] `carlos-instances.slice` and `carlos.slice`: `RefuseManualStop=yes`,
+ with the comment naming the remaining levers. The control service
+ starts `carlos-instances.slice`.
+- [ ] Missing `nft` binary or a failed load: full deny, reported.
+
+### Task 5: the probe and the guard
+
+- [ ] `box-addr` stays as it is (UDP `EPERM` on every box address).
+- [ ] New `box-addr-ports`: TCP to a non-web port on each box address
+ is refused (reset or `EPERM`, not a connect).
+- [ ] New `box-addr-edge`: TCP 443 on each box address connects when
+ the fence is active; `unverified` when it is off, with the reason.
+- [ ] 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`.
+
+### Task 6: reporting
+
+- [ ] The box report carries the fence state and reason, and
+ `carlos instances list` shows "same-box calls: on" or "off: <reason>"
+ per box (UX pass first, per AGENTS.md).
+
+### Task 7: census, review, drill
+
+- [ ] `make census-card`, CLAIMS, `make census-propose` (root binary
+ and units change).
+- [ ] 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.
+
+## 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.