tunnelclient: the hub half of tunnel WebSockets (#471 Task 2)
RoundTripUpgrade sends an upgrade to the box on a stream whose request body stays open: Connection and Upgrade become Carlos-Tunnel-Upgrade, the body is a pipe. A response without Carlos-Tunnel-Upgraded comes back unchanged. With it, the in-band 101 is read under a 64 KiB header cap and a 10 s deadline and must switch to the requested token; it comes back with Body an *UpgradeConn (early bytes, then the stream; Write to the pipe; CloseWrite sends END_STREAM; Close resets the stream). Every error path resets the stream. The context's end resets the stream before or after the 101, since x/net does not watch it while the body is open. Nothing calls it yet: upgrades stay refused at the hub until Task 5. Spec §7 reconciled with the census card (UpgradeConn.Read, name match).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
docs/superpowers/specs/2026-10-30-tunnel-websockets-design.md+10 −0internal/tunnelclient/upgrade.go+156 −2internal/tunnelclient/upgrade_hub_test.go+531 −0
Intent
<task-notification> <task-id>bhv3crxr3</task-id> <tool-use-id>toolu_015gyuArTu5PJJyFjRPzTHUY</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ba9fa944-a429-4788-9b3c-f2b2f42617f3/tasks/bhv3crxr3.output</output-file> <status>completed</status> <summary>Background command "Run Astra round 2 on the Plan 6 amendment" completed (exit code 0)</summary> </task-notification>
<task-notification> <task-id>a6df1701ef5c7b658</task-id> <tool-use-id>toolu_0151NbUQbXZQVEE1GtBQuNq7</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ba9fa944-a429-4788-9b3c-f2b2f42617f3/tasks/a6df1701ef5c7b658.output</output-file> <status>completed</status> <summary>Agent "Write the Plan 6 amendment" 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>Both round 2 findings are closed in the plan, and I swept for the same two problems elsewhere. The tip is `981322d3c8cde479f854a83ec9989cd814b7a623`, pushed to origin `rootfs-apps-6-interactive` and confirmed with `ls-remote`. It includes the round 2 findings file and the round 3 brief. No code was changed. - **P1, the Task 16 cutover witness: closed with Astra's fix as given.** - The cutover refusal and the no-redial rule are unchanged. - I checked the CLI timeline against `run.go` and the gate. The CLI's expire POST gets a 503 while the gate drains, and `runAnswer` doesn't treat a 503 as the console refusing the expiry, so the CLI keeps following and asks again about once a second. - The gate activates once 60 s have passed (`lifetimeSettle`), on the next 10 s watch pass or the operator's next cutover poll. - After that, whichever lands the expiry first, the CLI's own retry or the 30 s run sweep, the CLI exits 3 with today's "not picked up" line. The outcome is the same either way: one expiry, one result, one run-end row. - Two witnesses replace the old one: - `…ExpiresBySweep` holds the CLI's expire POST, so the sweep wins every time; the released POST then gets a 409 and writes nothing. - `…ExpiresByTheCLI` runs no sweep. - I corrected the deadline claim, the rev 2 disposition line and the bound on retrying the run's final record write. - **The same problem elsewhere, swept:** - Every session cutover test in Tasks 10 and 11 now activates the gate the only way it allows: advance the gate clock past 60 s, then run one `lifetimesWatchOnce`. - Task 10 now spells out the session timeline during a drain. - New test: `TestAWaitingSessionExpiresDuringTheDrain`. - **P2, Task 10's request budget: closed.** - The four scoped writes (two record writes, the grant write and the grant delete) each trigger an automatic change-index GET and conditional PUT: 8 requests. - That is counted separately from the serial bump's own GET and PUT, which touch no change index. - An ordinary session totals 21 requests with lifetimes on and 18 with them off, plus 2 for `carlos console`. - Record, lifetime-check, change-index and serial retries are listed separately, with their attempt limits. - I added the same accounting to Task 16 for a fleet run: 12 requests with lifetimes on and 10 off, beyond the output chunks. Keys under `runs/` don't trigger the change index. The round 3 brief marks this as the last round. It carries the dispositions for rounds 1 and 2, and says a NOT READY must state whether its P1s share a cause and whether refusing the case up front or cutting the feature would remove them. The two copy-gate tests are still red until the commit that applies Paul's copy review adds "RFS-6-C65" to `rootfsCopyIDs`. Brief: `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/rootfs-apps-6/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-rootfs-plan6-amendment-R3.md`</result> <usage><subagent_tokens>541228</subagent_tokens><tool_uses>33</tool_uses><duration_ms>297958</duration_ms></usage> </task-notification>
approved copy
<task-notification> <task-id>bbwg0b1ot</task-id> <tool-use-id>toolu_01MHCW3mQCYFizP2UmeJJpDt</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ba9fa944-a429-4788-9b3c-f2b2f42617f3/tasks/bbwg0b1ot.output</output-file> <status>completed</status> <summary>Background command "Run Astra round 3 on the Plan 6 amendment" completed (exit code 0)</summary> </task-notification>
Attributed to this commit: 28.2 g CO₂e (3,653,651 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/docs/superpowers/specs/2026-10-30-tunnel-websockets-design.md b/docs/superpowers/specs/2026-10-30-tunnel-websockets-design.md| index 1ff90669f..0cb4f0ad7 100644 |
| --- a/docs/superpowers/specs/2026-10-30-tunnel-websockets-design.md |
| +++ b/docs/superpowers/specs/2026-10-30-tunnel-websockets-design.md |
| @@ -973,6 +973,16 @@ writer, the constants) have no census row because they read nothing; |
| their changes are covered by the envelope re-pin, which the reviewer |
| reads function by function. |
| +Task 2 adds one more `new` unit for the same reason: |
| +`upgrade.go:UpgradeConn.Read`, with `reads +file:Read ×2`. It reads the |
| +bytes that came with the in-band 101 from memory, then the stream's |
| +HTTP/2 response body (the box's bytes, `c.body.Read`): no file and no |
| +root-owned state, so "no `reads`" still stands. `RoundTripUpgrade`, the |
| +rest of `UpgradeConn` (`Write`, `CloseWrite`, `Close`), |
| +`ErrUpgradeHandshake`, `MaxUpgradeHeaderBytes` and |
| +`UpgradeHandshakeTimeout` read nothing and have no row; the envelope |
| +re-pin covers them. |
| + |
| The reviewer is Astra (Claude author), recorded on #280. |
| Copy. Two new cause descriptions in `internal/apperr/availability.go` |
diff --git a/internal/tunnelclient/upgrade.go b/internal/tunnelclient/upgrade.go| index 98be1a376..56d79f2aa 100644 |
| --- a/internal/tunnelclient/upgrade.go |
| +++ b/internal/tunnelclient/upgrade.go |
| @@ -1,7 +1,7 @@ |
| package tunnelclient |
| -// The box half of an upgraded connection through the tunnel (#471, spec |
| -// §4.3 steps 6 and 8, §4.4, §4.8, §4.9). |
| +// Both halves of an upgraded connection through the tunnel (#471, spec |
| +// §4.3 to §4.9): the box's shim first, then the hub's RoundTripUpgrade. |
| // |
| // HTTP/2 has no Connection or Upgrade header, so the hub carries the |
| // upgrade token in UpgradeHeader on an ordinary stream whose request body |
| @@ -14,10 +14,14 @@ package tunnelclient |
| import ( |
| "bufio" |
| + "bytes" |
| + "context" |
| "errors" |
| + "fmt" |
| "io" |
| "net" |
| "net/http" |
| + "strings" |
| "sync" |
| "sync/atomic" |
| "time" |
| @@ -369,3 +373,153 @@ type streamAddr string |
| func (streamAddr) Network() string { return "carlos-tunnel" } |
| func (a streamAddr) String() string { return string(a) } |
| + |
| +// The hub half (#471 spec §4.3 steps 5 and 9, §4.7). |
| + |
| +const ( |
| + // MaxUpgradeHeaderBytes caps the in-band response the hub reads off an |
| + // upgraded stream: status line and headers together. |
| + MaxUpgradeHeaderBytes = 64 << 10 |
| + // UpgradeHandshakeTimeout bounds the wait for the in-band response |
| + // once the box has said it hijacked the stream. |
| + UpgradeHandshakeTimeout = 10 * time.Second |
| +) |
| + |
| +// ErrUpgradeHandshake is the error RoundTripUpgrade wraps, with the reason, |
| +// when it refuses a token or the box's in-band response. |
| +var ErrUpgradeHandshake = errors.New("tunnelclient: upgrade handshake failed") |
| + |
| +// upgradeHandshakeTimeout is UpgradeHandshakeTimeout, a variable only so |
| +// a test can shorten it. RoundTripUpgrade reads it once per call. |
| +var upgradeHandshakeTimeout = UpgradeHandshakeTimeout |
| + |
| +// hookHandshake, nil in production, runs once the box's marked 200 is in |
| +// and before the in-band read: a test's point "the hub is waiting for the |
| +// 101". |
| +var hookHandshake func() |
| + |
| +// RoundTripUpgrade sends an HTTP/1.1 upgrade request (Connection: Upgrade, |
| +// Upgrade: <tok>) to the box on a new stream of cc. The stream's request |
| +// body stays open as the hub's send side. |
| +// |
| +// If the box answers without UpgradedHeader (the gate, a 404, a 502: any |
| +// refusal), that response comes back unchanged and its body is the stream. |
| +// If it hijacked, the app's in-band response must be a 101 for the same |
| +// token, read within upgradeHandshakeTimeout and MaxUpgradeHeaderBytes; |
| +// it comes back with Body an *UpgradeConn. Anything else is an error |
| +// wrapping ErrUpgradeHandshake, and the stream is reset before it returns. |
| +// |
| +// ctx becomes the stream's context, and its end resets the stream, before |
| +// or after the 101. x/net alone does not watch the context while it waits |
| +// on an open request body, so the context's end fails the pipe, which |
| +// x/net answers with RST_STREAM. |
| +func RoundTripUpgrade(ctx context.Context, cc *http2.ClientConn, req *http.Request) (*http.Response, error) { |
| + tok := req.Header.Get("Upgrade") |
| + if !ValidUpgradeToken(tok) { |
| + return nil, fmt.Errorf("%w: the Upgrade token is not one token of at most %d bytes", ErrUpgradeHandshake, MaxUpgradeTokenLen) |
| + } |
| + timeout := upgradeHandshakeTimeout |
| + |
| + out := req.Clone(ctx) |
| + out.Header.Del("Connection") |
| + out.Header.Del("Upgrade") |
| + out.Header.Set(UpgradeHeader, tok) |
| + // Unknown length: HEADERS go without END_STREAM, and the pipe is the |
| + // client-to-app half of the socket. |
| + pr, pw := io.Pipe() |
| + out.Body = pr |
| + out.ContentLength = -1 |
| + out.GetBody = nil |
| + out.TransferEncoding = nil |
| + stopCtx := context.AfterFunc(ctx, func() { pw.CloseWithError(context.Cause(ctx)) }) |
| + |
| + resp, err := cc.RoundTrip(out) |
| + if err != nil { |
| + stopCtx() |
| + pw.CloseWithError(err) |
| + return nil, err |
| + } |
| + if resp.Header.Get(UpgradedHeader) != "1" { |
| + // The box answered without upgrading: nothing more goes to it. |
| + // The request body is complete, so x/net watches ctx itself. |
| + stopCtx() |
| + pw.Close() |
| + return resp, nil |
| + } |
| + |
| + // Reset the stream on every way out but success. |
| + fail := func(reason string, err error) (*http.Response, error) { |
| + stopCtx() |
| + resp.Body.Close() |
| + pw.CloseWithError(net.ErrClosed) |
| + if err != nil { |
| + return nil, fmt.Errorf("%w: %s: %w", ErrUpgradeHandshake, reason, err) |
| + } |
| + return nil, fmt.Errorf("%w: %s", ErrUpgradeHandshake, reason) |
| + } |
| + timer := time.AfterFunc(timeout, func() { |
| + resp.Body.Close() // unblocks the read below |
| + }) |
| + if hookHandshake != nil { |
| + hookHandshake() |
| + } |
| + br := bufio.NewReader(io.LimitReader(resp.Body, MaxUpgradeHeaderBytes)) |
| + in, err := http.ReadResponse(br, out) |
| + if !timer.Stop() { // it fired: the body is closed, whatever the read got |
| + return fail(fmt.Sprintf("no response within %s", timeout), nil) |
| + } |
| + if err != nil { |
| + return fail(fmt.Sprintf("reading the response (at most %d header bytes)", MaxUpgradeHeaderBytes), err) |
| + } |
| + if in.StatusCode != http.StatusSwitchingProtocols { |
| + return fail(fmt.Sprintf("status %d, want 101", in.StatusCode), nil) |
| + } |
| + if got := in.Header.Get("Upgrade"); !strings.EqualFold(got, tok) { |
| + return fail(fmt.Sprintf("switched to %q, %q was requested", got, tok), nil) |
| + } |
| + // Bytes the app sent after its 101 that the read above already took. |
| + early, _ := br.Peek(br.Buffered()) |
| + in.Body = &UpgradeConn{early: bytes.Clone(early), body: resp.Body, pw: pw, stopCtx: stopCtx} |
| + return in, nil |
| +} |
| + |
| +// UpgradeConn is the hub's end of an upgraded stream, the body of the 101 |
| +// RoundTripUpgrade returns: the reverse proxy splices it with the client. |
| +// One goroutine reads at a time; writes may come from any. |
| +type UpgradeConn struct { |
| + early []byte // what followed the 101 in the handshake read |
| + body io.ReadCloser // the stream's response body: the app's bytes |
| + pw *io.PipeWriter |
| + stopCtx func() bool // unregisters the context's reset |
| + closeOnce sync.Once |
| +} |
| + |
| +// Read returns the bytes that came with the 101, then the stream's. |
| +func (c *UpgradeConn) Read(p []byte) (int, error) { |
| + if len(c.early) > 0 { |
| + n := copy(p, c.early) |
| + c.early = c.early[n:] |
| + return n, nil |
| + } |
| + return c.body.Read(p) |
| +} |
| + |
| +// Write sends p to the box on the stream's request body. |
| +func (c *UpgradeConn) Write(p []byte) (int, error) { return c.pw.Write(p) } |
| + |
| +// CloseWrite ends the request body, which sends END_STREAM: the box reads |
| +// EOF and can still write. |
| +func (c *UpgradeConn) CloseWrite() error { return c.pw.Close() } |
| + |
| +// Close resets the stream (RST_STREAM CANCEL, unless both sides had |
| +// already ended it): the box's reads and writes fail, so its handler |
| +// returns even if a write was blocked on the hub's flow control. Later |
| +// reads and writes here fail. Idempotent. |
| +func (c *UpgradeConn) Close() error { |
| + c.closeOnce.Do(func() { |
| + c.stopCtx() |
| + c.body.Close() |
| + c.pw.CloseWithError(net.ErrClosed) |
| + }) |
| + return nil |
| +} |
diff --git a/internal/tunnelclient/upgrade_hub_test.go b/internal/tunnelclient/upgrade_hub_test.go| new file mode 100644 |
| index 000000000..74fb1733e |
| --- /dev/null |
| +++ b/internal/tunnelclient/upgrade_hub_test.go |
| @@ -0,0 +1,531 @@ |
| +package tunnelclient |
| + |
| +import ( |
| + "bufio" |
| + "bytes" |
| + "context" |
| + "crypto/rand" |
| + "errors" |
| + "io" |
| + "net" |
| + "net/http" |
| + "strings" |
| + "sync" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| +) |
| + |
| +// The hub half of an upgrade (#471 spec §4.3 steps 5 and 9, §8.1 cases 1 |
| +// to 5), over the same in-memory pair as the box tests: the box side is |
| +// Task 1's ServeWith over Mark of a test handler that plays the box edge's |
| +// reverse proxy (hijack, write the app's 101 in-band, splice). |
| + |
| +const ( |
| + wsKey = "dGhlIHNhbXBsZSBub25jZQ==" |
| + wsAccept = "s3pPLMBiTxaQ9kYGzzhZRbK+xOo=" |
| + wsProto = "actioncable-v1-json" |
| + the101 = "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n" + |
| + "Sec-WebSocket-Accept: " + wsAccept + "\r\nSec-WebSocket-Protocol: " + wsProto + "\r\n\r\n" |
| +) |
| + |
| +// upgradeRequest is the request as the hub's reverse proxy hands it to the |
| +// transport: HTTP/1.1 upgrade headers intact. |
| +func upgradeRequest(tok string) *http.Request { |
| + req, _ := http.NewRequest("GET", "https://shop.example.com/cable", nil) |
| + req.Header.Set("Connection", "Upgrade") |
| + req.Header.Set("Upgrade", tok) |
| + req.Header.Set("Sec-WebSocket-Key", wsKey) |
| + req.Header.Set("Sec-WebSocket-Version", "13") |
| + return req |
| +} |
| + |
| +// boxEnd is one box handler's view of the test: what it saw and when it |
| +// returned. |
| +type boxEnd struct { |
| + req chan *http.Request |
| + done chan struct{} |
| +} |
| + |
| +// hijackingBox is the box's edge as the shim sees it: it hijacks the |
| +// stream and hands the conn to play. Each request gets its own boxEnd |
| +// from ends, so a fixture serves several requests in order. |
| +func hijackingBox(t *testing.T, ends <-chan *boxEnd, play func(r *http.Request, conn net.Conn, brw *bufio.ReadWriter)) http.Handler { |
| + return Mark(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + e := <-ends |
| + defer close(e.done) |
| + e.req <- r |
| + hj, ok := w.(http.Hijacker) |
| + if !ok { |
| + t.Errorf("the shim's writer is not a Hijacker on an upgrade") |
| + return |
| + } |
| + conn, brw, err := hj.Hijack() |
| + if err != nil { |
| + t.Errorf("hijack: %v", err) |
| + return |
| + } |
| + defer conn.Close() |
| + play(r, conn, brw) |
| + })) |
| +} |
| + |
| +func newBoxEnd(ends chan<- *boxEnd) *boxEnd { |
| + e := &boxEnd{req: make(chan *http.Request, 1), done: make(chan struct{})} |
| + ends <- e |
| + return e |
| +} |
| + |
| +func waitDone(t *testing.T, done <-chan struct{}, what string) { |
| + t.Helper() |
| + select { |
| + case <-done: |
| + case <-time.After(5 * time.Second): |
| + t.Fatalf("%s did not return", what) |
| + } |
| +} |
| + |
| +// writeIn writes s in-band and flushes, as the box proxy's res.Write(brw). |
| +func writeIn(brw *bufio.ReadWriter, s string) { |
| + brw.WriteString(s) |
| + brw.Flush() |
| +} |
| + |
| +func TestRoundTripUpgradeReturnsThe101(t *testing.T) { |
| + ends := make(chan *boxEnd, 1) |
| + cc := h2Pair(t, hijackingBox(t, ends, func(r *http.Request, conn net.Conn, brw *bufio.ReadWriter) { |
| + if r.Header.Get("Sec-WebSocket-Key") != wsKey { |
| + writeIn(brw, "HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\n\r\n") |
| + return |
| + } |
| + // The app's first frame goes out in the same flush as its 101 (an |
| + // Action Cable welcome does): it must reach the hub after the 101, |
| + // from the bytes the handshake read had already buffered. |
| + writeIn(brw, the101+"welcome") |
| + io.Copy(io.Discard, conn) |
| + })) |
| + e := newBoxEnd(ends) |
| + req := upgradeRequest("websocket") |
| + resp, err := RoundTripUpgrade(context.Background(), cc, req) |
| + if err != nil { |
| + t.Fatalf("RoundTripUpgrade: %v", err) |
| + } |
| + r := <-e.req |
| + if r.Header.Get("Connection") != "Upgrade" || r.Header.Get("Upgrade") != "websocket" { |
| + t.Errorf("box saw Connection %q, Upgrade %q", r.Header.Get("Connection"), r.Header.Get("Upgrade")) |
| + } |
| + if req.Header.Get("Connection") != "Upgrade" || req.Header.Get("Upgrade") != "websocket" || req.Header.Get(UpgradeHeader) != "" { |
| + t.Errorf("the caller's request was changed: %v", req.Header) |
| + } |
| + if resp.StatusCode != http.StatusSwitchingProtocols || |
| + resp.Header.Get("Upgrade") != "websocket" || |
| + resp.Header.Get("Sec-WebSocket-Accept") != wsAccept || |
| + resp.Header.Get("Sec-WebSocket-Protocol") != wsProto { |
| + t.Fatalf("got %d %v, want the app's 101", resp.StatusCode, resp.Header) |
| + } |
| + rwc, ok := resp.Body.(io.ReadWriteCloser) |
| + if !ok { |
| + t.Fatalf("body %T is not an io.ReadWriteCloser", resp.Body) |
| + } |
| + if _, ok := resp.Body.(*UpgradeConn); !ok { |
| + t.Fatalf("body %T is not an *UpgradeConn", resp.Body) |
| + } |
| + first := make([]byte, len("welcome")) |
| + readc := make(chan error, 1) |
| + go func() { |
| + _, err := io.ReadFull(rwc, first) |
| + readc <- err |
| + }() |
| + select { |
| + case err := <-readc: |
| + if err != nil || string(first) != "welcome" { |
| + t.Fatalf("first bytes after the 101 = %q, %v", first, err) |
| + } |
| + case <-time.After(5 * time.Second): |
| + rwc.Close() |
| + <-readc |
| + t.Fatal("the bytes that came with the 101 never reached the hub's reader") |
| + } |
| + if err := rwc.Close(); err != nil { |
| + t.Fatalf("close: %v", err) |
| + } |
| + waitDone(t, e.done, "the box handler") |
| +} |
| + |
| +func TestUpgradeCarriesBytesVerbatim(t *testing.T) { |
| + const size = 1 << 20 |
| + var got bytes.Buffer // what the box received; read after its handler returns |
| + ends := make(chan *boxEnd, 1) |
| + cc := h2Pair(t, hijackingBox(t, ends, func(r *http.Request, conn net.Conn, brw *bufio.ReadWriter) { |
| + writeIn(brw, the101) |
| + io.Copy(conn, io.TeeReader(conn, &got)) // echo until the hub's half-close |
| + })) |
| + e := newBoxEnd(ends) |
| + resp, err := RoundTripUpgrade(context.Background(), cc, upgradeRequest("websocket")) |
| + if err != nil { |
| + t.Fatalf("RoundTripUpgrade: %v", err) |
| + } |
| + uc := resp.Body.(*UpgradeConn) |
| + defer uc.Close() |
| + |
| + sent := make([]byte, size) |
| + rand.Read(sent) |
| + werr := make(chan error, 1) |
| + go func() { |
| + _, err := uc.Write(sent) |
| + werr <- err |
| + }() |
| + back := make([]byte, size) |
| + if _, err := io.ReadFull(uc, back); err != nil { |
| + t.Fatalf("read the echo: %v", err) |
| + } |
| + if err := <-werr; err != nil { |
| + t.Fatalf("write: %v", err) |
| + } |
| + if err := uc.CloseWrite(); err != nil { |
| + t.Fatalf("CloseWrite: %v", err) |
| + } |
| + waitDone(t, e.done, "the box handler") |
| + if rest, err := io.ReadAll(uc); err != nil || len(rest) != 0 { |
| + t.Fatalf("after the box returned: %d bytes, %v; want a clean end", len(rest), err) |
| + } |
| + if !bytes.Equal(got.Bytes(), sent) { |
| + t.Fatalf("hub to box: the box received %d bytes that differ from the %d sent", got.Len(), size) |
| + } |
| + if !bytes.Equal(back, sent) { |
| + t.Fatalf("box to hub: the hub received bytes that differ from the box's echo") |
| + } |
| +} |
| + |
| +func TestRoundTripUpgradePassesRefusalsThrough(t *testing.T) { |
| + saw := make(chan *http.Request, 1) |
| + cc := h2Pair(t, Mark(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + saw <- r |
| + w.Header().Set("Location", "/.carlos/gate") |
| + w.WriteHeader(http.StatusFound) |
| + io.WriteString(w, "gate body") |
| + }))) |
| + resp, err := RoundTripUpgrade(context.Background(), cc, upgradeRequest("websocket")) |
| + if err != nil { |
| + t.Fatalf("RoundTripUpgrade: %v, want the box's 302", err) |
| + } |
| + defer resp.Body.Close() |
| + if r := <-saw; r.Header.Get("Upgrade") != "websocket" { |
| + t.Fatalf("the box did not see an upgrade: %v", r.Header) |
| + } |
| + if resp.StatusCode != http.StatusFound || resp.Header.Get("Location") != "/.carlos/gate" { |
| + t.Fatalf("got %d %v, want the 302", resp.StatusCode, resp.Header) |
| + } |
| + if _, ok := resp.Body.(*UpgradeConn); ok { |
| + t.Fatal("a refusal's body is an UpgradeConn") |
| + } |
| + if b, err := io.ReadAll(resp.Body); err != nil || string(b) != "gate body" { |
| + t.Fatalf("body = %q, %v", b, err) |
| + } |
| +} |
| + |
| +// boxReadErr is what the box handler's first conn Read returned. |
| +func boxReadErr(conn net.Conn, out chan<- error) { |
| + _, err := conn.Read(make([]byte, 1)) |
| + out <- err |
| +} |
| + |
| +// wantReset waits for the box handler's Read to fail with a stream reset: |
| +// not io.EOF, which is the hub's clean half-close. |
| +func wantReset(t *testing.T, readErr <-chan error, done <-chan struct{}) { |
| + t.Helper() |
| + select { |
| + case err := <-readErr: |
| + if err == nil || errors.Is(err, io.EOF) { |
| + t.Fatalf("box conn Read = %v, want the stream's reset", err) |
| + } |
| + case <-time.After(time.Second): |
| + t.Fatal("the box conn's Read did not fail within 1 s: the stream was not reset") |
| + } |
| + waitDone(t, done, "the box handler") |
| +} |
| + |
| +func TestRoundTripUpgradeRefusesBadInBand101(t *testing.T) { |
| + old := upgradeHandshakeTimeout |
| + upgradeHandshakeTimeout = 200 * time.Millisecond |
| + t.Cleanup(func() { upgradeHandshakeTimeout = old }) |
| + |
| + cases := []struct { |
| + name string |
| + inBand string // written after the hijack; "" writes nothing |
| + wantErr bool |
| + }{ |
| + {"control: a well-formed 101", the101, false}, |
| + {"65 KiB of headers", "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nX-Pad: " + |
| + strings.Repeat("a", 65<<10) + "\r\n\r\n", true}, |
| + {"nothing within the deadline", "", true}, |
| + {"not a 101", "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n", true}, |
| + {"another protocol", "HTTP/1.1 101 Switching Protocols\r\nUpgrade: h2c\r\nConnection: Upgrade\r\n\r\n", true}, |
| + {"not HTTP", "SSH-2.0-OpenSSH\r\n\r\n", true}, |
| + } |
| + for _, c := range cases { |
| + t.Run(c.name, func(t *testing.T) { |
| + // A pair per case, so one case's stream cannot meet another's box. |
| + readErr := make(chan error, 1) |
| + ends := make(chan *boxEnd, 1) |
| + cc := h2Pair(t, hijackingBox(t, ends, func(r *http.Request, conn net.Conn, brw *bufio.ReadWriter) { |
| + if c.inBand != "" { |
| + writeIn(brw, c.inBand) // may fail once the hub has reset: the Read below reports it |
| + } |
| + boxReadErr(conn, readErr) |
| + })) |
| + e := newBoxEnd(ends) |
| + type result struct { |
| + resp *http.Response |
| + err error |
| + } |
| + res := make(chan result, 1) |
| + go func() { |
| + resp, err := RoundTripUpgrade(context.Background(), cc, upgradeRequest("websocket")) |
| + res <- result{resp, err} |
| + }() |
| + var got result |
| + select { |
| + case got = <-res: |
| + case <-time.After(5 * time.Second): |
| + t.Fatal("RoundTripUpgrade did not return within 5 s (the test deadline is 200 ms)") |
| + } |
| + select { |
| + case <-e.req: |
| + case <-time.After(5 * time.Second): |
| + t.Fatalf("the box never saw the stream (%v)", got.err) |
| + } |
| + if !c.wantErr { |
| + if got.err != nil || got.resp.StatusCode != http.StatusSwitchingProtocols { |
| + t.Fatalf("control: %v, %v; want the 101", got.resp, got.err) |
| + } |
| + got.resp.Body.Close() |
| + wantReset(t, readErr, e.done) |
| + return |
| + } |
| + if !errors.Is(got.err, ErrUpgradeHandshake) { |
| + t.Fatalf("err = %v, want ErrUpgradeHandshake", got.err) |
| + } |
| + if got.resp != nil { |
| + t.Fatalf("a response came back with the error: %d", got.resp.StatusCode) |
| + } |
| + wantReset(t, readErr, e.done) |
| + }) |
| + } |
| +} |
| + |
| +func TestRoundTripUpgradeRefusesBadTokens(t *testing.T) { |
| + var streams atomic.Int32 // every stream the box serves, before the shim |
| + ends := make(chan *boxEnd, 1) |
| + box := hijackingBox(t, ends, func(r *http.Request, conn net.Conn, brw *bufio.ReadWriter) { |
| + writeIn(brw, the101) |
| + io.Copy(io.Discard, conn) |
| + }) |
| + cc := h2Pair(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + streams.Add(1) |
| + box.ServeHTTP(w, r) |
| + })) |
| + for _, tok := range []string{"web socket", strings.Repeat("a", MaxUpgradeTokenLen+1)} { |
| + resp, err := RoundTripUpgrade(context.Background(), cc, upgradeRequest(tok)) |
| + if !errors.Is(err, ErrUpgradeHandshake) || resp != nil { |
| + t.Fatalf("token %q: %v, %v; want ErrUpgradeHandshake", tok, resp, err) |
| + } |
| + } |
| + if n := streams.Load(); n != 0 { |
| + t.Fatalf("the box served %d streams for refused tokens, want 0", n) |
| + } |
| + // Control: the same fixture serves a valid token. |
| + e := newBoxEnd(ends) |
| + resp, err := RoundTripUpgrade(context.Background(), cc, upgradeRequest("websocket")) |
| + if err != nil { |
| + t.Fatalf("control: %v", err) |
| + } |
| + <-e.req |
| + resp.Body.Close() |
| + waitDone(t, e.done, "the box handler") |
| + if n := streams.Load(); n != 1 { |
| + t.Fatalf("control: the box served %d streams, want 1", n) |
| + } |
| +} |
| + |
| +func TestUpgradeConnCloseResetsBothWays(t *testing.T) { |
| + // upgraded opens one socket through a fresh pair whose box runs play. |
| + upgraded := func(t *testing.T, ctx context.Context, play func(conn net.Conn)) (*UpgradeConn, *boxEnd) { |
| + t.Helper() |
| + ends := make(chan *boxEnd, 1) |
| + cc := h2Pair(t, hijackingBox(t, ends, func(r *http.Request, conn net.Conn, brw *bufio.ReadWriter) { |
| + writeIn(brw, the101) |
| + play(conn) |
| + })) |
| + e := newBoxEnd(ends) |
| + resp, err := RoundTripUpgrade(ctx, cc, upgradeRequest("websocket")) |
| + if err != nil { |
| + t.Fatalf("RoundTripUpgrade: %v", err) |
| + } |
| + <-e.req |
| + return resp.Body.(*UpgradeConn), e |
| + } |
| + |
| + t.Run("Close resets the stream", func(t *testing.T) { |
| + readErr := make(chan error, 1) |
| + uc, e := upgraded(t, context.Background(), func(conn net.Conn) { boxReadErr(conn, readErr) }) |
| + if err := uc.Close(); err != nil { |
| + t.Fatalf("close: %v", err) |
| + } |
| + wantReset(t, readErr, e.done) |
| + if err := uc.Close(); err != nil { |
| + t.Fatalf("second close: %v", err) |
| + } |
| + if _, err := uc.Write([]byte("x")); err == nil { |
| + t.Fatal("Write after Close succeeded") |
| + } |
| + if _, err := uc.Read(make([]byte, 1)); err == nil { |
| + t.Fatal("Read after Close succeeded") |
| + } |
| + }) |
| + |
| + // Task 1's carry: a box Write blocked on the hub's flow control holds |
| + // the box handler open (its fence waits for the Write) until the hub |
| + // resets the stream. The hub never reads, and x/net's client stream |
| + // window is 4 MiB, so a 5 MiB Write cannot complete; hookWrite says the |
| + // Write is inside its guarded section. |
| + t.Run("Close ends a box Write blocked on flow control", func(t *testing.T) { |
| + inWrite := make(chan struct{}) |
| + writeErr := make(chan error, 1) |
| + uc, e := upgraded(t, context.Background(), func(conn net.Conn) { |
| + uc := conn.(*upgradedConn) |
| + var once sync.Once |
| + uc.hookWrite = func() { once.Do(func() { close(inWrite) }) } |
| + _, err := conn.Write(make([]byte, 5<<20)) |
| + writeErr <- err |
| + }) |
| + select { |
| + case <-inWrite: |
| + case <-time.After(5 * time.Second): |
| + t.Fatal("the box never started its Write") |
| + } |
| + select { |
| + case <-e.done: |
| + t.Fatal("the box handler returned with its 5 MiB Write unread") |
| + default: |
| + } |
| + uc.Close() |
| + select { |
| + case err := <-writeErr: |
| + if err == nil { |
| + t.Fatal("the box's blocked Write completed, want the reset's error") |
| + } |
| + case <-time.After(time.Second): |
| + t.Fatal("the box's blocked Write did not fail within 1 s of Close") |
| + } |
| + waitDone(t, e.done, "the box handler") |
| + }) |
| + |
| + t.Run("CloseWrite half-closes", func(t *testing.T) { |
| + boxRead := make(chan error, 1) |
| + uc, e := upgraded(t, context.Background(), func(conn net.Conn) { |
| + _, err := conn.Read(make([]byte, 1)) |
| + boxRead <- err |
| + if err == io.EOF { |
| + conn.Write([]byte("bye")) |
| + } |
| + }) |
| + defer uc.Close() |
| + if err := uc.CloseWrite(); err != nil { |
| + t.Fatalf("CloseWrite: %v", err) |
| + } |
| + select { |
| + case err := <-boxRead: |
| + if err != io.EOF { |
| + t.Fatalf("box conn Read = %v, want io.EOF", err) |
| + } |
| + case <-time.After(time.Second): |
| + t.Fatal("the box did not read EOF within 1 s of CloseWrite") |
| + } |
| + bye := make([]byte, 3) |
| + if _, err := io.ReadFull(uc, bye); err != nil || string(bye) != "bye" { |
| + t.Fatalf("hub read %q, %v; want bye", bye, err) |
| + } |
| + waitDone(t, e.done, "the box handler") |
| + if rest, err := io.ReadAll(uc); err != nil || len(rest) != 0 { |
| + t.Fatalf("after the box returned: %q, %v; want a clean end", rest, err) |
| + } |
| + if _, err := uc.Write([]byte("x")); err == nil { |
| + t.Fatal("Write after CloseWrite succeeded") |
| + } |
| + if err := uc.CloseWrite(); err != nil { |
| + t.Fatalf("second CloseWrite: %v", err) |
| + } |
| + }) |
| +} |
| + |
| +// The context RoundTripUpgrade is given is the stream's: its end resets |
| +// the stream while the hub waits for the in-band 101 (a hung app), and |
| +// after it. x/net does not watch it while the request body is open, so |
| +// this is RoundTripUpgrade's own doing; Task 3's release and backstop |
| +// rest on it. |
| +func TestRoundTripUpgradeEndsWithItsContext(t *testing.T) { |
| + t.Run("during the handshake", func(t *testing.T) { |
| + // The real deadline, so only the context can end this in time. |
| + old := upgradeHandshakeTimeout |
| + upgradeHandshakeTimeout = UpgradeHandshakeTimeout |
| + waiting := make(chan struct{}) |
| + hookHandshake = func() { close(waiting) } |
| + t.Cleanup(func() { upgradeHandshakeTimeout, hookHandshake = old, nil }) |
| + readErr := make(chan error, 1) |
| + ends := make(chan *boxEnd, 1) |
| + cc := h2Pair(t, hijackingBox(t, ends, func(r *http.Request, conn net.Conn, brw *bufio.ReadWriter) { |
| + boxReadErr(conn, readErr) // hijacked, never answers |
| + })) |
| + e := newBoxEnd(ends) |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + defer cancel() |
| + errc := make(chan error, 1) |
| + go func() { |
| + resp, err := RoundTripUpgrade(ctx, cc, upgradeRequest("websocket")) |
| + if resp != nil { |
| + resp.Body.Close() |
| + } |
| + errc <- err |
| + }() |
| + <-e.req |
| + select { |
| + case <-waiting: // the marked 200 is in; the hub is reading for the 101 |
| + case err := <-errc: |
| + t.Fatalf("RoundTripUpgrade returned before the handshake read: %v", err) |
| + } |
| + cancel() |
| + select { |
| + case err := <-errc: |
| + if !errors.Is(err, ErrUpgradeHandshake) || !errors.Is(err, context.Canceled) { |
| + t.Fatalf("err = %v, want ErrUpgradeHandshake from the context's end", err) |
| + } |
| + case <-time.After(time.Second): |
| + t.Fatal("RoundTripUpgrade did not return within 1 s of its context ending") |
| + } |
| + wantReset(t, readErr, e.done) |
| + }) |
| + |
| + t.Run("after the 101", func(t *testing.T) { |
| + readErr := make(chan error, 1) |
| + ends := make(chan *boxEnd, 1) |
| + cc := h2Pair(t, hijackingBox(t, ends, func(r *http.Request, conn net.Conn, brw *bufio.ReadWriter) { |
| + writeIn(brw, the101) |
| + boxReadErr(conn, readErr) |
| + })) |
| + e := newBoxEnd(ends) |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + defer cancel() |
| + resp, err := RoundTripUpgrade(ctx, cc, upgradeRequest("websocket")) |
| + if err != nil { |
| + t.Fatalf("RoundTripUpgrade: %v", err) |
| + } |
| + defer resp.Body.Close() |
| + <-e.req |
| + cancel() |
| + wantReset(t, readErr, e.done) |
| + if _, err := resp.Body.(*UpgradeConn).Write([]byte("x")); err == nil { |
| + t.Fatal("Write after the context ended succeeded") |
| + } |
| + }) |
| +} |