package callstest import ( "encoding/json" "net/http" "strings" "testing" "time" ) // signalJSON marshals body into the JSON string client.signal expects. // body must not carry "peer": client.signal always injects that itself // from the peer argument, the way every other test in this package // calls it with a literal string. This helper only exists because a // handful of chat/share cases below need dynamic values (a repeated // string, a peer id inlined as "to") that a literal template would make // unreadable. // // It normalises through a map (json.Marshal, then json.Unmarshal inside // client.signal itself), so it can only ever produce one well-formed // JSON object with each key once — it cannot express a duplicated key // or a raw, unescaped byte sequence. A case that needs either of those // byte-level shapes goes through client.signalRaw instead, which posts // its string argument verbatim. func signalJSON(t *testing.T, body map[string]any) string { t.Helper() b, err := json.Marshal(body) if err != nil { t.Fatal(err) } return string(b) } // Spec §4.3's fan-out: chat reaches every other admitted peer, never // the sender, and the envelope names the sender's peer id and display // name — never anything the sender's own request claimed. func TestChatReachesTheOtherAdmittedPeerWithTheSendersNameAndNotTheSender(t *testing.T) { x, sqid, _ := memberWithMeeting(t) a := x.browser(t) a.signIn("paul@example.com") sa := a.stream("/m/" + sqid + "/stream") defer sa.close() pa, _ := sa.hello() a.signal(sqid, pa, `{"type":"join"}`) sa.nextOf("roster", 2*time.Second) b := newMemberBrowser(t, x, "paul@rslw.com") sb := b.stream("/m/" + sqid + "/stream") defer sb.close() pb, _ := sb.hello() b.signal(sqid, pb, `{"type":"join"}`) sb.nextOf("roster", 2*time.Second) sa.nextOf("peer", 2*time.Second) res, _ := a.signal(sqid, pa, signalJSON(t, map[string]any{"type": "chat", "payload": map[string]any{"text": "hello there"}})) if res.StatusCode != http.StatusOK { t.Fatalf("chat: %d", res.StatusCode) } ev, data, ok := sb.nextOf("chat", 2*time.Second) if !ok || ev != "chat" { t.Fatal("Bob did not receive the chat") } s := string(data) if !strings.Contains(s, `"from":"`+pa+`"`) || !strings.Contains(s, `"name":"paul"`) || !strings.Contains(s, `"text":"hello there"`) || strings.Contains(s, `"seq"`) || strings.Contains(s, `"to"`) { t.Fatalf("envelope %s", s) } if ev, _, ok := sa.next(300 * time.Millisecond); ok && ev == "chat" { t.Fatal("the sender received its own chat") } } // Spec §2.5 and §4.3: a waiting guest is not admitted, so fan-out never // reaches it, and its own signal is the usual "a meeting that is not // yours does not exist" 404 — never a 403, whatever it tries to send. // A positive control closes the test: the same guest, once admitted, // does receive a chat — proof the silence above was the guest's // standing, not a stream that never delivers anything. // // ice_test.go's guestJoinedAndWaiting builds the identical waiting // guest but returns only (*client, peer): its own stream is registered // for t.Cleanup and never handed back. This test needs to read from // that stream directly (to prove the guest receives nothing, and later // that it does), so the same three steps — join link, sign in, open // stream, join — are inlined here instead of reusing that helper. func TestChatNeverReachesAWaitingGuestAndAWaitingGuestCannotSend(t *testing.T) { x, sqid, tok := memberWithMeeting(t) enableWaitingRoom(t, x, sqid) a := x.browser(t) a.signIn("paul@example.com") sa := a.stream("/m/" + sqid + "/stream") defer sa.close() pa, _ := sa.hello() a.signal(sqid, pa, `{"type":"join"}`) sa.nextOf("roster", 2*time.Second) g := x.browser(t) g.get("/j/" + tok) g.signIn("waiting-guest@example.com") gs := g.stream("/m/" + sqid + "/stream") defer gs.close() gpeer, _ := gs.hello() if resp, b := g.signal(sqid, gpeer, `{"type":"join"}`); resp.StatusCode != http.StatusOK { t.Fatalf("guest join (the knock): %d %s", resp.StatusCode, b) } sa.nextOf("knock", 2*time.Second) a.signal(sqid, pa, signalJSON(t, map[string]any{"type": "chat", "payload": map[string]any{"text": "secret"}})) if ev, data, ok := gs.next(500 * time.Millisecond); ok && (ev == "chat" || strings.Contains(string(data), "secret")) { t.Fatalf("a waiting guest received %s %s", ev, data) } res, body := g.signal(sqid, gpeer, signalJSON(t, map[string]any{"type": "chat", "payload": map[string]any{"text": "let me in"}})) if res.StatusCode != http.StatusNotFound || !strings.Contains(string(body), `"error":"not-found"`) { t.Fatalf("a waiting guest's chat must be the usual 404: %d %s", res.StatusCode, body) } if resp, b := a.signal(sqid, pa, `{"type":"admit","payload":{"peer":"`+gpeer+`"}}`); resp.StatusCode != http.StatusOK { t.Fatalf("admit: %d %s", resp.StatusCode, b) } if ev, _, ok := gs.nextOf("roster", 2*time.Second); !ok { t.Fatalf("the newly admitted guest never saw its own roster (got %q)", ev) } res, _ = a.signal(sqid, pa, signalJSON(t, map[string]any{"type": "chat", "payload": map[string]any{"text": "welcome"}})) if res.StatusCode != http.StatusOK { t.Fatalf("chat after admit: %d", res.StatusCode) } ev, data, ok := gs.nextOf("chat", 2*time.Second) if !ok || ev != "chat" || !strings.Contains(string(data), `"text":"welcome"`) { t.Fatalf("the now-admitted guest did not receive the chat: %q ok=%v %s", ev, ok, data) } } // Spec §4.4: chat text is capped at 2048 bytes, counted in bytes, not // characters; anything not exactly {text: string} (chat) or {on: bool} // (share), including a chat carrying "to", is the usual 400. func TestChatLimitsAndShapes(t *testing.T) { x, sqid, _ := memberWithMeeting(t) a := x.browser(t) a.signIn("paul@example.com") sa := a.stream("/m/" + sqid + "/stream") defer sa.close() pa, _ := sa.hello() a.signal(sqid, pa, `{"type":"join"}`) sa.nextOf("roster", 2*time.Second) cases := []struct { name string body map[string]any status int }{ {"2048 bytes ok", map[string]any{"type": "chat", "payload": map[string]any{"text": strings.Repeat("a", 2048)}}, http.StatusOK}, {"2049 bytes too large", map[string]any{"type": "chat", "payload": map[string]any{"text": strings.Repeat("a", 2049)}}, http.StatusRequestEntityTooLarge}, {"multibyte counted in bytes", map[string]any{"type": "chat", "payload": map[string]any{"text": strings.Repeat("é", 1025)}}, http.StatusRequestEntityTooLarge}, {"text not a string", map[string]any{"type": "chat", "payload": map[string]any{"text": 5}}, http.StatusBadRequest}, {"extra key", map[string]any{"type": "chat", "payload": map[string]any{"text": "x", "html": ""}}, http.StatusBadRequest}, {"empty text", map[string]any{"type": "chat", "payload": map[string]any{"text": ""}}, http.StatusBadRequest}, {"share on", map[string]any{"type": "share", "payload": map[string]any{"on": true}}, http.StatusOK}, {"share off", map[string]any{"type": "share", "payload": map[string]any{"on": false}}, http.StatusOK}, {"share not a bool", map[string]any{"type": "share", "payload": map[string]any{"on": "yes"}}, http.StatusBadRequest}, {"chat with a target", map[string]any{"type": "chat", "to": pa, "payload": map[string]any{"text": "x"}}, http.StatusBadRequest}, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { res, body := a.signal(sqid, pa, signalJSON(t, c.body)) if res.StatusCode != c.status { t.Fatalf("%s: %d, want %d", c.name, res.StatusCode, c.status) } switch c.status { case http.StatusRequestEntityTooLarge: if !strings.Contains(string(body), `"error":"too-large"`) { t.Fatalf("%s: body %s, want error=too-large", c.name, body) } case http.StatusBadRequest: if !strings.Contains(string(body), `"error":"bad-request"`) { t.Fatalf("%s: body %s, want error=bad-request", c.name, body) } } }) } } // Review fix round 1, item 1 (HIGH): the dispatch in signal.go hands // hub.Fanout the payload's raw bytes verbatim — never a re-encoding of // what validateFanout decoded — so validateFanout must judge those same // raw bytes, not just the decoded text's length. Each case here needs a // shape signalJSON cannot express (a duplicated JSON key, or a literal // invalid byte), so all five go through client.signalRaw, which posts // its string argument verbatim and, unlike client.signal, does not // inject "peer" itself. func TestChatRawPayloadSizeAndUTF8(t *testing.T) { x, sqid, _ := memberWithMeeting(t) a := x.browser(t) a.signIn("paul@example.com") sa := a.stream("/m/" + sqid + "/stream") defer sa.close() pa, _ := sa.hello() a.signal(sqid, pa, `{"type":"join"}`) sa.nextOf("roster", 2*time.Second) t.Run("4096-byte duplicated text key", func(t *testing.T) { // encoding/json keeps only the last value of a duplicated key — // this decodes to a one-byte "x" — but the raw payload handed to // Fanout still carries all 4096+ bytes of the first value. body := `{"peer":"` + pa + `","type":"chat","payload":{"text":"` + strings.Repeat("a", 4096) + `","text":"x"}}` res, respBody := a.signalRaw(sqid, body) if res.StatusCode != http.StatusRequestEntityTooLarge || !strings.Contains(string(respBody), `"error":"too-large"`) { t.Fatalf("duplicated text key: %d %s", res.StatusCode, respBody) } }) t.Run("5000 duplicated on keys", func(t *testing.T) { var b strings.Builder b.WriteByte('{') for i := 0; i < 5000; i++ { if i > 0 { b.WriteByte(',') } b.WriteString(`"on":true`) } b.WriteByte('}') body := `{"peer":"` + pa + `","type":"share","payload":` + b.String() + `}` res, respBody := a.signalRaw(sqid, body) if res.StatusCode != http.StatusRequestEntityTooLarge || !strings.Contains(string(respBody), `"error":"too-large"`) { t.Fatalf("duplicated on keys: %d %s", res.StatusCode, respBody) } }) t.Run("2048 backslash-u escapes", func(t *testing.T) { // Each A escape decodes to one ASCII byte ("A"), so the // decoded text is exactly 2048 bytes — at the cap, not over it — // while the raw escapes are six times that on the wire. text := strings.Repeat(`\u0041`, 2048) body := `{"peer":"` + pa + `","type":"chat","payload":{"text":"` + text + `"}}` res, respBody := a.signalRaw(sqid, body) if res.StatusCode != http.StatusRequestEntityTooLarge || !strings.Contains(string(respBody), `"error":"too-large"`) { t.Fatalf("escaped text: %d %s", res.StatusCode, respBody) } }) t.Run("2048-byte multibyte text is still accepted", func(t *testing.T) { // "é" is two raw UTF-8 bytes, unescaped: 1024 of them is exactly // 2048 bytes both raw and decoded — legitimate multibyte content // at the cap must not be caught by the new raw-size guard. text := strings.Repeat("é", 1024) body := `{"peer":"` + pa + `","type":"chat","payload":{"text":"` + text + `"}}` res, respBody := a.signalRaw(sqid, body) if res.StatusCode != http.StatusOK { t.Fatalf("multibyte text at the cap: %d %s", res.StatusCode, respBody) } }) t.Run("invalid UTF-8 is refused", func(t *testing.T) { body := `{"peer":"` + pa + `","type":"chat","payload":{"text":"bad` + "\xff" + `byte"}}` res, respBody := a.signalRaw(sqid, body) if res.StatusCode != http.StatusBadRequest || !strings.Contains(string(respBody), `"error":"bad-request"`) { t.Fatalf("invalid UTF-8: %d %s", res.StatusCode, respBody) } }) } // chatCap is spec §4.4's 2 KB, retyped here because callstest is an // external test package and cannot read meet's own constant. The tests // below fail loudly if the two ever disagree: 2048 + 32 is the raw cap // they post either side of. const chatCap = 2048 // chatPair opens a meeting with two admitted members and hands back the // sender (browser, room, peer) and the other member's stream, which is // where every assertion about what actually went out on the wire is // made. The four tests below need exactly this and nothing else from // the dance that builds it. func chatPair(t *testing.T) (*client, string, string, *sseReader) { t.Helper() x, sqid, _ := memberWithMeeting(t) a := x.browser(t) a.signIn("paul@example.com") sa := a.stream("/m/" + sqid + "/stream") t.Cleanup(sa.close) pa, _ := sa.hello() a.signal(sqid, pa, `{"type":"join"}`) sa.nextOf("roster", 2*time.Second) b := newMemberBrowser(t, x, "paul@rslw.com") sb := b.stream("/m/" + sqid + "/stream") t.Cleanup(sb.close) pb, _ := sb.hello() b.signal(sqid, pb, `{"type":"join"}`) sb.nextOf("roster", 2*time.Second) sa.nextOf("peer", 2*time.Second) return a, sqid, pa, sb } // Codex S4-1: encoding/json matches an object's keys to struct fields // case-insensitively, and DisallowUnknownFields does not change that. // {"text":"<2049 a>","Text":"x"} therefore validated the *last* match — // a one-byte text — while the raw bytes handed to Fanout carried both // keys, and every recipient reads the lowercase one: 2049 bytes // delivered through a 2048-byte cap, inside a raw payload small enough // to clear the +32 guard. So the keys are judged byte-exactly and // counted now, before any value is looked at. func TestChatKeysAreExactCaseSensitiveAndUnique(t *testing.T) { a, sqid, pa, _ := chatPair(t) cases := []struct { name string typ string payload string }{ {"a mixed-case second key smuggles the value past the cap", "chat", `{"text":"` + strings.Repeat("a", chatCap+1) + `","Text":"x"}`}, {"a capitalised key alone is not text", "chat", `{"Text":"hello"}`}, {"a shouted key alone is not text", "chat", `{"TEXT":"hello"}`}, {"a duplicated key below the raw cap", "chat", `{"text":"` + strings.Repeat("a", 64) + `","text":"x"}`}, {"a capitalised on is not on", "share", `{"On":true}`}, {"a duplicated on below the raw cap", "share", `{"on":true,"on":false}`}, {"a second key beside on", "share", `{"on":true,"off":false}`}, {"an empty payload object", "chat", `{}`}, {"a payload that is not an object", "chat", `"text"`}, {"trailing content after the object", "chat", `{"text":"x"} {}`}, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { body := `{"peer":"` + pa + `","type":"` + c.typ + `","payload":` + c.payload + `}` res, respBody := a.signalRaw(sqid, body) if res.StatusCode != http.StatusBadRequest || !strings.Contains(string(respBody), `"error":"bad-request"`) { t.Fatalf("%s: %d %s, want 400 bad-request", c.name, res.StatusCode, respBody) } }) } } // Codex S4-2, and the other half of S4-1: what reaches a recipient is // the *validated* payload, re-encoded from the value that was checked, // and never whatever byte sequence the sender chose to spell it with. // So an escape is delivered decoded, an angle bracket is delivered as // itself (writeEvent no longer HTML-escapes — SSE data is not HTML), // and the payload on the wire is byte-for-byte the canonical form. func TestChatDeliversTheCanonicalValidatedPayload(t *testing.T) { a, sqid, pa, sb := chatPair(t) cases := []struct { name string typ string sent string want string }{ {"angle brackets and ampersands go out as themselves", "chat", `{"text":"ac&d"}`, `"payload":{"text":"ac&d"}`}, // Codex S4-11: every case here used to be its own answer — a // canonical payload in and the same bytes out, which an // implementation that forwarded the request's raw bytes would // have passed just as well. The two escape cases are the ones // that cannot: they can only come out this way if the payload // was rebuilt from the value that was validated. Verified by // putting the raw bytes back on the wire, where these two fail // and nothing else does. (Whitespace is not a discriminator — // the SSE encoder compacts a RawMessage on its way out — but // the shape is worth pinning anyway.) The backslashes are real: // a Go raw string sends the six characters \u0041, not the // letter A. {"an escape really is delivered decoded", "chat", `{"text":"\u0041\u003c"}`, `"payload":{"text":"A<"}`}, {"a tab escape survives as the escape JSON gives it", "chat", `{"text":"a\u0009b"}`, `"payload":{"text":"a\tb"}`}, {"whitespace inside the payload is not the payload", "chat", `{ "text" : "spaced" }`, `"payload":{"text":"spaced"}`}, {"an ordinary line is untouched", "chat", `{"text":"plain"}`, `"payload":{"text":"plain"}`}, // And the other fan-out type, which had no output coverage at // all: `on` is rebuilt from the bool, so the spelling a sender // chose for it never reaches anybody. {"share on is canonical too", "share", `{"on":true}`, `"payload":{"on":true}`}, {"share off is canonical too", "share", `{ "on" :false }`, `"payload":{"on":false}`}, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { body := `{"peer":"` + pa + `","type":"` + c.typ + `","payload":` + c.sent + `}` if res, respBody := a.signalRaw(sqid, body); res.StatusCode != http.StatusOK { t.Fatalf("%s: %d %s", c.name, res.StatusCode, respBody) } ev, data, ok := sb.nextOf(c.typ, 2*time.Second) if !ok || ev != c.typ { t.Fatalf("%s: no %s arrived (%q)", c.name, c.typ, ev) } if !strings.Contains(string(data), c.want) { t.Fatalf("%s: wire %s, want it to carry %s", c.name, data, c.want) } }) } } // Codex S4-2: json.Marshal HTML-escapes `<`, `>` and `&` even inside a // json.RawMessage, so a text of 2048 literal `<` — 2059 raw bytes, // comfortably inside the cap both checks enforce — left this process as // 12,299 payload bytes, six times what was validated. The cap is a // promise about what the fan-out puts on every other peer's stream, so // the fan-out is where it has to hold. func TestChatDoesNotExpandOnTheWire(t *testing.T) { a, sqid, pa, sb := chatPair(t) text := strings.Repeat("<", chatCap) body := `{"peer":"` + pa + `","type":"chat","payload":{"text":"` + text + `"}}` if res, respBody := a.signalRaw(sqid, body); res.StatusCode != http.StatusOK { t.Fatalf("2048 angle brackets: %d %s", res.StatusCode, respBody) } ev, data, ok := sb.nextOf("chat", 2*time.Second) if !ok || ev != "chat" { t.Fatalf("no chat arrived (%q)", ev) } if want := `{"text":"` + text + `"}`; !strings.Contains(string(data), want) { t.Fatalf("the payload on the wire is not the 2059 bytes that were validated (%d bytes of event data)", len(data)) } // The envelope's own fields — type, from, name — are the only thing // beyond the payload, and all three are bounded: a peer id, a // display name, and the field names around them. if len(data) > chatCap+32+256 { t.Fatalf("one chat event is %d bytes on the wire for a %d-byte text", len(data), len(text)) } } // The whole-branch review's W4-1: the panel counted 2048 UTF-8 bytes of // the text and the server counted 2080 raw JSON bytes of the payload, so // a 2048-byte draft with twenty-three quotes in it passed the panel and // came back 413 — a refusal nothing on the client could have foreseen. // Both sides count one thing now: the JSON-escaped length of the text, // which is exactly what the canonical payload puts on the wire. The raw // cap stays as the outer guard, refusing an oversized body before any of // this is reached. func TestChatCapCountsTheEscapedText(t *testing.T) { a, sqid, pa, _ := chatPair(t) cases := []struct { name string text string status int }{ {"a quote at the boundary", strings.Repeat("a", chatCap-2) + `\"`, http.StatusOK}, {"a quote one byte past it", strings.Repeat("a", chatCap-1) + `\"`, http.StatusRequestEntityTooLarge}, {"a newline at the boundary", strings.Repeat("a", chatCap-2) + `\n`, http.StatusOK}, {"a newline one byte past it", strings.Repeat("a", chatCap-1) + `\n`, http.StatusRequestEntityTooLarge}, {"a backslash one byte past it", strings.Repeat("a", chatCap-1) + `\\`, http.StatusRequestEntityTooLarge}, {"twenty-three quotes inside 2048 bytes of text", strings.Repeat("a", chatCap-23) + strings.Repeat(`\"`, 23), http.StatusRequestEntityTooLarge}, {"angle brackets cost one byte each, not six", strings.Repeat("<", chatCap), http.StatusOK}, // Codex S4-7: the two characters Go escapes even with // SetEscapeHTML(false), and JavaScript's JSON.stringify leaves // literal. Three bytes on the wire as themselves, six once Go // has written them, and the composer used to count the first // number while the server counted the second — so a draft the // panel accepted came back 413. Sent here as themselves, which // is how a paste arrives. {"a line separator at the boundary", strings.Repeat("a", chatCap-6) + "\u2028", http.StatusOK}, {"a line separator one byte past it", strings.Repeat("a", chatCap-5) + "\u2028", http.StatusRequestEntityTooLarge}, {"a paragraph separator at the boundary", strings.Repeat("a", chatCap-6) + "\u2029", http.StatusOK}, {"a paragraph separator one byte past it", strings.Repeat("a", chatCap-5) + "\u2029", http.StatusRequestEntityTooLarge}, {"the draft the composer used to accept", strings.Repeat("a", 2045) + "\u2028", http.StatusRequestEntityTooLarge}, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { body := `{"peer":"` + pa + `","type":"chat","payload":{"text":"` + c.text + `"}}` res, respBody := a.signalRaw(sqid, body) if res.StatusCode != c.status { t.Fatalf("%s: %d %s, want %d", c.name, res.StatusCode, respBody, c.status) } }) } } // The wire is line-oriented and the payload is a person's own text, so // the one thing a chat must never be able to do is end its own frame // and start another. It cannot: JSON escapes a newline inside a string // rather than emitting one, and that stays true of the canonical // re-encoding. This is the test that says so, and it is why disabling // HTML escaping on the way out is safe. func TestChatCannotForgeASecondSSEFrame(t *testing.T) { a, sqid, pa, sb := chatPair(t) body := `{"peer":"` + pa + `","type":"chat","payload":{"text":"one\n\nevent: roster\ndata: {\"peers\":[]}\n\ntwo"}}` if res, respBody := a.signalRaw(sqid, body); res.StatusCode != http.StatusOK { t.Fatalf("newlines in text: %d %s", res.StatusCode, respBody) } ev, data, ok := sb.nextOf("chat", 2*time.Second) if !ok || ev != "chat" { t.Fatalf("no chat arrived (%q)", ev) } if !strings.Contains(string(data), `\n\nevent: roster`) { t.Fatalf("the newlines did not survive as escapes: %s", data) } if ev, data, ok := sb.next(300 * time.Millisecond); ok { t.Fatalf("a second event came out of one chat: %q %s", ev, data) } }