Lint / Lint (push) Successful in 1m29s
Security / Secrets (gitleaks) (push) Successful in 1m11s
Security / Dependencies (Trivy) (push) Successful in 1m59s
Tests / Dashboard checks (push) Successful in 1m49s
Security / Code (Semgrep) (push) Successful in 3m8s
Tests / Go backend (push) Successful in 2m50s
Docker / Docker Build & Push (push) Successful in 8m42s
- Target API 37 and use build-tools 37 for release signature checks - Adjust list pagination spacing and clarify shared backend docs
171 lines
6.2 KiB
Go
171 lines
6.2 KiB
Go
package syncsocket
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/coder/websocket"
|
|
"github.com/go-chi/chi/v5"
|
|
|
|
sharedauth "repos.gfranz.ch/Gabriel20xx/shared/backend/auth"
|
|
)
|
|
|
|
// syncRouter mounts the sync routes on hub. Auth is disabled, so every caller is the placeholder
|
|
// administrator.
|
|
func syncRouter(hub *Hub) chi.Router {
|
|
auth := sharedauth.NewWithStore(loginOffStore{}, "session", false, "", "testproject", sharedauth.Disabled())
|
|
router := chi.NewRouter()
|
|
MountRoutes(router, hub, auth.Optional, auth.Require)
|
|
return router
|
|
}
|
|
|
|
func putSync(router http.Handler, target, body string) *httptest.ResponseRecorder {
|
|
response := httptest.NewRecorder()
|
|
router.ServeHTTP(response, httptest.NewRequest(http.MethodPut, target, strings.NewReader(body)))
|
|
return response
|
|
}
|
|
|
|
func TestPutSyncRejectsBadInput(t *testing.T) {
|
|
router := syncRouter(NewHub())
|
|
for name, body := range map[string]string{
|
|
"not JSON": `nope`,
|
|
"missing clientId": `{"mediaId":"m1"}`,
|
|
"blank clientId": `{"clientId":" ","mediaId":"m1"}`,
|
|
"object mediaId": `{"clientId":"c1","mediaId":{"a":1}}`,
|
|
"boolean mediaId": `{"clientId":"c1","mediaId":true}`,
|
|
"array playAt": `{"clientId":"c1","mediaId":"m1","playAt":[1]}`,
|
|
"object playAt": `{"clientId":"c1","mediaId":"m1","playAt":{"a":1}}`,
|
|
"clientId not text": `{"clientId":5,"mediaId":"m1"}`,
|
|
} {
|
|
if response := putSync(router, "/sync", body); response.Code != http.StatusBadRequest {
|
|
t.Errorf("%s: status = %d, want 400 (body %s)", name, response.Code, response.Body.String())
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestPutSyncStoresBoundedStateThatGetSyncReturns(t *testing.T) {
|
|
hub := NewHub()
|
|
router := syncRouter(hub)
|
|
|
|
response := putSync(router, "/sync?sessionId=room-1", `{"clientId":"c1","mediaId":42,"timeMs":-5,"paused":true,"fps":100000,"frame":9,"playAt":"2026-10-19T10:00:00Z"}`)
|
|
if response.Code != http.StatusOK {
|
|
t.Fatalf("PUT status = %d, body %s", response.Code, response.Body.String())
|
|
}
|
|
var written struct {
|
|
Success bool `json:"success"`
|
|
State map[string]any `json:"state"`
|
|
}
|
|
if err := json.Unmarshal(response.Body.Bytes(), &written); err != nil || !written.Success {
|
|
t.Fatalf("PUT body = %s, %v", response.Body.String(), err)
|
|
}
|
|
state := written.State
|
|
if state["sessionId"] != "room-1" || state["fromClientId"] != "c1" || state["mediaId"] != float64(42) || state["paused"] != true {
|
|
t.Fatalf("state = %v", state)
|
|
}
|
|
if state["timeMs"] != float64(0) || state["fps"] != float64(240) || state["frame"] != float64(9) || state["playAt"] != "2026-10-19T10:00:00Z" {
|
|
t.Fatalf("a negative time was not clamped to 0, or fps to 240: %v", state)
|
|
}
|
|
|
|
get := httptest.NewRecorder()
|
|
router.ServeHTTP(get, httptest.NewRequest(http.MethodGet, "/sync?sessionId=room-1", nil))
|
|
var read map[string]any
|
|
if err := json.Unmarshal(get.Body.Bytes(), &read); err != nil || read["fromClientId"] != "c1" || read["mediaId"] != float64(42) {
|
|
t.Fatalf("GET /sync = %s, %v; want the stored state", get.Body.String(), err)
|
|
}
|
|
|
|
other := httptest.NewRecorder()
|
|
router.ServeHTTP(other, httptest.NewRequest(http.MethodGet, "/sync?sessionId=room-2", nil))
|
|
var empty map[string]any
|
|
if err := json.Unmarshal(other.Body.Bytes(), &empty); err != nil || empty["fromClientId"] == "c1" {
|
|
t.Fatalf("another session got %s, %v; want it untouched", other.Body.String(), err)
|
|
}
|
|
}
|
|
|
|
func TestPutSyncBoundsAnOversizedSessionAndClientID(t *testing.T) {
|
|
router := syncRouter(NewHub())
|
|
long := strings.Repeat("s", 300)
|
|
response := putSync(router, "/sync", `{"clientId":"`+strings.Repeat("c", 300)+`","mediaId":null,"sessionId":"`+long+`"}`)
|
|
if response.Code != http.StatusOK {
|
|
t.Fatalf("status = %d, body %s", response.Code, response.Body.String())
|
|
}
|
|
var written struct{ State map[string]any }
|
|
if err := json.Unmarshal(response.Body.Bytes(), &written); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if got := written.State["sessionId"].(string); len(got) != 128 {
|
|
t.Errorf("sessionId length = %d, want 128", len(got))
|
|
}
|
|
if got := written.State["fromClientId"].(string); len(got) != 128 {
|
|
t.Errorf("fromClientId length = %d, want 128", len(got))
|
|
}
|
|
}
|
|
|
|
// TestPutSyncBroadcastsToThePeersOfThatSession checks the HTTP write reaches websocket peers in
|
|
// the session, and only those.
|
|
func TestPutSyncBroadcastsToThePeersOfThatSession(t *testing.T) {
|
|
hub := NewHub()
|
|
router := syncRouter(hub)
|
|
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")
|
|
|
|
join := func(session string) (*websocket.Conn, string) {
|
|
conn, _, err := websocket.Dial(ctx, url, nil)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Cleanup(func() { conn.CloseNow() })
|
|
hello := readFrame(t, ctx, conn, "hello")
|
|
id := hello["clientId"].(string)
|
|
data, _ := json.Marshal(map[string]any{"type": "sync:hello", "clientId": id, "sessionId": session})
|
|
if err := conn.Write(ctx, websocket.MessageText, data); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
readFrame(t, ctx, conn, "sync:state")
|
|
return conn, id
|
|
}
|
|
inRoom, _ := join("room-1")
|
|
elsewhere, _ := join("room-2")
|
|
|
|
if response := putSync(router, "/sync?sessionId=room-1", `{"clientId":"http-client","mediaId":"clip-9","timeMs":1500}`); response.Code != http.StatusOK {
|
|
t.Fatalf("PUT status = %d", response.Code)
|
|
}
|
|
frame := readFrame(t, ctx, inRoom, "sync:state")
|
|
state, _ := frame["state"].(map[string]any)
|
|
if state["mediaId"] != "clip-9" || state["timeMs"] != float64(1500) {
|
|
t.Fatalf("the session peer got %v", frame)
|
|
}
|
|
|
|
short, shortCancel := context.WithTimeout(ctx, 300*time.Millisecond)
|
|
defer shortCancel()
|
|
if _, _, err := elsewhere.Read(short); err == nil {
|
|
t.Fatal("a peer in another session received the broadcast")
|
|
}
|
|
}
|
|
|
|
func readFrame(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.Fatal(err)
|
|
}
|
|
if message["type"] == want {
|
|
return message
|
|
}
|
|
}
|
|
}
|