package syncsocket import ( "context" "encoding/json" "fmt" "net/http" "net/http/httptest" "slices" "strings" "testing" "time" "github.com/coder/websocket" ) // TestSessionTimingMapsStayBounded checks that fresh client-chosen session IDs cannot grow the // per-session timing maps past maxSyncSessions. func TestSessionTimingMapsStayBounded(t *testing.T) { hub := NewHub() p := &peer{clientID: "client-1"} for i := 0; i < maxSyncSessions+100; i++ { hub.handleSyncUpdate(p, map[string]any{ "clientId": "client-1", "sessionId": fmt.Sprintf("session-%d", i), "paused": false, "playAt": "2026-10-19T10:00:00Z", "playAtLocalMs": float64(1), "capturedAtLocalMs": float64(1), }) } if n := len(hub.playAt); n > maxSyncSessions { t.Errorf("playAt holds %d sessions, want at most %d", n, maxSyncSessions) } if n := len(hub.playAtLocalMs); n > maxSyncSessions { t.Errorf("playAtLocalMs holds %d sessions, want at most %d", n, maxSyncSessions) } if n := len(hub.capturedAtMs); n > maxSyncSessions { t.Errorf("capturedAtMs holds %d sessions, want at most %d", n, maxSyncSessions) } } // TestHubRefusesPeersBeyondTheConnectionCap checks that the hub stops registering connections // once it holds maxSyncConnections peers. func TestHubRefusesPeersBeyondTheConnectionCap(t *testing.T) { hub := NewHub() for i := 0; i < maxSyncConnections; i++ { if !hub.add(&peer{}) { t.Fatalf("add refused peer %d, below the cap", i) } } if hub.add(&peer{}) { t.Fatal("add accepted a peer beyond maxSyncConnections") } } // TestWildcardOriginKeepsOriginVerification checks that CORS_ORIGIN "*" does not disable the // websocket origin check: only the request's own host is accepted. func TestWildcardOriginKeepsOriginVerification(t *testing.T) { req := httptest.NewRequest(http.MethodGet, "http://hub.example.com/ws", nil) options := websocketAcceptOptions(req, "*") if options.InsecureSkipVerify { t.Fatal("wildcard origin disabled origin verification") } if want := []string{"http://hub.example.com"}; !slices.Equal(options.OriginPatterns, want) { t.Fatalf("origin patterns = %v, want %v", options.OriginPatterns, want) } } // TestExplicitOriginIsAcceptedAlongsideTheRequestHost checks that a listed origin is accepted // without turning the check off. func TestExplicitOriginIsAcceptedAlongsideTheRequestHost(t *testing.T) { req := httptest.NewRequest(http.MethodGet, "https://hub.example.com/ws", nil) options := websocketAcceptOptions(req, "https://app.example.com/") if options.InsecureSkipVerify { t.Fatal("explicit origin disabled origin verification") } for _, want := range []string{"https://app.example.com", "https://hub.example.com"} { if !slices.Contains(options.OriginPatterns, want) { t.Errorf("origin patterns %v missing %q", options.OriginPatterns, want) } } } // TestClientListOmitsPeerAddressAndUserAgent checks that broadcast client entries carry no peer // IP address or user agent. func TestClientListOmitsPeerAddressAndUserAgent(t *testing.T) { hub := NewHub() hub.add(&peer{clientID: "client-1", sessionID: "session-1", remoteControlEnabled: true}) clients := hub.clientsLocked("session-1") if len(clients) != 1 { t.Fatalf("clients = %d, want 1", len(clients)) } for _, key := range []string{"ipAddress", "userAgent"} { if _, ok := clients[0][key]; ok { t.Errorf("client entry carries %q", key) } } if clients[0]["clientId"] != "client-1" { t.Errorf("clientId = %v, want client-1", clients[0]["clientId"]) } } // TestClientIdentityIsIssuedAtUpgradeAndEnforced checks the protocol change: each connection gets a // server-issued clientId in its hello frame, a message naming another identity is refused with an // error frame, and a message carrying the issued identity is applied. func TestClientIdentityIsIssuedAtUpgradeAndEnforced(t *testing.T) { hub := NewHub() server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { hub.ServeWebSocket(w, r, "") })) defer server.Close() ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() url := "ws" + strings.TrimPrefix(server.URL, "http") first := dialSyncSocket(t, ctx, url) defer first.CloseNow() second := dialSyncSocket(t, ctx, url) defer second.CloseNow() firstID := readSyncFrame(t, ctx, first, "hello")["clientId"].(string) secondID := readSyncFrame(t, ctx, second, "hello")["clientId"].(string) if len(firstID) != 32 || firstID == secondID { t.Fatalf("issued identities = %q and %q, want two distinct 32-character IDs", firstID, secondID) } writeSyncFrame(t, ctx, first, map[string]any{"type": "sync:hello", "clientId": secondID, "sessionId": "s1"}) refusal := readSyncFrame(t, ctx, first, "error") if refusal["code"] != "client-id-mismatch" || refusal["clientId"] != firstID { t.Fatalf("refusal = %v, want client-id-mismatch carrying the issued identity", refusal) } writeSyncFrame(t, ctx, first, map[string]any{"type": "sync:hello", "clientId": firstID, "sessionId": "s1"}) state := readSyncFrame(t, ctx, first, "sync:state") clients, _ := state["clients"].([]any) found := false for _, entry := range clients { if client, ok := entry.(map[string]any); ok && client["clientId"] == firstID { found = true } } if !found { t.Fatalf("clients = %v, want the issued identity %q listed", clients, firstID) } } func TestAcceptsClientIDOnlyForTheIssuedIdentity(t *testing.T) { p := &peer{clientID: "issued"} for _, tt := range []struct { name string message map[string]any want bool }{ {"no clientId", map[string]any{}, true}, {"the issued identity", map[string]any{"clientId": "issued"}, true}, {"another identity", map[string]any{"clientId": "other"}, false}, {"an oversized identity", map[string]any{"clientId": strings.Repeat("x", maxSyncIdentifier+1)}, false}, } { if got := p.acceptsClientID(tt.message); got != tt.want { t.Errorf("%s: acceptsClientID = %v, want %v", tt.name, got, tt.want) } } } // TestPeerMessageRateWindow checks the per-peer limit: maxPeerMessagesPerSecond messages are // allowed in a one-second window, the next is refused, and the count restarts with the next window. func TestPeerMessageRateWindow(t *testing.T) { p := &peer{} start := time.Unix(1000, 0) for i := 0; i < maxPeerMessagesPerSecond; i++ { if !p.allowMessage(start.Add(time.Duration(i) * time.Millisecond)) { t.Fatalf("message %d refused inside the limit", i+1) } } if p.allowMessage(start.Add(500 * time.Millisecond)) { t.Fatal("a message past the limit was allowed") } if !p.allowMessage(start.Add(time.Second)) { t.Fatal("the count did not restart with the next window") } } // TestPeerExceedingTheMessageRateIsDisconnected checks that a client flooding messages is closed // with a policy-violation status instead of being fanned out. func TestPeerExceedingTheMessageRateIsDisconnected(t *testing.T) { hub := NewHub() server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { hub.ServeWebSocket(w, r, "") })) defer server.Close() ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() conn := dialSyncSocket(t, ctx, "ws"+strings.TrimPrefix(server.URL, "http")) defer conn.CloseNow() readSyncFrame(t, ctx, conn, "hello") go func() { for i := 0; i < maxPeerMessagesPerSecond*4; i++ { if conn.Write(ctx, websocket.MessageText, []byte(`{"type":"ws:ping"}`)) != nil { return } } }() for { if _, _, err := conn.Read(ctx); err != nil { if got := websocket.CloseStatus(err); got != websocket.StatusPolicyViolation { t.Fatalf("close status = %v (error %v), want policy violation", got, err) } return } } } // TestBroadcastDropsAPeerWithAFullQueueWithoutBlocking checks that a peer that never drains its // write queue is stopped by Broadcast, which returns at once, and that a healthy peer in the same // session still receives the state. func TestBroadcastDropsAPeerWithAFullQueueWithoutBlocking(t *testing.T) { hub := NewHub() slowReady := make(chan *peer, 1) release := make(chan struct{}) server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/slow" { hub.ServeWebSocket(w, r, "") return } conn, err := websocket.Accept(w, r, nil) if err != nil { return } defer conn.CloseNow() p := &peer{ conn: conn, clientID: "slow", sessionID: "s1", out: make(chan []byte, maxPeerWriteQueue), done: make(chan struct{}), } for i := 0; i < maxPeerWriteQueue; i++ { p.out <- []byte("{}") } hub.mu.Lock() hub.peers[p] = struct{}{} hub.mu.Unlock() slowReady <- p <-release })) defer server.Close() defer close(release) ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() url := "ws" + strings.TrimPrefix(server.URL, "http") fast := dialSyncSocket(t, ctx, url) defer fast.CloseNow() fastID := readSyncFrame(t, ctx, fast, "hello")["clientId"].(string) writeSyncFrame(t, ctx, fast, map[string]any{"type": "sync:hello", "clientId": fastID, "sessionId": "s1"}) readSyncFrame(t, ctx, fast, "sync:state") slowClient := dialSyncSocket(t, ctx, url+"/slow") defer slowClient.CloseNow() slow := <-slowReady // Stopping a peer waits for a close frame that a stuck peer never sends, so Broadcast must not // do it inline: it would hold up the caller (an HTTP request, or another peer's read loop). started := time.Now() hub.Broadcast("s1") if elapsed := time.Since(started); elapsed > time.Second { t.Fatalf("Broadcast took %v behind a stuck peer, want it to return at once", elapsed) } select { case <-slow.done: default: t.Fatal("the peer with a full queue was not stopped") } state := readSyncFrame(t, ctx, fast, "sync:state") if _, ok := state["clients"].([]any); !ok { t.Fatalf("the healthy peer got %v, want a state with the client list", state) } if elapsed := time.Since(started); elapsed > time.Second { t.Fatalf("the healthy peer's state took %v, want it at once", elapsed) } } func dialSyncSocket(t *testing.T, ctx context.Context, url string) *websocket.Conn { t.Helper() conn, _, err := websocket.Dial(ctx, url, nil) if err != nil { t.Fatalf("dial %s: %v", url, err) } return conn } func writeSyncFrame(t *testing.T, ctx context.Context, conn *websocket.Conn, message map[string]any) { t.Helper() data, err := json.Marshal(message) if err != nil { t.Fatal(err) } if err := conn.Write(ctx, websocket.MessageText, data); err != nil { t.Fatalf("write %v: %v", message["type"], err) } } // readSyncFrame reads frames until one of the wanted type arrives, failing if the connection ends first. func readSyncFrame(t *testing.T, ctx context.Context, conn *websocket.Conn, want string) map[string]any { t.Helper() for { _, data, err := conn.Read(ctx) if err != nil { t.Fatalf("read while waiting for %q: %v", want, err) } var message map[string]any if err := json.Unmarshal(data, &message); err != nil { t.Fatalf("decode frame: %v", err) } if message["type"] == want { return message } } }