package api import ( "net/http" "net/http/httptest" "strconv" "strings" "sync" "testing" "time" "git.kmalloc.org/squid/parsimony/internal/store" ) type clock struct { mu sync.Mutex t time.Time } func (c *clock) now() time.Time { c.mu.Lock() defer c.mu.Unlock() return c.t } func (c *clock) advance(d time.Duration) { c.mu.Lock() c.t = c.t.Add(d) c.mu.Unlock() } func limited(t *testing.T) (http.Handler, *clock) { t.Helper() s, err := store.Open(":memory:") if err != nil { t.Fatal(err) } t.Cleanup(func() { s.Close() }) clk := &clock{t: time.Unix(2_000_000_000, 0)} return newHandler(s, token, nil, clk.now), clk } func attempt(h http.Handler, ip, bearer string) *httptest.ResponseRecorder { req := httptest.NewRequest("GET", "/api/v1/lists", nil) req.RemoteAddr = ip + ":40000" if bearer != "" { req.Header.Set("Authorization", "Bearer "+bearer) } rec := httptest.NewRecorder() h.ServeHTTP(rec, req) return rec } func TestTooManyWrongTokensLockTheAddressOut(t *testing.T) { h, _ := limited(t) for i := 0; i < maxFailures; i++ { if rec := attempt(h, "203.0.113.7", "wrong"+strconv.Itoa(i)); rec.Code != 401 { t.Fatalf("attempt %d: %d", i+1, rec.Code) } } rec := attempt(h, "203.0.113.7", token) // even the right token is refused while locked out if rec.Code != 429 { t.Fatalf("locked out: status %d", rec.Code) } secs, err := strconv.Atoi(rec.Header().Get("Retry-After")) if err != nil || secs < 1 || secs > int(lockout/time.Second) { t.Fatalf("Retry-After = %q", rec.Header().Get("Retry-After")) } if !strings.Contains(rec.Body.String(), "too many") { t.Fatalf("body: %s", rec.Body.String()) } // Other addresses are not affected. if rec := attempt(h, "203.0.113.8", token); rec.Code != 200 { t.Fatalf("another address: %d", rec.Code) } } func TestTheLockoutEnds(t *testing.T) { h, clk := limited(t) for i := 0; i < maxFailures; i++ { attempt(h, "203.0.113.7", "wrong") } clk.advance(lockout - time.Second) if rec := attempt(h, "203.0.113.7", token); rec.Code != 429 { t.Fatalf("still locked: %d", rec.Code) } clk.advance(2 * time.Second) if rec := attempt(h, "203.0.113.7", token); rec.Code != 200 { t.Fatalf("after the lockout: %d", rec.Code) } } func TestASuccessClearsTheCountAndOldFailuresExpire(t *testing.T) { h, clk := limited(t) for i := 0; i < maxFailures-1; i++ { attempt(h, "203.0.113.7", "wrong") } if rec := attempt(h, "203.0.113.7", token); rec.Code != 200 { t.Fatal("under the limit the right token works") } for i := 0; i < maxFailures-1; i++ { // a fresh allowance after a success attempt(h, "203.0.113.7", "wrong") } if rec := attempt(h, "203.0.113.7", token); rec.Code != 200 { t.Fatalf("a success resets the count: %d", rec.Code) } for i := 0; i < maxFailures-1; i++ { attempt(h, "203.0.113.7", "wrong") } clk.advance(failureWindow + time.Second) // the failures are old news for i := 0; i < maxFailures-1; i++ { attempt(h, "203.0.113.7", "wrong") } if rec := attempt(h, "203.0.113.7", token); rec.Code != 200 { t.Fatalf("failures older than the window do not add up: %d", rec.Code) } } func TestMissingTokensCountAndHealthDoesNot(t *testing.T) { h, _ := limited(t) for i := 0; i < maxFailures; i++ { health := httptest.NewRequest("GET", "/api/v1/health", nil) health.RemoteAddr = "203.0.113.7:1" rec := httptest.NewRecorder() h.ServeHTTP(rec, health) if rec.Code != 200 { t.Fatalf("health: %d", rec.Code) } attempt(h, "203.0.113.7", "") // no Authorization header at all } if rec := attempt(h, "203.0.113.7", token); rec.Code != 429 { t.Fatalf("probing without a token adds up too: %d", rec.Code) } } func TestForwardedForHeadersCannotEvadeTheLimit(t *testing.T) { h, _ := limited(t) for i := 0; i < maxFailures+3; i++ { req := httptest.NewRequest("GET", "/api/v1/lists", nil) req.RemoteAddr = "203.0.113.7:1" req.Header.Set("X-Forwarded-For", "198.51.100."+strconv.Itoa(i)) req.Header.Set("Authorization", "Bearer wrong") h.ServeHTTP(httptest.NewRecorder(), req) } if rec := attempt(h, "203.0.113.7", token); rec.Code != 429 { t.Fatalf("a spoofed header must not give a fresh allowance: %d", rec.Code) } } func TestAnEmptyServerTokenStillCountsFailures(t *testing.T) { s, _ := store.Open(":memory:") defer s.Close() h := newHandler(s, "", nil, time.Now) for i := 0; i < maxFailures; i++ { req := httptest.NewRequest("GET", "/api/v1/lists", nil) req.RemoteAddr = "203.0.113.7:1" req.Header.Set("Authorization", "Bearer ") h.ServeHTTP(httptest.NewRecorder(), req) } req := httptest.NewRequest("GET", "/api/v1/lists", nil) req.RemoteAddr = "203.0.113.7:1" rec := httptest.NewRecorder() h.ServeHTTP(rec, req) if rec.Code != 429 { t.Fatalf("%d", rec.Code) } } func TestTheLimiterForgetsOldAddresses(t *testing.T) { s, _ := store.Open(":memory:") defer s.Close() clk := &clock{t: time.Unix(2_000_000_000, 0)} l := newLimiter(clk.now) for i := 0; i < 5000; i++ { l.fail("10.0." + strconv.Itoa(i/250) + "." + strconv.Itoa(i%250)) } clk.advance(failureWindow + lockout + time.Second) l.fail("192.0.2.1") // the next failure sweeps expired entries if n := l.size(); n > 10 { t.Fatalf("the limiter keeps %d expired addresses: memory grows without bound", n) } } func TestTheLimitIsTenWrongTokensInFiveMinutes(t *testing.T) { // The numbers are part of the documented behaviour: do not derive them from the constants. h, clk := limited(t) for i := 1; i <= 10; i++ { if rec := attempt(h, "203.0.113.7", "wrong"); rec.Code != 401 { t.Fatalf("wrong token number %d must still be a plain 401, got %d", i, rec.Code) } } if rec := attempt(h, "203.0.113.7", token); rec.Code != 429 { t.Fatalf("the 11th attempt is locked out: %d", rec.Code) } clk.advance(4*time.Minute + 59*time.Second) if rec := attempt(h, "203.0.113.7", token); rec.Code != 429 { t.Fatalf("still locked just before 5 minutes: %d", rec.Code) } clk.advance(2 * time.Second) if rec := attempt(h, "203.0.113.7", token); rec.Code != 200 { t.Fatalf("free after 5 minutes: %d", rec.Code) } } func TestRetryAfterCountsDown(t *testing.T) { h, clk := limited(t) for i := 0; i < 10; i++ { attempt(h, "203.0.113.7", "wrong") } first, _ := strconv.Atoi(attempt(h, "203.0.113.7", token).Header().Get("Retry-After")) clk.advance(2 * time.Minute) later, _ := strconv.Atoi(attempt(h, "203.0.113.7", token).Header().Get("Retry-After")) if first != 300 || later != 180 { t.Fatalf("Retry-After is the time left: %d then %d, want 300 then 180", first, later) } }