refactor(backend): rename mediacore package to media
This commit is contained in:
1 parent
e8cb7c6c68
commit
75c08beec6
34 files changed
+837
-656
No files matched your search
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,126 @@
|
||||
package media
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
|
||||
sharedauth "repos.gfranz.ch/Gabriel20xx/shared/backend/auth"
|
||||
"repos.gfranz.ch/Gabriel20xx/shared/backend/authclient"
|
||||
)
|
||||
|
||||
// loginRequiredStore is a ProxyStore that always requires login, so the auth gate can be
|
||||
// exercised without a database.
|
||||
type loginRequiredStore struct{}
|
||||
|
||||
func (loginRequiredStore) LoginRequired(context.Context) (bool, error) { return true, nil }
|
||||
func (loginRequiredStore) SetLoginRequired(context.Context, bool) error { return nil }
|
||||
func (loginRequiredStore) IsSetupClaimed(context.Context) (bool, error) { return true, nil }
|
||||
func (loginRequiredStore) TryClaimSetup(context.Context) (bool, error) { return false, nil }
|
||||
func (loginRequiredStore) UnclaimSetup(context.Context) error { return nil }
|
||||
|
||||
// loginOffStore is loginRequiredStore with login switched off for the whole application.
|
||||
type loginOffStore struct{ loginRequiredStore }
|
||||
|
||||
func (loginOffStore) LoginRequired(context.Context) (bool, error) { return false, nil }
|
||||
|
||||
// TestMediaStreamAndThumbnailRequireLogin checks that anonymous requests to the media stream and
|
||||
// thumbnail routes are refused when login is required, before any database lookup or CarrierNode
|
||||
// call. The Core in this test has no database and no CarrierNode client, so reaching either would
|
||||
// panic.
|
||||
func TestMediaStreamAndThumbnailRequireLogin(t *testing.T) {
|
||||
auth := sharedauth.NewWithStore(loginRequiredStore{}, "session", false, "", "testproject")
|
||||
router := chi.NewRouter()
|
||||
New(Config{Auth: auth}).Mount(router)
|
||||
|
||||
for _, request := range []struct{ method, target string }{
|
||||
{http.MethodGet, "/media/stream?mediaKey=1"},
|
||||
{http.MethodHead, "/media/stream?mediaKey=1"},
|
||||
{http.MethodGet, "/media/thumb?mediaKey=1"},
|
||||
} {
|
||||
response := httptest.NewRecorder()
|
||||
router.ServeHTTP(response, httptest.NewRequest(request.method, request.target, nil))
|
||||
if response.Code != http.StatusUnauthorized {
|
||||
t.Errorf("%s %s status = %d, want %d", request.method, request.target, response.Code, http.StatusUnauthorized)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestMediaGateAllowsAnonymousWhenLoginIsOff checks the gate the media stream and thumbnail routes
|
||||
// use: with login disabled an anonymous request reaches the handler, as it does for the rest of
|
||||
// the application. The handler here is a stub, so no database or CarrierNode call is made.
|
||||
func TestMediaGateAllowsAnonymousWhenLoginIsOff(t *testing.T) {
|
||||
auth := sharedauth.NewWithStore(loginOffStore{}, "session", false, "", "testproject")
|
||||
reached := false
|
||||
gate := auth.RequireIfLoginRequired(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
reached = true
|
||||
}))
|
||||
for _, target := range []string{"/media/stream?mediaKey=1", "/media/thumb?mediaKey=1"} {
|
||||
reached = false
|
||||
response := httptest.NewRecorder()
|
||||
gate.ServeHTTP(response, httptest.NewRequest(http.MethodGet, target, nil))
|
||||
if !reached || response.Code != http.StatusOK {
|
||||
t.Errorf("GET %s with login off: reached = %v, status = %d; want reached and 200", target, reached, response.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// newRoleAuthGuard stands in for AuthGuard's GET /api/me. Each bearer token maps to one role, so a
|
||||
// test can act as a viewer, a moderator or an admin without a database.
|
||||
func newRoleAuthGuard(t *testing.T) *httptest.Server {
|
||||
t.Helper()
|
||||
roles := map[string]string{"viewer-token": "user", "moderator-token": "moderator", "admin-token": "admin"}
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
role, ok := roles[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":1,"username":"tester","role":%q}}`, role)
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
return server
|
||||
}
|
||||
|
||||
// TestOnlyModeratorsCanSeeHiddenMedia checks which callers get hidden media looked up at all.
|
||||
// Anonymous callers and viewers may not; moderators and admins may. With login off every caller
|
||||
// is the placeholder superadmin, as for the rest of the application. The active = FALSE filter
|
||||
// itself needs a database and is not exercised here.
|
||||
func TestOnlyModeratorsCanSeeHiddenMedia(t *testing.T) {
|
||||
guard := newRoleAuthGuard(t)
|
||||
login := sharedauth.NewWithStore(loginRequiredStore{}, "session", false, guard.URL, "testproject")
|
||||
loginOff := sharedauth.NewWithStore(loginOffStore{}, "session", false, guard.URL, "testproject")
|
||||
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
auth *sharedauth.Service
|
||||
token string
|
||||
want string
|
||||
}{
|
||||
{"anonymous with login required", login, "", "false"},
|
||||
{"viewer", login, "viewer-token", "false"},
|
||||
{"moderator", login, "moderator-token", "true"},
|
||||
{"admin", login, "admin-token", "true"},
|
||||
{"anonymous with login off", loginOff, "", "true"},
|
||||
} {
|
||||
router := chi.NewRouter()
|
||||
router.With(tc.auth.Optional).Get("/probe", func(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprint(w, canSeeHidden(r))
|
||||
})
|
||||
request := httptest.NewRequest(http.MethodGet, "/probe", nil)
|
||||
if tc.token != "" {
|
||||
request.AddCookie(&http.Cookie{Name: authclient.DefaultCookieName, Value: tc.token})
|
||||
}
|
||||
response := httptest.NewRecorder()
|
||||
router.ServeHTTP(response, request)
|
||||
if got := response.Body.String(); got != tc.want {
|
||||
t.Errorf("%s: canSeeHidden = %q, want %q", tc.name, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
package media
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"repos.gfranz.ch/Gabriel20xx/shared/backend/settings"
|
||||
)
|
||||
|
||||
// Migrate creates the settings table, then every table (and index) the media routes read or
|
||||
// write. Statements use CREATE TABLE/INDEX IF NOT EXISTS, so whichever service starts first
|
||||
// against a fresh database creates them and every other service's own startup is a no-op.
|
||||
//
|
||||
// users is created because several media tables reference it by foreign key. Identity itself lives
|
||||
// in AuthGuard, so the column is kept for foreign-key integrity and is not queried here.
|
||||
//
|
||||
// A service runs its own migration for any tables it alone owns (for example ContentScanner's
|
||||
// media_worker_jobs and CraftStudio's generated_media); those are not run here.
|
||||
func (c *Service) Migrate(ctx context.Context) error {
|
||||
if err := settings.Migrate(ctx, c.db); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, statement := range migrationStatements {
|
||||
if _, err := c.db.Exec(ctx, statement); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var migrationStatements = []string{
|
||||
`CREATE EXTENSION IF NOT EXISTS pgcrypto`,
|
||||
`CREATE EXTENSION IF NOT EXISTS pg_trgm`,
|
||||
`DROP INDEX IF EXISTS media_search_idx`,
|
||||
|
||||
`CREATE TABLE IF NOT EXISTS users (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
email TEXT NOT NULL UNIQUE,
|
||||
username TEXT,
|
||||
password_hash TEXT NOT NULL,
|
||||
avatar_url TEXT,
|
||||
bio TEXT,
|
||||
role TEXT NOT NULL DEFAULT 'user',
|
||||
permissions JSONB NOT NULL DEFAULT '{}'::jsonb,
|
||||
disabled BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
totp_secret TEXT,
|
||||
mfa_enabled BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
mfa_backup_codes JSONB,
|
||||
password_reset_token TEXT,
|
||||
password_reset_expires TIMESTAMPTZ,
|
||||
last_login_at TIMESTAMPTZ,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
)`,
|
||||
`CREATE UNIQUE INDEX IF NOT EXISTS users_username_unique ON users (LOWER(username)) WHERE username IS NOT NULL`,
|
||||
`CREATE INDEX IF NOT EXISTS users_email_idx ON users (LOWER(email))`,
|
||||
|
||||
`CREATE TABLE IF NOT EXISTS media (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
user_id BIGINT REFERENCES users(id) ON DELETE SET NULL,
|
||||
media_key TEXT NOT NULL UNIQUE,
|
||||
media_type TEXT NOT NULL DEFAULT 'unknown',
|
||||
app TEXT,
|
||||
source TEXT NOT NULL DEFAULT 'Filesystem',
|
||||
title TEXT,
|
||||
description TEXT,
|
||||
category TEXT,
|
||||
file_path TEXT,
|
||||
original_filename TEXT,
|
||||
active BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
content_scanner_processed BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
metadata JSONB NOT NULL DEFAULT '{}'::jsonb,
|
||||
width INT,
|
||||
height INT,
|
||||
duration_ms BIGINT,
|
||||
size_bytes BIGINT,
|
||||
is_vr BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
has_funscript BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
funscript_action_count INT,
|
||||
funscript_avg_speed REAL,
|
||||
funscript_max_speed REAL,
|
||||
speed REAL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
modified_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
)`,
|
||||
`ALTER TABLE media ADD COLUMN IF NOT EXISTS content_scanner_processed BOOLEAN NOT NULL DEFAULT FALSE`,
|
||||
`ALTER TABLE media ADD COLUMN IF NOT EXISTS funscript_action_count INT`,
|
||||
`ALTER TABLE media ADD COLUMN IF NOT EXISTS funscript_avg_speed REAL`,
|
||||
`ALTER TABLE media ADD COLUMN IF NOT EXISTS funscript_max_speed REAL`,
|
||||
`CREATE INDEX IF NOT EXISTS media_active_idx ON media (active)`,
|
||||
`CREATE INDEX IF NOT EXISTS media_file_path_idx ON media (file_path)`,
|
||||
`CREATE INDEX IF NOT EXISTS media_active_type_idx ON media (active, media_type)`,
|
||||
|
||||
`CREATE TABLE IF NOT EXISTS media_stats (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
media_id BIGINT REFERENCES media(id) ON DELETE CASCADE,
|
||||
media_key TEXT NOT NULL,
|
||||
user_id BIGINT REFERENCES users(id) ON DELETE SET NULL,
|
||||
stat_type TEXT NOT NULL,
|
||||
app TEXT,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
)`,
|
||||
`CREATE UNIQUE INDEX IF NOT EXISTS media_stats_like_unique ON media_stats (user_id, media_key) WHERE stat_type = 'like' AND user_id IS NOT NULL`,
|
||||
`CREATE INDEX IF NOT EXISTS media_stats_key_idx ON media_stats (media_key, stat_type)`,
|
||||
|
||||
`CREATE TABLE IF NOT EXISTS media_view_sessions (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
media_id BIGINT REFERENCES media(id) ON DELETE CASCADE,
|
||||
media_key TEXT NOT NULL,
|
||||
user_id BIGINT REFERENCES users(id) ON DELETE SET NULL,
|
||||
duration_ms BIGINT NOT NULL DEFAULT 0,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
)`,
|
||||
|
||||
`CREATE TABLE IF NOT EXISTS media_tags (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
media_id BIGINT REFERENCES media(id) ON DELETE CASCADE,
|
||||
media_key TEXT NOT NULL,
|
||||
tag TEXT NOT NULL,
|
||||
user_id BIGINT REFERENCES users(id) ON DELETE SET NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
UNIQUE (media_key, tag, user_id)
|
||||
)`,
|
||||
`CREATE INDEX IF NOT EXISTS media_tags_tag_idx ON media_tags (LOWER(tag))`,
|
||||
`CREATE INDEX IF NOT EXISTS media_tags_media_idx ON media_tags (media_key)`,
|
||||
// AI-attributed tags are inserted with user_id NULL; a plain UNIQUE(media_key, tag, user_id)
|
||||
// constraint does not dedupe NULLs against each other, so a dedicated partial index is
|
||||
// required to make repeated analysis runs idempotent instead of piling up duplicate tag rows.
|
||||
`CREATE UNIQUE INDEX IF NOT EXISTS media_tags_ai_tag_unique ON media_tags (media_key, tag) WHERE user_id IS NULL`,
|
||||
|
||||
`CREATE TABLE IF NOT EXISTS media_tag_votes (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
media_key TEXT NOT NULL,
|
||||
tag TEXT NOT NULL,
|
||||
user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
vote SMALLINT NOT NULL CHECK (vote IN (-1, 1)),
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
UNIQUE (media_key, tag, user_id)
|
||||
)`,
|
||||
|
||||
`CREATE TABLE IF NOT EXISTS playlists (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
name TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
UNIQUE (user_id, name)
|
||||
)`,
|
||||
`CREATE TABLE IF NOT EXISTS playlist_items (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
playlist_id BIGINT NOT NULL REFERENCES playlists(id) ON DELETE CASCADE,
|
||||
media_id BIGINT REFERENCES media(id) ON DELETE CASCADE,
|
||||
media_key TEXT NOT NULL,
|
||||
position INT,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
UNIQUE (playlist_id, media_key)
|
||||
)`,
|
||||
|
||||
`CREATE TABLE IF NOT EXISTS thumbnails (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
media_id BIGINT REFERENCES media(id) ON DELETE SET NULL,
|
||||
source_path TEXT UNIQUE,
|
||||
width INT,
|
||||
height INT,
|
||||
file_size_bytes BIGINT,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
)`,
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package media
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
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")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,515 @@
|
||||
package media
|
||||
|
||||
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 ./media/
|
||||
|
||||
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,
|
||||
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)
|
||||
h.insertMedia(t, "rt-stats", "video", "rt-stats.mp4", true)
|
||||
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")
|
||||
}
|
||||
// A tag keeps its rows after its media is hidden or leaves the library. Only the library's
|
||||
// media is listed for the tag, so a tag's examples never point at a thumbnail that is not found.
|
||||
h.insertMedia(t, "rt-tags", "video", "tagged/clip.mp4", true)
|
||||
h.insertMedia(t, "rt-tags-hidden", "video", "tagged/hidden.mp4", false)
|
||||
h.insertMedia(t, "rt-tags-new", "video", "tagged/new.mp4", true)
|
||||
if _, err := h.pool.Exec(context.Background(), `UPDATE media SET content_scanner_processed = TRUE WHERE media_key IN ('rt-tags', 'rt-tags-hidden')`); err != nil {
|
||||
t.Fatalf("mark media processed: %v", err)
|
||||
}
|
||||
h.do(http.MethodPost, "/media/rt-tags-hidden/tags", "alice-token", `{"tag":"Funny"}`)
|
||||
h.do(http.MethodPost, "/media/rt-tags-new/tags", "alice-token", `{"tag":"Funny"}`)
|
||||
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 only rt-tags (the hidden and unprocessed items are not listed)", listed)
|
||||
}
|
||||
|
||||
// Without a limit, suggestions list every tag, not only the first 1000.
|
||||
if _, err := h.pool.Exec(context.Background(), `INSERT INTO media_tags (media_key, tag, user_id) SELECT 'rt-many', 'bulk ' || g, NULL FROM generate_series(1, 1001) AS g`); err != nil {
|
||||
t.Fatalf("insert many tags: %v", err)
|
||||
}
|
||||
every := decode(t, h.do(http.MethodGet, "/tags/suggestions", "", ""))["tags"].([]any)
|
||||
if len(every) <= 1000 {
|
||||
t.Fatalf("suggestions without a limit = %d tags, want every tag (more than 1000)", len(every))
|
||||
}
|
||||
|
||||
// The tag's media is paged, and the pagination reports the whole count so the page can reach every page.
|
||||
if _, err := h.pool.Exec(context.Background(), `INSERT INTO media (media_key, media_type, file_path, active, content_scanner_processed) SELECT 'rt-page-' || g, 'video', 'paged/' || g || '.mp4', TRUE, TRUE FROM generate_series(1, 30) AS g`); err != nil {
|
||||
t.Fatalf("insert paged media: %v", err)
|
||||
}
|
||||
if _, err := h.pool.Exec(context.Background(), `INSERT INTO media_tags (media_key, tag, user_id) SELECT 'rt-page-' || g, 'Paged', NULL FROM generate_series(1, 30) AS g`); err != nil {
|
||||
t.Fatalf("tag paged media: %v", err)
|
||||
}
|
||||
pageTwo := decode(t, h.do(http.MethodGet, "/tags/paged/media?page=2&limit=24", "", ""))
|
||||
pagination, _ := pageTwo["pagination"].(map[string]any)
|
||||
if items := pageTwo["items"].([]any); len(items) != 6 || pagination["total"] != float64(30) || pagination["totalPages"] != float64(2) || pagination["page"] != float64(2) {
|
||||
t.Fatalf("page 2 at 24 per page = %d items, pagination %v; want 6 items on page 2 of 2, total 30", len(items), pagination)
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package media
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
|
||||
sharedauth "repos.gfranz.ch/Gabriel20xx/shared/backend/auth"
|
||||
)
|
||||
|
||||
// TestMediaRoutesRefuseAnonymousRequests walks the media route table: every route mounted behind
|
||||
// Require answers 401 to a caller with no session, before any handler runs. The Service has no
|
||||
// database or CarrierNode client, so a request that got past the gate would panic.
|
||||
func TestMediaRoutesRefuseAnonymousRequests(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.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)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user