carlos / platform Public

console: email sign-in rate limits

Co-Authored-By: Claude <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev a66b3231d97612063cba9272eaad5b83113b6fa0 parent 9407420
2 files changed, +515 −0
  • internal/console/emailsignin_limits.go +235 −0
  • internal/console/emailsignin_limits_test.go +280 −0
diff --git a/internal/console/emailsignin_limits.go b/internal/console/emailsignin_limits.go
new file mode 100644
index 000000000..201acb508
--- /dev/null
+++ b/internal/console/emailsignin_limits.go
@@ -0,0 +1,235 @@
+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.
+//
+// Callers pass an already-normalised address (trimmed, lower-cased) so that
+// " Bob@Example.COM " and "bob@example.com" share one budget.
+
+import (
+ "sync"
+ "time"
+)
+
+const (
+ submitsPerIPHour = 30 // /auth/continue submissions per IP
+ signinPerAddrHour = 5 // sign-in emails per address
+ signinPerAddrDay = 20 // sign-in emails per address
+ signinPerIPHour = 10 // sign-in emails per IP
+ signinGlobalHour = 200 // sign-in emails console-wide
+ stepUpPerAddrHour = 10 // step-up emails per address
+ wrongCodesPerAddrDay = 10 // wrong codes per address
+ wrongCodesPerIPHour = 30 // wrong codes per IP
+
+ emailResendGap = 60 * time.Second
+
+ // 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
+)
+
+// keyedWindow holds the recent event times for each key. The zero value is
+// ready to use; the owning emailLimits holds the lock.
+type keyedWindow struct {
+ hits map[string][]time.Time
+}
+
+// trim drops key's times older than limitStaleAfter, the longest any window
+// looks back, and the key itself when nothing is left. Shorter windows must
+// not prune on their own cutoff: the same key feeds the longer ones.
+func (w *keyedWindow) trim(key string, now time.Time) {
+ ts := w.hits[key]
+ if len(ts) == 0 {
+ return
+ }
+ cutoff := now.Add(-limitStaleAfter)
+ kept := ts[:0]
+ for _, t := range ts {
+ if t.After(cutoff) {
+ kept = append(kept, t)
+ }
+ }
+ if len(kept) == 0 {
+ delete(w.hits, key)
+ return
+ }
+ w.hits[key] = kept
+}
+
+// count is the number of times for key after cutoff.
+func (w *keyedWindow) count(key string, cutoff time.Time) int {
+ n := 0
+ for _, t := range w.hits[key] {
+ if t.After(cutoff) {
+ n++
+ }
+ }
+ return n
+}
+
+// last is the newest time for key after cutoff, or false.
+func (w *keyedWindow) last(key string, cutoff time.Time) (time.Time, bool) {
+ ts := w.hits[key]
+ if len(ts) == 0 || !ts[len(ts)-1].After(cutoff) {
+ return time.Time{}, false
+ }
+ return ts[len(ts)-1], true
+}
+
+func (w *keyedWindow) add(key string, now time.Time) {
+ if w.hits == nil {
+ w.hits = map[string][]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
+ for k, ts := range w.hits {
+ if dropped >= limitSweepBatch {
+ return
+ }
+ if len(ts) == 0 || !ts[len(ts)-1].After(cutoff) {
+ delete(w.hits, k)
+ dropped++
+ }
+ }
+}
+
+// emailLimits is the set of windows email sign-in needs. The zero value is
+// ready to use.
+type emailLimits struct {
+ mu sync.Mutex
+ now func() time.Time // nil: time.Now
+
+ submits keyedWindow // /auth/continue submissions, by IP
+ addrSends keyedWindow // sign-in emails, by address
+ ipSends keyedWindow // sign-in emails, by IP
+ globalSend []time.Time // sign-in emails, console-wide
+ stepUps keyedWindow // step-up emails, by address
+ addrWrong keyedWindow // wrong codes, by address
+ ipWrong keyedWindow // wrong codes, by IP
+}
+
+func (l *emailLimits) clock() time.Time {
+ if l.now != nil {
+ return l.now()
+ }
+ return time.Now()
+}
+
+// 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.
+func (l *emailLimits) submit(ip string) bool {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ now := l.clock()
+ l.sweep(now)
+ l.submits.trim(ip, now)
+ if l.submits.count(ip, now.Add(-time.Hour)) >= submitsPerIPHour {
+ return false
+ }
+ l.submits.add(ip, now)
+ return true
+}
+
+func (l *emailLimits) sweep(now time.Time) {
+ cutoff := now.Add(-limitStaleAfter)
+ for _, w := range []*keyedWindow{&l.submits, &l.addrSends, &l.ipSends, &l.stepUps, &l.addrWrong, &l.ipWrong} {
+ w.sweep(cutoff)
+ }
+}
+
+// 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.
+func (l *emailLimits) signinSend(addr, ip string) bool {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ now := l.clock()
+ hour, day := now.Add(-time.Hour), now.Add(-24*time.Hour)
+ l.addrSends.trim(addr, now)
+ l.ipSends.trim(ip, now)
+
+ if _, ok := l.addrSends.last(addr, now.Add(-emailResendGap)); ok {
+ return false
+ }
+ if l.addrSends.count(addr, hour) >= signinPerAddrHour {
+ return false
+ }
+ if l.addrSends.count(addr, day) >= signinPerAddrDay {
+ return false
+ }
+ if l.ipSends.count(ip, hour) >= signinPerIPHour {
+ return false
+ }
+ kept := l.globalSend[:0]
+ for _, t := range l.globalSend {
+ if t.After(hour) {
+ kept = append(kept, t)
+ }
+ }
+ l.globalSend = kept
+ if len(kept) >= signinGlobalHour {
+ return false
+ }
+
+ l.addrSends.add(addr, now)
+ l.ipSends.add(ip, now)
+ l.globalSend = append(l.globalSend, now)
+ return true
+}
+
+// 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.
+func (l *emailLimits) stepUpSend(addr string) bool {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ now := l.clock()
+ l.stepUps.trim(addr, now)
+ if _, ok := l.stepUps.last(addr, now.Add(-emailResendGap)); ok {
+ return false
+ }
+ if l.stepUps.count(addr, now.Add(-time.Hour)) >= stepUpPerAddrHour {
+ return false
+ }
+ l.stepUps.add(addr, now)
+ return true
+}
+
+// codeAllowed reports false once addr has 10 wrong codes in 24 hours, or ip has
+// 30 in an hour. It records nothing; codeFailed does.
+func (l *emailLimits) codeAllowed(addr, ip string) bool {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ now := l.clock()
+ l.addrWrong.trim(addr, now)
+ l.ipWrong.trim(ip, now)
+ if l.addrWrong.count(addr, now.Add(-24*time.Hour)) >= wrongCodesPerAddrDay {
+ return false
+ }
+ if l.ipWrong.count(ip, now.Add(-time.Hour)) >= wrongCodesPerIPHour {
+ return false
+ }
+ return true
+}
+
+// codeFailed records one wrong code for addr from ip.
+func (l *emailLimits) codeFailed(addr, ip string) {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ now := l.clock()
+ l.addrWrong.trim(addr, now)
+ l.ipWrong.trim(ip, now)
+ l.addrWrong.add(addr, now)
+ l.ipWrong.add(ip, now)
+}
diff --git a/internal/console/emailsignin_limits_test.go b/internal/console/emailsignin_limits_test.go
new file mode 100644
index 000000000..66f30b03c
--- /dev/null
+++ b/internal/console/emailsignin_limits_test.go
@@ -0,0 +1,280 @@
+package console
+
+import (
+ "fmt"
+ "testing"
+ "time"
+)
+
+// limitClock is an injectable, advanceable clock for emailLimits tests.
+type limitClock struct{ t time.Time }
+
+func newLimitClock() *limitClock {
+ return &limitClock{t: time.Date(2026, 10, 21, 9, 0, 0, 0, time.UTC)}
+}
+func (c *limitClock) now() time.Time { return c.t }
+func (c *limitClock) advance(d time.Duration) { c.t = c.t.Add(d) }
+
+func newTestLimits(c *limitClock) *emailLimits { return &emailLimits{now: c.now} }
+
+func TestSigninSendLimits(t *testing.T) {
+ c := newLimitClock()
+ l := newTestLimits(c)
+ const addr = "bob@example.com"
+
+ if !l.signinSend(addr, "1.1.1.1") {
+ t.Fatal("first send refused")
+ }
+ c.advance(30 * time.Second)
+ if l.signinSend(addr, "1.1.1.1") {
+ t.Fatal("second send within 60s allowed")
+ }
+ // The refusal recorded nothing: 30s later (60s after the first send) is
+ // allowed. A refusal that pushed the window would still be refused.
+ c.advance(30 * time.Second)
+ if !l.signinSend(addr, "1.1.1.1") {
+ t.Fatal("send at 60s refused: the earlier refusal must not have been recorded")
+ }
+
+ // Sends 3, 4 and 5 at 61s spacing; the 6th within the hour is refused.
+ for i := 3; i <= 5; i++ {
+ c.advance(61 * time.Second)
+ if !l.signinSend(addr, "1.1.1.1") {
+ t.Fatalf("send %d refused", i)
+ }
+ }
+ c.advance(61 * time.Second)
+ if l.signinSend(addr, "1.1.1.1") {
+ t.Fatal("6th send within an hour allowed")
+ }
+ // Once the first send leaves the hour, one more fits.
+ c.advance(time.Hour)
+ if !l.signinSend(addr, "1.1.1.1") {
+ t.Fatal("send after the hour rolled over refused")
+ }
+}
+
+func TestSigninSendDailyCap(t *testing.T) {
+ c := newLimitClock()
+ l := newTestLimits(c)
+ const addr = "bob@example.com"
+ // Four sends per hour-ish block, spaced so the hourly cap of 5 never binds,
+ // until 20 have gone out within the day.
+ sent := 0
+ for sent < 20 {
+ for i := 0; i < 4 && sent < 20; i++ {
+ if !l.signinSend(addr, "1.1.1.1") {
+ t.Fatalf("send %d refused", sent+1)
+ }
+ sent++
+ c.advance(61 * time.Second)
+ }
+ c.advance(time.Hour)
+ }
+ // 20 sends, the last about 20h in. The 21st must be refused by the daily cap.
+ if l.signinSend(addr, "1.1.1.1") {
+ t.Fatal("21st send within a day allowed")
+ }
+ // A refusal records nothing: after the first send ages out of the day, the
+ // address can send again.
+ c.advance(24 * time.Hour)
+ if !l.signinSend(addr, "1.1.1.1") {
+ t.Fatal("send after the day rolled over refused")
+ }
+}
+
+func TestSigninSendIPAndGlobal(t *testing.T) {
+ c := newLimitClock()
+ l := newTestLimits(c)
+ for i := 0; i < 10; i++ {
+ if !l.signinSend(fmt.Sprintf("u%d@example.com", i), "2.2.2.2") {
+ t.Fatalf("send %d from one IP refused", i+1)
+ }
+ }
+ if l.signinSend("u10@example.com", "2.2.2.2") {
+ t.Fatal("11th send from one IP allowed")
+ }
+ // All-or-nothing: the refused address was not charged, so it can still
+ // send from another IP straight away.
+ if !l.signinSend("u10@example.com", "3.3.3.3") {
+ t.Fatal("address charged by a send refused for its IP")
+ }
+
+ // Console-wide: 200 per hour in total.
+ c2 := newLimitClock()
+ g := newTestLimits(c2)
+ for i := 0; i < 200; i++ {
+ if !g.signinSend(fmt.Sprintf("g%d@example.com", i), fmt.Sprintf("10.0.%d.%d", i/250, i%250)) {
+ t.Fatalf("send %d console-wide refused", i+1)
+ }
+ }
+ if g.signinSend("g200@example.com", "10.9.9.9") {
+ t.Fatal("201st send console-wide allowed")
+ }
+ c2.advance(time.Hour + time.Second)
+ if !g.signinSend("g200@example.com", "10.9.9.9") {
+ t.Fatal("send after the hour refused")
+ }
+}
+
+func TestSigninSendRefusalByIPDoesNotChargeGlobal(t *testing.T) {
+ c := newLimitClock()
+ l := newTestLimits(c)
+ for i := 0; i < 10; i++ {
+ l.signinSend(fmt.Sprintf("u%d@example.com", i), "2.2.2.2")
+ }
+ // 190 refusals from the saturated IP must leave the global budget alone.
+ for i := 0; i < 190; i++ {
+ if l.signinSend(fmt.Sprintf("x%d@example.com", i), "2.2.2.2") {
+ t.Fatal("saturated IP allowed")
+ }
+ }
+ for i := 0; i < 190; i++ {
+ if !l.signinSend(fmt.Sprintf("y%d@example.com", i), fmt.Sprintf("10.1.%d.%d", i/100, i%100)) {
+ t.Fatalf("send %d refused: refusals charged the global window", i+1)
+ }
+ }
+}
+
+func TestStepUpSendSeparate(t *testing.T) {
+ c := newLimitClock()
+ l := newTestLimits(c)
+ const addr = "bob@example.com"
+
+ // A sign-in send does not consume step-up budget.
+ if !l.signinSend(addr, "1.1.1.1") {
+ t.Fatal("sign-in send refused")
+ }
+ if !l.stepUpSend(addr) {
+ t.Fatal("step-up send refused after a sign-in send")
+ }
+ // And a step-up send does not consume sign-in budget.
+ c.advance(61 * time.Second)
+ if !l.signinSend(addr, "1.1.1.1") {
+ t.Fatal("sign-in send refused after a step-up send")
+ }
+ if l.stepUpSend(addr) != true {
+ t.Fatal("step-up send at 61s refused")
+ }
+
+ // 1 per 60 s.
+ if l.stepUpSend(addr) {
+ t.Fatal("step-up send inside 60s allowed")
+ }
+ // 10 per hour: 8 more (10 total) at 61s spacing, then the 11th refused.
+ for i := 3; i <= 10; i++ {
+ c.advance(61 * time.Second)
+ if !l.stepUpSend(addr) {
+ t.Fatalf("step-up send %d refused", i)
+ }
+ }
+ c.advance(61 * time.Second)
+ if l.stepUpSend(addr) {
+ t.Fatal("11th step-up send within an hour allowed")
+ }
+ // Step-up sends never touched the sign-in per-address budget beyond the
+ // two sign-in sends above.
+ if !l.signinSend(addr, "1.1.1.1") {
+ t.Fatal("sign-in send refused after step-up sends")
+ }
+}
+
+func TestCodeGuessCaps(t *testing.T) {
+ c := newLimitClock()
+ l := newTestLimits(c)
+ const addr = "bob@example.com"
+
+ if !l.codeAllowed(addr, "1.1.1.1") {
+ t.Fatal("fresh address not allowed")
+ }
+ for i := 0; i < 9; i++ {
+ l.codeFailed(addr, fmt.Sprintf("9.9.9.%d", i))
+ }
+ if !l.codeAllowed(addr, "1.1.1.1") {
+ t.Fatal("blocked after 9 wrong codes")
+ }
+ l.codeFailed(addr, "9.9.9.99")
+ // Ten wrong codes against one address block it from any IP.
+ if l.codeAllowed(addr, "1.1.1.1") || l.codeAllowed(addr, "4.4.4.4") {
+ t.Fatal("address allowed after 10 wrong codes")
+ }
+ // Another address from a fresh IP is unaffected.
+ if !l.codeAllowed("other@example.com", "1.1.1.1") {
+ t.Fatal("other address blocked")
+ }
+ c.advance(24*time.Hour + time.Second)
+ if !l.codeAllowed(addr, "1.1.1.1") {
+ t.Fatal("address still blocked after 24h")
+ }
+}
+
+func TestCodeGuessIPCap(t *testing.T) {
+ c := newLimitClock()
+ l := newTestLimits(c)
+ for i := 0; i < 29; i++ {
+ l.codeFailed(fmt.Sprintf("a%d@example.com", i), "5.5.5.5")
+ }
+ if !l.codeAllowed("fresh@example.com", "5.5.5.5") {
+ t.Fatal("IP blocked after 29 wrong codes")
+ }
+ l.codeFailed("a29@example.com", "5.5.5.5")
+ // 30 wrong codes from one IP block that IP for any address.
+ if l.codeAllowed("fresh@example.com", "5.5.5.5") {
+ t.Fatal("IP allowed after 30 wrong codes")
+ }
+ if !l.codeAllowed("fresh@example.com", "6.6.6.6") {
+ t.Fatal("another IP blocked")
+ }
+ c.advance(time.Hour + time.Second)
+ if !l.codeAllowed("fresh@example.com", "5.5.5.5") {
+ t.Fatal("IP still blocked after an hour")
+ }
+}
+
+func TestSigninSendSubmitCap(t *testing.T) {
+ c := newLimitClock()
+ l := newTestLimits(c)
+ for i := 0; i < 30; i++ {
+ if !l.submit("7.7.7.7") {
+ t.Fatalf("submission %d refused", i+1)
+ }
+ }
+ if l.submit("7.7.7.7") {
+ t.Fatal("31st submission within an hour allowed")
+ }
+ if !l.submit("8.8.8.8") {
+ t.Fatal("another IP refused")
+ }
+ // The submit budget is separate from the sign-in send IP budget.
+ if !l.signinSend("a@example.com", "7.7.7.7") {
+ t.Fatal("sign-in send refused by the submit window")
+ }
+ c.advance(time.Hour + time.Second)
+ if !l.submit("7.7.7.7") {
+ t.Fatal("submission after the hour refused")
+ }
+}
+
+func TestSigninSendSweepDropsStaleKeys(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))
+ }
+ 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)
+ }
+ }
+ }
+}