package main import ( "io" "net/http" "net/http/httptest" "strconv" "strings" "testing" "time" ) func TestRateLimiterBlocksAfterLimitAndResetsWithWindow(t *testing.T) { now := time.Date(2026, 10, 19, 12, 0, 0, 0, time.UTC) limiter := newRateLimiter(3, time.Minute) limiter.now = func() time.Time { return now } for i := 0; i < 3; i++ { if blocked, _ := limiter.Blocked("a"); blocked { t.Fatalf("hit %d blocked before the budget was spent", i+1) } limiter.Hit("a") } blocked, retryAfter := limiter.Blocked("a") if !blocked { t.Fatal("fourth attempt was not blocked") } if retryAfter != time.Minute { t.Fatalf("retryAfter = %s, want 1m0s", retryAfter) } if blocked, _ := limiter.Blocked("b"); blocked { t.Fatal("budget for one key blocked another key") } now = now.Add(30 * time.Second) if blocked, retryAfter := limiter.Blocked("a"); !blocked || retryAfter != 30*time.Second { t.Fatalf("mid-window Blocked() = %v, %s; want true, 30s", blocked, retryAfter) } now = now.Add(31 * time.Second) if blocked, _ := limiter.Blocked("a"); blocked { t.Fatal("budget did not reset when the window ended") } } func TestRateLimiterBoundsDistinctKeys(t *testing.T) { now := time.Date(2026, 10, 19, 12, 0, 0, 0, time.UTC) limiter := newRateLimiter(5, time.Minute) limiter.maxKeys = 4 limiter.now = func() time.Time { return now } for i := 0; i < 20; i++ { limiter.Hit("ip-" + strconv.Itoa(i)) if len(limiter.counts) > limiter.maxKeys { t.Fatalf("tracked %d keys, want at most %d", len(limiter.counts), limiter.maxKeys) } } // Once the windows have expired, a new key evicts them instead of clearing live ones. now = now.Add(2 * time.Minute) limiter.Hit("fresh") if len(limiter.counts) != 1 { t.Fatalf("after expiry tracked %d keys, want 1", len(limiter.counts)) } } func TestPerClientBudgetCountsEveryRequest(t *testing.T) { limits := newAuthRateLimits(nil) reached := 0 handler := limits.perClient(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { reached++ w.WriteHeader(http.StatusOK) })) for i := 0; i < authIPLimit+1; i++ { recorder := httptest.NewRecorder() handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodPost, "/api/auth/totp/enable", nil)) if i < authIPLimit && recorder.Code != http.StatusOK { t.Fatalf("request %d status = %d, want 200", i+1, recorder.Code) } if i == authIPLimit { if recorder.Code != http.StatusTooManyRequests { t.Fatalf("request %d status = %d, want 429", i+1, recorder.Code) } if recorder.Header().Get("Retry-After") == "" { t.Fatal("429 response has no Retry-After header") } } } if reached != authIPLimit { t.Fatalf("handler ran %d times, want %d", reached, authIPLimit) } } // loginRequest sends one login attempt from the given address and returns the status. func loginRequest(handler http.Handler, remoteAddr, forwardedFor, body string) int { request := httptest.NewRequest(http.MethodPost, "/api/auth/login", strings.NewReader(body)) request.RemoteAddr = remoteAddr if forwardedFor != "" { request.Header.Set("X-Forwarded-For", forwardedFor) } recorder := httptest.NewRecorder() handler.ServeHTTP(recorder, request) return recorder.Code } func TestLoginLocksAccountAfterFailuresAcrossAddresses(t *testing.T) { limits := newAuthRateLimits(nil) handler := limits.login(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // The handler must still see the body that the limiter read. raw, _ := io.ReadAll(r.Body) if !strings.Contains(string(raw), `"password":"wrong"`) { t.Errorf("handler body = %q, want the original login body", raw) } w.WriteHeader(http.StatusUnauthorized) })) body := `{"identifier":" Alice@Example.com ","password":"wrong"}` for i := 0; i < loginFailureLimit; i++ { // A new address each time, so only the per-account budget can trip. addr := "198.51.100." + strconv.Itoa(i+1) + ":5000" if status := loginRequest(handler, addr, "", body); status != http.StatusUnauthorized { t.Fatalf("failed attempt %d status = %d, want 401", i+1, status) } } if status := loginRequest(handler, "203.0.113.50:5000", "", body); status != http.StatusTooManyRequests { t.Fatalf("attempt after lockout status = %d, want 429", status) } other := `{"identifier":"bob@example.com","password":"wrong"}` if status := loginRequest(handler, "203.0.113.51:5000", "", other); status != http.StatusUnauthorized { t.Fatalf("different account status = %d, want 401", status) } } func TestLoginSuccessesDoNotCountAgainstAccount(t *testing.T) { limits := newAuthRateLimits(nil) handler := limits.login(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) })) body := `{"email":"carol@example.com","password":"right"}` for i := 0; i < loginFailureLimit+5; i++ { if status := loginRequest(handler, "198.51.100.9:5000", "", body); status != http.StatusOK { t.Fatalf("successful attempt %d status = %d, want 200", i+1, status) } } } func TestLoginIPBudgetUsesForwardedClientOnlyFromTrustedProxy(t *testing.T) { trusted := mustTrusted(t, "10.0.0.1") body := `{"identifier":"someone","password":"x"}` ok := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) }) // Behind the trusted proxy, each forwarded client has its own budget. proxied := newAuthRateLimits(trusted).login(ok) for i := 0; i < authIPLimit+10; i++ { forwarded := "203.0.113." + strconv.Itoa(i+1) if status := loginRequest(proxied, "10.0.0.1:5000", forwarded, body); status != http.StatusOK { t.Fatalf("forwarded client %s status = %d, want 200", forwarded, status) } } // A caller that is not a trusted proxy cannot pick its own address. direct := newAuthRateLimits(trusted).login(ok) statuses := make(map[int]int) for i := 0; i < authIPLimit+10; i++ { forwarded := "203.0.113." + strconv.Itoa(i+1) statuses[loginRequest(direct, "192.0.2.9:5000", forwarded, body)]++ } if statuses[http.StatusTooManyRequests] == 0 { t.Fatalf("forged X-Forwarded-For bypassed the IP budget: %v", statuses) } } func TestRegisterRoutesLimitsLoginPerClient(t *testing.T) { // Auth is disabled, so login answers 200 without touching the database. server := &Server{auth: newAuthService(nil, "", false, true)} mux := http.NewServeMux() server.registerRoutes(mux, webFS) body := `{"identifier":"admin","password":"x"}` for i := 0; i < authIPLimit; i++ { if status := loginRequest(mux, "192.0.2.20:5000", "", body); status != http.StatusOK { t.Fatalf("attempt %d status = %d, want 200", i+1, status) } } if status := loginRequest(mux, "192.0.2.20:5000", "", body); status != http.StatusTooManyRequests { t.Fatalf("attempt over the budget status = %d, want 429", status) } if status := loginRequest(mux, "192.0.2.21:5000", "", body); status != http.StatusOK { t.Fatalf("other client status = %d, want 200", status) } } func TestWithHTTPSRequiredRefusesPlainHTTP(t *testing.T) { trusted := mustTrusted(t, "10.0.0.1") ok := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) }) handler := withHTTPSRequired(trusted, ok) cases := []struct { name string path string remoteAddr string proto string want int }{ {name: "plain request refused", path: "/api/lists", remoteAddr: "192.0.2.9:5000", want: http.StatusForbidden}, {name: "health probe stays open", path: "/health", remoteAddr: "192.0.2.9:5000", want: http.StatusOK}, {name: "trusted proxy over https allowed", path: "/api/lists", remoteAddr: "10.0.0.1:5000", proto: "https", want: http.StatusOK}, {name: "trusted proxy over http refused", path: "/api/lists", remoteAddr: "10.0.0.1:5000", proto: "http", want: http.StatusForbidden}, {name: "untrusted https claim refused", path: "/api/lists", remoteAddr: "192.0.2.9:5000", proto: "https", want: http.StatusForbidden}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { request := httptest.NewRequest(http.MethodGet, tc.path, nil) request.RemoteAddr = tc.remoteAddr if tc.proto != "" { request.Header.Set("X-Forwarded-Proto", tc.proto) } recorder := httptest.NewRecorder() handler.ServeHTTP(recorder, request) if recorder.Code != tc.want { t.Fatalf("status = %d, want %d", recorder.Code, tc.want) } }) } }