plan: edge PPv2, Astra plan review applied
Recovery refused rather than permitted, rollback checked before any drain, version --json, step tool predecessor map and convergence record, census/parity task, synchronised race tests.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2 files changed,
+121
−34
docs/superpowers/plans/2026-11-12-edge-proxy-protocol.md+60 −34docs/superpowers/plans/ASTRA-FINDINGS-edge-ppv2-plan-R1.md+61 −0
CI passed — 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| index 594b75e51..00fb47f55 100644 |
| --- a/docs/superpowers/plans/2026-11-12-edge-proxy-protocol.md |
| +++ b/docs/superpowers/plans/2026-11-12-edge-proxy-protocol.md |
| @@ -10,6 +10,8 @@ |
| **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. |
| +**Plan review:** one Astra round (`docs/superpowers/plans/ASTRA-FINDINGS-edge-ppv2-plan-R1.md`, NOT READY: 4 P1, 4 P2), all applied in this revision without a second round, as 8a3d302 set one round: recovery now refused, not permitted (Task 6); the step tool's predecessor map, convergence record and real collector (`carlos-edge`, `trust-status`) (Tasks 5, 8); the provider's string type for `preserve_client_ip` (Task 7); census, parity, projection and CLI docs (Task 10); rollback refused before any drain or journal (Task 6); `version --json` as the spec says (Task 6); the race tests synchronised mid-header and checked through the handler stack (Tasks 2, 4); the step tool's root input and the probe's expected client (Task 8). |
| + |
| ## 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>`. |
| @@ -25,7 +27,7 @@ |
| 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`). |
| +4. **An old binary reaching an armed box by rollback** (`carlos.prev` older than vN): refused, the running binary kept. Pinned in Task 6 (`TestRollbackRefusedBeforeDisruption`, `TestRecoveryRefusesPrevWithoutFeature`). |
| 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`). |
| --- |
| @@ -98,7 +100,7 @@ |
| - `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 (a)** `TestBarrierPendingHeaderCompletesAsNoClient`: a test hook in `export_test.go` (`setParseHook(func(stage string))`, called by the parser with `"signature-read"` after it has consumed the 12-byte signature and before it reads the fixed part) blocks on a channel. The trusted client sends the signature only; the test waits until the hook reports `"signature-read"` (proving the parse is pending mid-header), flips the barrier to true without calling `CloseTrusted()`, sends the rest of a valid PROXY header, releases the hook; `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. |
| @@ -153,9 +155,10 @@ |
| - `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. |
| + - `TestBarrierRacesThroughHandler` (the two mandatory races end to end, through the production handler stack of this task): schedule (a) as in Task 2's test (a), using the same parse hook, and schedule (b) a trusted connection opened after `RaiseTrustBarrier`; on each connection `GET /.carlos/lb-health` on `:80` gets `lbHealthAnswer`'s answer and `GET /` (on `:80` and on `:443` for TLS) gets 503 with `Connection: close`, and no upstream is called. |
| - `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 2: Run** `go test ./internal/edge/ -run 'TestProxied|TestNoClient|TestHairpinSurvives|TestShutdownEnds|TestTrustBarrier|TestBarrierRaces|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`. |
| @@ -169,9 +172,9 @@ |
| **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. |
| + - 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,"counters":{...},"proxied_by_node":{...}}`. 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. |
| + - Root verbs `carlos system edge trust-barrier`, `carlos system edge trust-resume` and `carlos system edge trust-status` (op role, as `group-maintenance`), each printing one JSON result line; `trust-status` prints `{"armed":bool,"barrier":bool,"counters":{...},"proxied_by_node":{"<ip>":N}}` from `GET /v1/edge/trust` (which carries the same fields); a non-armed box answers "this box is not armed for PROXY protocol" with exit 2. Task 8's collector uses `trust-status`. |
| - 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`: |
| @@ -188,26 +191,36 @@ |
| ### 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) |
| +- Modify: `commands.go` (`versionCommand` :210-228), `internal/host/systemapply.go` (`stageCandidate` :2532, `rollback` :2042, `restoreFiles` :2124, the `--recover` path), `internal/host/group_maintenance_prepare.go` (operator rollback, before `beginExecutableChange` :333), `internal/host/units/carlos-system-recover.service` (ExecStart :51), `system.go` (box verbs :60-92) |
| +- Create: `internal/version/features.go`, `internal/host/proxyfeature.go` |
| +- Test: `internal/host/proxyfeature_test.go`, the existing version command test file at the repo root |
| **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. |
| + - `carlos version --json` prints one line `{"version":"<Build>","features":["ingress-proxy-v2"]}` (spec §7.3). Bare `carlos version` stays byte-identical (install scripts parse it). An older binary given `--json` prints its bare line (`DefaultOn` includes `OnFlag`), which has no `features`, so it is refused. |
| + - `func binaryHasFeature(ctx context.Context, run func(ctx context.Context, binary string, args ...string) ([]byte, error), binary, feature string) bool` in `proxyfeature.go`: runs `<binary> version --json`, true only when the output parses as JSON and `features` contains `feature`. |
| + - `func proxyArmed(getenv func(string) string) bool`: `CARLOS_INGRESS_PROXY_SOURCES` non-empty in the box's host.env (read the way `systemapply.go` reads other host.env keys). |
| + - `func (a *systemApplier) requireFeatures(ctx context.Context, binary string) error`: nil when not armed; otherwise `binaryHasFeature(ctx, a.guardRun-with-systemVersionWait, binary, "ingress-proxy-v2")` or this error: "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." |
| + - Box verb `carlos system proxy-allows-prev <path>`: exit 0 when not armed or `<path>` has the feature, exit 1 otherwise. It is the recovery unit's gate, the same shape as `exec-sandbox-allows-prev` (`system.go:61`). |
| +- Every activation path checks **before** it disrupts anything: |
| + - `stageCandidate`, after the existing version check: covers `apply`, system-update adoption and `install-channel` (and so member boot). |
| + - Operator rollback: `requireFeatures(systemPrevPath(a.optDir))` before `beginExecutableChange` and before the journal is written (`group_maintenance_prepare.go:333-341`). `a.rollback` checks the same at entry, before any ingress drain or quiesce. A refusal leaves no journal and drains nothing. |
| + - `restoreFiles` keeps a final check on the restore copy before its rename, as defence in depth. |
| + - Boot recovery: the unit's ExecStart condition chain gains `&& /opt/carlos/carlos system proxy-allows-prev /opt/carlos/carlos.prev` beside `exec-sandbox-allows-prev`. If it fails, the unit falls through to `/opt/carlos/carlos system apply --recover`, whose restore path calls `requireFeatures` on `carlos.prev` and, when refused, leaves the current binary and the recovery journal in place, logs the error at error level and exits non-zero, so the operator sees it. |
| - [ ] **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. |
| + - `TestVersionJSONHasFeatures`: `carlos version --json` prints the JSON line with `ingress-proxy-v2`; bare `carlos version` output unchanged. |
| + - `TestBinaryHasFeature` (table): JSON with the feature: true; JSON without: false; `carlos v0.34.49` (old binary's bare line): false; run error: false. |
| + - `TestStageRefusesBinaryWithoutFeature`: armed; a fake staged binary printing `carlos v0.34.49` is refused with the message; the running binary path is untouched. |
| + - `TestStageAllowsWithoutKey`: same fake binary, not armed: allowed. |
| + - `TestRollbackRefusedBeforeDisruption`: armed; `carlos.prev` lacks the feature; operator rollback fails with the message, no journal file is written, the ingress drain seam and quiesce seam are not called, `/opt/carlos/carlos` unchanged. |
| + - `TestRecoveryRefusesPrevWithoutFeature`: armed; a recovery journal present; `carlos.prev` lacks the feature; `apply --recover` exits non-zero, the current binary and the journal stay. |
| + - `TestProxyAllowsPrevVerb`: exit codes 0 (not armed), 0 (armed, feature), 1 (armed, no feature). |
| + - `TestRecoverUnitGatesPrev`: the recovery unit's ExecStart contains `system proxy-allows-prev /opt/carlos/carlos.prev` inside the `.prev` condition chain (string test, as existing unit tests do). |
| 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 2: Run** `go test ./internal/host/ -run 'TestBinaryHasFeature|TestStage(Refuses|Allows)|TestRollbackRefusedBefore|TestRecoveryRefusesPrev|TestProxyAllowsPrev|TestRecoverUnitGates' && go test . -run TestVersionJSON`. 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 4: Run** the same commands, then `go test ./internal/host/ -run 'SystemApply|InstallChannel|Rollback|Recover'`. 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 |
| @@ -227,42 +240,55 @@ |
| - `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). |
| + - ingress: `defaults_keep_today` (both TGs `preserve_client_ip == "true"`: the provider exposes it as a string, as `group_ingress.tftest.hcl:79` already asserts; `proxy_protocol_v2 == false`, a bool; 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 |
| +### Task 8: Cutover tooling: step gate, probe, convergence record |
| **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`. |
| +- **How a step reaches the root.** Each root passes two maps to the ingress module from one file the script owns, `ppv2.auto.tfvars.json` in the root directory: `{"ppv2_preserve_client_ip":{"80":true,"443":true},"ppv2_proxy_protocol_v2":{"80":false,"443":false}}` (the roots' variable declarations are an infra card's job; the script only reads and writes this file). The script changes exactly one key, plans, and restores the file byte for byte on any refusal. |
| +- **Which resource.** `--tg-address` is the tofu address of the TG (for example `module.ingress_ie.aws_lb_target_group.target["443"]`); the script checks `tofu state show -json` for that address has `arn == --tg-arn` and `port == --port` before anything else. |
| +- **Steps and predecessors** (spec §6.2): `A80` (PPv2 on, `:80`), `A443`, `B80` (preservation off, `:80`), `B443`; reverse `R443` and `R80` (preservation on). Predecessor map: `A80` needs the prerequisites record `prereq.json` (all targets armed with the module's addresses, barrier down, alarm OK, both TGs in S0); `A443` needs `A80.json` passed; `B80` needs `A443.json`; `B443` needs `B80.json`; `R443` and `R80` need nothing. Any other move, any move from S3, and anything that would turn PPv2 off is refused (there is no step for it). |
| +- **`ppv2-step.py apply`**: `--root <dir> --profile <p> --region <r> --nlb-arn <arn> --tg-arn <arn> --tg-address <addr> --port {80,443} --step {A80,A443,B80,B443,R443,R80} --targets <instance-id,...> --record-dir <dir>`. It reads live attributes (`aws elbv2 describe-target-group-attributes`), classifies S0 to S3, checks the move and the predecessor record (whose `nlb_arn` must match), collects every target's `carlos system edge trust-status` over SSM (`aws ssm send-command` with `AWS-RunShellScript`) and refuses if any barrier is up or any target is unarmed, edits the tfvars key, runs `tofu plan -target=<tg-address> -out`, refuses unless `tofu show -json` has exactly one resource change, at that address, with exactly that one attribute differing, then applies the saved plan and writes `<step>-applied.json` (`nlb_arn`, `port`, `step`, `applied_at`, baseline `trust-status` of every target). |
| +- **`ppv2-step.py converge`**: `--step <s> --record-dir <dir> --probe-records <a.json>,<b.json> --targets ... --profile --region --tg-arn`. Runs after `apply`: polls `describe-target-health` every 10 s and every target's `trust-status` every 30 s until the probe records arrive, then writes `<step>.json` with `"passed": true` only when all of: both probe records (one per NLB address, each started after `applied_at`, same port) passed; every target healthy at every poll; on every target, `malformed`, `timeout`, `ignored_private`, `marker_trusted` and `no_client_refused` did not move from the baseline; and for `B80`/`B443`, every target's `proxied_by_node` rose for **both** node addresses. |
| +- **`ppv2-probe.py`** (spec §6.4, §10), on the probe host: `--nlb-ip <addr> --port {80,443} --host <echo host> --path <echo path> --expect-client <public ip> --source-ports <lo>-<hi> --expect {s0,s1,s2} --out <record.json>`. Every 2 s, on fresh connections bound to its port range: a plain request (`:443` must answer 200 with `X-Forwarded-For` last entry equal to `--expect-client`; `:80` must answer 302, not followed) and a marker request (PPv2 header with source `192.0.2.1`, then the same request; S0 expects the plain answer, S1/S2 expect a failure: an answer of 400, a TLS alert, or a close). Pass after 30 consecutive matching attempts; fail at once on a plain answer that differs, or an echo containing `192.0.2.1`. The record carries `nlb_ip`, `port`, `started_at`, `passed` and every attempt. |
| +- [ ] **Step 1: Write the failing tests** (`unittest`, recorded JSON and fake `aws`/`tofu` executables on `PATH`, no network): |
| + - `ppv2_step_test.py`: `test_allowed_moves`; `test_refused_moves` (S0->S2, S2->S0, S1->S0, from S3); `test_predecessor_map` (each step's required record, and a record for another NLB refused); `test_address_must_match_state`; `test_plan_must_change_one_attribute` (two attributes, two resources, or another address refused; the tfvars file restored byte for byte); `test_barrier_up_refuses`; `test_unarmed_target_refuses`; `test_converge_needs_both_probe_records`; `test_converge_fails_on_counter_move`; `test_converge_fails_on_unhealthy_poll`; `test_b_convergence_needs_both_nodes`. |
| + - `ppv2_probe_test.py`: `test_expectations_table` (each state x port x plain/marker, from recorded responses); `test_wrong_client_echo_fails` (an echo of another address fails even when consistent); `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 3: Implement** both scripts with `argparse`, `subprocess` for `aws`/`tofu`, `socket`/`ssl` for the probe. |
| - [ ] **Step 4: Run** the same command. Expected: PASS. |
| -- [ ] **Step 5: Commit** `scripts: PPv2 step gate and convergence probe`. |
| +- [ ] **Step 5: Commit** `scripts: PPv2 step gate, convergence record and 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. |
| +**Content (spec §6, §7.3), plain prose, one screen:** the prerequisites in order (§6.1, with the bootstrap object before the key); the steps through `scripts/ppv2-step.py apply` and `converge` with the probe on both NLB addresses; 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`. |
| + |
| +### Task 10: Integration artifacts: CLI projection, parity, docs, census |
| + |
| +**Files:** |
| +- Modify: `parity/cli.tsv` (regenerated), `parity/parity.tsv`, `docs/site/cli.md`, the parity page `make parity-doc` writes |
| +- Create: `testdata/plan14-root-reads-edge-ppv2.tsv`, its line in `testdata/plan14-root-reads-chain.tsv`, `docs/superpowers/notes/census-proposal-edge-ppv2.md` (all written by `make census-propose`), `docs/superpowers/notes/census-claims-edge-ppv2.tsv` |
| + |
| +**Interfaces:** none new; this task makes the enforced repository checks pass for Tasks 3 to 7 (AGENTS.md "The census", and the CLI and parity rules). |
| + |
| +- [ ] **Step 1: CLI projection and parity.** Run `go test . -run TestCLIProjection -update`; add `parity/parity.tsv` rows for `system edge trust-barrier`, `system edge trust-resume`, `system edge trust-status` and `system proxy-allows-prev` (box/op audience, as the neighbouring `system` rows), and for the `version --json` flag if the projection lists flags; add the `docs/site/cli.md` headings the docsite test asks for; run `make parity-doc`. |
| +- [ ] **Step 2: Verify:** `go test . -run 'TestCLIProjection|TestParity'` and `go test ./internal/parity/ ./internal/docsite/`. Expected: PASS. |
| +- [ ] **Step 3: Census.** `make census-card`; write `docs/superpowers/notes/census-claims-edge-ppv2.tsv` with one line per changed unit (`<file>:<unit><TAB><what changed, and the read added if any>`), naming in particular: the edge's new read of `<dataDir>/edge/trust-barrier` (written only by the agent's own verb through the drain socket); the recovery unit's new `proxy-allows-prev` gate; `requireFeatures` running the staged or previous binary (already run by `stageCandidate` today); the new host-env key; the infra changes. Then `make census-propose NAME=edge-ppv2 CLAIMS=docs/superpowers/notes/census-claims-edge-ppv2.tsv`. |
| +- [ ] **Step 4: Verify:** `go test ./internal/provision/ -run 'TestPlan14RootReadCensus|TestCensusScopeIsTheRootBinary'`. Expected: PASS. |
| +- [ ] **Step 5: Commit** `census, parity and CLI docs for edge PPv2`. The census card goes to the whole-branch Astra review, whose brief asks for a verdict per unit and envelope; the verdict is recorded on #280. |
| + |
diff --git a/docs/superpowers/plans/ASTRA-FINDINGS-edge-ppv2-plan-R1.md b/docs/superpowers/plans/ASTRA-FINDINGS-edge-ppv2-plan-R1.md| new file mode 100644 |
| index 000000000..49e920e2a |
| --- /dev/null |
| +++ b/docs/superpowers/plans/ASTRA-FINDINGS-edge-ppv2-plan-R1.md |
| @@ -0,0 +1,61 @@ |
| +Reviewed `fd950fe37504f5623a9659acef0740e1838486ae`. No files changed, tests run, or AWS calls made. |
| + |
| +1. **P1 — Task 6: recovery explicitly bypasses the activation guard.** |
| + [Plan:200–206](/home/paulca/amadan.net/carlos/platform-ppv2/docs/superpowers/plans/2026-11-12-edge-proxy-protocol.md:200) requires recovery to restore a featureless binary on an armed box. This contradicts [spec §7.3:239](/home/paulca/amadan.net/carlos/platform-ppv2/docs/superpowers/specs/2026-11-12-edge-proxy-protocol-design.md:239). The prerequisite order checks the running and bootstrap binaries; it does not establish that every recovery candidate supports PPv2. `carlos.prev` is retained or refreshed according to recorded installation state, not simply “the binary that last booted” ([systemapply.go:985](/home/paulca/amadan.net/carlos/platform-ppv2/internal/host/systemapply.go:985)). |
| + |
| + **Failure:** the setup expressly required by `TestRecoveryProceedsWithError` activates an incompatible edge while PPv2 remains enabled. Recovery can also execute `.prev` before reaching the new Go guard ([recovery unit:51](/home/paulca/amadan.net/carlos/platform-ppv2/internal/host/units/carlos-system-recover.service:51)). |
| + **Fix:** enforce the feature requirement on recovery and its executable-selection path; replace the permissive test with a refusal test preserving the current binary and recovery journal. |
| + **Invariant / fault family:** the PPv2 activation floor applies to every activation path. |
| + |
| +2. **P1 — Task 8: the proposed records cannot establish the required convergence gate.** |
| + [Plan:246–250](/home/paulca/amadan.net/carlos/platform-ppv2/docs/superpowers/plans/2026-11-12-edge-proxy-protocol.md:246) requires a previous record under the current port, but the specified sequence crosses ports: A80 → A443 → B80 → B443. Each probe writes a result for one address; no step combines both addresses, target counters and health observations into the authoritative record. The plan also omits the continuous target-health checks and zero-error counter requirements in [spec:198–205](/home/paulca/amadan.net/carlos/platform-ppv2/docs/superpowers/specs/2026-11-12-edge-proxy-protocol-design.md:198). |
| + |
| + The proposed live collector reads `journalctl -u carlos-agent`, while the agent actually runs in [carlos-edge.service:29](/home/paulca/amadan.net/carlos/platform-ppv2/internal/host/units/carlos-edge.service:29). Task 5 defines no `carlos system edge status` verb either. |
| + |
| + **Failure:** forward steps either cannot find their evidence or accept an incomplete record without proving the preceding step converged. |
| + **Fix:** define the four-step predecessor mapping, the initial-step rule, and one record assembler bound to the NLB, port and apply. Require both address probes, fresh target counter baselines, all specified counter checks, and health polling every ten seconds. Collect from the actual service and start convergence after applying. |
| + **Invariant / fault family:** each forward transition requires complete evidence from the immediately preceding transition. |
| + |
| +3. **P1 — Task 7: the default-state assertion uses the wrong provider type.** |
| + [Plan:230](/home/paulca/amadan.net/carlos/platform-ppv2/docs/superpowers/plans/2026-11-12-edge-proxy-protocol.md:230) specifies `preserve_client_ip == true`. The resource exposes this attribute as a string; the existing assertion correctly uses `"true"` ([group_ingress.tftest.hcl:79](/home/paulca/amadan.net/carlos/platform-ppv2/infra/modules/region-host/ingress/tests/group_ingress.tftest.hcl:79)). The provider also identifies its attribute type as string: [https://raw.githubusercontent.com/hashicorp/terraform-provider-aws/main/internal/service/elbv2/target_group.go](https://raw.githubusercontent.com/hashicorp/terraform-provider-aws/main/internal/service/elbv2/target_group.go). |
| + |
| + **Failure:** the prescribed new test fails on valid default infrastructure. |
| + **Fix:** compare against `"true"` or explicitly convert with `tobool`; retain boolean comparisons for `proxy_protocol_v2`. The planned group precondition already handles these differing types correctly. |
| + **Invariant / fault family:** assertions must match provider attribute types. |
| + |
| +4. **P1 — Tasks 3–7: required census and command-projection updates are absent.** |
| + The tasks change fingerprinted root-binary sources and infrastructure without scheduling a census proposal and approval. [TestPlan14RootReadCensus:700](/home/paulca/amadan.net/carlos/platform-ppv2/internal/provision/plan14_root_reads_test.go:700) rejects that drift. Tasks 5 and 6 also add commands without updating the CLI projection or parity rows: [TestCLIProjection:42](/home/paulca/amadan.net/carlos/platform-ppv2/cli_projection_test.go:42) and [TestParityCLIPaths:66](/home/paulca/amadan.net/carlos/platform-ppv2/internal/parity/repo_test.go:66) enforce those updates. |
| + |
| + **Failure:** implementing the listed files and tests leaves CI red. |
| + **Fix:** include census claims, proposal and independent approval before landing; include command registration, parity rows, regenerated projection/documentation and applicable CLI documentation with the command changes. |
| + **Invariant / fault family:** implementation tasks must include the repository’s enforced integration artifacts. |
| + |
| +5. **P2 — Task 6: the rollback refusal is placed after disruptive work.** |
| + [Plan:200](/home/paulca/amadan.net/carlos/platform-ppv2/docs/superpowers/plans/2026-11-12-edge-proxy-protocol.md:200) checks the restore copy before rename. That copy is created only after ingress draining and quiescing ([systemapply.go:2157–2177](/home/paulca/amadan.net/carlos/platform-ppv2/internal/host/systemapply.go:2157)). Operator rollback also writes its journal before calling `restoreFiles` ([group_maintenance_prepare.go:333–341](/home/paulca/amadan.net/carlos/platform-ppv2/internal/host/group_maintenance_prepare.go:333)). |
| + |
| + **Failure:** refusing an unsupported rollback can already have withdrawn serving traffic and left a recovery transaction. |
| + **Fix:** check the candidate before starting the rollback transaction or draining; retain any necessary final verification at activation. Test that refusal performs neither operation. |
| + **Invariant / fault family:** an unsupported activation is refused before disrupting the running installation. |
| + |
| +6. **P2 — Task 6: the feature-discovery interface differs from the approved spec.** |
| + [Plan:198–199](/home/paulca/amadan.net/carlos/platform-ppv2/docs/superpowers/plans/2026-11-12-edge-proxy-protocol.md:198) introduces `version features`, whereas [spec:239](/home/paulca/amadan.net/carlos/platform-ppv2/docs/superpowers/specs/2026-11-12-edge-proxy-protocol-design.md:239) requires `version --json` with a `features` list. |
| + |
| + **Failure:** the prescribed machine-readable feature query remains unsupported. |
| + **Fix:** implement and consume the specified JSON interface, preserving bare `version` output. |
| + **Invariant / fault family:** implementation follows the approved capability-discovery contract. |
| + |
| +7. **P2 — Tasks 2 and 4: the mandatory race witnesses are incomplete.** |
| + [Plan:101–102](/home/paulca/amadan.net/carlos/platform-ppv2/docs/superpowers/plans/2026-11-12-edge-proxy-protocol.md:101) asserts parse states only. Test (a) does not require synchronization proving parsing began before the barrier rose; both tests omit the required health-only HTTP outcome. [Spec:296](/home/paulca/amadan.net/carlos/platform-ppv2/docs/superpowers/specs/2026-11-12-edge-proxy-protocol-design.md:296) explicitly requires that outcome. |
| + |
| + **Failure:** test (a) can pass by starting resolution after the barrier, without exercising the pending-parser race. |
| + **Fix:** synchronize on a parser blocked mid-header before raising the barrier, then complete it. For both schedules, verify health succeeds and application traffic is refused through the production handler stack. |
| + **Invariant / fault family:** containment covers pending and later trusted connections through dispatch. |
| + |
| +8. **P2 — Task 8: the executable input contract needs completing.** |
| + [Plan:243–250](/home/paulca/amadan.net/carlos/platform-ppv2/docs/superpowers/plans/2026-11-12-edge-proxy-protocol.md:243) supplies a TG ARN but leaves the OpenTofu resource-address lookup and desired configuration preparation unspecified. The probe also has no explicit expected client address, although the spec requires the echo to equal the probe’s address. |
| + |
| + **Failure:** an implementer must invent root-specific configuration handling and may treat a consistently wrong echoed address as success. |
| + **Fix:** specify resource discovery and verification against state, how the requested change reaches root configuration, and an expected-client-address input or verified discovery method. |
| + **Invariant / fault family:** tooling inputs must identify both the intended mutation and its expected observable result. |
| + |
| +NOT READY (P1s listed). |
| \ No newline at end of file |