carlos / platform Public

console: the code guessing cap reserves before it checks

reserveGuess checks both caps and records the guess under one lock; a
right code takes it back. Two guesses at the boundary can no longer both
pass. codeAllowed/codeFailed are gone.
Co-Authored-By: Claude <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev ab84265e3099cea48ab3be102364cc8b327024c4 parent d3696e0
3 files changed, +154 −37
  • internal/console/emailsignin.go +8 −5
  • internal/console/emailsignin_limits.go +39 −19
  • internal/console/emailsignin_limits_test.go +107 −13
diff --git a/internal/console/emailsignin.go b/internal/console/emailsignin.go
index b003cac28..2661d0755 100644
--- a/internal/console/emailsignin.go
+++ b/internal/console/emailsignin.go
@@ -351,24 +351,27 @@ func (s *Server) handleEmailCode(w http.ResponseWriter, r *http.Request) {
s.renderCheckError(w, addr, r.PostFormValue("next"), copyText("check.code_used_up"))
return
}
+ // The cap is keyed by the stored challenge's address, never by the form.
+ // One guess is reserved before the check, so concurrent guesses cannot all
+ // pass on the same count; only a right code takes it back.
ip := s.clientIP(r)
- if !s.limits.codeAllowed(c.Address, ip) {
+ done, allowed := s.limits.reserveGuess(c.Address, ip)
+ if !allowed {
log.Printf("console: code for %s from %s refused: too many wrong codes", c.Address, ip)
s.renderCheckError(w, c.Address, c.Next, copyText("check.code_throttled"))
return
}
got, res := s.store.TakeEmailCode(id, strings.TrimSpace(r.PostFormValue("code")), ChallengeSignIn, now)
+ done(res == CodeOK)
switch res {
case CodeOK:
s.clearCookie(w, challengeCookie)
s.finishSignin(w, r, got.Address, "", MethodEmail, got.Next)
case CodeWrong:
- s.limits.codeFailed(c.Address, ip)
s.renderCheckError(w, c.Address, c.Next, copyText("check.code_wrong"))
- case CodeBurned:
- s.limits.codeFailed(c.Address, ip)
- s.renderCheckError(w, c.Address, c.Next, copyText("check.code_used_up"))
default:
+ // CodeBurned (this wrong code was the last) or CodeGone (the challenge
+ // went meanwhile, or predates a restart); both keep the reservation.
s.renderCheckError(w, c.Address, c.Next, copyText("check.code_used_up"))
}
}
diff --git a/internal/console/emailsignin_limits.go b/internal/console/emailsignin_limits.go
index 5b723a6a2..b4df23f16 100644
--- a/internal/console/emailsignin_limits.go
+++ b/internal/console/emailsignin_limits.go
@@ -81,6 +81,22 @@ func (w *keyedWindow) last(key string, cutoff time.Time) (time.Time, bool) {
return ts[len(ts)-1], true
}
+// remove drops one time equal to t from key, the newest such, if any.
+func (w *keyedWindow) remove(key string, t time.Time) {
+ ts := w.hits[key]
+ for i := len(ts) - 1; i >= 0; i-- {
+ if ts[i].Equal(t) {
+ ts = append(ts[:i], ts[i+1:]...)
+ break
+ }
+ }
+ if len(ts) == 0 {
+ delete(w.hits, key)
+ return
+ }
+ w.hits[key] = ts
+}
+
func (w *keyedWindow) add(key string, now time.Time) {
if w.hits == nil {
w.hits = map[string][]time.Time{}
@@ -229,32 +245,36 @@ func (l *emailLimits) stepUpSend(addr string) bool {
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.
+// reserveGuess is the guessing cap as one step, so concurrent guesses cannot
+// all pass on the same count. Under the lock it refuses (allowed false) once
+// addr has 10 guesses in 24 hours or ip has 30 in an hour; otherwise it
+// records one guess against both at once and returns done, through which the
+// caller reports the verdict: done(true), a right code, takes the reservation
+// back; done(false), any other outcome, keeps it as a wrong code. done acts
+// once; later calls do nothing. Refused, done is a no-op.
// Callers pass addr canonical (trimmed, lower-cased).
-func (l *emailLimits) codeAllowed(addr, ip string) bool {
+func (l *emailLimits) reserveGuess(addr, ip string) (done func(ok bool), allowed 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.addrWrong.count(addr, now.Add(-24*time.Hour)) >= wrongCodesPerAddrDay ||
+ l.ipWrong.count(ip, now.Add(-time.Hour)) >= wrongCodesPerIPHour {
+ return func(bool) {}, false
}
- if l.ipWrong.count(ip, now.Add(-time.Hour)) >= wrongCodesPerIPHour {
- return false
- }
- return true
-}
-
-// 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()
- now := l.clock()
- l.addrWrong.trim(addr, now)
- l.ipWrong.trim(ip, now)
l.addrWrong.add(addr, now)
l.ipWrong.add(ip, now)
+ var once sync.Once
+ return func(ok bool) {
+ once.Do(func() {
+ if !ok {
+ return
+ }
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ l.addrWrong.remove(addr, now)
+ l.ipWrong.remove(ip, now)
+ })
+ }, true
}
diff --git a/internal/console/emailsignin_limits_test.go b/internal/console/emailsignin_limits_test.go
index 1e0bc664a..ddc5e46ed 100644
--- a/internal/console/emailsignin_limits_test.go
+++ b/internal/console/emailsignin_limits_test.go
@@ -2,6 +2,8 @@ package console
import (
"fmt"
+ "sync"
+ "sync/atomic"
"testing"
"time"
)
@@ -179,31 +181,49 @@ func TestStepUpSendSeparate(t *testing.T) {
}
}
+// wrongGuess reserves one guess and keeps it, as a wrong code does.
+func wrongGuess(t *testing.T, l *emailLimits, addr, ip string) {
+ t.Helper()
+ done, ok := l.reserveGuess(addr, ip)
+ if !ok {
+ t.Fatalf("guess for %s from %s refused", addr, ip)
+ }
+ done(false)
+}
+
+// guessAllowed reports whether a guess would be allowed now, taking the
+// reservation straight back as a right code does.
+func guessAllowed(l *emailLimits, addr, ip string) bool {
+ done, ok := l.reserveGuess(addr, ip)
+ done(true)
+ return ok
+}
+
func TestCodeGuessCaps(t *testing.T) {
c := newLimitClock()
l := newTestLimits(c)
const addr = "bob@example.com"
- if !l.codeAllowed(addr, "1.1.1.1") {
+ if !guessAllowed(l, 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))
+ wrongGuess(t, l, addr, fmt.Sprintf("9.9.9.%d", i))
}
- if !l.codeAllowed(addr, "1.1.1.1") {
+ if !guessAllowed(l, addr, "1.1.1.1") {
t.Fatal("blocked after 9 wrong codes")
}
- l.codeFailed(addr, "9.9.9.99")
+ wrongGuess(t, l, 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") {
+ if guessAllowed(l, addr, "1.1.1.1") || guessAllowed(l, 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") {
+ if !guessAllowed(l, "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") {
+ if !guessAllowed(l, addr, "1.1.1.1") {
t.Fatal("address still blocked after 24h")
}
}
@@ -212,25 +232,99 @@ 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")
+ wrongGuess(t, l, fmt.Sprintf("a%d@example.com", i), "5.5.5.5")
}
- if !l.codeAllowed("fresh@example.com", "5.5.5.5") {
+ if !guessAllowed(l, "fresh@example.com", "5.5.5.5") {
t.Fatal("IP blocked after 29 wrong codes")
}
- l.codeFailed("a29@example.com", "5.5.5.5")
+ wrongGuess(t, l, "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") {
+ if guessAllowed(l, "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") {
+ if !guessAllowed(l, "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") {
+ if !guessAllowed(l, "fresh@example.com", "5.5.5.5") {
t.Fatal("IP still blocked after an hour")
}
}
+// A right code takes its reservation back, against both keys, once.
+func TestCodeGuessRightCodeRefunds(t *testing.T) {
+ c := newLimitClock()
+ l := newTestLimits(c)
+ const addr = "bob@example.com"
+ for i := 0; i < 9; i++ {
+ wrongGuess(t, l, addr, "1.1.1.1")
+ }
+ for i := 0; i < 5; i++ {
+ done, ok := l.reserveGuess(addr, "1.1.1.1")
+ if !ok {
+ t.Fatalf("right code %d refused after 9 wrong", i+1)
+ }
+ done(true)
+ done(true) // a second report changes nothing
+ }
+ if n := l.addrWrong.count(addr, c.now().Add(-24*time.Hour)); n != 9 {
+ t.Fatalf("address holds %d guesses, want the 9 wrong", n)
+ }
+ if n := l.ipWrong.count("1.1.1.1", c.now().Add(-time.Hour)); n != 9 {
+ t.Fatalf("IP holds %d guesses, want the 9 wrong", n)
+ }
+ // A kept reservation is the tenth wrong code.
+ done, _ := l.reserveGuess(addr, "1.1.1.1")
+ done(false)
+ done(true) // too late: done acts once
+ if guessAllowed(l, addr, "1.1.1.1") {
+ t.Fatal("address allowed after 10 kept guesses")
+ }
+}
+
+// The cap is one step: with nine wrong codes recorded, any number of guesses
+// arriving together let exactly one through.
+func TestCodeGuessConcurrentBoundary(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ addr, ip func(i int) string
+ have int
+ }{
+ {"address", func(int) string { return "bob@example.com" }, func(i int) string { return fmt.Sprintf("10.0.0.%d", i) }, wrongCodesPerAddrDay - 1},
+ {"ip", func(i int) string { return fmt.Sprintf("u%d@example.com", i) }, func(int) string { return "5.5.5.5" }, wrongCodesPerIPHour - 1},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ c := newLimitClock()
+ l := newTestLimits(c)
+ for i := 0; i < tc.have; i++ {
+ wrongGuess(t, l, tc.addr(1000+i), tc.ip(1000+i))
+ }
+ const n = 32
+ var (
+ start = make(chan struct{})
+ wg sync.WaitGroup
+ allowed atomic.Int32
+ )
+ for i := 0; i < n; i++ {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ <-start
+ if done, ok := l.reserveGuess(tc.addr(i), tc.ip(i)); ok {
+ allowed.Add(1)
+ done(false)
+ }
+ }()
+ }
+ close(start)
+ wg.Wait()
+ if got := allowed.Load(); got != 1 {
+ t.Fatalf("%d of %d concurrent guesses allowed at the boundary, want exactly 1", got, n)
+ }
+ })
+ }
+}
+
func TestSigninSendSubmitCap(t *testing.T) {
c := newLimitClock()
l := newTestLimits(c)