//go:build integration package integration_test import ( "bytes" "context" "encoding/json" "io" "log/slog" "net/http" "net/http/httptest" "testing" "time" "github.com/alicebob/miniredis/v2" "github.com/google/uuid" "github.com/redis/go-redis/v9" "github.com/alchemistkay/guestguard/internal/api" "github.com/alchemistkay/guestguard/internal/storage" ) // TestRateLimitSignup confirms the per-IP signup limit kicks in at the // configured threshold and includes a Retry-After header. func TestRateLimitSignup(t *testing.T) { if testing.Short() { t.Skip("skipping integration test in -short mode") } ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) t.Cleanup(cancel) logger := slog.New(slog.NewTextHandler(io.Discard, nil)) dsn := startPostgres(t, ctx) db, err := storage.NewDB(ctx, dsn) must(t, err, "connect db") t.Cleanup(db.Close) must(t, db.Migrate(ctx), "migrate") mr, err := miniredis.Run() must(t, err, "miniredis") t.Cleanup(mr.Close) rdb := redis.NewClient(&redis.Options{Addr: mr.Addr()}) t.Cleanup(func() { _ = rdb.Close() }) srv := httptest.NewServer(must1(api.NewServer(api.ServerDeps{ Logger: logger, DB: db, TokenTTL: 24 * time.Hour, JWTSecret: testJWTSecret, JWTIssuer: testJWTIssuer, AccessTokenTTL: 5 * time.Minute, RefreshTokenTTL: 24 * time.Hour, EmailVerificationTTL: 1 * time.Hour, PasswordResetTTL: 1 * time.Hour, PublicBaseURL: "http://localhost", Redis: rdb, }))(t).Handler()) t.Cleanup(srv.Close) // First 5 signups from the same IP succeed (httptest reuses 127.0.0.1). for i := 0; i < 5; i++ { body := map[string]any{ "email": uniqueEmail(t), "name": "Probe", "password": "correct-horse", } postJSONAuthed(t, srv.URL+"/auth/signup", "", body, http.StatusCreated, nil) } // 6th in the same window must be 429. req := buildJSON(t, http.MethodPost, srv.URL+"/auth/signup", "", map[string]any{"email": uniqueEmail(t), "name": "Probe", "password": "correct-horse"}) resp, err := http.DefaultClient.Do(req) must(t, err, "do 6th signup") defer resp.Body.Close() if resp.StatusCode != http.StatusTooManyRequests { body, _ := io.ReadAll(resp.Body) t.Fatalf("expected 429, got %d body=%s", resp.StatusCode, body) } if resp.Header.Get("Retry-After") == "" { t.Fatal("missing Retry-After header on 429") } } // TestLoginLockout confirms 5 consecutive bad-password attempts trip the // account-lock flag, login then 403s with a "locked" message, and only a // password reset clears it. func TestLoginLockout(t *testing.T) { if testing.Short() { t.Skip("skipping integration test in -short mode") } ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute) t.Cleanup(cancel) logger := slog.New(slog.NewTextHandler(io.Discard, nil)) dsn := startPostgres(t, ctx) db, err := storage.NewDB(ctx, dsn) must(t, err, "connect db") t.Cleanup(db.Close) must(t, db.Migrate(ctx), "migrate") mr, err := miniredis.Run() must(t, err, "miniredis") t.Cleanup(mr.Close) rdb := redis.NewClient(&redis.Options{Addr: mr.Addr()}) t.Cleanup(func() { _ = rdb.Close() }) emails := &recordingEmailSender{} srv := httptest.NewServer(must1(api.NewServer(api.ServerDeps{ Logger: logger, DB: db, TokenTTL: 24 * time.Hour, JWTSecret: testJWTSecret, JWTIssuer: testJWTIssuer, AccessTokenTTL: 5 * time.Minute, RefreshTokenTTL: 24 * time.Hour, EmailVerificationTTL: 1 * time.Hour, PasswordResetTTL: 1 * time.Hour, PublicBaseURL: "http://localhost", EmailSender: emails, Redis: rdb, }))(t).Handler()) t.Cleanup(srv.Close) email := "lockout-" + uuid.NewString() + "@guestguard.test" // Sign up and verify so we have a working account. postJSONAuthed(t, srv.URL+"/auth/signup", "", map[string]any{"email": email, "name": "Lock Probe", "password": "correct-horse"}, http.StatusCreated, nil) token := tokenFromQuery(t, emails.verifyLink, "token") postJSONAuthed(t, srv.URL+"/auth/verify-email", "", map[string]any{"token": token}, http.StatusOK, nil) // 5 bad-password attempts — the lockout middleware engages at the 5th. for i := 0; i < 5; i++ { req := buildJSON(t, http.MethodPost, srv.URL+"/auth/login", "", map[string]any{"email": email, "password": "wrong"}) resp, err := http.DefaultClient.Do(req) must(t, err, "do login") resp.Body.Close() } // Even correct password is now rejected with 403 "locked". { req := buildJSON(t, http.MethodPost, srv.URL+"/auth/login", "", map[string]any{"email": email, "password": "correct-horse"}) resp, err := http.DefaultClient.Do(req) must(t, err, "do correct login") defer resp.Body.Close() if resp.StatusCode != http.StatusForbidden { body, _ := io.ReadAll(resp.Body) t.Fatalf("expected 403 locked, got %d body=%s", resp.StatusCode, body) } } // Reset the password — should clear the lock. emails.resetLink = "" postJSONAuthed(t, srv.URL+"/auth/forgot-password", "", map[string]any{"email": email}, http.StatusAccepted, nil) if emails.resetLink == "" { t.Fatal("reset link not captured") } resetToken := tokenFromPath(t, emails.resetLink, "/reset-password/") postJSONAuthed(t, srv.URL+"/auth/reset-password", "", map[string]any{"token": resetToken, "new_password": "new-correct-horse"}, http.StatusOK, nil) // Now login succeeds with the new password. postJSONAuthed(t, srv.URL+"/auth/login", "", map[string]any{"email": email, "password": "new-correct-horse"}, http.StatusOK, nil) } func buildJSON(t *testing.T, method, url, bearer string, body any) *http.Request { t.Helper() var r io.Reader if body != nil { b, err := json.Marshal(body) must(t, err, "marshal body") r = bytes.NewReader(b) } req, err := http.NewRequest(method, url, r) must(t, err, "build req") if r != nil { req.Header.Set("Content-Type", "application/json") } if bearer != "" { req.Header.Set("Authorization", "Bearer "+bearer) } return req } func must1[T any](v T, err error) func(*testing.T) T { return func(t *testing.T) T { t.Helper() must(t, err, "api server") return v } }