interactive: one frame is one whole message; Dial checks the subprotocol (Task 2 fix 1)
Astra's Task 2 review, both P2s and the P3. Receive now reads at the frame level through x/net's own frame reader (ws.NewFrameReader with its raw header, then ws.HandleFrame for masking, pings and close), because x/net's codecs check neither FIN nor that a payload arrived whole. A frame without FIN, a continuation, a text frame, a reserved bit and an empty frame are ErrBadFrame; the payload is read with io.ReadFull to its declared length, so a frame cut short is an error wrapping io.ErrUnexpectedEOF, not a short success. Oversize is still websocket.ErrFrameTooLarge, checked before any payload is read. After any Receive error the connection is done; the caller closes it. DialFrame dials the transport itself, keeps the handshake response's bytes, and refuses (ErrNoSubprotocol) unless the response carries exactly one Sec-WebSocket-Protocol of carlos-interactive/1; x/net accepted a response naming none. MaxFrame and RunMaxFrame are unchanged. New raw-wire tests: fragmented, continuation, text, reserved-bit and empty frames refused at the client and (masked) at the server, a whole frame and one after a ping accepted; payloads and headers cut short refused, a frame split over many writes read whole; Dial refused for a server answering no protocol, "x" or a list. Each test was seen red first, and removing each fix fails it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
internal/interactive/frames.go+178 −23internal/interactive/frames_test.go+231 −13
Intent
<task-notification> <task-id>a232f2e8c830f59c6</task-id> <tool-use-id>toolu_01HukSoqQ5HXZEKdXMStNWd9</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ba9fa944-a429-4788-9b3c-f2b2f42617f3/tasks/a232f2e8c830f59c6.output</output-file> <status>completed</status> <summary>Agent "Plan 6 Task 2: interactive package" 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:** `6672a22e` "interactive: ids, limits, frames and the signed grant (rootfs plan 6)". It adds only the 6 files in `internal/interactive/`. go.mod is unchanged. **Tests:** all 14 tests in `internal/interactive` pass, including the brief's `-run` set under `-race`. `go vet` and `gofmt` are clean, and the package builds for windows/amd64, darwin/arm64 and linux/arm64. **Concerns:** - **`RunHello` is not in this commit.** Your message said Task 2 includes it, but the Task 2 brief doesn't list it. The plan's Task 16 interfaces, the index (line 167) and the preflight's Task 2/16 overlap row all put it in Task 16, along with `RunPicked`, `Grant.Kind` and `RunAttachPathPrefix`. `RunMaxFrame`, `DialFrame` and `SendFrame` are in. If you want `RunHello` now, it's a four-field struct plus tests. - **Four small, deliberate departures from the brief:** - **Host check:** it calls `controlname.ValidHostShape` instead of `provision.ValidHostShape`. The provision function is a one-line wrapper of the same check, so behaviour is identical. This keeps `provision` out of the package and avoids a future import cycle. - **`Receive`:** it uses a custom `websocket.Codec`. The brief named `websocket.Message.Receive`, but that accepts text frames silently, so text frames could not be refused as `ErrBadFrame` with it. The size limit and `ErrFrameTooLarge` still work. - **Extra grant checks:** `VerifyGrant` also refuses a version other than 1, a bad account or app, an empty token, missing times, and an `Attach` URL with userinfo, a query or a fragment. Each of these refuses a bad grant and passes a correct one. - **New exported names:** `ErrNotHTTP` and `MaxGrantSkew` (2 minutes). - **Test order:** I wrote the code before the tests, so the "fails because the package does not exist" step was never seen. - **Error strings:** they are `interactive: …` diagnostics, not user-facing copy. Tasks 10 and 13 must map them to approved RFS-6 rows before showing any to a user. - **Unchecked grant fields:** `Incarnation` and `By` aren't validated, because the brief gives no rule for them. The full report is at `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/rootfs-apps-6/.superpowers/sdd/2026-10-24-rootfs-apps-6-interactive/task-2-report.md`.</result> <usage><subagent_tokens>122327</subagent_tokens><tool_uses>35</tool_uses><duration_ms>340736</duration_ms></usage> </task-notification>
<task-notification> <task-id>bs2q5aket</task-id> <tool-use-id>toolu_018cKQd3vMtJr3sUf9ncrq4k</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ba9fa944-a429-4788-9b3c-f2b2f42617f3/tasks/bs2q5aket.output</output-file> <status>completed</status> <summary>Background command "Run Astra review round 1 on the Plan 6 amendment" completed (exit code 0)</summary> </task-notification>
<task-notification> <task-id>bbhpc2nu9</task-id> <tool-use-id>toolu_01RPTPmrNmezU6uXnh6mrWZ4</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ba9fa944-a429-4788-9b3c-f2b2f42617f3/tasks/bbhpc2nu9.output</output-file> <status>completed</status> <summary>Background command "Package Plan 6 Task 2 and run its Astra review" completed (exit code 0)</summary> </task-notification>
<task-notification> <task-id>a22c01ff96affa652</task-id> <tool-use-id>toolu_0185YfJjM55CX3sN1QnrkDk7</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ba9fa944-a429-4788-9b3c-f2b2f42617f3/tasks/a22c01ff96affa652.output</output-file> <status>completed</status> <summary>Agent "#471 Task 1: box half" 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. The concerns are notes for later tasks; none blocks this one. **Commit:** `13985af5` on design-tunnel-websockets-471, not pushed. **Tests:** all 15 tunnelclient tests pass, including under `-race -count=30`. The edge run (`TestTunnel|TestFleet|TestReqRecords|TestGuard`), the host tunnel tests, the root `TestFleetAppServesThroughTheHub`, build, vet, gofmt and the darwin/windows/arm64 cross-builds are all clean. All six mutations failed the tests they should, including the required one: dropping the `UpgradedHeader` delete makes `TestShimStripsAnAppSetUpgradedMarker` fail. **Concerns:** 1. **Brief deviation (frame-order test).** In x/net v0.60.0, the brief's order ("send preface and SETTINGS, then read") is racy: a SETTINGS ACK can arrive between the server's SETTINGS and its WINDOW_UPDATE, and it did intermittently. `readAdvertised` now sends the preface, reads the two frames, then sends SETTINGS. The order is deterministic with no sleeps, and the assertions are the ones the brief asks for. 2. **Census.** The card shows the `internal/tunnelclient` envelope re-pinned and one `new` unit, `upgradedConn.Read`, marked "reads +file:Read". That mark is the scanner matching the method name; the method reads the stream body, not a file. `Dial`, `Serve` and `markedHandler.ServeHTTP` have no census row because they read nothing. I added a paragraph to spec §7 saying both things, in the same commit. No overlay yet; that is Task 9. 3. **A blocked write can delay the handler's return.** The hijacked conn has a fence so nothing writes to the stream after the handler returns. Without it, x/net panics, and a test now covers that. But a write stuck because the hub isn't accepting data holds the handler until the hub resets the stream. Task 2 must keep the hub resetting the stream on `Close`. 4. **Notes for later tasks:** - The box conn has no `CloseWrite`, so when the app closes, the stream simply ends. - The rebuilt request still says `HTTP/2.0`; the Task 6 witness should confirm that works end to end. - The §4.8 invariant test should read the limits from `DefaultLimits`, not from separate constants. The full report (RED/GREEN, the mutation table, callers, census card) is in `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-tunnel-websockets-471/.superpowers/sdd/2026-10-30-tunnel-websockets/task-1-report.md`.</result> <usage><subagent_tokens>146338</subagent_tokens><tool_uses>40</tool_uses><duration_ms>1118688</duration_ms></usage> </task-notification>
Attributed to this commit: 19.7 g CO₂e (2,619,835 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on rootfs-apps-6-interactive, 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/interactive/frames.go b/internal/interactive/frames.go| index 68a850652..4c38fb6b4 100644 |
| --- a/internal/interactive/frames.go |
| +++ b/internal/interactive/frames.go |
| @@ -1,13 +1,19 @@ |
| package interactive |
| import ( |
| + "bufio" |
| + "bytes" |
| "context" |
| "crypto/tls" |
| "encoding/binary" |
| "encoding/json" |
| "errors" |
| + "fmt" |
| + "io" |
| + "net" |
| "net/http" |
| "slices" |
| + "time" |
| "golang.org/x/net/websocket" |
| ) |
| @@ -58,33 +64,96 @@ func SendJSON(ws *websocket.Conn, kind byte, v any) error { |
| return Send(ws, kind, b) |
| } |
| -// binaryOnly is websocket.Message's receive with the payload type kept: it |
| -// takes a binary message into a []byte and refuses a text one (and a |
| -// continuation, which no sender here writes) with ErrBadFrame. |
| -var binaryOnly = websocket.Codec{ |
| - Marshal: nil, // Receive only |
| - Unmarshal: func(data []byte, payloadType byte, v any) error { |
| - if payloadType != websocket.BinaryFrame { |
| - return ErrBadFrame |
| +// Receive reads one frame: exactly one complete WebSocket message, one |
| +// unfragmented binary frame, whose first byte is the kind. |
| +// |
| +// It reads at the frame level, through x/net's own frame reader, because |
| +// x/net's message codecs neither check the FIN bit (a fragmented message |
| +// would surface as several messages, each bounded alone) nor check that a |
| +// payload arrived whole (a frame cut short would read as a short success). |
| +// So: |
| +// - a frame without FIN, a continuation, a text frame, a frame with a |
| +// reserved bit set and an empty frame are ErrBadFrame; |
| +// - a frame over the connection's MaxPayloadBytes (set by Dial, |
| +// DialFrame and NewServer) is websocket.ErrFrameTooLarge, before any of |
| +// its payload is read; |
| +// - a payload that ends before its declared length is an error wrapping |
| +// io.ErrUnexpectedEOF; |
| +// - pings are answered and pongs skipped, and a close is io.EOF, as x/net |
| +// does. |
| +// |
| +// After any error the connection is done: the caller closes it. Receive is |
| +// the connection's only reader; it must not be mixed with ws.Read or a |
| +// websocket.Codec's Receive, and only one goroutine may call it at a time. |
| +func Receive(ws *websocket.Conn) (kind byte, payload []byte, err error) { |
| + for { |
| + fr, err := ws.NewFrameReader() |
| + if err != nil { |
| + return 0, nil, err |
| + } |
| + // The raw header, read before HandleFrame discards it and rewrites |
| + // a continuation's opcode to the message's. |
| + var hdr []byte |
| + if h := fr.HeaderReader(); h != nil { |
| + if hdr, err = io.ReadAll(h); err != nil { |
| + return 0, nil, err |
| + } |
| + } |
| + length, ok := declaredLength(hdr) |
| + if !ok { |
| + return 0, nil, ErrBadFrame |
| + } |
| + // HandleFrame enforces the masking rule for this end, answers a |
| + // ping, skips a pong and turns a close into io.EOF. |
| + f, err := ws.HandleFrame(fr) |
| + if err != nil { |
| + return 0, nil, err |
| + } |
| + if f == nil { |
| + continue |
| + } |
| + fin, rsv, op := hdr[0]&0x80 != 0, hdr[0]&0x70, hdr[0]&0x0f |
| + if !fin || rsv != 0 || op != websocket.BinaryFrame || length == 0 { |
| + return 0, nil, ErrBadFrame |
| + } |
| + limit := ws.MaxPayloadBytes |
| + if limit == 0 { |
| + limit = websocket.DefaultMaxPayloadBytes |
| + } |
| + if length > int64(limit) { |
| + return 0, nil, websocket.ErrFrameTooLarge |
| + } |
| + msg := make([]byte, length) |
| + if _, err := io.ReadFull(f, msg); err != nil { |
| + if err == io.EOF { |
| + err = io.ErrUnexpectedEOF |
| + } |
| + return 0, nil, fmt.Errorf("interactive: frame cut short: %w", err) |
| } |
| - *(v.(*[]byte)) = data |
| - return nil |
| - }, |
| + return msg[0], msg[1:], nil |
| + } |
| } |
| -// Receive reads one frame. The bound is the connection's MaxPayloadBytes |
| -// (set by Dial, DialFrame and NewServer): a larger frame is |
| -// websocket.ErrFrameTooLarge. An empty message or a text message is |
| -// ErrBadFrame. |
| -func Receive(ws *websocket.Conn) (kind byte, payload []byte, err error) { |
| - var msg []byte |
| - if err := binaryOnly.Receive(ws, &msg); err != nil { |
| - return 0, nil, err |
| +// declaredLength reads the payload length from a raw frame header (RFC 6455 |
| +// §5.2): 7 bits, or 16 or 63 bits after the markers 126 and 127. |
| +func declaredLength(hdr []byte) (int64, bool) { |
| + if len(hdr) < 2 { |
| + return 0, false |
| } |
| - if len(msg) == 0 { |
| - return 0, nil, ErrBadFrame |
| + switch n := hdr[1] & 0x7f; n { |
| + case 126: |
| + if len(hdr) < 4 { |
| + return 0, false |
| + } |
| + return int64(binary.BigEndian.Uint16(hdr[2:4])), true |
| + case 127: |
| + if len(hdr) < 10 { |
| + return 0, false |
| + } |
| + return int64(binary.BigEndian.Uint64(hdr[2:10]) &^ (1 << 63)), true |
| + default: |
| + return int64(n), true |
| } |
| - return msg[0], msg[1:], nil |
| } |
| // ResizePayload is a KindResize payload: cols then rows, each a big-endian |
| @@ -136,10 +205,19 @@ func Dial(ctx context.Context, url, origin string, header http.Header) (*websock |
| return DialFrame(ctx, url, origin, header, MaxFrame) |
| } |
| +// ErrNoSubprotocol is DialFrame's refusal of a server that did not answer |
| +// with exactly Subprotocol. |
| +var ErrNoSubprotocol = errors.New("interactive: the server did not choose " + Subprotocol) |
| + |
| // DialFrame opens a connection to url (ws or wss) offering Subprotocol, |
| // with header sent on the upgrade request, receiving frames of at most |
| // maxFrame bytes. TLS offers only http/1.1, since the upgrade is an |
| // HTTP/1.1 request. |
| +// |
| +// x/net's client accepts a response that names no subprotocol at all, so |
| +// DialFrame keeps the handshake response's bytes and refuses |
| +// (ErrNoSubprotocol) unless it carries exactly one Sec-WebSocket-Protocol |
| +// of Subprotocol. |
| func DialFrame(ctx context.Context, url, origin string, header http.Header, maxFrame int) (*websocket.Conn, error) { |
| cfg, err := websocket.NewConfig(url, origin) |
| if err != nil { |
| @@ -150,10 +228,87 @@ func DialFrame(ctx context.Context, url, origin string, header http.Header, maxF |
| } |
| cfg.Protocol = []string{Subprotocol} |
| cfg.TlsConfig = &tls.Config{NextProtos: []string{"http/1.1"}} |
| - ws, err := cfg.DialContext(ctx) |
| + |
| + raw, err := dialTransport(ctx, cfg) |
| if err != nil { |
| return nil, err |
| } |
| + rec := &handshakeRecorder{Conn: raw} |
| + if dl, ok := ctx.Deadline(); ok { |
| + _ = raw.SetDeadline(dl) |
| + } |
| + stop := context.AfterFunc(ctx, func() { _ = raw.SetDeadline(time.Unix(1, 0)) }) |
| + ws, err := websocket.NewClient(cfg, rec) |
| + if !stop() { |
| + raw.Close() |
| + return nil, ctx.Err() |
| + } |
| + if err == nil { |
| + err = raw.SetDeadline(time.Time{}) |
| + } |
| + rec.stopped = true |
| + if err == nil { |
| + err = negotiated(rec.buf.Bytes()) |
| + } |
| + if err != nil { |
| + raw.Close() |
| + return nil, err |
| + } |
| ws.MaxPayloadBytes = maxFrame |
| return ws, nil |
| } |
| + |
| +// dialTransport opens the TCP or TLS connection cfg.Location names, as |
| +// x/net's own dial does. |
| +func dialTransport(ctx context.Context, cfg *websocket.Config) (net.Conn, error) { |
| + u := cfg.Location |
| + port := u.Port() |
| + switch { |
| + case port != "": |
| + case u.Scheme == "ws": |
| + port = "80" |
| + case u.Scheme == "wss": |
| + port = "443" |
| + } |
| + addr := net.JoinHostPort(u.Hostname(), port) |
| + d := &net.Dialer{} |
| + switch u.Scheme { |
| + case "ws": |
| + return d.DialContext(ctx, "tcp", addr) |
| + case "wss": |
| + return (&tls.Dialer{NetDialer: d, Config: cfg.TlsConfig}).DialContext(ctx, "tcp", addr) |
| + } |
| + return nil, websocket.ErrBadScheme |
| +} |
| + |
| +// maxHandshake bounds what handshakeRecorder keeps. |
| +const maxHandshake = 64 << 10 |
| + |
| +// handshakeRecorder keeps a copy of the bytes read until stopped, so |
| +// DialFrame can read the handshake response x/net does not return. It may |
| +// keep the start of the first frames too; negotiated reads only the |
| +// response's head. |
| +type handshakeRecorder struct { |
| + net.Conn |
| + buf bytes.Buffer |
| + stopped bool |
| +} |
| + |
| +func (r *handshakeRecorder) Read(p []byte) (int, error) { |
| + n, err := r.Conn.Read(p) |
| + if !r.stopped && r.buf.Len() < maxHandshake { |
| + r.buf.Write(p[:min(n, maxHandshake-r.buf.Len())]) |
| + } |
| + return n, err |
| +} |
| + |
| +func negotiated(resp []byte) error { |
| + r, err := http.ReadResponse(bufio.NewReader(bytes.NewReader(resp)), nil) |
| + if err != nil { |
| + return ErrNoSubprotocol |
| + } |
| + if got := r.Header.Values("Sec-WebSocket-Protocol"); len(got) != 1 || got[0] != Subprotocol { |
| + return ErrNoSubprotocol |
| + } |
| + return nil |
| +} |
diff --git a/internal/interactive/frames_test.go b/internal/interactive/frames_test.go| index ccda9e616..4bab1c415 100644 |
| --- a/internal/interactive/frames_test.go |
| +++ b/internal/interactive/frames_test.go |
| @@ -1,9 +1,15 @@ |
| package interactive |
| import ( |
| + "bufio" |
| "bytes" |
| "context" |
| + "crypto/sha1" |
| + "encoding/base64" |
| "errors" |
| + "fmt" |
| + "io" |
| + "net" |
| "net/http" |
| "net/http/httptest" |
| "testing" |
| @@ -16,9 +22,9 @@ import ( |
| const testOrigin = "http://127.0.0.1/" |
| -// echoServer serves NewServer at maxFrame, echoing every frame it receives |
| -// and sending websocket.ErrFrameTooLarge's text back as a KindEnd detail, |
| -// so a test can see the server refuse an oversized frame. |
| +// echoServer serves NewServer at maxFrame, echoing every frame it receives. |
| +// On a refused frame it sends a KindEnd naming the refusal and closes, as |
| +// every caller must: after any Receive error the connection is done. |
| func echoServer(t *testing.T, maxFrame int) *httptest.Server { |
| t.Helper() |
| srv := httptest.NewServer(NewServer(func(ws *websocket.Conn) { |
| @@ -33,10 +39,10 @@ func echoServer(t *testing.T, maxFrame int) *httptest.Server { |
| switch { |
| case errors.Is(err, websocket.ErrFrameTooLarge): |
| _ = SendJSON(ws, KindEnd, End{Reason: EndRefused, Detail: "too large"}) |
| - continue |
| + return |
| case errors.Is(err, ErrBadFrame): |
| _ = SendJSON(ws, KindEnd, End{Reason: EndRefused, Detail: "bad frame"}) |
| - continue |
| + return |
| case err != nil: |
| return |
| } |
| @@ -142,28 +148,32 @@ func TestFramesRoundTripAndRefuseOversize(t *testing.T) { |
| t.Fatalf("Send of MaxFrame bytes = %v, want ErrFrameTooBig", err) |
| } |
| + // The refused Send wrote nothing: the connection still echoes. |
| + if err := Send(ws, KindAlive, nil); err != nil { |
| + t.Fatal(err) |
| + } |
| + if kind, _, err := Receive(ws); err != nil || kind != KindAlive { |
| + t.Fatalf("after a refused Send: %q, %v", kind, err) |
| + } |
| + |
| // A text message and an empty binary message are not frames. |
| + ws = dialT(t, wsURL(t, srv), MaxFrame) |
| if err := websocket.Message.Send(ws, "d hello"); err != nil { |
| t.Fatal(err) |
| } |
| wantRefusal(t, ws, "bad frame") |
| + ws = dialT(t, wsURL(t, srv), MaxFrame) |
| if err := websocket.Message.Send(ws, []byte{}); err != nil { |
| t.Fatal(err) |
| } |
| wantRefusal(t, ws, "bad frame") |
| - // A sender that ignores the bound: the receiver at MaxFrame refuses it, |
| - // and the connection still carries the next frame. |
| + // A sender that ignores the bound: the receiver at MaxFrame refuses it. |
| + ws = dialT(t, wsURL(t, srv), MaxFrame) |
| if err := SendFrame(ws, KindData, make([]byte, MaxFrame), MaxFrame+1); err != nil { |
| t.Fatal(err) |
| } |
| wantRefusal(t, ws, "too large") |
| - if err := Send(ws, KindAlive, nil); err != nil { |
| - t.Fatal(err) |
| - } |
| - if kind, _, err := Receive(ws); err != nil || kind != KindAlive { |
| - t.Fatalf("after an oversized frame: %q, %v", kind, err) |
| - } |
| } |
| func TestReceiveRefusesTextOnTheClient(t *testing.T) { |
| @@ -284,3 +294,211 @@ func TestDialSendsHeaders(t *testing.T) { |
| t.Fatal("handler never ran") |
| } |
| } |
| + |
| +// rawServer answers the WebSocket upgrade by hand, naming protocol in |
| +// Sec-WebSocket-Protocol (none when it is ""), and then lets script write |
| +// raw frames to the client. The connection closes when script returns. |
| +func rawServer(t *testing.T, protocol string, script func(c net.Conn, w *bufio.Writer)) *httptest.Server { |
| + t.Helper() |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + sum := sha1.Sum([]byte(r.Header.Get("Sec-WebSocket-Key") + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11")) |
| + c, rw, err := w.(http.Hijacker).Hijack() |
| + if err != nil { |
| + return |
| + } |
| + defer c.Close() |
| + fmt.Fprintf(rw, "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: %s\r\n", |
| + base64.StdEncoding.EncodeToString(sum[:])) |
| + if protocol != "" { |
| + fmt.Fprintf(rw, "Sec-WebSocket-Protocol: %s\r\n", protocol) |
| + } |
| + rw.WriteString("\r\n") |
| + if rw.Flush() != nil { |
| + return |
| + } |
| + script(c, rw.Writer) |
| + })) |
| + t.Cleanup(srv.Close) |
| + return srv |
| +} |
| + |
| +// writeHold writes b and keeps the connection open until the client closes. |
| +func writeHold(b ...[]byte) func(net.Conn, *bufio.Writer) { |
| + return func(c net.Conn, w *bufio.Writer) { |
| + for _, p := range b { |
| + w.Write(p) |
| + } |
| + w.Flush() |
| + _, _ = io.Copy(io.Discard, c) |
| + } |
| +} |
| + |
| +// writeClose writes b and closes the connection. |
| +func writeClose(b ...[]byte) func(net.Conn, *bufio.Writer) { |
| + return func(c net.Conn, w *bufio.Writer) { |
| + for _, p := range b { |
| + w.Write(p) |
| + } |
| + w.Flush() |
| + } |
| +} |
| + |
| +func receiveFrom(t *testing.T, script func(net.Conn, *bufio.Writer)) (byte, []byte, error) { |
| + t.Helper() |
| + ws := dialT(t, wsURL(t, rawServer(t, Subprotocol, script)), MaxFrame) |
| + return Receive(ws) |
| +} |
| + |
| +// Unmasked server-to-client frames: FIN|opcode, then a 7-bit length. |
| +const ( |
| + finBinary = 0x80 | websocket.BinaryFrame |
| + finText = 0x80 | websocket.TextFrame |
| + finCont = 0x80 | websocket.ContinuationFrame |
| + finPing = 0x80 | websocket.PingFrame |
| + noFinBinary = websocket.BinaryFrame |
| +) |
| + |
| +func TestReceiveRefusesFragments(t *testing.T) { |
| + // A whole binary frame is one message. |
| + kind, payload, err := receiveFrom(t, writeHold([]byte{finBinary, 2, 'd', 'C'})) |
| + if err != nil || kind != KindData || string(payload) != "C" { |
| + t.Fatalf("whole frame: %q, %q, %v", kind, payload, err) |
| + } |
| + // So is one after a ping, which the reader answers and skips. |
| + kind, payload, err = receiveFrom(t, writeHold([]byte{finPing, 1, 'p'}, []byte{finBinary, 2, 'd', 'C'})) |
| + if err != nil || kind != KindData || string(payload) != "C" { |
| + t.Fatalf("after a ping: %q, %q, %v", kind, payload, err) |
| + } |
| + |
| + for name, wire := range map[string][][]byte{ |
| + // "dA" + "dB" is one message, "dAdB"; it must never surface as |
| + // a data frame "A". |
| + "fragmented binary": {{noFinBinary, 2, 'd', 'A'}, {finCont, 2, 'd', 'B'}}, |
| + "fragmented, whole frame after": {{noFinBinary, 2, 'd', 'A'}, {finCont, 2, 'd', 'B'}, |
| + {finBinary, 2, 'd', 'C'}}, |
| + "lone continuation": {{finCont, 2, 'd', 'B'}}, |
| + "text": {{finText, 2, 'd', 'T'}}, |
| + "reserved bit": {{finBinary | 0x40, 2, 'd', 'R'}}, |
| + "empty": {{finBinary, 0}}, |
| + } { |
| + kind, payload, err := receiveFrom(t, writeHold(wire...)) |
| + if !errors.Is(err, ErrBadFrame) { |
| + t.Errorf("%s: Receive = %q, %q, %v; want ErrBadFrame", name, kind, payload, err) |
| + } |
| + } |
| +} |
| + |
| +func TestReceiveRefusesTruncatedFrames(t *testing.T) { |
| + for name, wire := range map[string][]byte{ |
| + "payload cut": {finBinary, 3, 'd', 'A'}, |
| + "no payload": {finBinary, 3}, |
| + "64-bit len, cut": {finBinary, 127, 0, 0, 0, 0, 0, 0, 0x01, 0x00, 'd'}, |
| + } { |
| + kind, payload, err := receiveFrom(t, writeClose(wire)) |
| + if !errors.Is(err, io.ErrUnexpectedEOF) { |
| + t.Errorf("%s: Receive = %q, %q, %v; want io.ErrUnexpectedEOF", name, kind, payload, err) |
| + } |
| + } |
| + for name, wire := range map[string][]byte{ |
| + "length cut": {finBinary, 126, 0x01}, |
| + "header cut": {finBinary}, |
| + } { |
| + kind, payload, err := receiveFrom(t, writeClose(wire)) |
| + if err == nil { |
| + t.Errorf("%s: Receive = %q, %q, nil; want an error", name, kind, payload) |
| + } |
| + } |
| + |
| + // A whole frame split across many transport writes is read whole. |
| + kind, payload, err := receiveFrom(t, func(c net.Conn, w *bufio.Writer) { |
| + for _, b := range []byte{finBinary, 4, 'd', 'A', 'B', 'C'} { |
| + w.WriteByte(b) |
| + w.Flush() |
| + time.Sleep(5 * time.Millisecond) |
| + } |
| + _, _ = io.Copy(io.Discard, c) |
| + }) |
| + if err != nil || kind != KindData || string(payload) != "ABC" { |
| + t.Fatalf("split frame: %q, %q, %v", kind, payload, err) |
| + } |
| + // And a 16-bit length frame cut short is refused, not shortened. |
| + long := append([]byte{finBinary, 126, 0x01, 0x00, 'd'}, bytes.Repeat([]byte{'z'}, 100)...) |
| + if kind, payload, err := receiveFrom(t, writeClose(long)); !errors.Is(err, io.ErrUnexpectedEOF) { |
| + t.Errorf("long frame cut: %q, %d bytes, %v; want io.ErrUnexpectedEOF", kind, len(payload), err) |
| + } |
| +} |
| + |
| +// rawClient upgrades a plain TCP connection to srv by hand and returns it, |
| +// so a test can write masked client frames byte by byte. |
| +func rawClient(t *testing.T, srv *httptest.Server) (net.Conn, *bufio.Reader) { |
| + t.Helper() |
| + c, err := net.Dial("tcp", srv.Listener.Addr().String()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { c.Close() }) |
| + _ = c.SetDeadline(time.Now().Add(10 * time.Second)) |
| + fmt.Fprintf(c, "GET /x HTTP/1.1\r\nHost: %s\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n"+ |
| + "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 13\r\n"+ |
| + "Sec-WebSocket-Protocol: %s\r\nOrigin: %s\r\n\r\n", srv.Listener.Addr(), Subprotocol, testOrigin) |
| + br := bufio.NewReader(c) |
| + resp, err := http.ReadResponse(br, nil) |
| + if err != nil || resp.StatusCode != http.StatusSwitchingProtocols { |
| + t.Fatalf("upgrade: %v, %v", resp, err) |
| + } |
| + return c, br |
| +} |
| + |
| +// masked is a client frame of one byte of flags and opcode and a short |
| +// payload, masked with the all-zero key (so the payload is sent as is). |
| +func masked(b0 byte, payload string) []byte { |
| + return append([]byte{b0, 0x80 | byte(len(payload)), 0, 0, 0, 0}, payload...) |
| +} |
| + |
| +// The console door reads client frames: the same rules hold there. |
| +func TestServerReceiveRefusesFragments(t *testing.T) { |
| + srv := echoServer(t, MaxFrame) |
| + readEnd := func(br *bufio.Reader) string { |
| + t.Helper() |
| + var hdr [2]byte |
| + if _, err := io.ReadFull(br, hdr[:]); err != nil { |
| + t.Fatal(err) |
| + } |
| + p := make([]byte, hdr[1]&0x7f) |
| + if _, err := io.ReadFull(br, p); err != nil { |
| + t.Fatal(err) |
| + } |
| + return string(p) |
| + } |
| + |
| + c, br := rawClient(t, srv) |
| + c.Write(masked(finBinary, "dW")) |
| + if got := readEnd(br); got != "dW" { |
| + t.Fatalf("whole masked frame echoed as %q", got) |
| + } |
| + |
| + c, br = rawClient(t, srv) |
| + c.Write(masked(noFinBinary, "dA")) |
| + c.Write(masked(finCont, "dB")) |
| + if got := readEnd(br); !bytes.Contains([]byte(got), []byte("bad frame")) { |
| + t.Fatalf("fragmented message: server answered %q, want a bad frame refusal", got) |
| + } |
| +} |
| + |
| +func TestDialRequiresTheNegotiatedSubprotocol(t *testing.T) { |
| + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| + defer cancel() |
| + for _, answered := range []string{"", "x", Subprotocol + ", x"} { |
| + srv := rawServer(t, answered, writeHold()) |
| + if ws, err := Dial(ctx, wsURL(t, srv), testOrigin, nil); err == nil { |
| + ws.Close() |
| + t.Errorf("server answering %q: Dial succeeded", answered) |
| + } |
| + } |
| + srv := rawServer(t, Subprotocol, writeHold()) |
| + ws, err := Dial(ctx, wsURL(t, srv), testOrigin, nil) |
| + if err != nil { |
| + t.Fatalf("server answering %q: %v", Subprotocol, err) |
| + } |
| + ws.Close() |
| +} |