ci: expand shared package validation and test coverage
- Add lint, formatting, vet, and publish workflow checks - Run Go database tests with PostgreSQL and add Java tests - Make consumer sync opt-in; update docs and Go dependency
This commit is contained in:
1 parent
937f51b4fb
commit
0ff94f9b10
107 files changed
+10124
-410
No files matched your search
@@ -0,0 +1,227 @@
|
||||
package mediacore
|
||||
|
||||
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"
|
||||
"repos.gfranz.ch/Gabriel20xx/shared/backend/syncsocket"
|
||||
)
|
||||
|
||||
// TestSessionRoutesRefuseAnonymousRequests walks the route table: every route mounted behind
|
||||
// Require answers 401 to a caller with no session, before any handler runs. The Core has no
|
||||
// database, sync hub or CarrierNode client, so a request that got past the gate would panic.
|
||||
func TestSessionRoutesRefuseAnonymousRequests(t *testing.T) {
|
||||
auth := sharedauth.NewWithStore(loginRequiredStore{}, "session", false, "", "testproject")
|
||||
router := chi.NewRouter()
|
||||
New(Config{Auth: auth}).Mount(router)
|
||||
|
||||
for _, route := range []struct{ method, target string }{
|
||||
{http.MethodGet, "/security/totp/status"},
|
||||
{http.MethodGet, "/security/totp/initiate"},
|
||||
{http.MethodPost, "/security/totp/verify"},
|
||||
{http.MethodPost, "/security/totp/disable"},
|
||||
{http.MethodPut, "/sync"},
|
||||
{http.MethodPost, "/media/like"},
|
||||
{http.MethodPost, "/media/save"},
|
||||
{http.MethodGet, "/media/liked"},
|
||||
{http.MethodPost, "/media/7/tags"},
|
||||
{http.MethodPost, "/media/7/tags/funny/vote"},
|
||||
{http.MethodGet, "/playlists"},
|
||||
{http.MethodPost, "/playlists"},
|
||||
{http.MethodDelete, "/playlists/3"},
|
||||
{http.MethodPost, "/playlists/3/items"},
|
||||
{http.MethodDelete, "/playlists/3/items"},
|
||||
{http.MethodPatch, "/playlists/3/items/reorder"},
|
||||
} {
|
||||
response := httptest.NewRecorder()
|
||||
router.ServeHTTP(response, httptest.NewRequest(route.method, route.target, strings.NewReader(`{}`)))
|
||||
if response.Code != http.StatusUnauthorized {
|
||||
t.Errorf("%s %s status = %d, want 401", route.method, route.target, response.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// syncRouter mounts the sync routes on a Core with no database. Auth is disabled, so every caller
|
||||
// is the placeholder administrator.
|
||||
func syncRouter(hub *syncsocket.Hub) chi.Router {
|
||||
auth := sharedauth.NewWithStore(loginOffStore{}, "session", false, "", "testproject", sharedauth.Disabled())
|
||||
router := chi.NewRouter()
|
||||
New(Config{Auth: auth, Sync: hub}).Mount(router)
|
||||
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(syncsocket.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 := syncsocket.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(syncsocket.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 := syncsocket.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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestProfileReportsTheSessionUser(t *testing.T) {
|
||||
guard := newRoleAuthGuard(t)
|
||||
auth := sharedauth.NewWithStore(loginRequiredStore{}, "session", false, guard.URL, "testproject")
|
||||
router := chi.NewRouter()
|
||||
New(Config{Auth: auth}).Mount(router)
|
||||
|
||||
anonymous := httptest.NewRecorder()
|
||||
router.ServeHTTP(anonymous, httptest.NewRequest(http.MethodGet, "/profile", nil))
|
||||
if anonymous.Code != http.StatusOK || strings.TrimSpace(anonymous.Body.String()) != `{"user":null}` {
|
||||
t.Fatalf("anonymous profile = %d %s, want a null user", anonymous.Code, anonymous.Body.String())
|
||||
}
|
||||
|
||||
request := httptest.NewRequest(http.MethodGet, "/profile", nil)
|
||||
request.AddCookie(&http.Cookie{Name: "auth_session", Value: "viewer-token"})
|
||||
known := httptest.NewRecorder()
|
||||
router.ServeHTTP(known, request)
|
||||
var body struct{ User map[string]any }
|
||||
if err := json.Unmarshal(known.Body.Bytes(), &body); err != nil || body.User["username"] != "tester" || body.User["role"] != "user" {
|
||||
t.Fatalf("profile = %s, %v", known.Body.String(), err)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user