plan: edge PROXY protocol v2 implementation (9 tasks)
Implements the approved spec 2026-11-12-edge-proxy-protocol-design.md; Astra plan review brief beside it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2 files changed,
+322
−0
docs/superpowers/plans/2026-11-12-edge-proxy-protocol.md+268 −0docs/superpowers/plans/CODEX-REVIEW-BRIEF-edge-ppv2-plan.md+54 −0
CI cancelled — superseded by a newer push — run details
Intent
diff --git a/docs/superpowers/plans/2026-11-12-edge-proxy-protocol.md b/docs/superpowers/plans/2026-11-12-edge-proxy-protocol.md| new file mode 100644 |
| index 000000000..594b75e51 |
| --- /dev/null |
| +++ b/docs/superpowers/plans/2026-11-12-edge-proxy-protocol.md |
| @@ -0,0 +1,268 @@ |
| +# Edge PROXY protocol v2 Implementation Plan |
| + |
| +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. |
| + |
| +**Goal:** The edge parses PROXY protocol v2 from its region NLB's private addresses, so client IP preservation can go off on the HA target groups without losing client addresses; plus the trust barrier, the trust metric and alarm, the activation guard, the tofu inputs and the cutover tooling. |
| + |
| +**Architecture:** A new dependency-free package `internal/proxyproto` owns the v2 parser and a listener wrapper whose connections resolve a parse state lazily on their own goroutine and rewrite `RemoteAddr`. The edge wraps `:80`/`:443` only when `CARLOS_INGRESS_PROXY_SOURCES` is set, adds a health-only gate for connections without a client, and owns a persistent trust barrier. The agent exposes the barrier through the existing drain socket, publishes one metric, and refuses to activate a binary without the `ingress-proxy-v2` feature on an armed box. Tofu and two Python scripts cover the NLB side. |
| + |
| +**Tech Stack:** Go 1.26 (net/http, crypto/tls, net/netip), OpenTofu modules with `tofu test` mocks, Python 3 scripts with `unittest`. |
| + |
| +**Spec:** `docs/superpowers/specs/2026-11-12-edge-proxy-protocol-design.md` (rev 5, approved 2026-11-12). Every task reads the sections it names. |
| + |
| +## Global Constraints |
| + |
| +- Branch `edge-ppv2` from `origin/main`; one commit per task; commit subjects under 80 characters, body after a blank line, ending with `Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>`. |
| +- No new Go module dependency. `go vet ./...` clean; the new and changed packages cross-build for `GOOS=darwin` and `GOOS=windows` (`GOOS=darwin go build ./...`, `GOOS=windows go build ./...`). |
| +- Local tests are targeted only: `go test ./internal/<pkg>/ -run <Name>`; never the full suite locally (CI runs it). Leave `GOCACHE` at its default. Use `TMPDIR=$TMPDIR` scratch only; never `/tmp` directly. |
| +- Dormant by default: a box without `CARLOS_INGRESS_PROXY_SOURCES` behaves byte for byte as today (no wrapper, no peek, no new route served, no metric, no guard). |
| +- Exact values from the spec: PPv2 signature `\r\n\r\n\x00\r\nQUIT\n` (12 bytes); version nibble 2; commands LOCAL (0x0) and PROXY (0x1); families UNSPEC (0x00), INET/STREAM (0x11), INET6/STREAM (0x21); header total at most 512 bytes; header read deadline 10 s from accept; key holds 1 to 16 private (RFC 1918) IPv4 addresses, no duplicates; marker source range `192.0.2.0/24`; feature name `ingress-proxy-v2`; metric `IngressProxyTrustViolations` in `Carlos/Host` with dimensions `Deployment` and `Region`. |
| +- Never run `git worktree prune`, never create or remove worktrees (the controller owns them). No infra apply, no AWS write, no SSM command: this branch is code, tests and docs only. |
| +- No user-facing copy beyond operator journal lines and CLI error text, written plainly; curly quotes are not needed in operator logs. |
| + |
| +## Review Focus |
| + |
| +1. **A trusted connection that sends nothing** (an NLB preconnect or a stalled client): the accept loop must keep accepting, `Shutdown`/`CloseIngress` must end it within their bounds, and the barrier sweep must close it. Pinned in Task 2 (`TestSilentTrustedDoesNotBlockAccept`, `TestCloseDuringPendingParse`) and Task 4 (`TestShutdownEndsPendingHeader`). |
| +2. **A health check from a trusted peer with a demo or unknown `Host`**: it must reach `lbHealthAnswer` and nothing else. Pinned in Task 4 (`TestNoClientHealthDispatchIgnoresHost`). |
| +3. **A hairpinned connection on a member** after wrapping: it must keep its public-address normalisation. Pinned in Task 4 (`TestHairpinSurvivesProxyWrap`). |
| +4. **An old binary reaching an armed box by rollback** (`carlos.prev` older than vN): refused, the running binary kept. Pinned in Task 6 (`TestRollbackRefusesPrevWithoutFeature`). |
| +5. **A key that misses one NLB node** (zone added later): that node's headers are ignored and counted `ignored_private`, never trusted. Pinned in Task 2 (`TestUntrustedPrivateHeaderCounted`). |
| + |
| +--- |
| + |
| +### Task 1: The PPv2 parser |
| + |
| +**Files:** |
| +- Create: `internal/proxyproto/header.go` |
| +- Test: `internal/proxyproto/header_test.go` |
| + |
| +**Interfaces:** |
| +- Produces: |
| + - `const Signature = "\r\n\r\n\x00\r\nQUIT\n"` |
| + - `type Command uint8` with `CommandLocal Command = 0`, `CommandProxy Command = 1` |
| + - `type Header struct { Command Command; Source netip.AddrPort; Destination netip.AddrPort; HasAddresses bool }` (`HasAddresses` false for LOCAL and UNSPEC) |
| + - `var ErrMalformed = errors.New("proxyproto: malformed header")` |
| + - `func ReadHeader(r io.Reader) (Header, error)`: reads exactly one header whose 12-byte signature the caller has already confirmed is next in `r` (it re-reads and checks the signature), the 4-byte fixed part, then the declared length; returns `ErrMalformed` (wrapped with detail) for any violation; never reads past the declared length. |
| + - `func UsableSource(a netip.Addr) bool`: unicast and not loopback, unspecified, link-local or multicast. |
| + |
| +- [ ] **Step 1: Write the failing tests** in `header_test.go`, table-driven, building headers with a test helper `build(cmd, fam byte, src, dst string, tlv []byte) []byte`: |
| + - `TestReadHeaderProxyV4`: PROXY INET `203.0.113.7:51000 -> 54.77.110.223:443` gives `Command==CommandProxy`, `Source==203.0.113.7:51000`, `HasAddresses`. |
| + - `TestReadHeaderProxyV6`: same for `[2001:db8::1]:51000`. |
| + - `TestReadHeaderLocal`: LOCAL with family UNSPEC and length 0 gives `HasAddresses==false`. |
| + - `TestReadHeaderUnspecProxy`: PROXY with UNSPEC gives `HasAddresses==false`. |
| + - `TestReadHeaderSkipsTLVs`: INET plus an `0xEA` TLV of 10 bytes parses; the reader is left exactly at the end of the declared length (assert the next byte read is the payload's first byte). |
| + - `TestReadHeaderRefuses` (table, each `errors.Is(err, ErrMalformed)`): version nibble 1; command 2; family 0x12 (INET/DGRAM); family 0x31 (UNIX); INET length 11; INET6 length 35; total length 513 (16 + 497); truncated after the fixed part; truncated inside the addresses. |
| + - `TestUsableSource`: true for `203.0.113.7`, `2001:db8::1`, `10.1.2.3`; false for `127.0.0.1`, `0.0.0.0`, `169.254.1.1`, `224.0.0.1`, `::1`, `fe80::1`. |
| +- [ ] **Step 2: Run** `go test ./internal/proxyproto/ -run 'TestReadHeader|TestUsableSource'`. Expected: build failure (package empty). |
| +- [ ] **Step 3: Implement** `header.go` to the interface above. Use `io.ReadFull` for each part; check `total = 16 + length <= 512` before reading the body. |
| +- [ ] **Step 4: Run** the same command. Expected: PASS. |
| +- [ ] **Step 5: Commit** `proxyproto: PPv2 header parser`. |
| + |
| +### Task 2: The listener wrapper, parse state and barrier hook |
| + |
| +**Files:** |
| +- Create: `internal/proxyproto/listener.go`, `internal/proxyproto/conn.go`, `internal/proxyproto/counters.go` |
| +- Test: `internal/proxyproto/listener_test.go` |
| + |
| +**Interfaces:** |
| +- Consumes: Task 1's `ReadHeader`, `UsableSource`, `Signature`. |
| +- Produces: |
| + - `type State int` with `StatePending, StateProxied, StateNoClient, StatePlain, StateFailed` |
| + - `type Config struct { Trusted []netip.Addr; HeaderTimeout time.Duration; Marker netip.Prefix; Barrier func() bool; Now func() time.Time }` (`Barrier` nil means never up; `Now` nil means `time.Now`) |
| + - `func NewListener(inner net.Listener, cfg Config) *Listener`; `(*Listener).Accept() (net.Conn, error)` returns at once with a `*Conn`; `Close`, `Addr` delegate. |
| + - `type Conn struct` implementing `net.Conn` plus: |
| + - `func (c *Conn) NetConn() net.Conn` (the wrapped connection) |
| + - `func (c *Conn) Peer() netip.AddrPort` (kernel peer, never blocks) |
| + - `func (c *Conn) Trusted() bool` (peer in `Trusted`, never blocks) |
| + - `func (c *Conn) State() State` (resolves the parse if pending; safe on the serving goroutine) |
| + - `func (l *Listener) CloseTrusted() int`: closes every live trusted `*Conn` (pending included), returns the count. Trusted conns are registered at `Accept` and removed on `Close`. |
| + - `type Counters struct { Proxied, NoClient, NoClientRefused, Ignored, IgnoredPrivate, MarkerTrusted, Malformed, Timeout uint64; ProxiedByNode map[netip.Addr]uint64 }`; `func (l *Listener) Counters() Counters` (a copy); `func (l *Listener) NoteRefused()` increments `NoClientRefused`. |
| +- Behaviour fixed by spec §4.3, §4.4, §4.7, §6.4: |
| + - `RemoteAddr()` on an untrusted conn returns the kernel peer at once; on a trusted conn it resolves the parse first, then returns the header source for `StateProxied`, else the kernel peer. |
| + - The first `Read` or `RemoteAddr` resolves once (`sync.Once`-style, but `Close` must not wait on the resolve lock: close the inner conn directly, which fails a pending read). |
| + - Signature detection reads byte by byte up to 12 bytes, stopping at the first mismatch; mismatched bytes are replayed to `Read`. |
| + - Trusted: deadline `HeaderTimeout` from accept, set before the first read and cleared after; timeout closes, `StateFailed`, `Timeout++`. |
| + - Trusted, PROXY with usable source: `StateProxied`, `Proxied++`, `ProxiedByNode[peer]++`. If `Marker` contains the source: close, `StateFailed`, `MarkerTrusted++`. If `Source` is not usable: close, `StateFailed`, `Malformed++`. |
| + - Trusted, LOCAL/UNSPEC, or no signature: `StateNoClient`, `NoClient++`. |
| + - **Barrier:** if `cfg.Barrier()` is true when a trusted conn's state resolves, a would-be `StateProxied` becomes `StateNoClient` (and is not counted `Proxied`). This one check at resolution is the whole barrier rule. |
| + - Untrusted with a valid header: header consumed, `StatePlain`, `Ignored++`, and `IgnoredPrivate++` when the peer is RFC 1918. Untrusted malformed: close, `Malformed++`. Untrusted, no signature: `StatePlain`. |
| + |
| +- [ ] **Step 1: Write the failing tests** in `listener_test.go`, over a real `net.Listen("tcp", "127.0.0.1:0")`. Trust is exercised by listing `127.0.0.1` in `Trusted` for the trusted cases and `127.0.0.2`-free configs for untrusted ones: |
| + - `TestTrustedProxyRewritesRemoteAddr`: header src `203.0.113.7:51000` then `GET`; `RemoteAddr()` is `203.0.113.7:51000`; the next `Read` returns `GET`. |
| + - `TestUntrustedHeaderIgnored`: untrusted config; the same bytes; `RemoteAddr()` is the loopback peer; `Read` returns `GET`; `Counters().Ignored==1`. |
| + - `TestUntrustedPrivateHeaderCounted`: wrap with a test-only peer override (`withPeer` option in an `export_test.go`) giving peer `172.31.99.9`; `IgnoredPrivate==1`. |
| + - `TestNoSignaturePassthrough`: TLS-like first byte `0x16` then data; untrusted and trusted both read the bytes unchanged; trusted state `StateNoClient`. |
| + - `TestLocalHeaderNoClient`: LOCAL header; `State()==StateNoClient`; `RemoteAddr()` is the kernel peer. |
| + - `TestSecondHeaderIsPayload`: two headers back to back; only one consumed; `Read` returns the second header's bytes. |
| + - `TestMarkerSourceClosed`: header src `192.0.2.1`; conn closed; `MarkerTrusted==1`. |
| + - `TestTrustedHeaderTimeout`: `HeaderTimeout: 50ms`, client sends nothing; `State()` is `StateFailed` within 1 s; `Timeout==1`. |
| + - `TestSilentTrustedDoesNotBlockAccept`: one silent trusted client, then a second client sends a valid header; the second is accepted and resolved within 1 s while the first is still pending. |
| + - `TestCloseDuringPendingParse`: a goroutine blocks in `State()` on a silent trusted conn; `Close()` returns within 100 ms and `State()` returns `StateFailed`. |
| + - **Mandatory race test (a)** `TestBarrierPendingHeaderCompletesAsNoClient`: trusted client sends the first 8 bytes of a header; barrier flips to true; `CloseTrusted()` is **not** called; the client sends the rest; `State()==StateNoClient`, `RemoteAddr()` is the kernel peer, `Proxied==0`. |
| + - **Mandatory race test (b)** `TestBarrierLaterAcceptIsNoClient`: barrier true; a new trusted client sends a full valid PROXY header; `State()==StateNoClient`. |
| + - `TestCloseTrustedClosesPendingAndOpen`: one pending and one resolved trusted conn plus one untrusted; `CloseTrusted()==2`; the untrusted conn still reads. |
| +- [ ] **Step 2: Run** `go test ./internal/proxyproto/ -run 'Test(Trusted|Untrusted|NoSignature|Local|Second|Marker|Silent|Close|Barrier)' -race`. Expected: build failure. |
| +- [ ] **Step 3: Implement** `listener.go`, `conn.go`, `counters.go` to the interfaces above (counters as atomics plus a mutex-guarded map). |
| +- [ ] **Step 4: Run** the same command. Expected: PASS, no race reports. |
| +- [ ] **Step 5: Commit** `proxyproto: listener with lazy parse state and barrier hook`. |
| + |
| +### Task 3: The host-env key |
| + |
| +**Files:** |
| +- Modify: `internal/hostenv/hostenv.go` (Optional list at :75-110, new validator beside `validateIngressTargetGroups` :253-285, calls in `Assemble` :231-237 and `Seed` :465) |
| +- Modify: `internal/hostenv/group.go` (`AssembleGroup` :135-138) |
| +- Test: `internal/hostenv/hostenv_test.go` |
| + |
| +**Interfaces:** |
| +- Produces: `func ParseProxySources(value string) ([]netip.Addr, error)` in `internal/hostenv` (exported: Task 4 uses it). Empty or whitespace gives `nil, nil`. Each comma-separated entry must parse as IPv4, be in 10/8, 172.16/12 or 192.168/16, with no duplicates and 1 to 16 entries; anything else is `ErrValue` naming `CARLOS_INGRESS_PROXY_SOURCES` only. |
| + |
| +- [ ] **Step 1: Write the failing tests**, copying the shape of `TestIngressTargetGroupsHostEnv` (:537), `TestIngressTargetGroupsRefusedWhenNotTargetGroupARNs` (:568) and `TestIngressTargetGroupsInAGroupBoxHostEnv` (:611): |
| + - `TestProxySourcesHostEnv`: `""`, `"172.31.29.110"`, `"172.31.29.110,172.31.11.189"` seed and fetch unchanged. |
| + - `TestProxySourcesRefused` (table): `"54.77.110.223"` (public), `"172.31.1.1,172.31.1.1"`, `"fe80::1"`, `"172.31.1.1,"`, 17 entries, `"172.31.1.1/32"`; each `errors.Is(err, ErrValue)` and the message names the key, never the value. |
| + - `TestProxySourcesInAGroupBoxHostEnv`: the key passes `AssembleGroup` with a valid value and is refused with a public address. |
| +- [ ] **Step 2: Run** `go test ./internal/hostenv/ -run TestProxySources`. Expected: FAIL. |
| +- [ ] **Step 3: Implement**: add `"CARLOS_INGRESS_PROXY_SOURCES"` to `Optional` in sort order; `ParseProxySources`; `validateProxySources(env map[string]string) error` called from `Assemble`, `Seed` and `AssembleGroup` next to `validateIngressTargetGroups`. |
| +- [ ] **Step 4: Run** the same command, then `go test ./internal/hostenv/`. Expected: PASS. |
| +- [ ] **Step 5: Commit** `hostenv: CARLOS_INGRESS_PROXY_SOURCES with validation`. |
| + |
| +### Task 4: Edge wiring, health-only gate, barrier, counters |
| + |
| +**Files:** |
| +- Create: `internal/edge/proxyingress.go` |
| +- Modify: `internal/edge/edge.go` (the `Serve` listener block at :5290-5312), `internal/edge/hairpin.go` (`hairpinConnContext` :84-92), `internal/edge/ingressdrain.go` (`publicServers` :91-95) |
| +- Test: `internal/edge/proxyingress_test.go` |
| + |
| +**Interfaces:** |
| +- Consumes: Task 2's `proxyproto.NewListener`, `Config`, `*Conn`, `State`, `CloseTrusted`, `Counters`, `NoteRefused`; Task 3's `hostenv.ParseProxySources`. |
| +- Produces (methods on `*Edge`, used by Task 5): |
| + - `func (e *Edge) RaiseTrustBarrier() (closed int, err error)`: write the barrier file (fsync file and directory), set the flag, then `CloseTrusted()` on both listeners; returns the total closed. Idempotent. |
| + - `func (e *Edge) ResumeTrust() error`: remove the file (fsync directory), then clear the flag. |
| + - `func (e *Edge) TrustBarrierUp() bool` |
| + - `func (e *Edge) ProxyCounters() (proxyproto.Counters, bool)`: summed over both listeners; `false` when unarmed. |
| +- Fixed values: barrier file `filepath.Join(dataDir, "edge", "trust-barrier")` (`dataDir` as at `edge.go:5026`); read once before either listener binds; a present file means the barrier is up at start. Header timeout 10 s. Marker `192.0.2.0/24`. |
| +- Behaviour (spec §4.1, §4.5, §4.6): |
| + - Armed only when `CARLOS_INGRESS_PROXY_SOURCES` parses non-empty; a parse error is fatal at start (`log.Fatal`, naming the key). Unarmed: no other change in this task applies. |
| + - Wrap order: `listen` -> `ConfigureGroupHairpin` -> `proxyproto.NewListener`, for both listeners. |
| + - `hairpinConnContext` unwraps `interface{ NetConn() net.Conn }` before its type assertion (loop: TLS conn, then proxy conn). |
| + - A `ConnContext` on both servers stores the `*proxyproto.Conn` (found by the same unwrapping) in the context without calling `RemoteAddr` or `State`. |
| + - Handler gate, outermost on both servers: if the conn's `State()` is `StateNoClient`: on `:80` a `GET`/`HEAD` of `lbhealth.Path` calls `e.lbHealthAnswer(w, r)` directly and returns (503 if it declines); every other request gets `503` with `Connection: close`, and `NoteRefused()`. No other state is touched. |
| + - Journal: at start `edge: proxy protocol: armed on :80 and :443, trusting <sorted list>, barrier <up|down>`; every minute while armed one line with all counters, `proxied` per node address (`proxied_by_node=172.31.29.110:N,172.31.11.189:M`) and the barrier state; `NoClientRefused` or `IgnoredPrivate` moving also logs one warning line a minute (use `e.logThrottled`). |
| +- [ ] **Step 1: Write the failing tests** in `proxyingress_test.go`. Build servers with the production helpers (`publicServers`, `ConfigureGroupHairpin` where a hairpin config fixture exists, and the new wrap) over loopback listeners with `127.0.0.1` trusted: |
| + - `TestProxiedRequestReachesLimiterAndXFF` (production-wired): a PROXY header from `203.0.113.7` then a request to an instance route whose upstream echoes `X-Forwarded-For`; the upstream sees `203.0.113.7`, and the rate limiter's client key (via the existing test seam used by `ratelimit` tests in `internal/edge`) is `203.0.113.7/32`. |
| + - `TestNoClientHealthDispatchIgnoresHost`: LOCAL header then `GET /.carlos/lb-health` with `Host` set to an ordinary route, a demo host, and an unknown host; each answer comes from `lbHealthAnswer` (assert its body or status as the existing lbhealth tests do), never a redirect or demo page. |
| + - `TestNoClientAppRequestRefused`: LOCAL header then `GET /` on `:443` and on `:80`; `503`, `Connection: close`; `NoClientRefused==2`; no upstream call. |
| + - `TestHairpinSurvivesProxyWrap`: with the hairpin fixture, a hairpin connection's request has `RemoteAddr` equal to the box's public address, as without the wrap. |
| + - `TestShutdownEndsPendingHeader`: a silent trusted conn; `httpsSrv.Shutdown` with a 6 s context returns before it expires, and `CloseIngress` (W6) likewise. |
| + - `TestTrustBarrierPersistsAndResumes`: `RaiseTrustBarrier` writes the file and closes trusted conns; a new `Edge` built over the same `dataDir` starts with `TrustBarrierUp()==true`; `ResumeTrust` removes it. |
| + - `TestUnarmedEdgeUnchanged`: without the key, `ProxyCounters` returns `false` and a request carrying a PPv2 header gets today's response (400 on `:80`). |
| +- [ ] **Step 2: Run** `go test ./internal/edge/ -run 'TestProxied|TestNoClient|TestHairpinSurvives|TestShutdownEnds|TestTrustBarrier|TestUnarmed' -race`. Expected: FAIL. |
| +- [ ] **Step 3: Implement** `proxyingress.go` and the edits to the interfaces above. |
| +- [ ] **Step 4: Run** the same command, then `go test ./internal/edge/ -run 'Hairpin|LBHealth|IngressDrain|PublicServers'`. Expected: PASS. |
| +- [ ] **Step 5: Commit** `edge: parse PPv2 from the NLB, health-only gate, trust barrier`. |
| + |
| +### Task 5: Agent: barrier verbs, socket routes, trust metric |
| + |
| +**Files:** |
| +- Modify: `internal/host/hadrain_socket.go` (`handler` :79-95, `drainClient` :~189), `internal/host/hadrain_call.go` (`drainCallOp` :141, `drainCallTxnless` :147, `socketDrainCall` :153, `drainCallResult` :~110), `internal/host/hadrain_call_linux.go`, `internal/host/hadrain_call_other.go`, `internal/host/agent.go` (socket serving condition :1300, metric wiring near :1087), `internal/host/memwatch.go`, `system.go` (verbs beside `group-maintenance` :60-92) |
| +- Create: `internal/host/edgetrust.go` (route handler and metric datum), `internal/host/edgetrust_test.go` |
| + |
| +**Interfaces:** |
| +- Consumes: Task 4's `RaiseTrustBarrier`, `ResumeTrust`, `TrustBarrierUp`, `ProxyCounters` (through the `demoEdge` atomic pointer, `agent.go:323`). |
| +- Produces: |
| + - Routes on the drain socket under a new prefix branch `/v1/edge/`: `POST /v1/edge/trust-barrier` -> `{"barrier":true,"closed":N}`; `POST /v1/edge/trust-resume` -> `{"barrier":false}`; `GET /v1/edge/trust` -> `{"armed":bool,"barrier":bool}`. Query strings refused like the ingress handler. |
| + - Drain-call ops `trust-barrier`, `trust-resume` (txnless), a `drainCallResult.Trust *trustResult` field. |
| + - Root verbs `carlos system edge trust-barrier` and `carlos system edge trust-resume` (op role, as `group-maintenance`), printing the result line; a non-armed box answers "this box is not armed for PROXY protocol" with exit 2. |
| + - Socket served when `driver.group != nil || ingressDrainServed(...) || proxySourcesSet(os.Getenv)`. |
| + - `func trustViolationDatum(dims []types.Dimension, delta uint64, now time.Time) types.MetricDatum` -> `IngressProxyTrustViolations`, unit Count, value `delta` (increase of `NoClientRefused + MarkerTrusted` since the last tick). Published in `memwatch.tick` on armed boxes with `CARLOS_HOST_METRICS=cloudwatch`, dimensions `Deployment` = `CARLOS_DEPLOYMENT_BUCKET` and `Region` = `readRoleRegionConfig(roleRegionConfigPath, CARLOS_REGION).RegionCode` (`group_metrics.go:40-64` pattern), on fixed boxes and members alike, independent of `CARLOS_GROUP_ADMISSION`. |
| +- [ ] **Step 1: Write the failing tests** in `edgetrust_test.go`: |
| + - `TestEdgeTrustRoutes`: with a fake edge, the three routes answer as above; a query string is 404. |
| + - `TestDrainSocketServedWhenArmed`: the serving predicate is true for a fixed box with only `CARLOS_INGRESS_PROXY_SOURCES` set, false with nothing set. |
| + - `TestTrustViolationDatum`: name, unit, dimensions and value for `delta=3`. |
| + - `TestMemwatchPublishesTrustDelta`: two ticks with counters 0 then 5 put one datum with value 5; an unarmed edge puts none. |
| + - `TestDrainCallTrustRoundTrip`: `parseDrainCall` accepts the new result field (it uses `DisallowUnknownFields`). |
| +- [ ] **Step 2: Run** `go test ./internal/host/ -run 'TestEdgeTrust|TestDrainSocketServed|TestTrustViolation|TestMemwatchPublishesTrust|TestDrainCallTrust'`. Expected: FAIL. |
| +- [ ] **Step 3: Implement** to the interfaces above, copying the ingress drain op's path end to end. |
| +- [ ] **Step 4: Run** the same command, then `go test ./internal/host/ -run 'Drain|Memwatch|GroupMetric'` and `GOOS=darwin go build ./... && GOOS=windows go build ./...`. Expected: PASS and clean builds. |
| +- [ ] **Step 5: Commit** `host: trust barrier verbs and the trust-violation metric`. |
| + |
| +### Task 6: The activation guard |
| + |
| +**Files:** |
| +- Modify: `commands.go` (`versionCommand` :210-228), `internal/host/systemapply.go` (`stageCandidate` :2532, `restoreFiles` :2124) |
| +- Create: `internal/version/features.go` |
| +- Test: `internal/host/systemapply_features_test.go`, `commands_test.go` (or the existing version command test file) |
| + |
| +**Interfaces:** |
| +- Produces: |
| + - `var Features = []string{"ingress-proxy-v2"}` in `internal/version`. |
| + - CLI `carlos version features`: prints each feature on its own line, nothing else. `carlos version` itself stays byte-identical (install scripts parse it). |
| + - `func (a *systemApplier) requireFeatures(ctx context.Context, binary string) error`: when `CARLOS_INGRESS_PROXY_SOURCES` is set in the box's host.env (read the same way `systemapply.go` reads other host.env keys), runs `a.guardRun(ctx, systemVersionWait, binary, "version", "features")` and refuses unless one output line equals `ingress-proxy-v2`. The refusal error says: "this box parses PROXY protocol from its load balancer (CARLOS_INGRESS_PROXY_SOURCES is set); <binary> does not, so it cannot run here. Roll forward, or to a build at or above the first one with ingress-proxy-v2." |
| + - Called in `stageCandidate` after the existing version check (covers `apply`, system-update adoption and `install-channel`, hence member boot) and in `restoreFiles` on the restore copy before its rename, for operator rollback only. Boot recovery (`--recover`) logs the same message at error level and proceeds, because it restores the binary that last booted, which under §6.1's order already has the feature. |
| +- [ ] **Step 1: Write the failing tests**: |
| + - `TestVersionFeaturesCommand`: `carlos version features` prints `ingress-proxy-v2\n`; `carlos version` output unchanged. |
| + - `TestStageRefusesBinaryWithoutFeature`: key set; a fake staged binary whose `version features` prints `carlos v0.34.49` is refused with the message; the running binary path is untouched. |
| + - `TestStageAllowsWithoutKey`: same fake binary, key unset: allowed. |
| + - `TestRollbackRefusesPrevWithoutFeature`: key set; `carlos.prev` lacks the feature; operator rollback fails, `/opt/carlos/carlos` unchanged. |
| + - `TestRecoveryProceedsWithError`: same setup under recovery: restores and logs the message. |
| + Use the fake-binary and `guardRun` seams the existing `systemapply` tests use. |
| +- [ ] **Step 2: Run** `go test ./internal/host/ -run 'TestStage(Refuses|Allows)|TestRollbackRefusesPrev|TestRecoveryProceeds' && go test . -run TestVersionFeatures`. Expected: FAIL. |
| +- [ ] **Step 3: Implement** to the interfaces above. |
| +- [ ] **Step 4: Run** the same commands, then `go test ./internal/host/ -run 'SystemApply|InstallChannel|Rollback'`. Expected: PASS. |
| +- [ ] **Step 5: Commit** `system: refuse binaries without ingress-proxy-v2 on armed boxes`. |
| + |
| +### Task 7: Tofu: target group attributes, sources output, alarms, group precondition |
| + |
| +**Files:** |
| +- Modify: `infra/modules/region-host/ingress/main.tf` (`aws_lb_target_group.target` :97-126), `variables.tf`, `outputs.tf`, `alarms.tf` |
| +- Modify: `infra/modules/region-host/group.tf` (precondition :182-187) |
| +- Test: `infra/modules/region-host/ingress/tests/group_ingress.tftest.hcl`, `infra/modules/region-host/tests/group.tftest.hcl` |
| + |
| +**Interfaces:** |
| +- Produces (module inputs and outputs the roots use): |
| + - `variable "preserve_client_ip"`: `map(bool)`, default `{ "80" = true, "443" = true }`, keys exactly `80` and `443`. |
| + - `variable "proxy_protocol_v2"`: `map(bool)`, default `{ "80" = false, "443" = false }`, keys exactly `80` and `443`; validation refuses any port where `preserve_client_ip[p] == false && proxy_protocol_v2[p] == false` (cross-variable validation, OpenTofu 1.9+; if the module's `required_version` is lower, put it as a precondition on `aws_lb_target_group.target` instead). |
| + - `variable "proxy_trust_alarm"`: `object({ deployment = string, region = string, topic_arn = string })`, default `null`. A precondition on `aws_lb_target_group.target` refuses `proxy_protocol_v2[each.key] == true` while it is null. |
| + - `aws_cloudwatch_metric_alarm.proxy_trust` (`count = var.proxy_trust_alarm == null ? 0 : 1`): name `${var.name}-proxy-trust`, `Carlos/Host`, `IngressProxyTrustViolations`, `Maximum`, period 60, 1 of 1, threshold 0, `GreaterThanThreshold`, `treat_missing_data = "notBreaching"`, dimensions `Deployment`/`Region` from the input, `alarm_actions` and `ok_actions` `[topic_arn]`. |
| + - `aws_cloudwatch_metric_alarm.port_allocation` (same count): `${var.name}-port-allocation`, `AWS/NetworkELB`, `PortAllocationErrorCount`, `Sum`, period 300, threshold 0, `GreaterThanThreshold`, `notBreaching`, dimension `LoadBalancer = aws_lb.nlb.arn_suffix`, same topic. |
| + - `data "aws_network_interface" "node"` (`for_each = var.zones`), filters `description = "ELB ${aws_lb.nlb.arn_suffix}"` and `subnet-id = each.value.subnet_id`; output `proxy_protocol_sources = sort([for n in data.aws_network_interface.node : n.private_ip])`. |
| + - `group.tf` precondition: `(tg.preserve_client_ip == "true" || tg.proxy_protocol_v2)` replaces `tg.preserve_client_ip == "true"`; error message: "existing target groups must preserve client IPs or send PROXY protocol v2, and serve TCP 80 and 443 in the group VPC through the selected NLB". |
| +- [ ] **Step 1: Write the failing runs** (`command = plan`, mock provider as in the files today): |
| + - ingress: `defaults_keep_today` (both TGs `preserve_client_ip == true`, `proxy_protocol_v2 == false`, no alarms); `ppv2_on_80_with_alarm` (alarm input set, `proxy_protocol_v2 = {"80"=true,"443"=false}` plans); `ppv2_without_alarm_refused` (`expect_failures = [aws_lb_target_group.target]`); `s3_refused` (`preserve_client_ip = {"80"=false,...}` with PPv2 false, `expect_failures = [var.proxy_protocol_v2]` or the TG precondition); `sources_output` (mock two interfaces with `override_data` per zone; output equals the sorted two addresses); `alarms_shape` (asserts names, namespace, metric, statistic, dimensions and actions). |
| + - group: `existing_tg_s1_accepted`, `existing_tg_s2_accepted`, `existing_tg_s3_refused` via `override_data` on `data.aws_lb_target_group.group_http`/`group_https`. |
| +- [ ] **Step 2: Run** from `infra/modules/region-host/ingress`: `tofu init -backend=false && tofu test -filter=tests/group_ingress.tftest.hcl`; from `infra/modules/region-host`: `tofu test -filter=tests/group.tftest.hcl`. Expected: the new runs fail. |
| +- [ ] **Step 3: Implement** to the interfaces above. |
| +- [ ] **Step 4: Run** the same commands. Expected: all runs pass, the existing ones included. |
| +- [ ] **Step 5: Commit** `infra: PPv2 attributes, NLB sources output, trust alarms`. |
| + |
| +### Task 8: Cutover tooling: step script and probe |
| + |
| +**Files:** |
| +- Create: `scripts/ppv2-step.py`, `scripts/ppv2_step_test.py`, `scripts/ppv2-probe.py`, `scripts/ppv2_probe_test.py`, `scripts/testdata/ppv2/` (recorded JSON) |
| + |
| +**Interfaces:** |
| +- `ppv2-step.py` (spec §6.3), run from a root directory: `ppv2-step.py --root <dir> --profile <p> --region <r> --tg-arn <arn> --port {80,443} --set {ppv2-on,preserve-off,preserve-on} --record-dir <dir> [--dry-run --attributes <json> --plan <json> --targets <json>]`. |
| + - Reads live attributes (`aws elbv2 describe-target-group-attributes`), classifies S0/S1/S2/S3; allows only S0->S1 (`ppv2-on`), S1->S2 (`preserve-off`), S2->S1 (`preserve-on`); refuses everything else, including any move from S3 and every request that would set PPv2 off (there is no `ppv2-off` choice; a plan that sets it is refused). |
| + - Runs `tofu plan -target=<module address of that TG> -out` then `tofu show -json`; refuses unless exactly one resource changes, it is that TG, and exactly that one attribute differs. |
| + - Forward moves require `<record-dir>/<port>-<previous-step>.json` with `"passed": true` from the probe; S2->S1 requires none. |
| + - Convergence after `preserve-off` (spec §6.4) also requires, from `--targets`, that every target's `proxied_by_node` rose for **both** node addresses since the apply and its `no_client_refused` did not move. |
| + - Forward moves require every target's barrier down: `--targets` JSON (in production gathered with `aws ssm send-command` running `carlos system edge` status through `journalctl -u carlos-agent -g "proxy protocol:" -n 1`, parsed for `barrier down`). |
| + - Then applies the saved plan and writes `<record-dir>/<port>-<step>-applied.json`. |
| +- `ppv2-probe.py` (spec §6.4, §10), run on the probe host: `ppv2-probe.py --nlb-ip <addr> --port {80,443} --host <echo host> --path <echo path> --source-ports <lo>-<hi> --expect {s0,s1,s2} --out <record.json>`; sends plain and marker requests every 2 s on fresh connections bound to its source-port range; per the §6.4 table decides pass after 30 consecutive matching attempts, fails fast on a marker answer that echoes `192.0.2.1` or on a plain answer that changes; writes `{"passed":bool, "attempts":[...]}`. |
| +- [ ] **Step 1: Write the failing tests** (`unittest`, recorded JSON, no network): |
| + - `ppv2_step_test.py`: `test_allowed_moves` (S0->S1, S1->S2, S2->S1 pass dry-run); `test_refused_moves` (S0->S2, S2->S0, S1->S0, any from S3); `test_plan_must_change_one_attribute` (a plan touching two attributes or two resources refused); `test_forward_needs_record` and `test_reverse_needs_no_record`; `test_barrier_up_refuses_forward`; `test_b_convergence_needs_both_nodes` (one node's `proxied_by_node` flat refuses the next step). |
| + - `ppv2_probe_test.py`: `test_expectations_table` (each state's plain and marker answers on both ports per §6.4, including `:80` 302 not followed and a closed marker in S3 counted as a failure, not a pass); `test_forgery_echo_fails_fast`; `test_thirty_consecutive_needed`. |
| +- [ ] **Step 2: Run** `python3 -m unittest scripts/ppv2_step_test.py scripts/ppv2_probe_test.py`. Expected: FAIL. |
| +- [ ] **Step 3: Implement** both scripts with `argparse`, `subprocess` for `aws`/`tofu`, `socket`/`ssl` for the probe; dry-run paths read the recorded files instead of calling out. |
| +- [ ] **Step 4: Run** the same command. Expected: PASS. |
| +- [ ] **Step 5: Commit** `scripts: PPv2 step gate and convergence probe`. |
| + |
| +### Task 9: Runbook: the vN floor and the cutover card |
| + |
| +**Files:** |
| +- Modify: `docs/region-ha-runbook.md` (new section "PROXY protocol v2 on the region NLBs") |
| + |
| +**Content (spec §6, §7.3), plain prose, one screen:** the prerequisites in order (§6.1, with the bootstrap object before the key); the four steps through `scripts/ppv2-step.py` with the probe; rollback ends at S1; the S3 incident (barrier, preservation on, verify, resume); and **the floor**: once A80 is done on a region's NLB, no build below vN on its targets; the release recipe reads `proxy_protocol_v2.enabled` on every region NLB target group before promoting a build to a channel, changing a bootstrap object or re-pinning a launch template, and refuses builds below vN; the roll card names the exact rollback build (vN or later) or a forward fix, and checks the armed lines and the trust alarm after the roll. |
| + |
| +- [ ] **Step 1: Write the section.** |
| +- [ ] **Step 2: Check** every command and flag named exists in Tasks 5, 6 and 8 (`grep` the script and the CLI help). |
| +- [ ] **Step 3: Commit** `docs: region HA runbook, PPv2 cutover and the vN floor`. |
diff --git a/docs/superpowers/plans/CODEX-REVIEW-BRIEF-edge-ppv2-plan.md b/docs/superpowers/plans/CODEX-REVIEW-BRIEF-edge-ppv2-plan.md| new file mode 100644 |
| index 000000000..61ef1ff54 |
| --- /dev/null |
| +++ b/docs/superpowers/plans/CODEX-REVIEW-BRIEF-edge-ppv2-plan.md |
| @@ -0,0 +1,54 @@ |
| +# Review brief: Edge PROXY protocol v2 implementation plan, round 1 of 1 |
| + |
| +Repo carlos/platform, branch `edge-ppv2`, the commit named in your prompt. |
| +Under review: `docs/superpowers/plans/2026-11-12-edge-proxy-protocol.md`. |
| +Authority (MERGED on main): `docs/superpowers/specs/2026-11-12-edge-proxy-protocol-design.md` (rev 5, approved). |
| +Code at the branch's base on main. |
| + |
| +You are an independent reviewer. Read the plan, the spec, then the code the plan names, and check every |
| +interface, file:line and assumption against that code. |
| + |
| +## Fixed: do not re-argue |
| + |
| +- Everything the spec decides (one-way PPv2, the trust rule, the trust barrier as state, the activation |
| + guard, the alarm, the cutover order). Its §11-§15 record the decisions and three spec review rounds. |
| +- Report only places where the plan fails to implement the spec, would not compile or work against the |
| + real code, or leaves an implementer a choice the spec forbids. |
| + |
| +## What to check |
| + |
| +1. Every file:line, function, type and seam the plan names exists and has the shape the plan assumes |
| + (systemapply.go stageCandidate/restoreFiles/guardRun, hadrain socket and drain-call plumbing, |
| + memwatch/group_metrics, hostenv validators, edge Serve listener block, hairpinConnContext, |
| + publicServers, lbHealthAnswer, versionCommand). |
| +2. Task 2's parse-state contract: lazy resolution on the serving goroutine, Close never waiting, the |
| + barrier check at resolution, CloseTrusted covering pending conns. Do the two mandatory race tests |
| + really test the races spec §15 names? |
| +3. Task 4: does the handler gate run before every other handler on both servers, including ACME and the |
| + demo redirect on :80? Does wrapping order preserve hairpin? Is the barrier file read before bind? |
| +4. Task 5: is the metric published on group members as well as fixed boxes with the dimensions the alarm |
| + uses, and does the IAM allow it for both? Is the drain socket reachable on every armed box? |
| +5. Task 6: does the guard cover every way a binary becomes active on an armed box (apply, system-update |
| + adoption, install-channel at member boot, operator rollback)? Is "boot recovery proceeds" safe given |
| + spec §6.1's order? |
| +6. Task 7: OpenTofu version support for cross-variable validation in this module; the data source filter; |
| + the group precondition expression against the provider's attribute types. |
| +7. Task 8: can the scripts do what spec §6.3 and §6.4 require with the inputs named? |
| +8. Task sizing and order: can each task's tests pass with only earlier tasks merged? |
| + |
| +## Severity |
| + |
| +- **P1**: unsafe, would not compile, a test fails, or it would not work. Blocks the build. |
| +- **P2**: wrong or missing. Fixed without reopening this review. |
| +- **P3**: clarity or polish. Follow-up list only. |
| + |
| +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 task, the problem, the evidence (file:line, verified), the |
| +failure scenario, a concrete fix and the invariant it breaks (its fault family). End with exactly one verdict: |
| +READY, READY AFTER FIXES (no P1), or NOT READY (P1s listed). |
| + |
| +This plan gets one review round (agent manager's instruction). Do not edit files. Do not spawn |
| +Anthropic-model reviewers or subagents of your own. Do not run the full test suites. No AWS calls. |