sonda/internal/api/http/stream_test.go
tgiachi 46463846b3 feat(library): named media libraries managed through the API
- feat(storage): libraries table (name, path); audio_files points at a library
  by id instead of repeating the root path; migration 0005 for both drivers
  turns every existing root into a library and keeps file ids, tracks and the
  missing flag
- feat(library): Libraries service validates names and paths: absolute, an
  existing directory, never the filesystem root, never inside or around
  another library (checked on real paths, so symlinks cannot hide an overlap)
- feat(api): admin-only GET/POST /libraries, PATCH/DELETE /libraries/{id} and
  POST /libraries/{id}/scan; deleting a library drops its index entries and
  keeps tracks and listening history
- feat(library): the scanner and the scan manager work on libraries; scanning
  with no libraries answers 409 no_libraries
- feat(streaming): the library directory comes from the database instead of
  a configured list of roots
- breaking(config): library.roots is removed; an old config fails with a hint
  to use POST /api/v1/libraries
- test: CRUD and duplicates on both databases, path change keeps files,
  upgrade of a database written before libraries existed
2026-11-11 13:30:25 +01:00

256 lines
8.4 KiB
Go

package httpapi
import (
"bytes"
"context"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strconv"
"testing"
"time"
"codeberg.org/squidd/sonda/internal/streaming"
)
type mapSource map[int64]streaming.File
func (m mapSource) PlayableFile(_ context.Context, id int64) (streaming.File, error) {
f, ok := m[id]
if !ok {
return streaming.File{}, streaming.ErrNotFound
}
return f, nil
}
// streamFixture serves track 1 (a 1000-byte mp3), track 2 (file gone from
// disk) and track 3 (a path that escapes the root).
type streamFixture struct {
h http.Handler
token string
data []byte
}
func newStreamFixture(t *testing.T) streamFixture {
t.Helper()
root := t.TempDir()
data := make([]byte, 1000)
for i := range data {
data[i] = byte(i % 251)
}
if err := os.WriteFile(filepath.Join(root, "song.mp3"), data, 0o644); err != nil {
t.Fatal(err)
}
src := mapSource{
1: {Root: root, RelPath: "song.mp3"},
2: {Root: root, RelPath: "gone.mp3"},
3: {Root: root, RelPath: "../escape.mp3"},
}
h := newTestAPIWith(t, func(d *Deps) { d.Streams = streaming.NewService(src) })
return streamFixture{h: h, token: registerAndLogin(t, h), data: data}
}
func (f streamFixture) get(t *testing.T, method, path string, headers map[string]string) *httptest.ResponseRecorder {
t.Helper()
req := httptest.NewRequest(method, path, nil)
for k, v := range headers {
req.Header.Set(k, v)
}
rec := httptest.NewRecorder()
f.h.ServeHTTP(rec, req)
return rec
}
func (f streamFixture) auth() map[string]string {
return map[string]string{"Authorization": "Bearer " + f.token}
}
func TestStreamRequiresAuth(t *testing.T) {
f := newStreamFixture(t)
for _, method := range []string{"GET", "HEAD"} {
if rec := f.get(t, method, "/api/v1/tracks/1/stream", nil); rec.Code != http.StatusUnauthorized {
t.Errorf("%s without token: %d", method, rec.Code)
}
}
if rec := f.get(t, "GET", "/api/v1/tracks/1/stream?access_token=garbage", nil); rec.Code != http.StatusUnauthorized {
t.Errorf("garbage query token: %d", rec.Code)
}
// The header wins: a bad header is not rescued by a good query token.
rec := f.get(t, "GET", "/api/v1/tracks/1/stream?access_token="+f.token, map[string]string{"Authorization": "Bearer garbage"})
if rec.Code != http.StatusUnauthorized {
t.Errorf("bad header with good query token: %d", rec.Code)
}
}
// A header that is present but not a Bearer token is not rescued by the query.
func TestStreamIgnoresQueryTokenWhenAnyAuthorizationHeaderIsPresent(t *testing.T) {
f := newStreamFixture(t)
for _, header := range []string{f.token, "Basic " + f.token, "Token x"} {
rec := f.get(t, "GET", "/api/v1/tracks/1/stream?access_token="+f.token, map[string]string{"Authorization": header})
if rec.Code != http.StatusUnauthorized {
t.Errorf("Authorization %.12q... with a valid query token: %d, want 401", header, rec.Code)
}
}
}
func TestStreamAcceptsHeaderAndQueryToken(t *testing.T) {
f := newStreamFixture(t)
if rec := f.get(t, "GET", "/api/v1/tracks/1/stream", f.auth()); rec.Code != http.StatusOK {
t.Errorf("header token: %d", rec.Code)
}
if rec := f.get(t, "GET", "/api/v1/tracks/1/stream?access_token="+f.token, nil); rec.Code != http.StatusOK {
t.Errorf("query token: %d", rec.Code)
}
}
func TestQueryTokenIsAcceptedOnlyForStreaming(t *testing.T) {
f := newStreamFixture(t)
for _, path := range []string{"/api/v1/auth/me", "/api/v1/users", "/api/v1/library/scan"} {
if rec := f.get(t, "GET", path+"?access_token="+f.token, nil); rec.Code != http.StatusUnauthorized {
t.Errorf("%s accepted a token in the URL: %d", path, rec.Code)
}
}
}
func TestStreamFullFile(t *testing.T) {
f := newStreamFixture(t)
rec := f.get(t, "GET", "/api/v1/tracks/1/stream", f.auth())
if rec.Code != http.StatusOK || !bytes.Equal(rec.Body.Bytes(), f.data) {
t.Fatalf("status %d, %d bytes", rec.Code, rec.Body.Len())
}
want := map[string]string{
"Content-Type": "audio/mpeg",
"Content-Length": "1000",
"Accept-Ranges": "bytes",
"X-Content-Type-Options": "nosniff",
"Referrer-Policy": "no-referrer",
"Cache-Control": "private, no-cache",
}
for k, v := range want {
if got := rec.Header().Get(k); got != v {
t.Errorf("%s = %q, want %q", k, got, v)
}
}
if rec.Header().Get("Last-Modified") == "" {
t.Error("Last-Modified missing")
}
}
func TestStreamHead(t *testing.T) {
f := newStreamFixture(t)
rec := f.get(t, "HEAD", "/api/v1/tracks/1/stream", f.auth())
if rec.Code != http.StatusOK || rec.Body.Len() != 0 {
t.Fatalf("HEAD: %d with a %d byte body", rec.Code, rec.Body.Len())
}
if rec.Header().Get("Content-Length") != "1000" || rec.Header().Get("Content-Type") != "audio/mpeg" ||
rec.Header().Get("Accept-Ranges") != "bytes" {
t.Errorf("HEAD headers = %v", rec.Header())
}
}
func TestStreamRanges(t *testing.T) {
f := newStreamFixture(t)
tests := []struct {
name, header string
first, last int
}{
{"first bytes", "bytes=0-99", 0, 99},
{"middle", "bytes=100-199", 100, 199},
{"open ended", "bytes=900-", 900, 999},
{"suffix", "bytes=-50", 950, 999},
{"single byte", "bytes=5-5", 5, 5},
{"end beyond the file is clamped", "bytes=990-5000", 990, 999},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
h := f.auth()
h["Range"] = tt.header
rec := f.get(t, "GET", "/api/v1/tracks/1/stream", h)
if rec.Code != http.StatusPartialContent {
t.Fatalf("status = %d, want 206", rec.Code)
}
wantRange := "bytes " + strconv.Itoa(tt.first) + "-" + strconv.Itoa(tt.last) + "/1000"
if got := rec.Header().Get("Content-Range"); got != wantRange {
t.Errorf("Content-Range = %q, want %q", got, wantRange)
}
if got := rec.Header().Get("Content-Length"); got != strconv.Itoa(tt.last-tt.first+1) {
t.Errorf("Content-Length = %q", got)
}
if !bytes.Equal(rec.Body.Bytes(), f.data[tt.first:tt.last+1]) {
t.Error("body does not match the requested bytes")
}
})
}
}
func TestStreamRangeOnHeadHasNoBody(t *testing.T) {
f := newStreamFixture(t)
h := f.auth()
h["Range"] = "bytes=0-9"
rec := f.get(t, "HEAD", "/api/v1/tracks/1/stream", h)
if rec.Code != http.StatusPartialContent || rec.Body.Len() != 0 || rec.Header().Get("Content-Length") != "10" {
t.Fatalf("HEAD with Range: %d, body %d, length %q", rec.Code, rec.Body.Len(), rec.Header().Get("Content-Length"))
}
}
func TestStreamUnsatisfiableRange(t *testing.T) {
f := newStreamFixture(t)
// Well-formed but outside the file: 416 and the real size in Content-Range.
for _, rng := range []string{"bytes=2000-3000", "bytes=1000-"} {
h := f.auth()
h["Range"] = rng
rec := f.get(t, "GET", "/api/v1/tracks/1/stream", h)
if rec.Code != http.StatusRequestedRangeNotSatisfiable {
t.Errorf("Range %q: status %d, want 416", rng, rec.Code)
continue
}
if got := rec.Header().Get("Content-Range"); got != "bytes */1000" {
t.Errorf("Range %q: Content-Range = %q, want %q", rng, got, "bytes */1000")
}
}
// Malformed: also refused with 416, and no audio is sent.
for _, rng := range []string{"bytes=abc", "bytes=9-1"} {
h := f.auth()
h["Range"] = rng
rec := f.get(t, "GET", "/api/v1/tracks/1/stream", h)
if rec.Code != http.StatusRequestedRangeNotSatisfiable || bytes.Contains(rec.Body.Bytes(), f.data[:50]) {
t.Errorf("Range %q: status %d", rng, rec.Code)
}
}
}
func TestStreamConditionalRequest(t *testing.T) {
f := newStreamFixture(t)
h := f.auth()
h["If-Modified-Since"] = time.Now().Add(time.Hour).UTC().Format(http.TimeFormat)
rec := f.get(t, "GET", "/api/v1/tracks/1/stream", h)
if rec.Code != http.StatusNotModified || rec.Body.Len() != 0 {
t.Fatalf("If-Modified-Since in the future: %d with %d bytes", rec.Code, rec.Body.Len())
}
}
func TestStreamErrors(t *testing.T) {
f := newStreamFixture(t)
tests := []struct {
name, path string
status int
code string
}{
{"unknown track", "/api/v1/tracks/99/stream", http.StatusNotFound, "track_not_found"},
{"file gone from disk", "/api/v1/tracks/2/stream", http.StatusNotFound, "file_missing"},
{"path escaping the root", "/api/v1/tracks/3/stream", http.StatusNotFound, "file_missing"},
{"id is not a number", "/api/v1/tracks/abc/stream", http.StatusBadRequest, "invalid_input"},
{"id is zero", "/api/v1/tracks/0/stream", http.StatusBadRequest, "invalid_input"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
r := do(t, f.h, "GET", tt.path, f.token, nil)
if r.Code != tt.status || errCode(r) != tt.code {
t.Fatalf("%d %v, want %d %s", r.Code, r.Body, tt.status, tt.code)
}
})
}
}