package api import ( "context" "encoding/json" "fmt" "io" "log/slog" "net/http" "net/http/httptest" "strconv" "strings" "testing" "time" "github.com/go-chi/chi/v5" "github.com/jackc/pgx/v5/pgxpool" "github.com/Fabled-Sword/minstrel/internal/apierror" "github.com/Fabled-Sword/minstrel/internal/auth" "github.com/Fabled-Sword/minstrel/internal/backup" "github.com/Fabled-Sword/minstrel/internal/config" "github.com/Fabled-Sword/minstrel/internal/db/dbq" "github.com/Fabled-Sword/minstrel/internal/eventbus" "github.com/Fabled-Sword/minstrel/internal/playevents" ) // publicRoutes are the API routes a request without a session may reach. // Every other route answers 401 to it. The stream routes take a session or // a signed token and check it themselves. var publicRoutes = map[string]bool{ "POST /api/auth/login": true, "POST /api/auth/register": true, "GET /api/auth/setup-status": true, "POST /api/auth/restore": true, "POST /api/auth/forgot-password": true, "POST /api/auth/reset-password": true, "GET /api/tracks/{id}/stream": true, "GET /api/tracks/{id}/stream.{ext}": true, "GET /api/tracks/{id}/leveled.flac": true, } // mountedAPI is the production router: every route Mount registers, behind // the middleware it registers them with. func mountedAPI(t *testing.T) (chi.Router, *handlers) { t.Helper() h, _ := testHandlers(t) r := chi.NewRouter() w := playevents.NewWriter(h.pool, slog.New(slog.NewTextHandler(io.Discard, nil)), 30*time.Minute, 0.5, 30000) Mount(r, h.pool, h.logger, w, config.RecommendationConfig{RadioSize: 50, RadioSizeMax: 200, RecentlyPlayedHours: 1}, h.recSettings, h.quarantine, h.tracks, h.playlists, h.coverart, h.coverSettings, h.tagSettings, h.scanner, h.scanCfg, h.dataDir, nil, eventbus.New(), nil, nil, h.netSettings, nil, nil, nil, nil, backup.NewService(h.pool, h.logger, "test"), nil) return r, h } // mountedRoute is one registered method and pattern, with a request path // that fills each {param} in. type mountedRoute struct{ method, pattern, path string } func mountedRoutes(t *testing.T, r chi.Router) []mountedRoute { t.Helper() var out []mountedRoute err := chi.Walk(r, func(method, pattern string, _ http.Handler, _ ...func(http.Handler) http.Handler) error { path := pattern for strings.Contains(path, "{") { open := strings.Index(path, "{") end := strings.Index(path[open:], "}") path = path[:open] + "00000000-0000-0000-0000-000000000001" + path[open+end+1:] } out = append(out, mountedRoute{method, pattern, strings.TrimSuffix(path, "/*")}) return nil }) if err != nil { t.Fatalf("walk routes: %v", err) } if len(out) < 50 { t.Fatalf("walked %d routes; Mount registers far more, so the walk is not seeing them", len(out)) } return out } // sessionCookie signs user in the way the web app does. func sessionCookie(t *testing.T, pool *pgxpool.Pool, user dbq.User) *http.Cookie { t.Helper() token, err := auth.MintSessionToken() if err != nil { t.Fatalf("mint session: %v", err) } if _, err := dbq.New(pool).InsertSession(context.Background(), dbq.InsertSessionParams{ UserID: user.ID, TokenHash: auth.HashSessionToken(token), UserAgent: "test-agent", Ip: "192.0.2.1", }); err != nil { t.Fatalf("insert session: %v", err) } return &http.Cookie{Name: auth.SessionCookieName, Value: token} } // reachedHandler stands for a request that got past the access checks into a // handler, which then panicked on the walk's bare wiring. const reachedHandler = -1 // serveGuarded serves one request and returns its status, or reachedHandler // when a handler panicked. Without the recover, one route mounted outside its // group would take down the whole test binary and hide every other failure. func serveGuarded(r http.Handler, req *http.Request) (code int) { defer func() { if recover() != nil { code = reachedHandler } }() w := httptest.NewRecorder() r.ServeHTTP(w, req) return w.Code } func describeCode(code int) string { if code == reachedHandler { return "from inside its handler (it ran, and panicked)" } return strconv.Itoa(code) } // Every API route but the public ones answers 401 without a session, and // every admin route answers 403 to a signed-in user who is not an admin. // The routes come from the production router, so a route registered outside // its group fails here. func TestMountedRoutes_RequireASessionAndAdminRoutesAnAdmin(t *testing.T) { r, h := mountedAPI(t) listener := seedUser(t, h.pool, "listener", "pw", false) cookie := sessionCookie(t, h.pool, listener) var admin int public := map[string]bool{} for _, rt := range mountedRoutes(t, r) { key := rt.method + " " + rt.pattern if publicRoutes[key] { public[key] = true continue } if code := serveGuarded(r, httptest.NewRequest(rt.method, rt.path, nil)); code != http.StatusUnauthorized { t.Errorf("%s answered %s without a session, want 401", key, describeCode(code)) } if !strings.HasPrefix(rt.pattern, "/api/admin/") { continue } admin++ req := httptest.NewRequest(rt.method, rt.path, nil) req.AddCookie(cookie) if code := serveGuarded(r, req); code != http.StatusForbidden { t.Errorf("%s answered %s to a non-admin, want 403", key, describeCode(code)) } } if admin < 50 { t.Errorf("only %d admin routes walked; the admin group is not being reached", admin) } for key := range publicRoutes { if !public[key] { t.Errorf("public route %s is not registered", key) } } } // An id that is not a UUID answers 400, and one that names nothing answers // 404, on every route that looks a record up by id. The error message names // what was not found where the clients show it. func TestMountedRoutes_AMalformedIDIs400AndAnUnknownOneIs404(t *testing.T) { r, h := mountedAPI(t) listener := seedUser(t, h.pool, "listener", "pw", false) cookie := sessionCookie(t, h.pool, listener) const unknown = "00000000-0000-0000-0000-000000000099" for _, tc := range []struct { method, path string // path holds %s where the id goes wantMessage string // on the 404, when the clients show it }{ {http.MethodGet, "/api/tracks/%s", ""}, {http.MethodGet, "/api/albums/%s", ""}, {http.MethodGet, "/api/artists/%s", ""}, {http.MethodGet, "/api/artists/%s/tracks", ""}, {http.MethodGet, "/api/albums/%s/cover", "album not found"}, {http.MethodGet, "/api/tracks/%s/stream", "track not found"}, {http.MethodGet, "/api/playlists/%s", ""}, {http.MethodPost, "/api/likes/tracks/%s", ""}, {http.MethodGet, "/api/radio?seed_track=%s", ""}, } { for _, id := range []string{"not-a-uuid", unknown} { req := httptest.NewRequest(tc.method, fmt.Sprintf(tc.path, id), nil) req.AddCookie(cookie) w := httptest.NewRecorder() r.ServeHTTP(w, req) want := http.StatusBadRequest if id == unknown { want = http.StatusNotFound } if w.Code != want { t.Errorf("%s %s answered %d, want %d", tc.method, fmt.Sprintf(tc.path, id), w.Code, want) continue } if id == unknown && tc.wantMessage != "" { var body apierror.Body _ = json.Unmarshal(w.Body.Bytes(), &body) if body.Error.Message != tc.wantMessage { t.Errorf("%s %s message = %q, want %q", tc.method, tc.path, body.Error.Message, tc.wantMessage) } } } } } // The routes the web app and the phone call are registered: a missing one // answers 404 rather than reaching the session check. func TestMountedRoutes_TheClientsRoutesAreRegistered(t *testing.T) { r, _ := mountedAPI(t) for _, p := range []string{ "/api/artists", "/api/artists/00000000-0000-0000-0000-000000000001", "/api/albums/00000000-0000-0000-0000-000000000001", "/api/albums/00000000-0000-0000-0000-000000000001/cover", "/api/tracks/00000000-0000-0000-0000-000000000001", "/api/search?q=x", "/api/library/genres", "/api/library/years", "/api/admin/library/missing", "/api/admin/library/fingerprints", "/api/admin/library/fingerprint-settings", "/api/admin/library/duplicates", } { w := httptest.NewRecorder() r.ServeHTTP(w, httptest.NewRequest(http.MethodGet, p, nil)) if w.Code != http.StatusUnauthorized { t.Errorf("GET %s answered %d, want 401 (404 means the route is not registered)", p, w.Code) } } }