ci: expand shared package validation and test coverage
Lint / Lint (push) Successful in 32s
Docker / Docker Build & Push (push) Failing after 2m22s
Tests / Go backend (push) Failing after 1m2s
Tests / Dashboard checks (push) Failing after 35s

- 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:
Gabriel20xx committed 2026-10-19 21:46:52 +00:00
1 parent 937f51b4fb
commit 0ff94f9b10
107 files changed
+10124 -410

No files matched your search

+90 -11
View File
@@ -51,6 +51,10 @@ import (
"repos.gfranz.ch/Gabriel20xx/shared/backend/syncsocket"
)
// maxPlaylistReorderItems caps one reorder request. The reorder runs as a single statement, so the
// cap bounds its size; a playlist longer than this is reordered in more than one request.
const maxPlaylistReorderItems = 10000
// Config wires a Core to the rest of one service's dependencies.
type Config struct {
DB *pgxpool.Pool
@@ -157,6 +161,8 @@ func (c *Core) putSyncState(w http.ResponseWriter, r *http.Request) {
state["playAt"] = playAt
}
c.sync.SetHTTPState(sessionID, state)
// Broadcast queues immutable messages without waiting for network writes, so a slow
// websocket peer does not hold this response or create one goroutine per request.
c.sync.Broadcast(sessionID)
writeJSON(w, http.StatusOK, map[string]any{"success": true, "state": state})
}
@@ -194,7 +200,12 @@ func (c *Core) streamMediaIdentifier(w http.ResponseWriter, r *http.Request, ide
writeError(w, http.StatusNotFound, "media not found")
return
}
c.carrierNode.Proxy(w, r, "/media/"+urlPath(record.FilePath))
upstream, ok := upstreamMediaPath(record.FilePath)
if !ok {
writeError(w, http.StatusNotFound, "media not found")
return
}
c.carrierNode.Proxy(w, r, "/media/"+upstream)
}
func (c *Core) thumbnailMediaByQuery(w http.ResponseWriter, r *http.Request) {
@@ -222,9 +233,9 @@ func (c *Core) thumbnailMediaIdentifier(w http.ResponseWriter, r *http.Request,
SELECT t.id::text
FROM thumbnails t
JOIN media m ON m.id = t.media_id OR t.source_path = COALESCE(NULLIF(m.file_path, ''), m.media_key)
WHERE m.media_key=$1 OR CAST(m.id AS TEXT)=$1
WHERE m.media_key=$1 OR m.id=$2
ORDER BY t.created_at DESC
LIMIT 1`, id).Scan(&thumbnailID); err == nil && SafeRelative(thumbnailID) {
LIMIT 1`, id, mediaIDArg(id)).Scan(&thumbnailID); err == nil && SafeRelative(thumbnailID) {
// A row whose file CarrierNode no longer has falls through to the original image below,
// rather than proxying CarrierNode's 404.
if c.carrierNode.ProxyThumbnail(w, r, c.serviceName, thumbnailID) {
@@ -236,7 +247,12 @@ func (c *Core) thumbnailMediaIdentifier(w http.ResponseWriter, r *http.Request,
writeError(w, http.StatusNotFound, "thumbnail not found")
return
}
c.carrierNode.Proxy(w, r, "/media/"+urlPath(record.FilePath))
upstream, ok := upstreamMediaPath(record.FilePath)
if !ok {
writeError(w, http.StatusNotFound, "thumbnail not found")
return
}
c.carrierNode.Proxy(w, r, "/media/"+upstream)
}
func (c *Core) mediaState(w http.ResponseWriter, r *http.Request) {
@@ -390,9 +406,9 @@ func (c *Core) mediaLiked(w http.ResponseWriter, r *http.Request) {
func (c *Core) mediaTags(w http.ResponseWriter, r *http.Request) {
key := strings.TrimSpace(chi.URLParam(r, "id"))
rows, err := c.db.Query(r.Context(), `
SELECT tag, COALESCE(SUM(vote), 0) AS score
SELECT mt.tag, COALESCE(SUM(mv.vote), 0) AS score
FROM media_tags mt LEFT JOIN media_tag_votes mv ON mv.media_key = mt.media_key AND LOWER(mv.tag) = LOWER(mt.tag)
WHERE mt.media_key = $1 GROUP BY tag ORDER BY score DESC, LOWER(tag)`, key)
WHERE mt.media_key = $1 GROUP BY mt.tag ORDER BY score DESC, LOWER(mt.tag)`, key)
if err != nil {
writeJSON(w, http.StatusOK, map[string]any{"tags": []any{}})
return
@@ -723,8 +739,31 @@ func (c *Core) reorderPlaylist(w http.ResponseWriter, r *http.Request) {
if len(ids) == 0 {
ids = input.ItemIDs
}
for position, itemID := range ids {
_, _ = c.db.Exec(r.Context(), `UPDATE playlist_items SET position=$1 WHERE id=$2 AND playlist_id=$3 AND EXISTS (SELECT 1 FROM playlists WHERE id=$3 AND user_id=$4)`, position, itemID, id, user.ID)
if len(ids) > maxPlaylistReorderItems {
writeError(w, http.StatusBadRequest, "too many items to reorder")
return
}
positions := make([]int32, len(ids))
for position := range ids {
positions[position] = int32(position)
}
tx, err := c.db.Begin(r.Context())
if err != nil {
writeError(w, http.StatusInternalServerError, "could not reorder playlist")
return
}
defer func() { _ = tx.Rollback(r.Context()) }()
if _, err := tx.Exec(r.Context(), `
UPDATE playlist_items AS i SET position=v.position
FROM unnest($1::bigint[], $2::int[]) AS v(item_id, position)
WHERE i.id=v.item_id AND i.playlist_id=$3
AND EXISTS (SELECT 1 FROM playlists WHERE id=$3 AND user_id=$4)`, ids, positions, id, user.ID); err != nil {
writeError(w, http.StatusInternalServerError, "could not reorder playlist")
return
}
if err := tx.Commit(r.Context()); err != nil {
writeError(w, http.StatusInternalServerError, "could not reorder playlist")
return
}
writeJSON(w, http.StatusOK, success(map[string]any{"ok": true}, "Playlist reordered"))
}
@@ -749,8 +788,8 @@ func canSeeHidden(r *http.Request) bool {
func (c *Core) isHiddenMedia(ctx context.Context, identifier string) bool {
var hidden bool
err := c.db.QueryRow(ctx, `
SELECT EXISTS (SELECT 1 FROM media WHERE NOT active AND (media_key=$1 OR CAST(id AS TEXT)=$1))`,
strings.TrimSpace(identifier)).Scan(&hidden)
SELECT EXISTS (SELECT 1 FROM media WHERE NOT active AND (media_key=$1 OR id=$2))`,
strings.TrimSpace(identifier), mediaIDArg(strings.TrimSpace(identifier))).Scan(&hidden)
return err != nil || hidden
}
@@ -765,7 +804,7 @@ func (c *Core) findMedia(ctx context.Context, identifier string, includeHidden b
COALESCE(width, 0), COALESCE(height, 0), COALESCE(duration_ms, 0), COALESCE(size_bytes, 0),
COALESCE(is_vr, FALSE), COALESCE(has_funscript, FALSE), funscript_action_count,
funscript_avg_speed, funscript_max_speed, COALESCE(speed, 0), COALESCE(modified_at, created_at)
FROM media WHERE (media_key=$1 OR CAST(id AS TEXT)=$1) AND (active OR $2) LIMIT 1`, identifier, includeHidden)
FROM media WHERE (media_key=$1 OR id=$2) AND (active OR $3) LIMIT 1`, identifier, mediaIDArg(identifier), includeHidden)
var title, description string
var width, height int
var duration, size int64
@@ -1029,6 +1068,46 @@ func urlPath(value string) string {
return value
}
// upstreamMediaPath returns the escaped CarrierNode path for a stored file path. It reports false
// when the stored path is not a safe relative path, or when it contains a query or fragment marker
// that CarrierNode would read as the end of the path.
func upstreamMediaPath(filePath string) (string, bool) {
relative := urlPath(filePath)
if !SafeRelative(relative) || strings.ContainsAny(relative, "?#") {
return "", false
}
// Escape each segment so percent-escapes and other reserved characters in a stored name
// reach CarrierNode as literal text, not as an escape or a traversal it decodes later.
segments := strings.Split(relative, "/")
for i, segment := range segments {
segments[i] = url.PathEscape(segment)
}
return strings.Join(segments, "/"), true
}
// canonicalMediaID returns the numeric media id that identifier spells exactly. Leading zeros, signs
// and whitespace are not canonical, so they never match an id.
func canonicalMediaID(identifier string) (int64, bool) {
if identifier == "" || strings.Trim(identifier, "0123456789") != "" {
return 0, false
}
id, err := strconv.ParseInt(identifier, 10, 64)
if err != nil || strconv.FormatInt(id, 10) != identifier {
return 0, false
}
return id, true
}
// mediaIDArg is the id query argument for identifier: the id when identifier is a canonical number,
// otherwise NULL, which matches no row. Comparing the id column directly, instead of casting it to
// text, lets the planner use the primary-key index for the id arm.
func mediaIDArg(identifier string) any {
if id, ok := canonicalMediaID(identifier); ok {
return id
}
return nil
}
func firstNonEmpty(values ...string) string {
for _, value := range values {
if strings.TrimSpace(value) != "" {
+101
View File
@@ -0,0 +1,101 @@
package mediacore
import (
"errors"
"os"
"path/filepath"
"testing"
)
func TestSafeRelativeRejectsTraversalAndAbsolutePaths(t *testing.T) {
for _, value := range []string{"", ".", "..", "../x", "a/../../x", "sub/../a.mp4x", "/etc/passwd", `\etc\passwd`, `C:\x`, "a\x00b"} {
if SafeRelative(value) {
t.Errorf("SafeRelative(%q) = true, want false", value)
}
}
for _, value := range []string{"a.mp4", "sub/b.mp4", "v1..2/clip.mp4"} {
if !SafeRelative(value) {
t.Errorf("SafeRelative(%q) = false, want true", value)
}
}
}
func TestResolveUnderRootsStaysInsideTheRoots(t *testing.T) {
root := t.TempDir()
if err := os.MkdirAll(filepath.Join(root, "sub"), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(root, "a.mp4"), []byte("a"), 0o600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(root, "sub", "b.mp4"), []byte("b"), 0o600); err != nil {
t.Fatal(err)
}
outside := filepath.Join(t.TempDir(), "secret.txt")
if err := os.WriteFile(outside, []byte("s"), 0o600); err != nil {
t.Fatal(err)
}
_ = os.Symlink(outside, filepath.Join(root, "link.txt"))
for value, want := range map[string]string{
"a.mp4": filepath.Join(root, "a.mp4"),
"/media/a.mp4": filepath.Join(root, "a.mp4"),
"sub/b.mp4": filepath.Join(root, "sub", "b.mp4"),
"/media/sub/b.mp4": filepath.Join(root, "sub", "b.mp4"),
} {
got, err := ResolveUnderRoots(value, []string{root})
if err != nil || got != want {
t.Errorf("ResolveUnderRoots(%q) = %q, %v; want %q", value, got, err, want)
}
}
for _, value := range []string{"../secret.txt", "sub", "missing.mp4", "link.txt", "", "a\x00b"} {
if _, err := ResolveUnderRoots(value, []string{root}); err == nil {
t.Errorf("ResolveUnderRoots(%q) resolved, want an error", value)
}
}
if _, err := ResolveUnderRoots("missing.mp4", []string{root}); !errors.Is(err, os.ErrNotExist) {
t.Errorf("missing file error = %v, want os.ErrNotExist", err)
}
}
func TestUpstreamMediaPathRefusesQueryFragmentAndTraversal(t *testing.T) {
for _, stored := range []string{"x?y.mp4", "a#b.mp4", "../x.mp4", "media/../../x.mp4", `..\x.mp4`} {
if _, ok := upstreamMediaPath(stored); ok {
t.Errorf("upstreamMediaPath(%q) accepted, want refused", stored)
}
}
}
func TestUpstreamMediaPathEscapesEachSegment(t *testing.T) {
cases := map[string]string{
"clips/clip.mp4": "clips/clip.mp4",
"my clip.mp4": "my%20clip.mp4",
"100%.mp4": "100%25.mp4",
"media/a b/c.mp4": "a%20b/c.mp4",
"/leading.mp4": "leading.mp4",
}
for stored, want := range cases {
got, ok := upstreamMediaPath(stored)
if !ok || got != want {
t.Errorf("upstreamMediaPath(%q) = %q, %v; want %q", stored, got, ok, want)
}
}
}
func TestCanonicalMediaIDAcceptsOnlyCanonicalDecimals(t *testing.T) {
for _, value := range []string{"", "007", "+1", "-1", "4a", " 4", "4 ", "99999999999999999999"} {
if id, ok := canonicalMediaID(value); ok {
t.Errorf("canonicalMediaID(%q) = %d, want refused", value, id)
}
}
if id, ok := canonicalMediaID("42"); !ok || id != 42 {
t.Errorf("canonicalMediaID(42) = %d, %v; want 42, true", id, ok)
}
if mediaIDArg("abc") != nil {
t.Error("mediaIDArg(non-numeric) is not NULL")
}
if mediaIDArg("42") != int64(42) {
t.Error("mediaIDArg(42) is not 42")
}
}
+483
View File
@@ -0,0 +1,483 @@
package mediacore
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"strings"
"sync"
"testing"
"github.com/go-chi/chi/v5"
"github.com/jackc/pgx/v5/pgxpool"
sharedauth "repos.gfranz.ch/Gabriel20xx/shared/backend/auth"
"repos.gfranz.ch/Gabriel20xx/shared/backend/carriernodeclient"
"repos.gfranz.ch/Gabriel20xx/shared/backend/postgres"
"repos.gfranz.ch/Gabriel20xx/shared/backend/syncsocket"
)
// The tests in this file run the media routes against a real PostgreSQL database and a stand-in
// CarrierNode. They create the media tables and a few rows, so they are skipped unless
// SHARED_TEST_DATABASE_URL points at a scratch database, for example:
//
// SHARED_TEST_DATABASE_URL=postgres://user:pass@localhost:5432/scratch?sslmode=disable go test ./mediacore/
const (
aliceID = 9101
bobID = 9102
modID = 9103
)
// newIdentityAuthGuard answers GET /api/me for three fixed sessions: two ordinary users and a moderator.
func newIdentityAuthGuard(t *testing.T) *httptest.Server {
t.Helper()
people := map[string]struct {
id int64
role string
}{"alice-token": {aliceID, "user"}, "bob-token": {bobID, "user"}, "mod-token": {modID, "moderator"}}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
person, ok := people[strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")]
if !ok || r.URL.Path != "/api/me" {
w.WriteHeader(http.StatusUnauthorized)
return
}
w.Header().Set("Content-Type", "application/json")
fmt.Fprintf(w, `{"user":{"id":%d,"username":"u%d","role":%q}}`, person.id, person.id, person.role)
}))
t.Cleanup(server.Close)
return server
}
// stubCarrierNode serves a body for every /media/ path and 404s the rest, recording what it was asked.
type stubCarrierNode struct {
mu sync.Mutex
requests []string
}
func (n *stubCarrierNode) ServeHTTP(w http.ResponseWriter, r *http.Request) {
n.mu.Lock()
n.requests = append(n.requests, r.Method+" "+r.URL.EscapedPath())
n.mu.Unlock()
if !strings.HasPrefix(r.URL.Path, "/media/") {
http.NotFound(w, r)
return
}
w.Header().Set("Content-Type", "application/octet-stream")
if r.Method != http.MethodHead {
_, _ = io.WriteString(w, "BYTES")
}
}
func (n *stubCarrierNode) seen() []string {
n.mu.Lock()
defer n.mu.Unlock()
return append([]string(nil), n.requests...)
}
type dbHarness struct {
pool *pgxpool.Pool
router chi.Router
carrier *stubCarrierNode
hub *syncsocket.Hub
}
func newDBHarness(t *testing.T) *dbHarness {
t.Helper()
url := os.Getenv("SHARED_TEST_DATABASE_URL")
if url == "" {
t.Skip("SHARED_TEST_DATABASE_URL not set; skipping Postgres route tests")
}
ctx := context.Background()
pool, err := postgres.Open(ctx, postgres.DefaultConfig(url))
if err != nil {
t.Fatalf("open pool: %v", err)
}
t.Cleanup(pool.Close)
carrier := &stubCarrierNode{}
carrierServer := httptest.NewServer(carrier)
t.Cleanup(carrierServer.Close)
guard := newIdentityAuthGuard(t)
auth := sharedauth.NewWithStore(loginRequiredStore{}, "session", false, guard.URL, "testproject")
hub := syncsocket.NewHub()
core := New(Config{
DB: pool,
Auth: auth,
Sync: hub,
CarrierNode: carriernodeclient.New("", func(context.Context) string { return carrierServer.URL }),
ServiceName: "routes-test",
})
if err := core.Migrate(ctx); err != nil {
t.Fatalf("Migrate() error = %v", err)
}
cleanup := func() {
for _, statement := range []string{
`DELETE FROM playlists WHERE user_id IN (9101, 9102, 9103)`,
`DELETE FROM media_stats WHERE media_key LIKE 'rt-%' OR user_id IN (9101, 9102, 9103)`,
`DELETE FROM media_view_sessions WHERE media_key LIKE 'rt-%'`,
`DELETE FROM media_tag_votes WHERE media_key LIKE 'rt-%'`,
`DELETE FROM media_tags WHERE media_key LIKE 'rt-%'`,
`DELETE FROM media WHERE media_key LIKE 'rt-%'`,
`DELETE FROM users WHERE id IN (9101, 9102, 9103)`,
} {
if _, err := pool.Exec(ctx, statement); err != nil {
t.Fatalf("cleanup %q: %v", statement, err)
}
}
}
cleanup()
t.Cleanup(cleanup)
for _, id := range []int64{aliceID, bobID, modID} {
if _, err := pool.Exec(ctx, `INSERT INTO users (id, email, username, password_hash) VALUES ($1, $2, $3, 'x')`, id, fmt.Sprintf("rt%d@example.com", id), fmt.Sprintf("rt%d", id)); err != nil {
t.Fatalf("insert user: %v", err)
}
}
router := chi.NewRouter()
core.Mount(router)
return &dbHarness{pool: pool, router: router, carrier: carrier, hub: hub}
}
func (h *dbHarness) insertMedia(t *testing.T, key, mediaType, filePath string, active bool) {
t.Helper()
if _, err := h.pool.Exec(context.Background(), `INSERT INTO media (media_key, media_type, file_path, active) VALUES ($1, $2, $3, $4)`, key, mediaType, filePath, active); err != nil {
t.Fatalf("insert media %s: %v", key, err)
}
}
func (h *dbHarness) do(method, target, token, body string) *httptest.ResponseRecorder {
var reader io.Reader
if body != "" {
reader = strings.NewReader(body)
}
request := httptest.NewRequest(method, target, reader)
if token != "" {
request.AddCookie(&http.Cookie{Name: "auth_session", Value: token})
}
response := httptest.NewRecorder()
h.router.ServeHTTP(response, request)
return response
}
func decode(t *testing.T, response *httptest.ResponseRecorder) map[string]any {
t.Helper()
var out map[string]any
if err := json.Unmarshal(response.Body.Bytes(), &out); err != nil {
t.Fatalf("body %q is not JSON: %v", response.Body.String(), err)
}
return out
}
func dataOf(t *testing.T, response *httptest.ResponseRecorder) map[string]any {
t.Helper()
data, _ := decode(t, response)["data"].(map[string]any)
if data == nil {
t.Fatalf("response %s has no data object", response.Body.String())
}
return data
}
func TestMediaStreamAndThumbnailAgainstPostgres(t *testing.T) {
h := newDBHarness(t)
h.insertMedia(t, "rt-visible", "video", "folder/clip one.mp4", true)
h.insertMedia(t, "rt-hidden", "video", "secret.mp4", false)
h.insertMedia(t, "rt-image", "image", "pics/photo.jpg", true)
h.insertMedia(t, "rt-escape", "video", "../etc/passwd", true)
h.insertMedia(t, "rt-query", "video", "a?b.mp4", true)
var visibleID int64
if err := h.pool.QueryRow(context.Background(), `SELECT id FROM media WHERE media_key='rt-visible'`).Scan(&visibleID); err != nil {
t.Fatal(err)
}
t.Run("an anonymous caller is refused while login is required", func(t *testing.T) {
if code := h.do(http.MethodGet, "/media/stream?mediaKey=rt-visible", "", "").Code; code != http.StatusUnauthorized {
t.Fatalf("status = %d, want 401", code)
}
})
t.Run("a stored path reaches CarrierNode escaped, by key or by id, for GET and HEAD", func(t *testing.T) {
for _, target := range []string{"/media/stream?mediaKey=rt-visible", fmt.Sprintf("/media/stream?id=%d", visibleID)} {
response := h.do(http.MethodGet, target, "alice-token", "")
if response.Code != http.StatusOK || response.Body.String() != "BYTES" {
t.Fatalf("GET %s = %d %q, want the proxied bytes", target, response.Code, response.Body.String())
}
}
if response := h.do(http.MethodHead, "/media/stream?mediaKey=rt-visible", "alice-token", ""); response.Code != http.StatusOK || response.Body.Len() != 0 {
t.Fatalf("HEAD = %d with %d body bytes, want 200 and none", response.Code, response.Body.Len())
}
for _, request := range h.carrier.seen() {
if request != "GET /media/folder/clip%20one.mp4" && request != "HEAD /media/folder/clip%20one.mp4" {
t.Fatalf("CarrierNode saw %q, want the escaped stored path", request)
}
}
})
t.Run("unsafe stored paths and unknown keys are not found, and never reach CarrierNode", func(t *testing.T) {
before := len(h.carrier.seen())
for _, key := range []string{"rt-escape", "rt-query", "rt-missing", ""} {
if code := h.do(http.MethodGet, "/media/stream?mediaKey="+key, "alice-token", "").Code; code != http.StatusNotFound {
t.Errorf("stream of %q status = %d, want 404", key, code)
}
}
if got := len(h.carrier.seen()); got != before {
t.Fatalf("CarrierNode got %d extra requests, want none", got-before)
}
})
t.Run("hidden media is visible to moderators only", func(t *testing.T) {
for _, target := range []string{"/media/stream?mediaKey=rt-hidden", "/media/thumb?mediaKey=rt-hidden"} {
if code := h.do(http.MethodGet, target, "alice-token", "").Code; code != http.StatusNotFound {
t.Errorf("viewer GET %s = %d, want 404", target, code)
}
}
if response := h.do(http.MethodGet, "/media/stream?mediaKey=rt-hidden", "mod-token", ""); response.Code != http.StatusOK {
t.Errorf("moderator stream of hidden media = %d, want 200", response.Code)
}
})
t.Run("a thumbnail falls back to the original image, and only for images", func(t *testing.T) {
response := h.do(http.MethodGet, "/media/thumb?mediaKey=rt-image", "alice-token", "")
if response.Code != http.StatusOK || response.Body.String() != "BYTES" {
t.Fatalf("image thumbnail = %d %q, want the original image", response.Code, response.Body.String())
}
if code := h.do(http.MethodGet, "/media/thumb?mediaKey=rt-visible", "alice-token", "").Code; code != http.StatusNotFound {
t.Errorf("video without a thumbnail = %d, want 404", code)
}
if code := h.do(http.MethodGet, "/media/thumb?mediaKey=../x", "alice-token", "").Code; code != http.StatusBadRequest {
t.Errorf("unsafe thumbnail id = %d, want 400", code)
}
})
}
func TestMediaStatsAndViewsAgainstPostgres(t *testing.T) {
h := newDBHarness(t)
state := func(token string) map[string]any {
return dataOf(t, h.do(http.MethodGet, "/media/state?mediaKey=rt-stats", token, ""))
}
if code := h.do(http.MethodGet, "/media/state", "", "").Code; code != http.StatusBadRequest {
t.Fatalf("state without a key = %d, want 400", code)
}
for _, body := range []string{`{}`, `{"mediaKey":"rt-stats","bogus":1}`, `nope`} {
if code := h.do(http.MethodPost, "/media/like", "alice-token", body).Code; code != http.StatusBadRequest {
t.Errorf("like with %q = %d, want 400", body, code)
}
}
h.do(http.MethodPost, "/media/like", "alice-token", `{"mediaKey":"rt-stats"}`)
h.do(http.MethodPost, "/media/like", "alice-token", `{"mediaKey":"rt-stats"}`) // a repeat is not a second like
h.do(http.MethodPost, "/media/like", "bob-token", `{"mediaKey":"rt-stats","like":true}`)
h.do(http.MethodPost, "/media/save", "alice-token", `{"mediaKey":"rt-stats"}`)
if got := state("alice-token"); got["likeCount"] != float64(2) || got["saveCount"] != float64(1) || got["likedByUser"] != true || got["savedByUser"] != true {
t.Fatalf("state for alice = %v", got)
}
if got := state("bob-token"); got["likedByUser"] != true || got["savedByUser"] != false {
t.Fatalf("state for bob = %v", got)
}
if response := h.do(http.MethodPost, "/media/like", "alice-token", `{"mediaKey":"rt-stats","like":false}`); dataOf(t, response)["enabled"] != false {
t.Fatalf("unlike = %s", response.Body.String())
}
if got := state("alice-token"); got["likeCount"] != float64(1) || got["likedByUser"] != false {
t.Fatalf("state after unliking = %v", got)
}
h.do(http.MethodPost, "/media/like", "bob-token", `{"mediaKey":"rt-stats","value":false}`)
if got := state(""); got["likeCount"] != float64(0) {
t.Fatalf("anonymous state after both unlikes = %v", got)
}
h.do(http.MethodPost, "/media/like", "alice-token", `{"mediaKey":"rt-liked"}`)
liked := decode(t, h.do(http.MethodGet, "/media/liked", "alice-token", ""))["items"].([]any)
if len(liked) != 1 || liked[0].(map[string]any)["mediaKey"] != "rt-liked" {
t.Fatalf("liked = %v, want only rt-liked", liked)
}
// Views and watch sessions can be recorded without logging in.
if code := h.do(http.MethodPost, "/media/view?mediaKey=rt-stats", "", "").Code; code != http.StatusOK {
t.Fatalf("anonymous view = %d, want 200", code)
}
if code := h.do(http.MethodPost, "/media/view", "", "").Code; code != http.StatusBadRequest {
t.Fatalf("view without a key = %d, want 400", code)
}
if code := h.do(http.MethodPost, "/media/view-session", "", `{"mediaKey":"rt-stats","durationMs":1500}`).Code; code != http.StatusOK {
t.Fatalf("view session = %d, want 200", code)
}
for _, body := range []string{`{"mediaKey":"rt-stats"}`, `{"mediaKey":"rt-stats","durationMs":-3}`, `{"durationMs":10}`} {
if code := h.do(http.MethodPost, "/media/view-session", "", body).Code; code != http.StatusBadRequest {
t.Errorf("view session %q = %d, want 400", body, code)
}
}
if got := state(""); got["viewCount"] != float64(1) {
t.Fatalf("view count = %v, want 1", got["viewCount"])
}
}
func TestTagsAgainstPostgres(t *testing.T) {
h := newDBHarness(t)
for _, body := range []string{`{}`, `{"tag":" "}`, `{"tag":"` + strings.Repeat("x", 81) + `"}`, `nope`} {
if code := h.do(http.MethodPost, "/media/rt-tags/tags", "alice-token", body).Code; code != http.StatusBadRequest {
t.Errorf("add tag %q = %d, want 400", body, code)
}
}
if code := h.do(http.MethodPost, "/media/rt-tags/tags", "alice-token", `{"tag":"Funny"}`).Code; code != http.StatusCreated {
t.Fatalf("add tag = %d, want 201", code)
}
h.do(http.MethodPost, "/media/rt-tags/tags", "alice-token", `{"tag":"Funny"}`) // the same user's repeat is ignored
h.do(http.MethodPost, "/media/rt-tags/tags", "bob-token", `{"tag":"Quiet"}`)
for _, vote := range []string{"2", "-2", "\"up\""} {
if code := h.do(http.MethodPost, "/media/rt-tags/tags/Funny/vote", "alice-token", `{"vote":`+vote+`}`).Code; code != http.StatusBadRequest {
t.Errorf("vote %s = %d, want 400", vote, code)
}
}
h.do(http.MethodPost, "/media/rt-tags/tags/Funny/vote", "alice-token", `{"vote":1}`)
h.do(http.MethodPost, "/media/rt-tags/tags/Funny/vote", "bob-token", `{"vote":1}`)
h.do(http.MethodPost, "/media/rt-tags/tags/Quiet/vote", "alice-token", `{"vote":-1}`)
h.do(http.MethodPost, "/media/rt-tags/tags/Funny/vote", "bob-token", `{"vote":0}`) // clears bob's vote
tags := decode(t, h.do(http.MethodGet, "/media/rt-tags/tags", "", ""))["tags"].([]any)
if len(tags) != 2 {
t.Fatalf("tags = %v, want Funny and Quiet", tags)
}
first, second := tags[0].(map[string]any), tags[1].(map[string]any)
if first["tag"] != "Funny" || first["score"] != float64(1) || second["tag"] != "Quiet" || second["score"] != float64(-1) {
t.Fatalf("tags = %v, want Funny at 1 ahead of Quiet at -1", tags)
}
suggestions := decode(t, h.do(http.MethodGet, "/tags/suggestions?limit=5", "", ""))["tags"].([]any)
if len(suggestions) == 0 {
t.Fatal("suggestions are empty")
}
listed := decode(t, h.do(http.MethodGet, "/tags/funny/media?limit=10", "", ""))["items"].([]any)
if len(listed) != 1 || listed[0].(map[string]any)["mediaKey"] != "rt-tags" {
t.Fatalf("media for the tag = %v, want rt-tags (the tag matches ignoring case)", listed)
}
}
func TestPlaylistsAgainstPostgres(t *testing.T) {
h := newDBHarness(t)
create := func(token, name string) *httptest.ResponseRecorder {
return h.do(http.MethodPost, "/playlists", token, `{"name":`+fmt.Sprintf("%q", name)+`}`)
}
for _, name := range []string{"", " ", strings.Repeat("n", 121)} {
if code := create("alice-token", name).Code; code != http.StatusBadRequest {
t.Errorf("create %q = %d, want 400", name, code)
}
}
response := create("alice-token", "Road trip")
if response.Code != http.StatusCreated {
t.Fatalf("create = %d, body %s", response.Code, response.Body.String())
}
id := int64(dataOf(t, response)["playlist"].(map[string]any)["id"].(float64))
if again := create("alice-token", "Road trip"); int64(dataOf(t, again)["playlist"].(map[string]any)["id"].(float64)) != id {
t.Fatal("creating the same name again made a second playlist")
}
base := fmt.Sprintf("/playlists/%d", id)
// Another user cannot see, change or delete it.
if code := h.do(http.MethodGet, base, "bob-token", "").Code; code != http.StatusNotFound {
t.Errorf("bob reading alice's playlist = %d, want 404", code)
}
if code := h.do(http.MethodPost, base+"/items", "bob-token", `{"mediaKey":"rt-a"}`).Code; code != http.StatusNotFound {
t.Errorf("bob adding to alice's playlist = %d, want 404", code)
}
if code := h.do(http.MethodDelete, base, "bob-token", "").Code; code != http.StatusNotFound {
t.Errorf("bob deleting alice's playlist = %d, want 404", code)
}
if code := h.do(http.MethodGet, base+"/items", "", "").Code; code != http.StatusNotFound {
t.Errorf("anonymous items = %d, want 404", code)
}
if code := h.do(http.MethodPost, "/playlists/abc/items", "alice-token", `{"mediaKey":"rt-a"}`).Code; code != http.StatusBadRequest {
t.Errorf("bad playlist id = %d, want 400", code)
}
for _, key := range []string{"rt-a", "rt-b", "rt-c"} {
if code := h.do(http.MethodPost, base+"/items", "alice-token", `{"mediaKey":"`+key+`"}`).Code; code != http.StatusCreated {
t.Fatalf("add %s = %d, want 201", key, code)
}
}
h.do(http.MethodPost, base+"/items", "alice-token", `{"media_key":"rt-a"}`) // a repeat is ignored
if code := h.do(http.MethodPost, base+"/items", "alice-token", `{}`).Code; code != http.StatusBadRequest {
t.Errorf("add without a key = %d, want 400", code)
}
keys := func() []string {
var out []string
for _, item := range dataOf(t, h.do(http.MethodGet, base+"/items", "alice-token", ""))["items"].([]any) {
out = append(out, item.(map[string]any)["mediaKey"].(string))
}
return out
}
itemIDs := map[string]int64{}
for _, item := range dataOf(t, h.do(http.MethodGet, base+"/items", "alice-token", ""))["items"].([]any) {
entry := item.(map[string]any)
itemIDs[entry["mediaKey"].(string)] = int64(entry["id"].(float64))
}
if len(itemIDs) != 3 {
t.Fatalf("items = %v, want three distinct entries", itemIDs)
}
reorder := fmt.Sprintf(`{"ids":[%d,%d,%d]}`, itemIDs["rt-c"], itemIDs["rt-a"], itemIDs["rt-b"])
if code := h.do(http.MethodPatch, base+"/items/reorder", "alice-token", reorder).Code; code != http.StatusOK {
t.Fatalf("reorder = %d, want 200", code)
}
if got := strings.Join(keys(), ","); got != "rt-c,rt-a,rt-b" {
t.Fatalf("order after reorder = %s, want rt-c,rt-a,rt-b", got)
}
// The older field name still works, and another user's reorder changes nothing.
h.do(http.MethodPatch, base+"/items/reorder", "alice-token", fmt.Sprintf(`{"itemIds":[%d,%d,%d]}`, itemIDs["rt-b"], itemIDs["rt-c"], itemIDs["rt-a"]))
if got := strings.Join(keys(), ","); got != "rt-b,rt-c,rt-a" {
t.Fatalf("order after itemIds reorder = %s, want rt-b,rt-c,rt-a", got)
}
h.do(http.MethodPatch, base+"/items/reorder", "bob-token", reorder)
if got := strings.Join(keys(), ","); got != "rt-b,rt-c,rt-a" {
t.Fatalf("bob's reorder changed alice's playlist to %s", got)
}
tooMany := make([]string, maxPlaylistReorderItems+1)
for i := range tooMany {
tooMany[i] = "1"
}
if code := h.do(http.MethodPatch, base+"/items/reorder", "alice-token", `{"ids":[`+strings.Join(tooMany, ",")+`]}`).Code; code != http.StatusBadRequest {
t.Errorf("an oversized reorder = %d, want 400", code)
}
random := dataOf(t, h.do(http.MethodGet, base+"/random", "alice-token", ""))
if key, _ := random["mediaKey"].(string); key != "rt-a" && key != "rt-b" && key != "rt-c" {
t.Fatalf("random item = %v", random)
}
if code := h.do(http.MethodGet, base+"/random", "bob-token", "").Code; code != http.StatusNotFound {
t.Errorf("bob's random pick from alice's playlist = %d, want 404", code)
}
summary := dataOf(t, h.do(http.MethodGet, "/playlists/summary", "alice-token", ""))["playlists"].([]any)
if len(summary) != 1 || summary[0].(map[string]any)["item_count"] != float64(3) {
t.Fatalf("summary = %v, want one playlist with three items", summary)
}
if anonymous := dataOf(t, h.do(http.MethodGet, "/playlists/summary", "", ""))["playlists"].([]any); len(anonymous) != 0 {
t.Fatalf("anonymous summary = %v, want none", anonymous)
}
deleteBody := `{"mediaKey":"rt-a"}`
if code := h.do(http.MethodDelete, base+"/items", "bob-token", deleteBody).Code; code != http.StatusNotFound {
t.Errorf("bob removing alice's item = %d, want 404", code)
}
if code := h.do(http.MethodDelete, base+"/items", "alice-token", deleteBody).Code; code != http.StatusOK {
t.Errorf("alice removing her item = %d, want 200", code)
}
if code := h.do(http.MethodDelete, base+"/items", "alice-token", deleteBody).Code; code != http.StatusNotFound {
t.Errorf("removing it twice = %d, want 404", code)
}
if code := h.do(http.MethodDelete, base, "alice-token", "").Code; code != http.StatusOK {
t.Errorf("deleting the playlist = %d, want 200", code)
}
if code := h.do(http.MethodGet, base, "alice-token", "").Code; code != http.StatusNotFound {
t.Errorf("the deleted playlist = %d, want 404", code)
}
if listed := dataOf(t, h.do(http.MethodGet, "/playlists", "alice-token", ""))["playlists"].([]any); len(listed) != 0 {
t.Fatalf("playlists after deleting = %v, want none", listed)
}
}
+227
View File
@@ -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)
}
}