edge: the kept -tunnel login body is read under a deadline (#471 Task 6 fix round 3)
Astra re-review 2, P2: the ReadAll of a login body kept for an ungated -tunnel row had no time bound, ran before rate admission, and the production listeners set only ReadHeaderTimeout, so a client could send the headers, hold the body back and pin a handler. The capture now runs under http.NewResponseController(w).SetReadDeadline at now + loginBodyTimeout (10 s; the gate has no body timeout to reuse; loginBodyReadTimeout is the package variable a test shortens), cleared once the body is in so a passed-through login is not cut off. On a failed read the deadline stays in the past and the answer carries Connection: close, so net/http's drain of the unread body cannot wait on the client again. A writer without deadline support (ErrNotSupported) reads as before; the comment names what that covers. Test-first: TestStalledTunnelLoginBodyEndsWithinTheBound (HTTP/1 raw and HTTP/2 over TLS; 5 of the form's bytes, then nothing) hung past 5 s before, and now gets a complete 413 within the 300 ms bound, nothing at the box. TestPassedLoginOutlivesTheBodyDeadline: a passed login whose box answers well after the bound is answered, and the connection serves a second request. Census card unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
internal/edge/edge.go+32 −0internal/edge/tunnel_login_test.go+132 −0
Intent
<task-notification> <task-id>a58070cdd3a43a333</task-id> <tool-use-id>toolu_01KcUFSFdgvTEba9qEbjPyJq</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ba9fa944-a429-4788-9b3c-f2b2f42617f3/tasks/a58070cdd3a43a333.output</output-file> <status>completed</status> <summary>Agent "#471 Task 6: production-wired witness" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>**Status:** DONE_WITH_CONCERNS **Commit:** `12e5531d` on `design-tunnel-websockets-471`, on top of `021c7307`. Not pushed. **Tests:** the e2e cases, the new tunnel-login tests and the edge gate, login, door and forward tests pass under `-race` with no data races. The neighbouring edge tests pass, and so do the darwin, windows and linux/arm64 builds. What changed: 1. **P1 (the misroute):** the hub now resolves `next` first, as it does for any gated host. A login for an ungated `-tunnel` row goes down the tunnel only when `next` selects that row itself. A prefix target that is gated is judged by its own gate at the hub; one that is ungated answers 404. The new `tunnel_login_test.go` showed the bug first: the target's password reached the front's box with a 200. Now the cookie is signed for the target and nothing reaches the box. A mutation that drops the `next` check fails the test. 2. **M18:** a gated `-tunnel` front with a gated prefix target that has a different password now signs the cookie for the target. M18 now fails the test, in both new tests. 3. **P2 (`closedBy`):** each endpoint records when it closed, and `closedBy` judges that time against the one deadline. A close after the deadline fails even if checks in between delay `closedBy`. The census card is re-derived and recorded in spec §7, and the seal is unchanged. `Edge.ServeHTTP` now shows a `reads` row: `+file:ReadAll` (the request body, capped at the gate's form limit), `+registry:Gate` and `+whole:Route`. `loginPassesThrough(front, target)` is a new unit. The §4.5 sentence now says the pass-through happens only when the login's target is the tunnel row itself. **Concerns:** - **One mutation survives (M21).** Letting a hub-gated `-tunnel` row's own login through changes nothing. When the target is gated, `gate.Admit` catches the login POST and judges it at the hub, whatever the pass-through decides. The `Gate == ""` checks in `loginPassesThrough` are a second guard only. The reviewer may want them removed so no condition goes untested. - **A multipart login to an ungated `-tunnel` front goes to that front.** The form parser does not read multipart bodies, so `next` is empty and selects the front. No gate form is multipart, so only a hand-built POST takes this path, and it carries the visitor's own input. The fix report and the ruling are appended to `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-tunnel-websockets-471/.superpowers/sdd/2026-10-30-tunnel-websockets/task-6-report.md`. Scratch is removed and no processes are left running.</result> <usage><subagent_tokens>416026</subagent_tokens><tool_uses>22</tool_uses><duration_ms>659498</duration_ms></usage> </task-notification>
<task-notification> <task-id>ban3lcftd</task-id> <tool-use-id>toolu_01GGTcNL7ANBA1xWsuLLTTk6</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ba9fa944-a429-4788-9b3c-f2b2f42617f3/tasks/ban3lcftd.output</output-file> <status>completed</status> <summary>Background command "Run second Astra re-review of #471 Task 6" completed (exit code 0)</summary> </task-notification>
Attributed to this commit: 5.63 g CO₂e (633,925 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on design-tunnel-websockets-471, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.
diff --git a/internal/edge/edge.go b/internal/edge/edge.go| index 93ee63501..c40a3e51e 100644 |
| --- a/internal/edge/edge.go |
| +++ b/internal/edge/edge.go |
| @@ -2035,11 +2035,32 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| front := up |
| var kept []byte |
| if front.tenancy.Arm == ArmTunnel && front.route.Gate == "" { |
| + // The read is bounded in time as well as size |
| + // (loginBodyTimeout), and the deadline is cleared once the body |
| + // is in, so a login passed on is not cut off while the box |
| + // answers. A writer that cannot set deadlines (ErrNotSupported) |
| + // reads as before: every listener this edge serves on is a |
| + // net/http server, whose HTTP/1 and HTTP/2 writers both support |
| + // it, and the wrappers in front of ServeHTTP (the ACME fallback, |
| + // the door) hand that writer on; what is left is a writer with |
| + // neither SetReadDeadline nor Unwrap, such as a test's |
| + // httptest.ResponseRecorder. |
| + // |
| + // On a failed read the deadline is left in the past: net/http |
| + // tries to drain an unread body before it writes the answer, |
| + // and that drain must fail at once rather than wait on the |
| + // client again. The connection is closed after the answer. |
| + rc := http.NewResponseController(w) |
| + bounded := rc.SetReadDeadline(time.Now().Add(loginBodyReadTimeout)) == nil |
| b, err := io.ReadAll(http.MaxBytesReader(w, r.Body, gate.MaxFormBody)) |
| if err != nil { |
| + w.Header().Set("Connection", "close") |
| http.Error(w, http.StatusText(http.StatusRequestEntityTooLarge), http.StatusRequestEntityTooLarge) |
| return |
| } |
| + if bounded { |
| + rc.SetReadDeadline(time.Time{}) |
| + } |
| kept = b |
| r.Body = io.NopCloser(bytes.NewReader(b)) |
| } else { |
| @@ -3346,6 +3367,17 @@ func tunnelProxy(name string, hub *TunnelHub) *httputil.ReverseProxy { |
| } |
| } |
| +// loginBodyTimeout bounds how long the hub waits for the body of a login |
| +// POST it keeps to pass down a -tunnel row (#471, Task 6 fix round 3). The |
| +// read comes before any rate admission and the production listeners set |
| +// only ReadHeaderTimeout, so without it a client that sends the headers and |
| +// holds the body back would hold a handler for as long as it liked. The |
| +// gate has no body timeout of its own to reuse. loginBodyReadTimeout is |
| +// the value in force; a test shortens it. |
| +const loginBodyTimeout = 10 * time.Second |
| + |
| +var loginBodyReadTimeout = loginBodyTimeout |
| + |
| // loginPassesThrough reports whether a login POST that arrived on front, an |
| // ungated static -tunnel row, and whose `next` selected target, goes down |
| // front's tunnel to the box that holds the gate (#471 spec §4.5): only when |
diff --git a/internal/edge/tunnel_login_test.go b/internal/edge/tunnel_login_test.go| index 082320565..766be8a16 100644 |
| --- a/internal/edge/tunnel_login_test.go |
| +++ b/internal/edge/tunnel_login_test.go |
| @@ -15,7 +15,10 @@ package edge |
| // a tunnel row). |
| import ( |
| + "bufio" |
| + "fmt" |
| "io" |
| + "net" |
| "net/http" |
| "net/http/httptest" |
| "net/url" |
| @@ -41,13 +44,19 @@ const ( |
| type boxRecorder struct { |
| mu sync.Mutex |
| seen []string // "METHOD path body" |
| + // hold, when set, keeps the box from answering until it closes. |
| + hold chan struct{} |
| } |
| func (b *boxRecorder) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| body, _ := io.ReadAll(r.Body) |
| b.mu.Lock() |
| b.seen = append(b.seen, r.Method+" "+r.URL.Path+" "+string(body)) |
| + hold := b.hold |
| b.mu.Unlock() |
| + if hold != nil { |
| + <-hold |
| + } |
| io.WriteString(w, "the front box") |
| } |
| @@ -188,3 +197,126 @@ func TestHubGatedTunnelFrontPrefixLoginIsJudgedByItsTarget(t *testing.T) { |
| t.Fatalf("a login on a hub-gated -tunnel row went down the tunnel: the box saw %q", got) |
| } |
| } |
| + |
| +// rawLogin opens a connection to srv and sends a login POST for host |
| +// whose Content-Length is the whole form, but writes only the first sent |
| +// bytes of it (all of it when sent is negative). It returns the connection |
| +// and the form. |
| +func rawLogin(t *testing.T, srv *httptest.Server, host string, sent int) (net.Conn, string) { |
| + t.Helper() |
| + form := url.Values{"password": {tlFrontPass}, "next": {"/"}}.Encode() |
| + if sent < 0 { |
| + sent = len(form) |
| + } |
| + c, err := net.Dial("tcp", strings.TrimPrefix(srv.URL, "http://")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { c.Close() }) |
| + fmt.Fprintf(c, "POST %s HTTP/1.1\r\nHost: %s\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length: %d\r\n\r\n%s", |
| + gate.LoginPath, host, len(form), form[:sent]) |
| + return c, form |
| +} |
| + |
| +// The login body the hub keeps for a -tunnel row is read under a deadline |
| +// (Astra re-review 2, P2): a client that sends the headers and holds back |
| +// part of a body below the cap gets the 413 within the bound, and the |
| +// handler returns (the whole answer arrives and the connection ends); |
| +// nothing reaches the box. The bound is shortened here. |
| +func TestStalledTunnelLoginBodyEndsWithinTheBound(t *testing.T) { |
| + old := loginBodyReadTimeout |
| + loginBodyReadTimeout = 300 * time.Millisecond |
| + t.Cleanup(func() { loginBodyReadTimeout = old }) |
| + srv, _, _, box, _ := tunnelLoginScene(t, false) |
| + |
| + c, form := rawLogin(t, srv, tlFront, 5) |
| + if len(form) <= 5 || len(form) > gate.MaxFormBody { |
| + t.Fatalf("the form is %d bytes; want more than the 5 sent and within the %d cap", len(form), gate.MaxFormBody) |
| + } |
| + start := time.Now() |
| + c.SetReadDeadline(start.Add(5 * time.Second)) |
| + resp, err := http.ReadResponse(bufio.NewReader(c), nil) |
| + if err != nil { |
| + t.Fatalf("no answer to the stalled login within 5 s: %v", err) |
| + } |
| + if _, err := io.ReadAll(resp.Body); err != nil { |
| + t.Fatalf("the answer did not complete: %v", err) |
| + } |
| + if elapsed := time.Since(start); resp.StatusCode != http.StatusRequestEntityTooLarge || elapsed > 2*time.Second { |
| + t.Fatalf("the stalled login: %d after %s, want 413 within the bound (%s) and well inside 2 s", resp.StatusCode, elapsed, loginBodyReadTimeout) |
| + } |
| + if got := box.take(); len(got) != 0 { |
| + t.Fatalf("the box saw %q", got) |
| + } |
| + |
| + // The same over HTTP/2 on TLS, the production listener's shape: the |
| + // stream's read deadline ends the stalled body. |
| + h2 := httptest.NewUnstartedServer(srv.Config.Handler) |
| + h2.EnableHTTP2 = true |
| + h2.StartTLS() |
| + t.Cleanup(h2.Close) |
| + pr, pw := io.Pipe() |
| + t.Cleanup(func() { pw.Close() }) |
| + req, err := http.NewRequest(http.MethodPost, h2.URL+gate.LoginPath, pr) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + req.Host = tlFront |
| + req.ContentLength = int64(len(form)) |
| + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| + go pw.Write([]byte(form[:5])) // and then nothing |
| + start = time.Now() |
| + client := h2.Client() |
| + client.Timeout = 5 * time.Second |
| + resp, err = client.Do(req) |
| + if err != nil { |
| + t.Fatalf("no HTTP/2 answer to the stalled login within 5 s: %v", err) |
| + } |
| + io.ReadAll(resp.Body) |
| + resp.Body.Close() |
| + if elapsed := time.Since(start); resp.ProtoMajor != 2 || resp.StatusCode != http.StatusRequestEntityTooLarge || elapsed > 2*time.Second { |
| + t.Fatalf("the stalled HTTP/2 login: %s %d after %s, want HTTP/2 413 within the bound", resp.Proto, resp.StatusCode, elapsed) |
| + } |
| + if got := box.take(); len(got) != 0 { |
| + t.Fatalf("the box saw %q", got) |
| + } |
| +} |
| + |
| +// The deadline is cleared once the body is in: a login passed down the |
| +// tunnel whose box answers well after the bound is still answered, and |
| +// the connection serves a second request. |
| +func TestPassedLoginOutlivesTheBodyDeadline(t *testing.T) { |
| + old := loginBodyReadTimeout |
| + loginBodyReadTimeout = 200 * time.Millisecond |
| + t.Cleanup(func() { loginBodyReadTimeout = old }) |
| + srv, _, _, box, _ := tunnelLoginScene(t, false) |
| + hold := make(chan struct{}) |
| + box.mu.Lock() |
| + box.hold = hold |
| + box.mu.Unlock() |
| + |
| + c, form := rawLogin(t, srv, tlFront, -1) |
| + // The one wall-clock wait: the box holds its answer until well past |
| + // the bound, which is what a deadline left set would cut off. The |
| + // deadline is the subject, so time has to pass. |
| + time.Sleep(3 * loginBodyReadTimeout) |
| + close(hold) |
| + c.SetReadDeadline(time.Now().Add(5 * time.Second)) |
| + br := bufio.NewReader(c) |
| + resp, err := http.ReadResponse(br, nil) |
| + if err != nil { |
| + t.Fatalf("the passed login: %v", err) |
| + } |
| + b, _ := io.ReadAll(resp.Body) |
| + if resp.StatusCode != http.StatusOK || string(b) != "the front box" { |
| + t.Fatalf("the passed login: %d %q, want the box's answer", resp.StatusCode, b) |
| + } |
| + if got := box.take(); len(got) != 1 || got[0] != "POST "+gate.LoginPath+" "+form { |
| + t.Fatalf("the box saw %q", got) |
| + } |
| + fmt.Fprintf(c, "GET /after HTTP/1.1\r\nHost: %s\r\n\r\n", tlFront) |
| + resp, err = http.ReadResponse(br, nil) |
| + if err != nil || resp.StatusCode != http.StatusOK { |
| + t.Fatalf("a second request on the connection: %v, %v", resp, err) |
| + } |
| +} |