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) } } }) } }