package auth import ( "context" "encoding/json" "io" "net/http" "net/http/httptest" "strings" "sync" "testing" "repos.gfranz.ch/Gabriel20xx/shared/backend/authclient" ) // recordedCall is one request a fakeAuthGuard received. type recordedCall struct { Method string Path string Forwarded string Authorization string Body map[string]any } // fakeAuthGuard is an httptest AuthGuard that records every call and answers from a route table. type fakeAuthGuard struct { mu sync.Mutex calls []recordedCall routes map[string]func(w http.ResponseWriter, body map[string]any) server *httptest.Server } func newFakeAuthGuard(t *testing.T) *fakeAuthGuard { t.Helper() f := &fakeAuthGuard{routes: map[string]func(http.ResponseWriter, map[string]any){}} f.server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { raw, _ := io.ReadAll(r.Body) var body map[string]any _ = json.Unmarshal(raw, &body) f.mu.Lock() f.calls = append(f.calls, recordedCall{ Method: r.Method, Path: r.URL.Path, Forwarded: r.Header.Get("X-Forwarded-For"), Authorization: r.Header.Get("Authorization"), Body: body, }) route := f.routes[r.Method+" "+r.URL.Path] f.mu.Unlock() if route == nil { http.NotFound(w, r) return } route(w, body) })) t.Cleanup(f.server.Close) return f } func (f *fakeAuthGuard) handle(route string, handler func(w http.ResponseWriter, body map[string]any)) { f.mu.Lock() defer f.mu.Unlock() f.routes[route] = handler } func (f *fakeAuthGuard) reply(route string, status int, payload any) { f.handle(route, func(w http.ResponseWriter, _ map[string]any) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(status) _ = json.NewEncoder(w).Encode(payload) }) } func (f *fakeAuthGuard) callsTo(route string) []recordedCall { f.mu.Lock() defer f.mu.Unlock() var matched []recordedCall for _, call := range f.calls { if call.Method+" "+call.Path == route { matched = append(matched, call) } } return matched } func (f *fakeAuthGuard) service(t *testing.T, options ...ServiceOption) (*Service, *fakeProxyStore) { t.Helper() store := &fakeProxyStore{loginRequired: true} return NewWithStore(store, "session", false, f.server.URL, "testproject", options...), store } func jsonRequest(method, target, body string) *http.Request { req := httptest.NewRequest(method, target, strings.NewReader(body)) req.Header.Set("Content-Type", "application/json") return req } func withSession(req *http.Request, token string) *http.Request { req.AddCookie(&http.Cookie{Name: authclient.DefaultCookieName, Value: token}) return req } func withUser(req *http.Request, user *ProxyUser) *http.Request { return req.WithContext(context.WithValue(req.Context(), proxyUserContextKey, user)) } func decodeBody(t *testing.T, rec *httptest.ResponseRecorder) map[string]any { t.Helper() var out map[string]any if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil { t.Fatalf("response body %q is not JSON: %v", rec.Body.String(), err) } return out } func TestLoginForwardsTheVerifiedClientAddressToAuthGuard(t *testing.T) { tests := []struct { name string trusted string remote string forwarded string want string }{ {"peer without trusted proxies", "", "203.0.113.7:4444", "", "203.0.113.7"}, {"spoofed header from an untrusted peer", "10.0.0.0/8", "203.0.113.7:4444", "6.6.6.6", "203.0.113.7"}, {"client behind a trusted proxy", "10.0.0.0/8", "10.0.0.2:4444", "6.6.6.6, 198.51.100.9", "198.51.100.9"}, {"unparseable peer sends nothing", "", "not-an-address", "", ""}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { guard := newFakeAuthGuard(t) guard.reply("POST /api/login", http.StatusOK, map[string]any{"user": map[string]any{"id": 1, "username": "a", "role": "user"}}) networks, err := ParseTrustedProxies(tt.trusted) if err != nil { t.Fatal(err) } service, _ := guard.service(t, WithTrustedProxies(networks)) req := jsonRequest(http.MethodPost, "/auth/login", `{"identifier":"a","password":"password123"}`) req.RemoteAddr = tt.remote if tt.forwarded != "" { req.Header.Set("X-Forwarded-For", tt.forwarded) } rec := httptest.NewRecorder() service.Login(rec, req) if rec.Code != http.StatusOK { t.Fatalf("login status = %d, body %s", rec.Code, rec.Body.String()) } calls := guard.callsTo("POST /api/login") if len(calls) != 1 || calls[0].Forwarded != tt.want { t.Fatalf("AuthGuard saw X-Forwarded-For %+v, want %q", calls, tt.want) } }) } } func TestLoginMapsAuthGuardAnswers(t *testing.T) { login := func(guard *fakeAuthGuard) *httptest.ResponseRecorder { service, _ := guard.service(t) rec := httptest.NewRecorder() service.Login(rec, jsonRequest(http.MethodPost, "/auth/login", `{"email":"a@b.com","password":"password123"}`)) return rec } t.Run("success forwards the session cookie", func(t *testing.T) { guard := newFakeAuthGuard(t) guard.handle("POST /api/login", func(w http.ResponseWriter, _ map[string]any) { http.SetCookie(w, &http.Cookie{Name: "auth_session", Value: "tok", Path: "/", HttpOnly: true}) w.Header().Set("Content-Type", "application/json") _, _ = w.Write([]byte(`{"user":{"id":3,"username":"a","email":"a@b.com","role":"admin","totp_enabled":true}}`)) }) rec := login(guard) if rec.Code != http.StatusOK { t.Fatalf("status = %d", rec.Code) } user := decodeBody(t, rec)["user"].(map[string]any) if user["role"] != "admin" || user["canManageUsers"] != true || user["mfaEnabled"] != true { t.Fatalf("user = %v", user) } if cookies := rec.Result().Cookies(); len(cookies) != 1 || cookies[0].Value != "tok" { t.Fatalf("cookies = %v, want the AuthGuard session cookie", cookies) } if body := guard.callsTo("POST /api/login")[0].Body; body["username_or_email"] != "a@b.com" { t.Fatalf("AuthGuard body = %v, want the email used as the identifier", body) } }) t.Run("wrong credentials answer 401 with the generic message", func(t *testing.T) { guard := newFakeAuthGuard(t) guard.reply("POST /api/login", http.StatusUnauthorized, map[string]any{"error": "no such account"}) rec := login(guard) if rec.Code != http.StatusUnauthorized || decodeBody(t, rec)["error"] != ErrInvalidLogin.Error() { t.Fatalf("status = %d, body %s", rec.Code, rec.Body.String()) } }) t.Run("a required second factor is reported as mfaRequired", func(t *testing.T) { guard := newFakeAuthGuard(t) guard.reply("POST /api/login", http.StatusUnauthorized, map[string]any{"error": "code required", "totp_required": true}) rec := login(guard) if rec.Code != http.StatusUnauthorized || decodeBody(t, rec)["mfaRequired"] != true { t.Fatalf("status = %d, body %s", rec.Code, rec.Body.String()) } }) t.Run("an unreachable AuthGuard answers 500 with the unavailable message", func(t *testing.T) { guard := newFakeAuthGuard(t) service, _ := guard.service(t) guard.server.Close() rec := httptest.NewRecorder() service.Login(rec, jsonRequest(http.MethodPost, "/auth/login", `{"identifier":"a","password":"password123"}`)) if rec.Code != http.StatusInternalServerError || decodeBody(t, rec)["error"] != errAuthGuardUnavailable.Error() { t.Fatalf("status = %d, body %s", rec.Code, rec.Body.String()) } }) t.Run("a missing identifier and a non-JSON body are refused before AuthGuard", func(t *testing.T) { guard := newFakeAuthGuard(t) service, _ := guard.service(t) rec := httptest.NewRecorder() service.Login(rec, jsonRequest(http.MethodPost, "/auth/login", `{"password":"password123"}`)) if rec.Code != http.StatusUnauthorized { t.Fatalf("missing identifier status = %d, want 401", rec.Code) } plain := httptest.NewRequest(http.MethodPost, "/auth/login", strings.NewReader(`{"identifier":"a"}`)) rec = httptest.NewRecorder() service.Login(rec, plain) if rec.Code != http.StatusBadRequest { t.Fatalf("form-typed body status = %d, want 400", rec.Code) } if len(guard.callsTo("POST /api/login")) != 0 { t.Fatal("a refused login still reached AuthGuard") } }) } func TestLoginIsLimitedPerClientAddress(t *testing.T) { guard := newFakeAuthGuard(t) guard.reply("POST /api/login", http.StatusUnauthorized, map[string]any{"error": "bad"}) service, _ := guard.service(t) attempt := func(i int, remote string) int { req := jsonRequest(http.MethodPost, "/auth/login", `{"identifier":"user`+strings.Repeat("x", i)+`","password":"guess"}`) req.RemoteAddr = remote rec := httptest.NewRecorder() service.Login(rec, req) return rec.Code } for i := 0; i < loginClientLimit; i++ { if code := attempt(i, "203.0.113.7:1"); code == http.StatusTooManyRequests { t.Fatalf("attempt %d refused before the limit", i+1) } } if code := attempt(loginClientLimit, "203.0.113.7:1"); code != http.StatusTooManyRequests { t.Fatalf("attempt past the per-address limit status = %d, want 429", code) } if code := attempt(loginClientLimit+1, "203.0.113.8:1"); code == http.StatusTooManyRequests { t.Fatal("a different client address was refused") } } func TestSignupForwardsTheClientAddressAndClaimsSetup(t *testing.T) { guard := newFakeAuthGuard(t) guard.reply("GET /api/setup-status", http.StatusOK, map[string]any{"setup_required": true}) guard.reply("POST /api/register", http.StatusCreated, map[string]any{"user": map[string]any{"id": 1, "username": "root", "email": "root@example.com", "role": "superadmin"}}) service, store := guard.service(t) req := jsonRequest(http.MethodPost, "/auth/signup", `{"email":"Root@Example.com","username":"root","password":"password123"}`) req.RemoteAddr = "198.51.100.20:5555" rec := httptest.NewRecorder() service.Signup(rec, req) if rec.Code != http.StatusCreated { t.Fatalf("signup status = %d, body %s", rec.Code, rec.Body.String()) } if !store.setupClaimed { t.Fatal("signup did not claim the setup flag") } calls := guard.callsTo("POST /api/register") if len(calls) != 1 || calls[0].Forwarded != "198.51.100.20" || calls[0].Body["email"] != "root@example.com" { t.Fatalf("register call = %+v", calls) } } func TestSignupValidatesInputBeforeClaimingSetup(t *testing.T) { guard := newFakeAuthGuard(t) service, store := guard.service(t) for name, body := range map[string]string{ "missing username": `{"email":"a@b.com","password":"password123"}`, "bad email": `{"email":"nope","username":"a","password":"password123"}`, "at in username": `{"email":"a@b.com","username":"a@b.com","password":"password123"}`, "short password": `{"email":"a@b.com","username":"a","password":"short"}`, } { rec := httptest.NewRecorder() service.Signup(rec, jsonRequest(http.MethodPost, "/auth/signup", body)) if rec.Code != http.StatusBadRequest { t.Errorf("%s: status = %d, want 400", name, rec.Code) } } if store.setupClaimed || len(guard.calls) != 0 { t.Fatal("a refused signup claimed setup or reached AuthGuard") } } func TestSignupReleasesTheClaimWhenAuthGuardAlreadyHasAnAccount(t *testing.T) { guard := newFakeAuthGuard(t) guard.reply("GET /api/setup-status", http.StatusOK, map[string]any{"setup_required": false}) service, store := guard.service(t) rec := httptest.NewRecorder() service.Signup(rec, jsonRequest(http.MethodPost, "/auth/signup", `{"email":"a@b.com","username":"a","password":"password123"}`)) if rec.Code != http.StatusConflict || store.setupClaimed { t.Fatalf("status = %d, claimed = %v; want 409 and a released claim", rec.Code, store.setupClaimed) } } func TestTOTPVerifyAndDisableForwardTheAddressAndShareAUserLimit(t *testing.T) { guard := newFakeAuthGuard(t) guard.reply("POST /api/totp/verify", http.StatusUnauthorized, map[string]any{"error": "bad code"}) guard.reply("POST /api/totp/disable", http.StatusUnauthorized, map[string]any{"error": "bad code"}) service, _ := guard.service(t) user := &ProxyUser{ID: 7, Role: "user"} post := func(handler http.HandlerFunc, body string) int { req := withUser(withSession(jsonRequest(http.MethodPost, "/totp", body), "tok-7"), user) req.RemoteAddr = "198.51.100.30:9" rec := httptest.NewRecorder() handler(rec, req) return rec.Code } for i := 0; i < totpAttemptLimit-1; i++ { if code := post(service.TOTPVerify, `{"totpToken":"000000"}`); code != http.StatusUnauthorized { t.Fatalf("verify attempt %d status = %d, want 401", i+1, code) } } if code := post(service.TOTPDisable, `{"token":"000000"}`); code != http.StatusUnauthorized { t.Fatalf("disable attempt status = %d, want 401", code) } if code := post(service.TOTPVerify, `{"totpToken":"123456"}`); code != http.StatusTooManyRequests { t.Fatalf("verify past the shared limit status = %d, want 429", code) } if code := post(service.TOTPDisable, `{"token":"123456"}`); code != http.StatusTooManyRequests { t.Fatalf("disable past the shared limit status = %d, want 429", code) } verifies, disables := guard.callsTo("POST /api/totp/verify"), guard.callsTo("POST /api/totp/disable") if len(verifies) != totpAttemptLimit-1 || len(disables) != 1 { t.Fatalf("AuthGuard saw %d verify and %d disable calls, want %d and 1", len(verifies), len(disables), totpAttemptLimit-1) } for _, call := range append(verifies, disables...) { if call.Forwarded != "198.51.100.30" || call.Authorization != "Bearer tok-7" { t.Fatalf("call = %+v, want the client address and the session token", call) } } if verifies[0].Body["token"] != "000000" { t.Fatalf("verify body = %v, want the totpToken sent as token", verifies[0].Body) } other := withUser(withSession(jsonRequest(http.MethodPost, "/totp", `{"token":"1"}`), "tok-8"), &ProxyUser{ID: 8}) rec := httptest.NewRecorder() service.TOTPVerify(rec, other) if rec.Code == http.StatusTooManyRequests { t.Fatal("another user shares the first user's TOTP limit") } } func TestTOTPHandlersNeedASessionUser(t *testing.T) { guard := newFakeAuthGuard(t) service, _ := guard.service(t) for name, handler := range map[string]http.HandlerFunc{ "status": service.TOTPStatus, "initiate": service.TOTPInitiate, "verify": service.TOTPVerify, "disable": service.TOTPDisable, } { rec := httptest.NewRecorder() handler(rec, jsonRequest(http.MethodPost, "/totp", `{}`)) if rec.Code != http.StatusUnauthorized { t.Errorf("%s without a session user: status = %d, want 401", name, rec.Code) } } if len(guard.calls) != 0 { t.Fatal("an unauthenticated TOTP request reached AuthGuard") } } func TestTOTPInitiateAndStatus(t *testing.T) { guard := newFakeAuthGuard(t) guard.reply("POST /api/totp/enable", http.StatusOK, map[string]any{"secret": "JBSWY3DP", "otpauth_url": "otpauth://totp/x", "enabled": false}) service, _ := guard.service(t) rec := httptest.NewRecorder() service.TOTPStatus(rec, withUser(httptest.NewRequest(http.MethodGet, "/totp/status", nil), &ProxyUser{ID: 1, MFAEnabled: true})) if body := decodeBody(t, rec); body["enabled"] != true || body["mfaEnabled"] != true { t.Fatalf("status = %v", body) } rec = httptest.NewRecorder() service.TOTPInitiate(rec, withUser(withSession(httptest.NewRequest(http.MethodPost, "/totp/initiate", nil), "tok"), &ProxyUser{ID: 1})) data := decodeBody(t, rec)["data"].(map[string]any) if rec.Code != http.StatusOK || data["secret"] != "JBSWY3DP" || data["otpauthUrl"] != "otpauth://totp/x" { t.Fatalf("initiate status = %d, data %v", rec.Code, data) } rec = httptest.NewRecorder() service.TOTPInitiate(rec, withUser(httptest.NewRequest(http.MethodPost, "/totp/initiate", nil), &ProxyUser{ID: 1, MFAEnabled: true})) if rec.Code != http.StatusConflict { t.Fatalf("initiate while enabled status = %d, want 409", rec.Code) } cross := withUser(httptest.NewRequest(http.MethodPost, "/totp/initiate", nil), &ProxyUser{ID: 1}) cross.Header.Set("Sec-Fetch-Site", "cross-site") rec = httptest.NewRecorder() service.TOTPInitiate(rec, cross) if rec.Code != http.StatusForbidden { t.Fatalf("cross-site initiate status = %d, want 403", rec.Code) } } func TestUpdateMeValidatesAndForwardsToAuthGuard(t *testing.T) { guard := newFakeAuthGuard(t) guard.handle("POST /api/login", func(w http.ResponseWriter, _ map[string]any) { w.Header().Add("Set-Cookie", authclient.DefaultCookieName+"=reauth-token; Path=/; HttpOnly") w.Header().Set("Content-Type", "application/json") _ = json.NewEncoder(w).Encode(map[string]any{"user": map[string]any{"id": 7, "username": "boss", "email": "boss@example.com", "role": "admin"}}) }) guard.reply("POST /api/logout", http.StatusOK, map[string]any{"ok": true}) guard.reply("PUT /api/admin/users/7", http.StatusOK, map[string]any{}) guard.reply("GET /api/me", http.StatusOK, map[string]any{"user": map[string]any{"id": 7, "username": "boss", "email": "boss@example.com", "role": "admin"}}) service, _ := guard.service(t) update := func(user *ProxyUser, body string) *httptest.ResponseRecorder { req := withSession(jsonRequest(http.MethodPut, "/auth/me", body), "tok-7") if user != nil { req = withUser(req, user) } rec := httptest.NewRecorder() service.UpdateMe(rec, req) return rec } manager := &ProxyUser{ID: 7, Username: "boss", Role: "admin", MFAEnabled: true} if rec := update(nil, `{}`); rec.Code != http.StatusUnauthorized { t.Fatalf("no session user: status = %d, want 401", rec.Code) } if rec := update(&ProxyUser{ID: 7, Role: "user"}, `{"email":"a@b.com"}`); rec.Code != http.StatusForbidden { t.Fatalf("ordinary user: status = %d, want 403", rec.Code) } for name, body := range map[string]string{ "bad email": `{"email":"nope","username":"boss"}`, "at in username": `{"email":"a@b.com","username":"a@b.com"}`, "short password": `{"email":"a@b.com","username":"boss","password":"short"}`, "long password": `{"email":"a@b.com","username":"boss","password":"` + strings.Repeat("a", 73) + `"}`, "missing current password": `{"email":"a@b.com","username":"boss","password":"new-password"}`, "missing current totp": `{"email":"a@b.com","username":"boss","password":"new-password","currentPassword":"current-password"}`, "not JSON": `nope`, } { if rec := update(manager, body); rec.Code != http.StatusBadRequest { t.Errorf("%s: status = %d, want 400", name, rec.Code) } } if len(guard.callsTo("PUT /api/admin/users/7")) != 0 { t.Fatal("a refused update reached AuthGuard") } rec := update(manager, `{"email":"Boss@Example.com","username":" boss "}`) if rec.Code != http.StatusOK { t.Fatalf("update status = %d, body %s", rec.Code, rec.Body.String()) } calls := guard.callsTo("PUT /api/admin/users/7") if len(calls) != 1 || calls[0].Authorization != "Bearer tok-7" || calls[0].Body["email"] != "boss@example.com" || calls[0].Body["username"] != "boss" { t.Fatalf("AuthGuard update = %+v", calls) } if _, sent := calls[0].Body["password"]; sent { t.Fatal("an update without a password sent one to AuthGuard") } rec = update(manager, `{"email":"boss@example.com","username":"boss","password":"new-password","currentPassword":"current-password","totpToken":"123456"}`) if rec.Code != http.StatusOK { t.Fatalf("password update status = %d, body %s", rec.Code, rec.Body.String()) } loginCalls := guard.callsTo("POST /api/login") if len(loginCalls) != 1 || loginCalls[0].Body["username_or_email"] != "boss" || loginCalls[0].Body["password"] != "current-password" || loginCalls[0].Body["totp_token"] != "123456" { t.Fatalf("reauthentication request = %+v", loginCalls) } calls = guard.callsTo("PUT /api/admin/users/7") if len(calls) != 2 || calls[1].Body["password"] != "new-password" { t.Fatalf("password update request = %+v", calls) } if _, sent := calls[1].Body["currentPassword"]; sent { t.Fatal("current password was forwarded to the managed-user API") } if _, sent := calls[1].Body["totpToken"]; sent { t.Fatal("TOTP code was forwarded to the managed-user API") } logoutCalls := guard.callsTo("POST /api/logout") if len(logoutCalls) != 1 || logoutCalls[0].Authorization != "Bearer reauth-token" { t.Fatalf("temporary login session was not removed: %+v", logoutCalls) } if user := decodeBody(t, rec)["user"].(map[string]any); user["username"] != "boss" { t.Fatalf("response user = %v", user) } } func TestManagedUserHandlers(t *testing.T) { guard := newFakeAuthGuard(t) guard.reply("GET /api/admin/users", http.StatusOK, map[string]any{"users": []map[string]any{ {"id": 1, "username": "root", "email": "root@example.com", "role": "superadmin"}, {"id": 2, "username": "pat", "email": "pat@example.com", "role": "weird-role"}, }}) guard.reply("POST /api/admin/users", http.StatusCreated, map[string]any{"user": map[string]any{"id": 3, "username": "new", "email": "new@example.com", "role": "admin"}}) guard.reply("PUT /api/admin/users/2", http.StatusOK, map[string]any{}) guard.reply("DELETE /api/admin/users/2", http.StatusOK, map[string]any{}) guard.reply("DELETE /api/admin/users/1", http.StatusForbidden, map[string]any{"error": "the superadmin cannot be deleted"}) service, _ := guard.service(t) t.Run("list normalizes roles", func(t *testing.T) { rec := httptest.NewRecorder() service.ManagedUsers(rec, withSession(httptest.NewRequest(http.MethodGet, "/users", nil), "tok")) var users []map[string]any if err := json.Unmarshal(rec.Body.Bytes(), &users); err != nil || len(users) != 2 { t.Fatalf("users = %s, %v", rec.Body.String(), err) } if users[0]["role"] != "superadmin" || users[1]["role"] != "user" { t.Fatalf("roles = %v, %v; want superadmin and the unknown role reduced to user", users[0]["role"], users[1]["role"]) } if call := guard.callsTo("GET /api/admin/users")[0]; call.Authorization != "Bearer tok" { t.Fatalf("list call = %+v, want the session token", call) } }) t.Run("create forwards the role", func(t *testing.T) { rec := httptest.NewRecorder() req := withSession(jsonRequest(http.MethodPost, "/users", `{"email":"new@example.com","username":"new","password":"password123","role":" admin "}`), "tok") service.ManagedCreateUser(rec, req) if rec.Code != http.StatusCreated || decodeBody(t, rec)["role"] != "admin" { t.Fatalf("create status = %d, body %s", rec.Code, rec.Body.String()) } if body := guard.callsTo("POST /api/admin/users")[0].Body; body["role"] != "admin" || body["username"] != "new" { t.Fatalf("create body = %v", body) } }) t.Run("update answers with the refreshed user, or 404", func(t *testing.T) { req := withSession(jsonRequest(http.MethodPut, "/users/2", `{"username":"pat2"}`), "tok") req.SetPathValue("id", "2") rec := httptest.NewRecorder() service.ManagedUpdateUser(rec, req) if rec.Code != http.StatusOK || decodeBody(t, rec)["username"] != "pat" { t.Fatalf("update status = %d, body %s", rec.Code, rec.Body.String()) } missing := withSession(jsonRequest(http.MethodPut, "/users/9", `{}`), "tok") missing.SetPathValue("id", "9") guard.reply("PUT /api/admin/users/9", http.StatusOK, map[string]any{}) rec = httptest.NewRecorder() service.ManagedUpdateUser(rec, missing) if rec.Code != http.StatusNotFound { t.Fatalf("update of an id that is not listed: status = %d, want 404", rec.Code) } }) t.Run("delete", func(t *testing.T) { del := func(id string, header http.Header) *httptest.ResponseRecorder { req := withSession(httptest.NewRequest(http.MethodDelete, "/users/"+id, nil), "tok") req.SetPathValue("id", id) for key, values := range header { req.Header[key] = values } rec := httptest.NewRecorder() service.ManagedDeleteUser(rec, req) return rec } if rec := del("2", nil); rec.Code != http.StatusOK { t.Fatalf("delete status = %d", rec.Code) } if rec := del("1", nil); rec.Code != http.StatusForbidden || !strings.Contains(rec.Body.String(), "superadmin") { t.Fatalf("AuthGuard refusal status = %d, body %s; want it forwarded", rec.Code, rec.Body.String()) } if rec := del("abc", nil); rec.Code != http.StatusBadRequest { t.Fatalf("bad id status = %d, want 400", rec.Code) } before := len(guard.callsTo("DELETE /api/admin/users/2")) if rec := del("2", http.Header{"Sec-Fetch-Site": {"cross-site"}}); rec.Code != http.StatusForbidden { t.Fatalf("cross-site delete status = %d, want 403", rec.Code) } if len(guard.callsTo("DELETE /api/admin/users/2")) != before { t.Fatal("a cross-site delete reached AuthGuard") } }) } func TestLogoutForwardsTheTokenAndClearsCookies(t *testing.T) { guard := newFakeAuthGuard(t) guard.handle("POST /api/logout", func(w http.ResponseWriter, _ map[string]any) { http.SetCookie(w, &http.Cookie{Name: "auth_session", Value: "", Path: "/", MaxAge: -1}) w.Header().Set("Content-Type", "application/json") _, _ = w.Write([]byte(`{}`)) }) service, _ := guard.service(t) rec := httptest.NewRecorder() service.Logout(rec, withSession(httptest.NewRequest(http.MethodPost, "/auth/logout", nil), "tok")) if rec.Code != http.StatusOK { t.Fatalf("logout status = %d", rec.Code) } if calls := guard.callsTo("POST /api/logout"); len(calls) != 1 || calls[0].Authorization != "Bearer tok" { t.Fatalf("logout calls = %+v", calls) } cleared := false for _, cookie := range rec.Result().Cookies() { if cookie.Name == "auth_session" && cookie.MaxAge < 0 { cleared = true } } if !cleared { t.Fatalf("cookies = %v, want the session cookie cleared", rec.Result().Cookies()) } guard.reply("POST /api/logout", http.StatusUnauthorized, map[string]any{"error": "expired"}) rec = httptest.NewRecorder() service.Logout(rec, withSession(httptest.NewRequest(http.MethodPost, "/auth/logout", nil), "stale")) if rec.Code != http.StatusOK { t.Fatalf("logout of an expired session status = %d, want 200", rec.Code) } cross := withSession(httptest.NewRequest(http.MethodPost, "/auth/logout", nil), "tok") cross.Header.Set("Sec-Fetch-Site", "cross-site") rec = httptest.NewRecorder() service.Logout(rec, cross) if rec.Code != http.StatusForbidden { t.Fatalf("cross-site logout status = %d, want 403", rec.Code) } } func TestGatingMiddlewaresResolveSessionsThroughAuthGuard(t *testing.T) { guard := newFakeAuthGuard(t) roles := map[string]string{"user-tok": "user", "admin-tok": "admin", "mod-tok": "moderator"} service, _ := guard.service(t) served := func(role string) { guard.reply("GET /api/me", http.StatusOK, map[string]any{"user": map[string]any{"id": 5, "username": "u", "role": role}}) } ok := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNoContent) }) run := func(mw func(http.Handler) http.Handler, token string) int { req := httptest.NewRequest(http.MethodGet, "/x", nil) if token != "" { withSession(req, token) } rec := httptest.NewRecorder() mw(ok).ServeHTTP(rec, req) return rec.Code } guard.reply("GET /api/me", http.StatusUnauthorized, map[string]any{"error": "no session"}) if code := run(service.Require, ""); code != http.StatusUnauthorized { t.Fatalf("Require without a cookie = %d, want 401", code) } if code := run(service.Require, "stale"); code != http.StatusUnauthorized { t.Fatalf("Require with an expired session = %d, want 401", code) } for token, role := range roles { served(role) wantAdmin := http.StatusForbidden if role == "admin" || role == "moderator" { wantAdmin = http.StatusNoContent } wantManager := http.StatusForbidden if role == "admin" { wantManager = http.StatusNoContent } if code := run(service.Require, token); code != http.StatusNoContent { t.Errorf("Require as %s = %d, want 204", role, code) } if code := run(service.RequireAdmin, token); code != wantAdmin { t.Errorf("RequireAdmin as %s = %d, want %d", role, code, wantAdmin) } if code := run(service.RequireUserManager, token); code != wantManager { t.Errorf("RequireUserManager as %s = %d, want %d", role, code, wantManager) } } guard.server.Close() if code := run(service.Require, "any-token"); code != http.StatusInternalServerError { t.Fatalf("Require with AuthGuard down = %d, want 500", code) } } func TestMeReportsTheSessionUserAndLoginRequirement(t *testing.T) { guard := newFakeAuthGuard(t) guard.reply("GET /api/me", http.StatusOK, map[string]any{"user": map[string]any{"id": 5, "username": "u", "email": "u@example.com", "role": "user"}}) service, store := guard.service(t) rec := httptest.NewRecorder() service.Me(rec, withSession(httptest.NewRequest(http.MethodGet, "/auth/me", nil), "tok")) body := decodeBody(t, rec) if rec.Code != http.StatusOK || body["authRequired"] != true || body["user"].(map[string]any)["username"] != "u" { t.Fatalf("me status = %d, body %v", rec.Code, body) } // The login setting is cached for a moment, so the second answer comes from a fresh Service. service, store = guard.service(t) store.loginRequired = false rec = httptest.NewRecorder() service.Me(rec, httptest.NewRequest(http.MethodGet, "/auth/me", nil)) body = decodeBody(t, rec) if body["authRequired"] != false || body["user"].(map[string]any)["username"] != "Admin" { t.Fatalf("me with login off = %v, want the local admin and authRequired false", body) } }