carlos / platform Public

tests: app region mid-request test writes its form body in order

TestAppRegionBrowserRefusesAnAppReplacedMidRequest flaked with 403. The
403 was the CSRF refusal, correct for the body it got: the test wrote
"csrf=" from a separate goroutine and the token from the main one, and
the handler can start reading (firing the test's signal) before either
write supplies a byte, so the token could land first and the body had no
csrf field. The prefix is now written from the main goroutine before the
wait; io.Pipe returns only once the client took every byte, so the order
is fixed. Production is unchanged. A handler that read the form before
resolving the app still fails the test.

Reviewed by Astra (round 1, READY AFTER FIXES; both P2s corrected the
brief's explanation, not the code).

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

Squashed from flake-appregion-replaced into main.
claude agent, operated by paul@keymail.dev ade96357ef78c81ac6e3dbef21f2b5fb723e4a7b parent 976f645
3 files changed, +204 −1
  • docs/superpowers/reviews/FINDINGS-flake-appregion-replaced.md +26 −0
  • docs/superpowers/reviews/REVIEW-BRIEF-flake-appregion-replaced.md +169 −0
  • internal/console/appregionset_test.go +9 −1

CI cancelled — superseded by a newer push — run details

diff --git a/docs/superpowers/reviews/FINDINGS-flake-appregion-replaced.md b/docs/superpowers/reviews/FINDINGS-flake-appregion-replaced.md
new file mode 100644
index 000000000..40e16a47a
--- /dev/null
+++ b/docs/superpowers/reviews/FINDINGS-flake-appregion-replaced.md
@@ -0,0 +1,26 @@
+Reviewed commit `2a5f24c10f1ce8b37bc5fe358d188fc47a6a476f` against the brief’s base, `619c64c5`. Round 1. No P1 findings; two P2 corrections to the brief. No defect found in the test change.
+
+1. **P2 — The 200 ms probe explanation does not apply to this POST.**
+ Evidence: [review brief:65](/home/paulca/amadan.net/carlos/platform-flake-appregion/docs/superpowers/reviews/REVIEW-BRIEF-flake-appregion-replaced.md:65). In the installed Go 1.26.10 source, [transfer.go:179](/home/paulca/.local/go-dist/src/net/http/transfer.go:179) restricts `probeRequestBody` to methods that usually lack bodies; POST skips it. Instead, [transfer.go:106](/home/paulca/.local/go-dist/src/net/http/transfer.go:106) sets `FlushHeaders`, and [request.go:754](/home/paulca/.local/go-dist/src/net/http/request.go:754) flushes before copying the body.
+
+ The failure scenario remains valid: the handler can signal `reading` before either pipe write supplies bytes. However, no 200 ms delay is required. **Fix:** explain the direct header flush and remove the probe-based timing explanation.
+
+2. **P2 — The resolver’s response-status list omits the linked-app guard.**
+ Evidence: [review brief:40](/home/paulca/amadan.net/carlos/platform-flake-appregion/docs/superpowers/reviews/REVIEW-BRIEF-flake-appregion-replaced.md:40). [appregionset.go:488](/home/paulca/amadan.net/carlos/platform-flake-appregion/internal/console/appregionset.go:488) calls `refuseLinkedPage`, which renders the guard’s status. That guard returns 503 on lookup failure at [linkedpolicy.go:340](/home/paulca/amadan.net/carlos/platform-flake-appregion/internal/console/linkedpolicy.go:340), or 409 for a linked app at line 354.
+
+ Those cases contradict the stated list of 302, 404 and 500, although neither introduces a 403. **Fix:** include 409 and 503, or state only that the resolver cannot return 403.
+
+The six requested checks otherwise hold:
+
+- **403 attribution:** The route registration, wrappers, admission gate, account resolver and linked-app guard provide no alternative 403 path for this request. The CSRF refusal at `appregionset.go:439` explains it.
+- **Blocking and timeout:** The client transport consumes the five-byte prefix independently of the handler reading it. An early transport failure closes the request body, releasing the pipe writer with an error. Once the prefix is consumed, the existing 10-second select still detects a handler that never reads. That timer does not cover the preceding write or provide an overall request deadline.
+- **Signal ordering:** The middleware wraps the body without reading it. `accountAppIncarnation` completes before `csrfFormOK` initiates the read that fires `firstReadSignal`. Standard-library socket buffering does not invoke this wrapper.
+- **Preserved coverage:** The prefix write completes before the replacement, while the token, region and EOF remain withheld until afterwards. The unchanged assertions still check 303, unchanged replacement region and no region audit event. Moving `ParseForm` ahead of incarnation resolution is a valid mutation witness: it would resolve the replacement and permit its region change.
+- **Comment accuracy:** The new comment correctly describes pipe-write ordering and the signal firing before bytes arrive.
+- **Transport errors:** `t.Error(err)` marks the test failed; sending a nil response does not conceal the error. The later “no response” check adds another failure.
+
+Validation was limited to source inspection. The permitted targeted test command failed before compilation because Go could not create its build directory in the read-only sandbox. I did not independently reproduce the brief’s stress or mutation results. No files were changed.
+
+Apply the two P2 documentation corrections without another review round.
+
+**READY AFTER FIXES**
\ No newline at end of file
diff --git a/docs/superpowers/reviews/REVIEW-BRIEF-flake-appregion-replaced.md b/docs/superpowers/reviews/REVIEW-BRIEF-flake-appregion-replaced.md
new file mode 100644
index 000000000..12f7a3d2f
--- /dev/null
+++ b/docs/superpowers/reviews/REVIEW-BRIEF-flake-appregion-replaced.md
@@ -0,0 +1,169 @@
+# Review brief: the replaced-app region test's body writes, round 1 of 3
+
+Repo carlos/platform, branch `flake-appregion-replaced`.
+Under review: the diff `origin/main..flake-appregion-replaced` (base
+619c64c5). One code change, test-only:
+
+- `internal/console/appregionset_test.go`,
+ `TestAppRegionBrowserRefusesAnAppReplacedMidRequest` (line 549)
+
+This brief is the other file. No product code changed.
+Authorities: `internal/console/appregionset.go` (`handleAppRegionSet`
+line 434, `accountAppIncarnation` line 473), `internal/console/csrf.go`
+(`csrfFormOK` line 51), and the Go standard library's `io.Pipe` and
+`net/http` client and server body handling.
+
+You are an independent reviewer. Read this brief, then the code it
+names, and check every claim against that code.
+
+## The failure
+
+CI, 2026-11-19, branch `flake-lease-teardown` at 90b93f3d (which does not
+touch the console), main 619c64c5:
+
+```
+--- FAIL: TestAppRegionBrowserRefusesAnAppReplacedMidRequest (0.39s)
+ appregionset_test.go:605: status = 403, want the flash redirect
+```
+
+The test starts a browser POST to `/a/<sqid>/apps/shop/region` whose
+body comes through an `io.Pipe`. Its server-side wrapper
+(`firstReadSignal`, line 681) closes `reading` on the handler's first
+body Read. After `reading`, the test trashes, purges and re-creates
+`shop`, then writes the CSRF token and `&region=uk`. It expects a 303
+flash redirect, no region on the replacement and no audit event.
+
+## Root cause: the test, not production
+
+**Which path answered 403.** In `handleAppRegionSet` the only 403 is the
+CSRF refusal (appregionset.go:439-441, "Cross-site request blocked.").
+`accountAppIncarnation` answers 302, 404 or 500, never 403. The other
+refusals after it are 404 (`canSetAppRegion`) and 409 (`HostClaim`).
+Nothing in front of the mux answers 403 for this route:
+`ServeHTTP` (server.go:2256) redirects or goes to `serveAdmitted`, which
+answers 503 at most.
+
+**What the CSRF check depends on.** `csrfFormOK` (csrf.go:51) compares
+the body's single `csrf` field with the session's token. The session does
+not depend on the app row, so trashing, purging and re-creating `shop`
+cannot change the result. The 403 is therefore deterministic for a given
+body: production answers 403 only when the body carries no valid `csrf`
+field. For a body like that, 403 is the right answer.
+
+**How the test sent a body without one.** The old test wrote the body in
+two writes from two goroutines:
+
+```go
+go pw.Write([]byte("csrf=")) // goroutine
+<-reading
+... replace the app ...
+pw.Write([]byte(url.QueryEscape(csrf) + "&region=uk")) // test goroutine
+pw.Close()
+```
+
+`reading` fires when the handler *calls* Read, not when a byte arrives.
+The client transport flushes the request headers on its own: for a body
+of unknown length it probes for a first byte for 200 ms, then sends the
+headers anyway (`net/http` `probeRequestBody`, `FlushHeaders`). So the
+handler can reach its first Read, fire `reading`, and let the test
+goroutine write the token before the `csrf=` goroutine has taken the
+pipe. `io.Pipe` serializes concurrent writes, but it does not order them.
+The body is then `<token>&region=uk`, sometimes followed by `csrf=`, or
+with `csrf=` refused because the pipe is already closed. That body has
+no `csrf` field with the token as its value, so the CSRF check answers 403.
+
+**Evidence.** A throwaway copy of the test (since deleted) that started
+the `csrf=` goroutine with a 400 ms delay failed 3 of 3 runs with exactly
+the CI message, `status = 403, want the flash redirect`. The unmodified
+test passed 500 serial runs and 1,200 runs under load (six processes at
+once, `-test.cpu 1,2`, `-test.count=100`). The race needs the
+goroutine to be descheduled for the whole replacement, which is rare
+locally but plausible on a busy CI runner.
+
+The precondition the test relies on is still true: the first body Read is
+inside `csrfFormOK`, after `accountAppIncarnation` has resolved the
+incarnation (appregionset.go:435, then 439). Nothing between the wrapper
+and the handler reads the body.
+
+## The fix
+
+`"csrf="` is now written from the test goroutine, before it waits for
+`reading`, and its error is checked (test line 584). `io.Pipe`'s Write
+returns only once the reader (the client transport) has taken every
+byte. So by the time the test waits for `reading`, `csrf=` is already in
+the request body, and the token can only follow it. No sleep, no retry,
+and none of the assertions changed.
+
+Checks run (throwaway checks were deleted afterwards):
+
+- Fixed test, 500 serial runs: pass. Six processes at once with
+ `-test.cpu 1,2 -test.count=100` (1,200 runs): pass.
+- A throwaway copy of the fixed test with a 400 ms sleep before the
+ `csrf=` write. This is the flake's precondition, with the handler
+ reading before any byte arrives. It passed 3 of 3.
+- A throwaway mutation of `handleAppRegionSet` that calls `r.ParseForm()`
+ before `accountAppIncarnation`, so the handler resolves the app after
+ the body arrives. The fixed test fails 3 of 3 with "the replacement's
+ region became "uk"". The test still catches late resolution.
+- `go test ./internal/console -run TestAppRegion -count=1`: ok.
+
+## What to check
+
+1. Is the 403 really only reachable through `csrfFormOK` for this request?
+ Check `accountAppIncarnation`, `s.account`, `refuseLinkedPage`,
+ `serveAdmitted` and anything the route declaration
+ (routedecls.go:304) wraps around the handler.
+2. Can the synchronous `pw.Write([]byte("csrf="))` deadlock or hang? It
+ needs the client transport to read the body before the server
+ answers. If `c.Do` fails first, does the transport close the pipe's
+ reader so that Write returns an error and does not block? Does the
+ 10 s `reading` timeout still cover a handler that never reads?
+3. Does `reading` still fire only after the incarnation is resolved? Is
+ there any server-side read of the body (by `net/http` or a console
+ middleware) before `csrfFormOK`?
+4. Does the change weaken anything the test proved? The assertions (303,
+ no region on the replacement, no audit event) are unchanged. Is the
+ mutation check above a fair witness that it still catches a handler
+ that resolves the app after reading the body?
+5. Is the new comment at test lines 578-583 accurate about `io.Pipe` and
+ the first-Read signal?
+6. Does the client goroutine's `t.Error(err)` hide a transport error? It
+ sends a nil response, and the test then fails with "no response".
+
+## Severity
+
+- **P1**: unsafe, would not compile, a test fails, or it would not work.
+ Blocks merge.
+- **P2**: wrong or missing. Fixed without reopening this review.
+- **P3**: clarity or polish. Goes on a follow-up list; never a reason for
+ another round.
+
+A P1 states its failure scenario and the evidence (file:line). Do not
+raise a P2 to P1 to keep the review open.
+
+## Output
+
+Findings ranked P1, P2, P3. Each gives the problem, the evidence
+(file:line, verified), the failure scenario and a concrete fix. End with
+exactly one verdict:
+
+- **READY**: no P1 and no P2.
+- **READY AFTER FIXES**: no P1. The listed P2s are fixed without another
+ round.
+- **NOT READY**: one or more P1s, listed.
+
+Do not edit files. Do not spawn subagents of your own. Do not run the
+full test suites. If you run anything, run only
+`go test ./internal/console -run 'TestAppRegionBrowserRefusesAnAppReplacedMidRequest$' -count=20`.
+
+## Corrections after review (Astra round 1, READY AFTER FIXES)
+
+1. The 200 ms body-probe explanation above is wrong for this request:
+ net/http restricts probeRequestBody to methods that usually lack a
+ body, and POST skips it. The client flushes the request headers
+ directly, so the handler can start reading, and fire `reading`, before
+ either pipe write has supplied a byte. The race and the fix stand; no
+ 200 ms delay is involved.
+2. The resolver steps before the CSRF check can also answer 409 and 503
+ (the linked-app guard, refuseLinkedPage). None of them answers 403, so
+ the attribution of the 403 to the CSRF refusal stands.
diff --git a/internal/console/appregionset_test.go b/internal/console/appregionset_test.go
index b37fc0a03..092596181 100644
--- a/internal/console/appregionset_test.go
+++ b/internal/console/appregionset_test.go
@@ -575,7 +575,15 @@ func TestAppRegionBrowserRefusesAnAppReplacedMidRequest(t *testing.T) {
}
done <- res
}()
- go pw.Write([]byte("csrf="))
+ // The body's first part is written here, not from a goroutine: the
+ // handler's first Read signals before any byte need arrive, so a
+ // goroutine's write could lose the pipe to the token's write below and
+ // send "<token>&region=uk" with no csrf field (a true 403). A pipe
+ // write returns once the client has taken every byte, so "csrf=" is in
+ // the body before the rest can be.
+ if _, err := pw.Write([]byte("csrf=")); err != nil {
+ t.Fatal(err)
+ }
select {
case <-reading:
case <-time.After(10 * time.Second):