carlos / platform Public

console: email sign-in limits, bounded sweep

Co-Authored-By: Claude <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 94a73d9307c85529b77eacb3668efa8205c840f3 parent a66b323
2 files changed, +110 −33
  • internal/console/emailsignin_limits.go +42 −17
  • internal/console/emailsignin_limits_test.go +68 −16
diff --git a/internal/console/emailsignin_limits.go b/internal/console/emailsignin_limits.go
index 201acb508..5b723a6a2 100644
--- a/internal/console/emailsignin_limits.go
+++ b/internal/console/emailsignin_limits.go
@@ -2,9 +2,10 @@ package console
// In-memory rate limits for email sign-in (spec §5, §7). Same shape as
// inviteWindow: a mutex, an injectable clock, and a map of timestamps pruned
-// when a key is touched. State is per process and lost on restart, which is
-// the right trade for abuse limits: a restart only ever loosens them for a
-// minute, and nothing here guards a secret.
+// when a key is touched. State is per process and lost on restart: a restart
+// resets every window, the hourly and daily send and wrong-code budgets
+// included, so an abuser gets a fresh budget after each restart. That is an
+// accepted trade for abuse limits that guard no secret.
//
// Callers pass an already-normalised address (trimmed, lower-cased) so that
// " Bob@Example.COM " and "bob@example.com" share one budget.
@@ -28,8 +29,8 @@ const (
// A key untouched for this long holds nothing that matters to any window.
limitStaleAfter = 24 * time.Hour
- // submit sweeps at most this many stale keys per window per call.
- limitSweepBatch = 64
+ // submit inspects at most this many keys per call, across all windows.
+ limitSweepBudget = 64
)
// keyedWindow holds the recent event times for each key. The zero value is
@@ -87,20 +88,21 @@ func (w *keyedWindow) add(key string, now time.Time) {
w.hits[key] = append(w.hits[key], now)
}
-// sweep drops up to limitSweepBatch keys whose newest time is older than the
-// stale cutoff. Map iteration order is random, so repeated calls cover the
-// whole map.
-func (w *keyedWindow) sweep(cutoff time.Time) {
- dropped := 0
+// sweep inspects at most budget keys, drops those whose newest time is older
+// than cutoff, and returns how many it inspected. Go starts each map range at
+// a random position, so repeated calls cover the whole map over time.
+func (w *keyedWindow) sweep(cutoff time.Time, budget int) int {
+ inspected := 0
for k, ts := range w.hits {
- if dropped >= limitSweepBatch {
- return
+ if inspected >= budget {
+ break
}
+ inspected++
if len(ts) == 0 || !ts[len(ts)-1].After(cutoff) {
delete(w.hits, k)
- dropped++
}
}
+ return inspected
}
// emailLimits is the set of windows email sign-in needs. The zero value is
@@ -116,6 +118,8 @@ type emailLimits struct {
stepUps keyedWindow // step-up emails, by address
addrWrong keyedWindow // wrong codes, by address
ipWrong keyedWindow // wrong codes, by IP
+
+ sweepNext int // index into sweepWindows() where the next sweep starts
}
func (l *emailLimits) clock() time.Time {
@@ -127,7 +131,8 @@ func (l *emailLimits) clock() time.Time {
// submit records one /auth/continue submission from ip and reports true, or
// reports false without recording when ip already has 30 in the last hour. It
-// also sweeps stale keys out of every window, so memory follows live traffic.
+// also runs one bounded cleanup step (see sweep), so memory follows live
+// traffic.
func (l *emailLimits) submit(ip string) bool {
l.mu.Lock()
defer l.mu.Unlock()
@@ -141,16 +146,33 @@ func (l *emailLimits) submit(ip string) bool {
return true
}
-func (l *emailLimits) sweep(now time.Time) {
+func (l *emailLimits) sweepWindows() []*keyedWindow {
+ return []*keyedWindow{&l.submits, &l.addrSends, &l.ipSends, &l.stepUps, &l.addrWrong, &l.ipWrong}
+}
+
+// sweep is one bounded step of cleanup: it inspects at most limitSweepBudget
+// keys in total across all windows (not per window), dropping stale ones, and
+// returns the number inspected. It starts at the window after where the last
+// call ran out of budget, so a huge live window cannot starve the others. The
+// caller holds l.mu.
+func (l *emailLimits) sweep(now time.Time) int {
cutoff := now.Add(-limitStaleAfter)
- for _, w := range []*keyedWindow{&l.submits, &l.addrSends, &l.ipSends, &l.stepUps, &l.addrWrong, &l.ipWrong} {
- w.sweep(cutoff)
+ ws := l.sweepWindows()
+ budget := limitSweepBudget
+ for n := 0; n < len(ws) && budget > 0; n++ {
+ i := (l.sweepNext + n) % len(ws)
+ budget -= ws[i].sweep(cutoff, budget)
+ if budget <= 0 {
+ l.sweepNext = (i + 1) % len(ws)
+ }
}
+ return limitSweepBudget - budget
}
// signinSend reports whether a sign-in email may go to addr from ip, and if so
// records it in every window. All or nothing: a refusal by any one limit
// charges none of them, so a refused call does not push any window forward.
+// Callers pass addr canonical (trimmed, lower-cased).
func (l *emailLimits) signinSend(addr, ip string) bool {
l.mu.Lock()
defer l.mu.Unlock()
@@ -191,6 +213,7 @@ func (l *emailLimits) signinSend(addr, ip string) bool {
// stepUpSend reports whether a step-up email may go to addr (one per 60
// seconds, ten per hour) and records it if so. Its budget is separate from
// signinSend's.
+// Callers pass addr canonical (trimmed, lower-cased).
func (l *emailLimits) stepUpSend(addr string) bool {
l.mu.Lock()
defer l.mu.Unlock()
@@ -208,6 +231,7 @@ func (l *emailLimits) stepUpSend(addr string) bool {
// codeAllowed reports false once addr has 10 wrong codes in 24 hours, or ip has
// 30 in an hour. It records nothing; codeFailed does.
+// Callers pass addr canonical (trimmed, lower-cased).
func (l *emailLimits) codeAllowed(addr, ip string) bool {
l.mu.Lock()
defer l.mu.Unlock()
@@ -224,6 +248,7 @@ func (l *emailLimits) codeAllowed(addr, ip string) bool {
}
// codeFailed records one wrong code for addr from ip.
+// Callers pass addr canonical (trimmed, lower-cased).
func (l *emailLimits) codeFailed(addr, ip string) {
l.mu.Lock()
defer l.mu.Unlock()
diff --git a/internal/console/emailsignin_limits_test.go b/internal/console/emailsignin_limits_test.go
index 66f30b03c..1e0bc664a 100644
--- a/internal/console/emailsignin_limits_test.go
+++ b/internal/console/emailsignin_limits_test.go
@@ -255,26 +255,78 @@ func TestSigninSendSubmitCap(t *testing.T) {
}
}
-func TestSigninSendSweepDropsStaleKeys(t *testing.T) {
+func limitKeyCount(l *emailLimits) int {
+ n := 0
+ for _, w := range l.sweepWindows() {
+ n += len(w.hits)
+ }
+ return n
+}
+
+func TestSigninSendSweepIsBounded(t *testing.T) {
c := newLimitClock()
l := newTestLimits(c)
- for i := 0; i < 10; i++ {
- l.submit(fmt.Sprintf("10.0.0.%d", i))
- l.signinSend(fmt.Sprintf("s%d@example.com", i), fmt.Sprintf("10.0.0.%d", i))
- l.codeFailed(fmt.Sprintf("s%d@example.com", i), fmt.Sprintf("10.0.0.%d", i))
+ // 10,000 live keys in one window: one call inspects at most 64 and drops none.
+ for i := 0; i < 10000; i++ {
+ l.submits.add(fmt.Sprintf("ip%d", i), c.now())
}
- c.advance(25 * time.Hour)
- l.submit("11.0.0.1")
l.mu.Lock()
- defer l.mu.Unlock()
- for name, w := range map[string]*keyedWindow{
- "submits": &l.submits, "addrSend": &l.addrSends, "ipSend": &l.ipSends,
- "addrWrong": &l.addrWrong, "ipWrong": &l.ipWrong,
- } {
- for k := range w.hits {
- if k != "11.0.0.1" {
- t.Errorf("%s: stale key %q survived the sweep", name, k)
- }
+ inspected := l.sweep(c.now())
+ l.mu.Unlock()
+ if inspected > limitSweepBudget || inspected == 0 {
+ t.Fatalf("sweep inspected %d keys, want 1..%d", inspected, limitSweepBudget)
+ }
+ if got := len(l.submits.hits); got != 10000 {
+ t.Fatalf("sweep dropped live keys: %d left", got)
+ }
+ // The same bound holds through submit, spread over several large windows.
+ for i := 0; i < 10000; i++ {
+ l.addrSends.add(fmt.Sprintf("a%d", i), c.now())
+ l.stepUps.add(fmt.Sprintf("s%d", i), c.now())
+ }
+ for i := 0; i < 5; i++ {
+ l.mu.Lock()
+ inspected = l.sweep(c.now())
+ l.mu.Unlock()
+ if inspected > limitSweepBudget {
+ t.Fatalf("sweep inspected %d keys, budget is %d", inspected, limitSweepBudget)
+ }
+ }
+ if !l.submit("probe") {
+ t.Fatal("submit refused")
+ }
+ if got := limitKeyCount(l); got != 30001 {
+ t.Fatalf("live keys changed: %d, want 30001", got)
+ }
+}
+
+func TestSigninSendSweepCleansStaleAcrossCalls(t *testing.T) {
+ c := newLimitClock()
+ l := newTestLimits(c)
+ // 50 stale keys in each of the six windows: 300 in all, well over one
+ // call's budget, including stepUps.
+ for i := 0; i < 50; i++ {
+ for _, w := range l.sweepWindows() {
+ w.add(fmt.Sprintf("old%d", i), c.now())
}
}
+ if got := limitKeyCount(l); got != 300 {
+ t.Fatalf("setup: %d keys", got)
+ }
+ c.advance(25 * time.Hour)
+ l.submit("11.0.0.1")
+ left := limitKeyCount(l)
+ if left == 0 || left < 300-limitSweepBudget-1 {
+ t.Fatalf("one submit left %d of 301 keys; want a bounded step (dropped at most %d)", left, limitSweepBudget)
+ }
+ for i := 0; i < 20 && limitKeyCount(l) > 1; i++ {
+ l.submit("11.0.0.1")
+ }
+ // Only the live submit key remains, and every window was cleaned, stepUps too.
+ if got := limitKeyCount(l); got != 1 {
+ t.Fatalf("%d keys left after repeated submits, want 1", got)
+ }
+ if len(l.stepUps.hits) != 0 {
+ t.Fatal("stepUps not swept")
+ }
}