carlos / platform Public

console: global sign-in mail cap counts strangers only (H4-M5)

The 200-an-hour console-wide cap could be spent by about 20 client
addresses (one IPv6 /64), after which no one got a sign-in email. The
cap now counts and refuses only addresses the console does not know;
a user, member or live invitee (Store.KnownAddress) is bounded by its
own per-address limits and the sender's per-IP limit.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 9e9eff97359fad4967a910264cba6f57bcc9c64c parent c2eccb6
6 files changed, +159 −9
  • internal/console/emailsignin_limits.go +24 −8
  • internal/console/emailsignin_limits_test.go +25 −0
  • internal/console/emailsignin_store.go +16 −0
  • internal/console/emailsignin_store_test.go +32 −0
  • internal/console/hunt_H4-M5_test.go +57 −0
  • internal/console/server.go +5 −1
diff --git a/internal/console/emailsignin_limits.go b/internal/console/emailsignin_limits.go
index c7c297cad..ff4a2db6f 100644
--- a/internal/console/emailsignin_limits.go
+++ b/internal/console/emailsignin_limits.go
@@ -20,7 +20,7 @@ const (
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
+ signinGlobalHour = 200 // sign-in emails to unknown addresses, console-wide
newPersonPerIPHour = 10 // new people per IP
newPersonGlobalHour = 200 // new people console-wide
stepUpPerAddrHour = 10 // step-up emails per address
@@ -137,7 +137,7 @@ type emailLimits struct {
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
+ globalSend []time.Time // sign-in emails to unknown addresses, console-wide
stepUps keyedWindow // step-up emails, by address
addrWrong keyedWindow // wrong codes, by address
ipWrong keyedWindow // wrong codes, by IP
@@ -223,11 +223,25 @@ func (l *emailLimits) sweep(now time.Time) int {
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).
+// signinSend is signinSendTo for an address the console does not know: every
+// limit applies, the console-wide one included.
func (l *emailLimits) signinSend(addr, ip string) bool {
+ return l.signinSendTo(addr, ip, false)
+}
+
+// signinSendTo reports whether a sign-in email may go to addr from ip, and if
+// so records it in every window that applies. 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).
+//
+// The console-wide cap is a backstop against spraying mail at addresses the
+// console has never seen, and it counts only those (known false). A known
+// address (Store.KnownAddress) skips it: its own per-address limits bound
+// what it can be sent, and the per-IP limit bounds the sender. Otherwise a
+// few dozen client addresses (one IPv6 /64 holds plenty) could spend the
+// hour's 200 on strangers and stop every existing person signing in by
+// email (H4-M5).
+func (l *emailLimits) signinSendTo(addr, ip string, known bool) bool {
l.mu.Lock()
defer l.mu.Unlock()
now := l.clock()
@@ -254,13 +268,15 @@ func (l *emailLimits) signinSend(addr, ip string) bool {
}
}
l.globalSend = kept
- if len(kept) >= signinGlobalHour {
+ if !known && len(kept) >= signinGlobalHour {
return false
}
l.addrSends.add(addr, now)
l.ipSends.add(ip, now)
- l.globalSend = append(l.globalSend, now)
+ if !known {
+ l.globalSend = append(l.globalSend, now)
+ }
return true
}
diff --git a/internal/console/emailsignin_limits_test.go b/internal/console/emailsignin_limits_test.go
index 74d7994cd..af5dbf785 100644
--- a/internal/console/emailsignin_limits_test.go
+++ b/internal/console/emailsignin_limits_test.go
@@ -220,6 +220,31 @@ func TestSigninSendIPAndGlobal(t *testing.T) {
}
}
+// The console-wide cap counts and refuses only unknown addresses (H4-M5): a
+// known address still gets its email when strangers have spent the hour, its
+// own limits still apply, and its sends leave the strangers' budget alone.
+func TestSigninSendKnownAddressSkipsTheGlobalCap(t *testing.T) {
+ c := newLimitClock()
+ l := newTestLimits(c)
+ for i := 0; i < signinGlobalHour; i++ {
+ if !l.signinSend(fmt.Sprintf("g%d@example.com", i), fmt.Sprintf("10.0.%d.%d", i/250, i%250)) {
+ t.Fatalf("stranger send %d refused", i+1)
+ }
+ }
+ if l.signinSendTo("stranger@example.com", "10.9.9.9", false) {
+ t.Fatal("a stranger was sent past the console-wide cap")
+ }
+ if !l.signinSendTo("member@example.com", "10.9.9.9", true) {
+ t.Fatal("a known address was refused by the console-wide cap")
+ }
+ if l.signinSendTo("member@example.com", "10.9.9.8", true) {
+ t.Fatal("a known address skipped its own 60-second gap")
+ }
+ if len(l.globalSend) != signinGlobalHour {
+ t.Fatalf("console-wide window holds %d, want %d: a known send was charged to it", len(l.globalSend), signinGlobalHour)
+ }
+}
+
func TestSigninSendRefusalByIPDoesNotChargeGlobal(t *testing.T) {
c := newLimitClock()
l := newTestLimits(c)
diff --git a/internal/console/emailsignin_store.go b/internal/console/emailsignin_store.go
index 1cc647364..b16775c17 100644
--- a/internal/console/emailsignin_store.go
+++ b/internal/console/emailsignin_store.go
@@ -367,3 +367,19 @@ func scanEmailChallenge(row *sql.Row) (*EmailChallenge, int64, error) {
c.ExpiresAt = time.Unix(exp, 0)
return &c, exp, nil
}
+
+// KnownAddress reports whether the console already knows addr as a person:
+// a user, an email sign-in method, a membership, or an unaccepted, unexpired
+// invite. Sign-in mail to a known address is bounded by that address's own
+// limits, not the console-wide cap (emailsignin_limits.go), so strangers'
+// sends cannot use up the people who already have a way in. Callers pass
+// addr canonical (trimmed, lower-cased).
+func (s *Store) KnownAddress(addr string, now time.Time) (bool, error) {
+ var known bool
+ err := s.db.QueryRow(`SELECT EXISTS (SELECT 1 FROM users WHERE address = ?)
+OR EXISTS (SELECT 1 FROM sign_in_methods WHERE kind = ? AND subject = ?)
+OR EXISTS (SELECT 1 FROM memberships WHERE address = ?)
+OR EXISTS (SELECT 1 FROM invites WHERE address = ? AND accepted_at = 0 AND expires_at >= ?)`,
+ addr, MethodEmail, addr, addr, addr, now.Unix()).Scan(&known)
+ return known, err
+}
diff --git a/internal/console/emailsignin_store_test.go b/internal/console/emailsignin_store_test.go
index ae85bd099..6114c700a 100644
--- a/internal/console/emailsignin_store_test.go
+++ b/internal/console/emailsignin_store_test.go
@@ -431,3 +431,35 @@ func TestSessionMethodPreMigrationRowReadsKeymail(t *testing.T) {
t.Fatalf("pre-migration session = %q %q %v, want keymail", a, m, ok)
}
}
+
+// KnownAddress is what lets a sign-in email skip the console-wide cap
+// (H4-M5): a user, a member, or a live invite is known; a stranger, or an
+// address whose only invite has expired, is not.
+func TestKnownAddress(t *testing.T) {
+ st := openTestStore(t)
+ now := time.Now()
+ if err := st.CreateAccount(42, "cdef", "shop", "owner@example.com", now); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := st.EnsureUser("user@example.com", now); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := st.CreateInvite(42, "invitee@example.com", "owner@example.com", now); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := st.CreateInvite(42, "lapsed@example.com", "owner@example.com", now.Add(-2*InviteTTL)); err != nil {
+ t.Fatal(err)
+ }
+ for addr, want := range map[string]bool{
+ "owner@example.com": true,
+ "user@example.com": true,
+ "invitee@example.com": true,
+ "lapsed@example.com": false,
+ "stranger@example.com": false,
+ } {
+ got, err := st.KnownAddress(addr, now)
+ if err != nil || got != want {
+ t.Errorf("KnownAddress(%s) = %v, %v; want %v", addr, got, err, want)
+ }
+ }
+}
diff --git a/internal/console/hunt_H4-M5_test.go b/internal/console/hunt_H4-M5_test.go
new file mode 100644
index 000000000..874310ffe
--- /dev/null
+++ b/internal/console/hunt_H4-M5_test.go
@@ -0,0 +1,57 @@
+package console
+
+import (
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestHunt_H4_M5_GlobalBudgetCannotBlockUnrelatedSignin(t *testing.T) {
+ fx, mail := newEmailFixture(t, true)
+ submit := func(address, ip string) {
+ t.Helper()
+ lookupAnswers(fx, address, http.StatusNotFound)
+ req := httptest.NewRequest(http.MethodPost, fx.ts.URL+"/auth/continue", strings.NewReader(url.Values{"address": {address}}.Encode()))
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ req.Header.Set("Origin", fx.ts.URL)
+ req.RemoteAddr = ip
+ w := httptest.NewRecorder()
+ fx.srv.ServeHTTP(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("continue: status=%d", w.Code)
+ }
+ }
+ victim := "victim@example.com"
+ if err := fx.st.CreateAccount(42, "cdef", "victim", victim, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ for ip := 1; ip <= 20; ip++ {
+ for n := 0; n < 10; n++ {
+ submit(fmt.Sprintf("attacker-%d-%d@example.com", ip, n), fmt.Sprintf("[2001:db8:1::%x]:12345", ip))
+ waitChallengeSent(t, fx, 1)
+ }
+ }
+ if sent := len(mail.sentCopy()); sent != 200 {
+ t.Fatalf("setup sent=%d; want 200", sent)
+ }
+ submit(victim, "[2001:db8:2::1]:12345")
+ // Give the asynchronous sender its normal completion hook; no hook means
+ // the production send gate never scheduled a message.
+ select {
+ case <-fx.srv.challengeSent:
+ case <-time.After(250 * time.Millisecond):
+ }
+ victimSent := false
+ for _, msg := range mail.sentCopy() {
+ if strings.HasPrefix(msg, victim+"|") {
+ victimSent = true
+ }
+ }
+ if !victimSent {
+ t.Errorf("unrelated existing user's sign-in email suppressed after 200 unauthenticated sends from 20 IPv6 addresses in one /64: victim_delivered=false total_sent=%d; want victim delivery", len(mail.sentCopy()))
+ }
+}
diff --git a/internal/console/server.go b/internal/console/server.go
index 75f01ce82..28cbfd69d 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -3794,7 +3794,11 @@ func (s *Server) signinChallenge(flow, addr, next, ip string, underCap bool, now
return "", "", false, nil
}
c := EmailChallenge{Purpose: ChallengeSignIn, Address: addr, Next: next, FlowHash: hashToken(flow)}
- if !s.limits.signinSend(addr, ip) {
+ known, err := s.store.KnownAddress(addr, now)
+ if err != nil {
+ return "", "", false, err
+ }
+ if !s.limits.signinSendTo(addr, ip, known) {
log.Printf("console: sign-in email to %s from %s refused by its limits; not sent", addr, ip)
return "", "", false, s.store.HoldEmailChallenge(c, now)
}