test(api): one walk over the mounted router checks access and id errors (#8295)
release / go (push) Successful in 2m3s
release / web (push) Successful in 1m29s
release / govulncheck (push) Successful in 19s
release / integration (push) Successful in 3m29s
release / Attach APK to the Release (tag releases only) (push) Canceled after 0s
release / Build + push container image (push) Canceled after 0s
release / Publish the release image to GHCR (dispatch only) (push) Canceled after 0s
release / Verify release artifacts (tag releases only) (push) Canceled after 0s
release / android (push) Canceled after 3m28s
release / Build signed APK (push) Canceled after 3m3s
release / go (push) Successful in 2m3s
release / web (push) Successful in 1m29s
release / govulncheck (push) Successful in 19s
release / integration (push) Successful in 3m29s
release / Attach APK to the Release (tag releases only) (push) Canceled after 0s
release / Build + push container image (push) Canceled after 0s
release / Publish the release image to GHCR (dispatch only) (push) Canceled after 0s
release / Verify release artifacts (tag releases only) (push) Canceled after 0s
release / android (push) Canceled after 3m28s
release / Build signed APK (push) Canceled after 3m3s
The access tests checked hand-built routers that applied RequireAdmin themselves, so none could catch a production route mounted outside its group. One test now walks every route Mount registers: each non-public route answers 401 without a session, and each admin route 403 to a listener. The per-endpoint malformed-id (400) and unknown-id (404) tests become one table over the real routes. Profile updates, playlist kind filters and empty searches each fold into one table; writeErr's envelope tests move to apierror.Write, which they were testing. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,210 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"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}
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
anon := httptest.NewRecorder()
|
||||
r.ServeHTTP(anon, httptest.NewRequest(rt.method, rt.path, nil))
|
||||
if anon.Code != http.StatusUnauthorized {
|
||||
t.Errorf("%s answered %d without a session, want 401", key, anon.Code)
|
||||
}
|
||||
if !strings.HasPrefix(rt.pattern, "/api/admin/") {
|
||||
continue
|
||||
}
|
||||
admin++
|
||||
req := httptest.NewRequest(rt.method, rt.path, nil)
|
||||
req.AddCookie(cookie)
|
||||
signedIn := httptest.NewRecorder()
|
||||
r.ServeHTTP(signedIn, req)
|
||||
if signedIn.Code != http.StatusForbidden {
|
||||
t.Errorf("%s answered %d to a non-admin, want 403", key, signedIn.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)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user