carlos / platform Public

edgefence: render, load and read back the same-box fence table (#990)

Task 1 (edge audit: no peer-address trust, no edge task) and Task 2 of
the edge-fence plan. The package renders the table in nft's own
readback form, so one text is loaded and compared; the golden fixture
is nft's output from a real kernel. Verify names a recreated slice
(bare cgroup id) as ErrStale. Nothing calls it yet.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
James Adam pushed by james@keymail.dev abf9a7a8cbc45f93f0b946d891aa396c6e67f6f7 parent 23b01bc
4 files changed, +469 −1
  • docs/superpowers/plans/2026-11-13-same-box-calls-edge-fence.md +26 −1
  • internal/edgefence/edgefence.go +220 −0
  • internal/edgefence/edgefence_test.go +212 −0
  • internal/edgefence/testdata/readback-v4-v6.txt +11 −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
index d781b82ef..f46c7a42b 100644
--- 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
@@ -260,11 +260,36 @@ root code changes.
### Task 1: audit the edge for peer-address trust (no code)
-- [ ] Grep `internal/edge` and `internal/activator` for any decision
+- [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`
- [ ] `Rules(addrs []netip.Addr) (string, error)`: the table above,
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..d3bdaf31e
--- /dev/null
+++ b/internal/edgefence/edgefence_test.go
@@ -0,0 +1,212 @@
+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")
+ }
+}
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
+ }
+}