Files
minstrel/internal/auth/admin_test.go
T
bvandeusenandClaude Opus 5.5 cfdbfa30e3
release / web (push) Successful in 1m41s
release / go (push) Successful in 2m4s
release / govulncheck (push) Successful in 23s
release / integration (push) Successful in 3m5s
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 4m35s
release / Build signed APK (push) Canceled after 3m53s
test(backup, scrobble, playevents, recsettings, apierror, auth, providers): merge repeated cases (#8299)
- backup: schema coverage's three tests and the three AWS signing
  examples, one table each.
- scrobble: Qualifies' six boundary tests; the ListenBrainz client's
  refusal mapping, twelve tests of the same rule across three calls, one
  table over call x status; the two similarity lookups' success and URL
  tests, one table.
- playevents: the skip rule's three plays share one fixture. Dropped
  TestRecordPlayEnded_SubThreshold_NoEnqueue: the writer only calls
  scrobble.MaybeEnqueue, whose own test and Qualifies' table hold that
  case; the qualifying-play test still proves the writer calls it.
- recsettings: the three tag-scale tests share one database reset.
- apierror: Error() and From, one test each; auth: RequireAdmin's three.
- providers: GetJSON's not-found and transient answers, one table. Its
  two 401 tests expected the same answer with and without
  TreatAuthAsTransient, which changes only the error's text; the table
  says so.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 15:16:20 -05:00

73 lines
2.4 KiB
Go

package auth
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/Fabled-Sword/minstrel/internal/apierror"
"github.com/Fabled-Sword/minstrel/internal/db/dbq"
)
// injectUser returns a copy of r with the given user stored under userCtxKey.
// This mirrors what RequireUser does at runtime.
func injectUser(r *http.Request, u dbq.User) *http.Request {
ctx := context.WithValue(r.Context(), userCtxKey, u)
return r.WithContext(ctx)
}
// assertErrorCode checks the response is the /api error envelope with code.
// Clients read only that shape, so a flat {"error":"code"} must fail here.
func assertErrorCode(t *testing.T, w *httptest.ResponseRecorder, code string) {
t.Helper()
var env apierror.Body
if err := json.Unmarshal(w.Body.Bytes(), &env); err != nil {
t.Fatalf("body %q is not the error envelope: %v", w.Body.String(), err)
}
if env.Error.Code != code {
t.Errorf("error.code = %q, want %q; body %q", env.Error.Code, code, w.Body.String())
}
}
// RequireAdmin passes an admin through, answers anyone else 403, and answers
// 500 when no user is in the context at all (RequireUser was not mounted in
// front of it), always as the /api error envelope.
func TestRequireAdmin(t *testing.T) {
for _, tc := range []struct {
name string
user *dbq.User
wantCode int
wantErr string // "" when the handler is reached
}{
{"an admin", &dbq.User{IsAdmin: true}, http.StatusOK, ""},
{"a listener", &dbq.User{}, http.StatusForbidden, "not_authorized"},
{"no user in the context", nil, http.StatusInternalServerError, "server_error"},
} {
t.Run(tc.name, func(t *testing.T) {
reached := false
h := RequireAdmin()(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
reached = true
w.WriteHeader(http.StatusOK)
}))
req := httptest.NewRequest(http.MethodGet, "/api/admin/test", nil)
if tc.user != nil {
req = injectUser(req, *tc.user)
}
w := httptest.NewRecorder()
h.ServeHTTP(w, req)
if w.Code != tc.wantCode || reached != (tc.wantErr == "") {
t.Fatalf("status %d, handler reached %v; want %d, %v", w.Code, reached, tc.wantCode, tc.wantErr == "")
}
if tc.wantErr != "" {
assertErrorCode(t, w, tc.wantErr)
if ct := w.Header().Get("Content-Type"); !strings.HasPrefix(ct, "application/json") {
t.Errorf("Content-Type = %q, want application/json", ct)
}
}
})
}
}