package auth import ( "context" "net/http" "net/http/httptest" "strconv" "strings" "testing" "time" ) // fakeProxyStore is a minimal in-memory ProxyStore for constructing a // Service in tests without a real database. type fakeProxyStore struct { loginRequired bool setupClaimed bool } func (s *fakeProxyStore) LoginRequired(context.Context) (bool, error) { return s.loginRequired, nil } func (s *fakeProxyStore) SetLoginRequired(_ context.Context, v bool) error { s.loginRequired = v return nil } func (s *fakeProxyStore) IsSetupClaimed(context.Context) (bool, error) { return s.setupClaimed, nil } func (s *fakeProxyStore) TryClaimSetup(context.Context) (bool, error) { if s.setupClaimed { return false, nil } s.setupClaimed = true return true, nil } func (s *fakeProxyStore) UnclaimSetup(context.Context) error { s.setupClaimed = false return nil } type noOpLoginProxyStore struct{ fakeProxyStore } func (s *noOpLoginProxyStore) SetLoginRequired(context.Context, bool) error { return nil } // TestPendingModeStillGatesRequests locks in the fix that made an empty // authGuardURL at construction mean "pending" (auth still enabled, calls // fail closed until a real URL arrives via SetAuthGuardBaseURL) instead of // "disabled" (nothing gated, a fixed superadmin identity) - the bug that // made AUTHGUARD_URL a de-facto requirement even though ProjectConfigurator // can push it live after startup. func TestPendingModeStillGatesRequests(t *testing.T) { service := NewWithStore(&fakeProxyStore{loginRequired: true}, "session", false, "", "testproject") if !service.enabled() { t.Fatal("Service with no authGuardURL and no Disabled() option should still be enabled (pending), not disabled") } req := httptest.NewRequest(http.MethodGet, "/", nil) req.AddCookie(&http.Cookie{Name: "auth_session", Value: "sometoken"}) if _, err := service.CurrentUser(req); err == nil { t.Fatal("pending Service (no AuthGuard URL yet) should fail closed on a real session cookie, not silently resolve a user") } } // TestDisabledOptionSkipsGating confirms the explicit opt-out still works // exactly like the old "empty authGuardURL" behavior. func TestDisabledOptionSkipsGating(t *testing.T) { service := NewWithStore(&fakeProxyStore{}, "session", false, "", "testproject", Disabled()) if service.enabled() { t.Fatal("Service built with Disabled() should report enabled() == false") } req := httptest.NewRequest(http.MethodGet, "/", nil) user, err := service.CurrentUser(req) if err != nil || user == nil || user.Username != "Admin" || !IsAdmin(user) { t.Fatalf("Disabled() Service should resolve the fixed Admin superadmin profile, got user=%+v err=%v", user, err) } } func TestLoginDisabledUsesAdminIdentityWithoutCredentials(t *testing.T) { store := &fakeProxyStore{loginRequired: false} service := NewWithStore(store, "session", false, "", "testproject") req := httptest.NewRequest(http.MethodGet, "/", nil) user, err := service.CurrentUser(req) if err != nil || user == nil || user.Username != "Admin" || !IsAdmin(user) { t.Fatalf("login-disabled Service should resolve the Admin identity, got user=%+v err=%v", user, err) } called := false handler := service.RequireAdminIfLoginRequired(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { called = true contextUser := UserFromContext(r.Context()) if contextUser == nil || contextUser.Username != "Admin" || !IsAdmin(contextUser) { t.Errorf("middleware context user = %+v, want Admin superadmin", contextUser) } w.WriteHeader(http.StatusNoContent) })) response := httptest.NewRecorder() handler.ServeHTTP(response, req) if response.Code != http.StatusNoContent || !called { t.Fatalf("login-disabled admin middleware status = %d/called=%v, want %d/true", response.Code, called, http.StatusNoContent) } } // TestNoOpStoreDoesNotKeepAProcessLocalLoginOverride checks that the login-required setting is read // from the store on each call. A store that discards writes keeps login required everywhere, rather // than letting one process diverge from the rest. func TestNoOpStoreDoesNotKeepAProcessLocalLoginOverride(t *testing.T) { store := &noOpLoginProxyStore{fakeProxyStore: fakeProxyStore{loginRequired: true}} service := NewWithStore(store, "session", false, "", "testproject") if err := service.SetLoginRequired(context.Background(), false); err != nil { t.Fatalf("SetLoginRequired() error = %v", err) } user, err := service.CurrentUser(httptest.NewRequest(http.MethodGet, "/", nil)) if err != nil || user != nil { t.Fatalf("no-op store resolved user=%+v err=%v, want no user while login is still required", user, err) } } // TestBodylessStateChangesRefuseCrossSite checks the routes that take no JSON body, which // decodeProxyJSON cannot guard, refuse a request the browser marks as cross-site. func TestBodylessStateChangesRefuseCrossSite(t *testing.T) { service := NewWithStore(&fakeProxyStore{loginRequired: true}, "session", false, "", "testproject") handlers := map[string]http.HandlerFunc{ "logout": service.Logout, "totp initiate": service.TOTPInitiate, "delete user": service.ManagedDeleteUser, } for name, handler := range handlers { req := httptest.NewRequest(http.MethodPost, "/", nil) req.Header.Set("Sec-Fetch-Site", "cross-site") rec := httptest.NewRecorder() handler(rec, req) if rec.Code != http.StatusForbidden { t.Errorf("%s with Sec-Fetch-Site: cross-site returned %d, want 403", name, rec.Code) } } } func TestSetLoginRequiredNeedsAStore(t *testing.T) { service := NewWithStore(nil, "session", false, "", "testproject") if err := service.SetLoginRequired(context.Background(), false); err == nil { t.Fatal("SetLoginRequired with no store succeeded, want an error") } } func TestDecodeProxyJSONRequiresAJSONBodyAndRefusesCrossSite(t *testing.T) { decode := func(contentType, fetchSite string) error { req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(`{"loginRequired":true}`)) if contentType != "" { req.Header.Set("Content-Type", contentType) } if fetchSite != "" { req.Header.Set("Sec-Fetch-Site", fetchSite) } var input struct { LoginRequired bool `json:"loginRequired"` } return decodeProxyJSON(req, &input) } if err := decode("application/json", ""); err != nil { t.Fatalf("application/json body refused: %v", err) } if err := decode("application/json; charset=utf-8", "same-site"); err != nil { t.Fatalf("same-site application/json body refused: %v", err) } for _, contentType := range []string{"", "text/plain", "application/x-www-form-urlencoded", "multipart/form-data; boundary=x"} { if err := decode(contentType, ""); err == nil { t.Errorf("Content-Type %q accepted, want refused", contentType) } } if err := decode("application/json", "cross-site"); err == nil { t.Error("cross-site application/json body accepted, want refused") } } func TestSignupIsRefusedWhileLoginIsNotRequired(t *testing.T) { store := &fakeProxyStore{loginRequired: false} service := NewWithStore(store, "session", false, "", "testproject") req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(`{"email":"a@b.com","username":"a","password":"password123"}`)) req.Header.Set("Content-Type", "application/json") rec := httptest.NewRecorder() service.Signup(rec, req) if rec.Code != http.StatusConflict { t.Fatalf("signup with login off status = %d, want 409", rec.Code) } if store.setupClaimed { t.Fatal("refused signup still claimed the setup flag") } } func TestLoginIsRateLimitedPerAccount(t *testing.T) { service := NewWithStore(&fakeProxyStore{loginRequired: true}, "session", false, "", "testproject") post := func() int { req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(`{"identifier":"Victim","password":"guess"}`)) req.Header.Set("Content-Type", "application/json") rec := httptest.NewRecorder() service.Login(rec, req) return rec.Code } for i := 0; i < loginAccountLimit; i++ { if code := post(); code == http.StatusTooManyRequests { t.Fatalf("attempt %d refused before the limit", i+1) } } if code := post(); code != http.StatusTooManyRequests { t.Fatalf("attempt past the limit status = %d, want 429", code) } } func TestAttemptLimiterWindowAndTableBound(t *testing.T) { now := time.Now() limiter := newAttemptLimiter(time.Minute, 2) if !limiter.allow("k", now) || !limiter.allow("k", now) { t.Fatal("attempts within the limit were refused") } if limiter.allow("k", now) { t.Fatal("attempt past the limit was allowed") } if !limiter.allow("k", now.Add(time.Minute)) { t.Fatal("limit did not reset after the window") } full := newAttemptLimiter(time.Hour, 1) for i := 0; i < maxTrackedAttemptKeys; i++ { full.allow(strconv.Itoa(i), now) } if full.allow("new-key", now) { t.Fatal("a new key was tracked past the table bound") } } func TestValidateProxyPasswordRefusesMoreThan72Bytes(t *testing.T) { if err := validateProxyPassword(strings.Repeat("a", 72)); err != nil { t.Fatalf("72-byte password refused: %v", err) } if err := validateProxyPassword(strings.Repeat("a", 73)); err == nil { t.Fatal("73-byte password accepted, want refused") } if err := validateProxyPassword(strings.Repeat("é", 40)); err == nil { t.Fatal("80-byte multi-byte password accepted, want refused") } } func TestNormalizeProxyUsernameRefusesAt(t *testing.T) { if _, err := normalizeProxyUsername("name@example.com"); err == nil { t.Fatal("username containing @ accepted") } if got, err := normalizeProxyUsername(" plain "); err != nil || got != "plain" { t.Fatalf("plain username = %q, %v", got, err) } } func TestNormalizeProxyCredentials(t *testing.T) { email, username, password, err := normalizeProxyCredentials(" User@Example.com ", "user", "correct horse battery staple") if err != nil { t.Fatal(err) } if email != "user@example.com" || username != "user" || password == "" { t.Fatalf("normalized credentials = %q, %q, %q", email, username, password) } } func TestNormalizeProxyCredentialsAllowsAdminEmailOnly(t *testing.T) { if _, _, _, err := normalizeProxyCredentials("admin@example.com", "", "correct horse battery staple"); err != nil { t.Fatalf("empty optional username rejected: %v", err) } } func TestNormalizePlatformRole(t *testing.T) { if normalizePlatformRole("MODERATOR") != "moderator" { t.Fatal("moderator role was not normalized") } if normalizePlatformRole("unknown") != "user" { t.Fatal("unknown role was not reduced to user") } }