Bound the key cache and ration lookups of unknown keys per client address

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Ilker ManapandClaude Opus 5.5 committed 2026-10-04 10:19:38 +02:00
1 parent ebf437a36a
commit d3fb217b31
5 files changed
+154 -4

No files matched your search

+40
View File
@@ -438,3 +438,43 @@ func TestAlterAlwaysChangesTheKey(t *testing.T) {
t.Error("alter is a no-op when the key already ends in the replacement")
}
}
func TestAFloodOfMadeUpKeysFromOneAddressIsSlowedBeforeTheDatabase(t *testing.T) {
s, secret, _ := fixture(t)
a := New(s, DefaultConfig())
now := time.Now()
a.now = func() time.Time { return now }
ctx := context.Background()
throttled := 0
for i := 0; i < 200; i++ {
madeUp, _, _ := store.NewKey("x", "x", "proj1")
if _, err := a.AuthenticateFrom(ctx, madeUp, "203.0.113.9"); errors.Is(err, ErrThrottled) {
throttled++
}
}
if throttled < 100 {
t.Errorf("only %d of 200 made-up keys were held back", throttled)
}
// Another address, and the real key, are not caught by it.
if _, err := a.AuthenticateFrom(ctx, secret, "198.51.100.1"); err != nil {
t.Errorf("a real key from another address: %v", err)
}
// Time restores the allowance.
now = now.Add(5 * time.Second)
madeUp, _, _ := store.NewKey("y", "y", "proj1")
if _, err := a.AuthenticateFrom(ctx, madeUp, "203.0.113.9"); errors.Is(err, ErrThrottled) {
t.Error("still held back after waiting")
}
}
func TestTheCacheDoesNotGrowWithoutBound(t *testing.T) {
s, _, _ := fixture(t)
a := New(s, DefaultConfig())
for i := 0; i < maxCached+10; i++ {
a.store_(string(rune(i))+"-"+time.Now().String(), entry{expires: time.Now().Add(time.Hour)})
}
if n := len(a.cache); n > maxCached {
t.Errorf("%d entries", n)
}
}