carlos / platform Public

console: one flow, one rule for sent and unsent challenges (H4-M5/M6 R2)

Astra R2: a held challenge kept its attempts while a sent one reset, so
replacement told a known address from an unknown one. HoldEmailChallenge
is merged into CreateEmailChallenge(c, now, send): every request replaces
the flow's challenge and resets attempts, held when no code goes out; a
same-address repeat inside 60 s is a no-op either way. Shared send
windows are charged as for an unknown address; a known address refused
only by the global cap mails through its own window. Randomized
known-vs-unknown transcript test (500 sequences, seeded) and Astra's R2
sequence as a regression.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev e5167a36a7ea7eb95de3c2679f3e9eab60f9c0a0 parent 0053a00
13 files changed, +424 −134
  • internal/console/claim_invariant_probes_nonapp_test.go +1 −1
  • internal/console/demo_claim_auth.go +2 −5
  • internal/console/demo_claim_auth_test.go +1 −1
  • internal/console/demo_claim_page.go +2 −5
  • internal/console/emailsignin.go +3 −3
  • internal/console/emailsignin_limits.go +41 −25
  • internal/console/emailsignin_lockout_test.go +58 −0
  • internal/console/emailsignin_oracle_test.go +199 −0
  • internal/console/emailsignin_store.go +51 −49
  • internal/console/emailsignin_store_test.go +53 −34
  • internal/console/emailsignin_test.go +1 −1
  • internal/console/perfwalk_test.go +2 −2
  • internal/console/server.go +10 −8
diff --git a/internal/console/claim_invariant_probes_nonapp_test.go b/internal/console/claim_invariant_probes_nonapp_test.go
index 60e2e4fba..bbb9cb559 100644
--- a/internal/console/claim_invariant_probes_nonapp_test.go
+++ b/internal/console/claim_invariant_probes_nonapp_test.go
@@ -162,7 +162,7 @@ func claimEmailChallengeWorld(t *testing.T, cx *claimCase) {
if err != nil {
t.Fatal(err)
}
- link, code, err := cx.st.CreateEmailChallenge(EmailChallenge{Purpose: ChallengeSignIn, Address: claimFxOwner, FlowHash: hashToken(flow)}, time.Now())
+ link, code, _, err := cx.st.CreateEmailChallenge(EmailChallenge{Purpose: ChallengeSignIn, Address: claimFxOwner, FlowHash: hashToken(flow)}, time.Now(), nil)
if err != nil {
t.Fatal(err)
}
diff --git a/internal/console/demo_claim_auth.go b/internal/console/demo_claim_auth.go
index 4d4e6f2eb..c39dcd160 100644
--- a/internal/console/demo_claim_auth.go
+++ b/internal/console/demo_claim_auth.go
@@ -206,11 +206,8 @@ func (s *Server) handleDemoClaimStart(w http.ResponseWriter, r *http.Request) {
return nil
}
c := EmailChallenge{Purpose: ChallengeDemoClaim, FlowHash: flow.Hash, Address: flow.Address, ExpiresAt: flow.ExpiresAt}
- if !s.limits.signinSend(address, ip) {
- return s.store.HoldEmailChallenge(c, now)
- }
- link, code, err = s.store.CreateEmailChallenge(c, now)
- sent = err == nil
+ // The send limits' clock decides the repeat rule, as for sign-in.
+ link, code, sent, err = s.store.CreateEmailChallenge(c, s.limits.clock(), func() bool { return s.limits.signinSend(address, ip) })
return err
})
if err != nil {
diff --git a/internal/console/demo_claim_auth_test.go b/internal/console/demo_claim_auth_test.go
index 1707ef27b..040875830 100644
--- a/internal/console/demo_claim_auth_test.go
+++ b/internal/console/demo_claim_auth_test.go
@@ -121,7 +121,7 @@ func TestDemoClaimProofBinding(t *testing.T) {
purpose = ChallengeStepUp
}
var err error
- _, code, err = s.store.CreateEmailChallenge(EmailChallenge{Purpose: purpose, Address: "shop@example.com", FlowHash: hashToken(flow), SessionHash: hashToken(flow)}, time.Now())
+ _, code, _, err = s.store.CreateEmailChallenge(EmailChallenge{Purpose: purpose, Address: "shop@example.com", FlowHash: hashToken(flow), SessionHash: hashToken(flow)}, time.Now(), nil)
if err != nil {
t.Fatal(err)
}
diff --git a/internal/console/demo_claim_page.go b/internal/console/demo_claim_page.go
index 4e0de4ede..99cf03d00 100644
--- a/internal/console/demo_claim_page.go
+++ b/internal/console/demo_claim_page.go
@@ -502,11 +502,8 @@ func (s *Server) handleDemoClaimBrowserProof(w http.ResponseWriter, r *http.Requ
return nil
}
c := EmailChallenge{Purpose: ChallengeDemoClaim, FlowHash: f.Hash, Address: address, ExpiresAt: f.ExpiresAt}
- if !s.limits.signinSend(address, ip) {
- return s.store.HoldEmailChallenge(c, now)
- }
- link, code, err = s.store.CreateEmailChallenge(c, now)
- sent = err == nil
+ // The send limits' clock decides the repeat rule, as for sign-in.
+ link, code, sent, err = s.store.CreateEmailChallenge(c, s.limits.clock(), func() bool { return s.limits.signinSend(address, ip) })
return err
})
mu.Unlock()
diff --git a/internal/console/emailsignin.go b/internal/console/emailsignin.go
index b0f8486ee..65c835934 100644
--- a/internal/console/emailsignin.go
+++ b/internal/console/emailsignin.go
@@ -445,7 +445,7 @@ func (s *Server) handleEmailCode(w http.ResponseWriter, r *http.Request) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return
}
- now := time.Now()
+ now := s.limits.clock() // handleContinue's clock
flow := s.requestFlow(r)
// The page shows the address and next the form carried, never the stored
// challenge's: shown only, never used as a key.
@@ -516,13 +516,13 @@ func (s *Server) emailStepUp(w http.ResponseWriter, r *http.Request, addr, raw s
return false
}
// It replaces this session's earlier step-up challenge, if any.
- link, code, err := s.store.CreateEmailChallenge(EmailChallenge{
+ link, code, _, err := s.store.CreateEmailChallenge(EmailChallenge{
Purpose: ChallengeStepUp,
Address: addr,
SessionHash: hashToken(raw),
PendingHash: hashToken(pending),
ExpiresAt: now.Add(stepUpFlowTTL),
- }, now)
+ }, now, nil)
if err != nil {
log.Printf("console: step-up challenge for %s: %v", addr, err)
s.renderMessage(w, r, http.StatusInternalServerError, "Error", "Could not start the confirmation. Please try again.")
diff --git a/internal/console/emailsignin_limits.go b/internal/console/emailsignin_limits.go
index d7701f7b9..56406a679 100644
--- a/internal/console/emailsignin_limits.go
+++ b/internal/console/emailsignin_limits.go
@@ -20,7 +20,9 @@ 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 to unknown addresses, console-wide
+ signinGlobalHour = 200 // sign-in emails console-wide (see signinSendTo)
+ knownPastCapHour = 5 // sign-in emails per known address past the console-wide cap
+ knownPastCapDay = 10 // sign-in emails per known address past the console-wide cap
newPersonPerIPHour = 10 // new people per IP
newPersonGlobalHour = 200 // new people console-wide
stepUpPerAddrHour = 10 // step-up emails per address
@@ -137,7 +139,8 @@ 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 to unknown addresses, console-wide
+ globalSend []time.Time // sign-in emails, console-wide
+ pastCap keyedWindow // known addresses' sign-in emails past the console-wide cap, by address
stepUps keyedWindow // step-up emails, by address
stepWrong keyedWindow // wrong step-up codes, by session hash
ipWrong keyedWindow // wrong codes, by IP
@@ -174,7 +177,7 @@ func (l *emailLimits) submit(ip string) bool {
}
func (l *emailLimits) sweepWindows() []*keyedWindow {
- return []*keyedWindow{&l.submits, &l.addrSends, &l.ipSends, &l.stepUps, &l.stepWrong, &l.ipWrong, &l.alertConfirms, &l.ipNewPeople}
+ return []*keyedWindow{&l.submits, &l.addrSends, &l.ipSends, &l.stepUps, &l.pastCap, &l.stepWrong, &l.ipWrong, &l.alertConfirms, &l.ipNewPeople}
}
// newPerson reserves one new-person slot across all sign-in paths (social
@@ -229,18 +232,22 @@ 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).
+// signinSendTo reports whether a sign-in email may go to addr from ip, and
+// records it. 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).
+// Every shared window (the address's, the IP's, the console-wide one) is
+// decided and charged exactly as for an unknown address, all or nothing: a
+// refusal by any one limit charges none of them. So their state never
+// depends on whether the console knows addr, and nothing a requester can
+// see later (its own sends, another address's) can tell (H4-M5/M6 review 2).
+//
+// The console-wide cap is a backstop against spraying mail at strangers. A
+// few dozen client addresses (one IPv6 /64 holds plenty) can fill it, which
+// must not stop existing people signing in by email (H4-M5). So when the
+// console-wide cap is the ONLY refusal and addr is known (Store.KnownAddress),
+// the email still goes, charged to pastCap alone: its own budget of
+// knownPastCapHour and knownPastCapDay per address with the usual 60-second
+// gap, which nothing but this decision reads.
func (l *emailLimits) signinSendTo(addr, ip string, known bool) bool {
l.mu.Lock()
defer l.mu.Unlock()
@@ -268,15 +275,22 @@ func (l *emailLimits) signinSendTo(addr, ip string, known bool) bool {
}
}
l.globalSend = kept
- if !known && len(kept) >= signinGlobalHour {
- return false
+ if len(kept) >= signinGlobalHour {
+ if !known {
+ return false
+ }
+ l.pastCap.trim(addr, now)
+ if _, ok := l.pastCap.last(addr, now.Add(-emailResendGap)); ok ||
+ l.pastCap.count(addr, hour) >= knownPastCapHour || l.pastCap.count(addr, day) >= knownPastCapDay {
+ return false
+ }
+ l.pastCap.add(addr, now)
+ return true
}
l.addrSends.add(addr, now)
l.ipSends.add(ip, now)
- if !known {
- l.globalSend = append(l.globalSend, now)
- }
+ l.globalSend = append(l.globalSend, now)
return true
}
@@ -336,15 +350,17 @@ func (l *emailLimits) stepUpSend(addr string) bool {
// - A code is checked only against the newest challenge of the guessing
// browser's own flow, and the fifth wrong code burns it
// (emailCodeAttempts, counted in the row).
-// - A held challenge (Store.HoldEmailChallenge) never redeems a code: its
+// - A held challenge (one Store.CreateEmailChallenge made unsent) never redeems a code: its
// code was never sent. Guessing it is worthless, so its number is
// unbounded without harm.
-// - A sent challenge exists only when signinSend lets an email go to the
-// address: at most signinPerAddrDay (20) a day, demo claims included.
+// - A sent challenge exists only when signinSendTo lets an email go to
+// the address: at most signinPerAddrDay (20) a day, demo claims
+// included, plus, for a known address while the console-wide cap is
+// full, knownPastCapDay (10) more.
//
-// So an address faces at most 20 x 5 = 100 guesses a day at codes that
-// redeem, each right with probability 1 in 10^6: at most 1e-4 a day, about
-// 3.6% over a year of continuous attack on one address. A restart resets the
+// So an address faces at most 30 x 5 = 150 guesses a day at codes that
+// redeem, each right with probability 1 in 10^6: at most 1.5e-4 a day, about
+// 5.3% over a year of continuous attack on one address. A restart resets the
// send windows (see the top of this file) and buys a fresh day; the IP
// budget below caps how fast any one client gets there. Step-up codes go to
// a budget keyed by the session that asked (only that session can type
diff --git a/internal/console/emailsignin_lockout_test.go b/internal/console/emailsignin_lockout_test.go
index 184383979..6d5b9fca6 100644
--- a/internal/console/emailsignin_lockout_test.go
+++ b/internal/console/emailsignin_lockout_test.go
@@ -137,3 +137,61 @@ func TestKnownAndUnknownAddressAnswerAlike(t *testing.T) {
}
}
}
+
+// fillStrangerCap spends the console-wide send budget on strangers from
+// filler IPs, as a flood of unrelated requests would.
+func fillStrangerCap(t *testing.T, fx *consoleFixture, tag string) {
+ t.Helper()
+ for i := 0; ; i++ {
+ if !fx.srv.limits.signinSend(fmt.Sprintf("fill-%s-%d@example.net", tag, i), fmt.Sprintf("10.%d.%d.%d", 100+i/65000, i/250%250, i%250)) {
+ return
+ }
+ if i > 10*signinGlobalHour {
+ t.Fatal("console-wide cap never filled")
+ }
+ }
+}
+
+// Astra's review-2 sequence: with the stranger budget full, one flow asks
+// for an unknown seed address, spends four wrong codes, then asks for the
+// target, and types one more wrong code. Known or not, the last answer is
+// the same (both replace the challenge and reset its attempts).
+func TestR2ReplacementDoesNotRevealAKnownAddress(t *testing.T) {
+ const target, seedAddr = "target@example.com", "seed@example.org"
+ run := func(known bool) []string {
+ fx, _ := newEmailFixture(t, true)
+ lookupAnswers(fx, target, http.StatusNotFound)
+ lookupAnswers(fx, seedAddr, http.StatusNotFound)
+ if known {
+ if err := fx.st.CreateAccount(42, "cdef", "target", target, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ }
+ fillStrangerCap(t, fx, "r2")
+ const ip, flow = "198.51.100.9:40000", "r2-flow-dddddddddddddddddddddddddddddddddddddddd"
+ var seen []string
+ step := func(path string, form url.Values) {
+ status, body := postAs(t, fx, ip, flow, path, form)
+ seen = append(seen, fmt.Sprintf("%s %d\n%s", path, status, strings.ReplaceAll(body, fx.ts.URL, "ORIGIN")))
+ }
+ step("/auth/continue", url.Values{"address": {seedAddr}})
+ for i := 0; i < emailCodeAttempts-1; i++ {
+ step("/auth/email/code", url.Values{"code": {"zzzzzz"}})
+ }
+ step("/auth/continue", url.Values{"address": {target}})
+ step("/auth/email/code", url.Values{"code": {"zzzzzz"}})
+ if known {
+ waitChallengeSent(t, fx, 1)
+ }
+ return seen
+ }
+ known, unknown := run(true), run(false)
+ for i := range known {
+ if known[i] != unknown[i] {
+ t.Errorf("step %d differs between a known and an unknown target:\nknown:\n%s\nunknown:\n%s", i+1, known[i], unknown[i])
+ }
+ }
+ if last := known[len(known)-1]; !strings.Contains(last, esc(copyText("check.code_wrong"))) {
+ t.Errorf("the code after asking for the target = %s; want a wrong code on a fresh challenge", last)
+ }
+}
diff --git a/internal/console/emailsignin_oracle_test.go b/internal/console/emailsignin_oracle_test.go
new file mode 100644
index 000000000..f8f3a399b
--- /dev/null
+++ b/internal/console/emailsignin_oracle_test.go
@@ -0,0 +1,199 @@
+package console
+
+// "One flow, one rule" (H4-M5/M6 review 2, Paul's ruling): a requester who
+// does not hold the target's mailbox must see exactly the same thing whether
+// the console knows the target or not. Random sequences of what such a
+// requester can do run twice, once with the target a known person and once
+// not; every response (status, headers, body), and every email that goes to
+// an address other than the target (one the requester might own), must be
+// the same both times. Only the target's own mail may differ.
+
+import (
+ "flag"
+ "fmt"
+ "math/rand/v2"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "regexp"
+ "sort"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+var oracleSeed = flag.Uint64("oracle.seed", 0, "seed for TestKnownAddressOracleInvariant (0: time-based)")
+
+const (
+ oracleTarget = "target@example.com"
+ oracleSequences = 500
+)
+
+var serverTimingDur = regexp.MustCompile(`dur=[0-9.]+`)
+
+var oracleSeeds = []string{"seed-a@example.org", "seed-b@example.org"}
+
+// oracleOp is one requester action.
+type oracleOp struct {
+ kind string // continue, wrong, flow, ip, advance, fill
+ addr string
+ d time.Duration
+}
+
+func (o oracleOp) String() string {
+ switch o.kind {
+ case "continue":
+ return "continue " + o.addr
+ case "advance":
+ return "advance " + o.d.String()
+ }
+ return o.kind
+}
+
+func oracleSequence(r *rand.Rand) []oracleOp {
+ ops := []oracleOp{}
+ if r.IntN(2) == 0 {
+ ops = append(ops, oracleOp{kind: "fill"})
+ }
+ addrs := append([]string{oracleTarget, oracleTarget}, oracleSeeds...)
+ for n := 3 + r.IntN(12); n > 0; n-- {
+ switch k := r.IntN(10); {
+ case k < 4:
+ ops = append(ops, oracleOp{kind: "continue", addr: addrs[r.IntN(len(addrs))]})
+ case k < 7:
+ ops = append(ops, oracleOp{kind: "wrong"})
+ case k == 7:
+ ops = append(ops, oracleOp{kind: []string{"flow", "ip"}[r.IntN(2)]})
+ case k == 8:
+ ops = append(ops, oracleOp{kind: "advance", d: []time.Duration{20 * time.Second, emailResendGap + time.Second, 16 * time.Minute, time.Hour + time.Second}[r.IntN(4)]})
+ default:
+ ops = append(ops, oracleOp{kind: "fill"})
+ }
+ }
+ return ops
+}
+
+// oracleWorld is one fixture, known or not, reused across sequences.
+type oracleWorld struct {
+ fx *consoleFixture
+ mail *fakeConsoleMail
+ off atomic.Int64
+}
+
+func newOracleWorld(t *testing.T, known bool) *oracleWorld {
+ fx, m := newEmailFixture(t, true)
+ fx.srv.challengeSent = make(chan struct{}, 64)
+ for _, a := range append([]string{oracleTarget}, oracleSeeds...) {
+ lookupAnswers(fx, a, http.StatusNotFound)
+ }
+ if known {
+ if err := fx.st.CreateAccount(42, "cdef", "target", oracleTarget, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ }
+ w := &oracleWorld{fx: fx, mail: m}
+ return w
+}
+
+// newest is the flow's newest challenge row and whether it is held.
+func (w *oracleWorld) newest(flow string) (id string, held bool) {
+ w.fx.st.db.QueryRow(`SELECT id_hash, held FROM email_challenges WHERE flow_hash = ? ORDER BY created_at DESC, rowid DESC LIMIT 1`,
+ hashToken(flow)).Scan(&id, &held)
+ return id, held
+}
+
+// run plays ops from a clean slate and returns the transcript.
+func (w *oracleWorld) run(t *testing.T, seq int, ops []oracleOp) []string {
+ fx := w.fx
+ base := time.Now().Add(time.Duration(w.off.Load()))
+ w.off.Store(0)
+ var off atomic.Int64
+ fx.srv.limits = emailLimits{now: func() time.Time { return base.Add(time.Duration(off.Load())) }}
+ if _, err := fx.st.db.Exec(`DELETE FROM email_challenges`); err != nil {
+ t.Fatal(err)
+ }
+ flowN, ipN := 0, 0
+ flow := func() string {
+ return fmt.Sprintf("oracle-%04d-flow-%02d-eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", seq, flowN)
+ }
+ ip := func() string { return fmt.Sprintf("203.0.%d.%d:40000", 1+ipN, 1+seq%250) }
+ var out []string
+ for i, op := range ops {
+ var line string
+ switch op.kind {
+ case "fill":
+ fillStrangerCap(t, fx, fmt.Sprintf("%d-%d", seq, i))
+ line = "filled"
+ case "flow":
+ flowN++
+ line = "new flow"
+ case "ip":
+ ipN++
+ line = "new ip"
+ case "advance":
+ off.Add(int64(op.d))
+ line = "advanced"
+ case "continue", "wrong":
+ path, form := "/auth/email/code", url.Values{"code": {"zzzzzz"}}
+ if op.kind == "continue" {
+ path, form = "/auth/continue", url.Values{"address": {op.addr}}
+ }
+ before, _ := w.newest(flow())
+ sentBefore := len(w.mail.sentCopy())
+ r := httptest.NewRequest(http.MethodPost, path, strings.NewReader(form.Encode()))
+ r.RemoteAddr = ip()
+ r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ r.AddCookie(&http.Cookie{Name: flowCookie, Value: flow()})
+ rec := httptest.NewRecorder()
+ fx.srv.ServeHTTP(rec, r)
+ if after, held := w.newest(flow()); op.kind == "continue" && after != "" && after != before && !held {
+ select { // a send was scheduled: let it land
+ case <-fx.srv.challengeSent:
+ case <-time.After(5 * time.Second):
+ t.Fatal("a scheduled send never finished")
+ }
+ }
+ var others []string
+ for _, m := range w.mail.sentCopy()[sentBefore:] {
+ if to, _, _ := strings.Cut(m, "|"); to != oracleTarget {
+ others = append(others, to)
+ }
+ }
+ var hdr []string
+ for k, vs := range rec.Result().Header {
+ v := strings.Join(vs, ", ")
+ if k == "Server-Timing" { // measured durations: noise, not state
+ v = serverTimingDur.ReplaceAllString(v, "dur=N")
+ }
+ hdr = append(hdr, k+": "+v)
+ }
+ sort.Strings(hdr)
+ line = fmt.Sprintf("%d\n%s\n%s\nmail to others: %v", rec.Code, strings.Join(hdr, "\n"), rec.Body.String(), others)
+ line = strings.ReplaceAll(line, fx.ts.URL, "ORIGIN")
+ }
+ out = append(out, op.String()+" -> "+line)
+ }
+ w.off.Store(off.Load())
+ return out
+}
+
+func TestKnownAddressOracleInvariant(t *testing.T) {
+ seed := *oracleSeed
+ if seed == 0 {
+ seed = uint64(time.Now().UnixNano())
+ }
+ known, unknown := newOracleWorld(t, true), newOracleWorld(t, false)
+ start := time.Now()
+ for seq := 0; seq < oracleSequences; seq++ {
+ ops := oracleSequence(rand.New(rand.NewPCG(seed, uint64(seq))))
+ a, b := known.run(t, seq, ops), unknown.run(t, seq, ops)
+ for i := range a {
+ if a[i] != b[i] {
+ t.Fatalf("seed %d (rerun with -oracle.seed=%d), sequence %d, step %d of %v differs between a known and an unknown target:\nknown:\n%s\n\nunknown:\n%s",
+ seed, seed, seq, i+1, ops, a[i], b[i])
+ }
+ }
+ }
+ t.Logf("seed %d: %d sequences alike in %v", seed, oracleSequences, time.Since(start).Round(time.Millisecond))
+}
diff --git a/internal/console/emailsignin_store.go b/internal/console/emailsignin_store.go
index d2c440f1c..74a87ab62 100644
--- a/internal/console/emailsignin_store.go
+++ b/internal/console/emailsignin_store.go
@@ -49,7 +49,7 @@ type EmailChallenge struct {
// row is the challenge's row key (id_hash), set by LiveEmailChallenge, so
// TakeEmailCode checks the very challenge that was read.
row string
- // held, set by LiveEmailChallenge, is a challenge HoldEmailChallenge
+ // held, set by LiveEmailChallenge, is a challenge CreateEmailChallenge
// stored for a refused request: its code was never sent, and no code
// redeems it.
held bool
@@ -97,7 +97,7 @@ func (s *Store) migrateEmailSignin() error {
!strings.Contains(err.Error(), "duplicate column") {
return err
}
- // Additive: 1 marks a held challenge (HoldEmailChallenge), whose code was
+ // Additive: 1 marks a held challenge (CreateEmailChallenge), whose code was
// never sent and never redeems. Rows from before it read 0, as they did.
if _, err := s.db.Exec(`ALTER TABLE email_challenges ADD COLUMN held INTEGER NOT NULL DEFAULT 0`); err != nil &&
!strings.Contains(err.Error(), "duplicate column") {
@@ -136,62 +136,64 @@ func (s *Store) codeMAC(linkHash, code string) string {
return s.codeEpoch + ":" + hex.EncodeToString(m.Sum(nil))
}
-// CreateEmailChallenge stores a challenge and returns the emailed link token
-// and the six-digit code. A zero ExpiresAt means ConfirmationTTL from now. In
-// the same transaction it deletes every earlier challenge of the same purpose
-// and binding (the flow's sign-ins, or the session's step-ups), so only the
-// newest email's link and code work. An empty binding replaces nothing.
-func (s *Store) CreateEmailChallenge(c EmailChallenge, now time.Time) (link, code string, err error) {
+// CreateEmailChallenge is the one way a challenge comes to be, sent or not
+// (H4-M5/M6 review 2, "one flow, one rule"). It returns the link token and
+// six-digit code to email, and whether to email them. A zero ExpiresAt means
+// ConfirmationTTL from now. In one transaction:
+//
+// - A requester's repeat is kept as it is: when send is not nil and the
+// binding's newest live challenge is for c.Address and less than
+// emailResendGap old, nothing changes, send is not asked, and sent is
+// false. A double-click or an impatient resubmission so leaves the email
+// already on its way working, and resets no attempts.
+// - Otherwise send is asked (nil means yes); every earlier challenge of
+// the same purpose and binding (the flow's sign-ins, or the session's
+// step-ups) is deleted; and a new one is stored with no attempts, so
+// only the newest email's link and code work. When send said no, the
+// new row is held: its link and code are told to nobody, and no code
+// ever redeems it (TakeEmailCode), so guessing it is worthless.
+//
+// Whether a code goes out is the only difference between the two, and it
+// shows to nobody but the mailbox: the requester sees the same challenge
+// replaced, the same attempts and the same expiry either way, so nothing it
+// can do tells a known address from an unknown one, or a sent challenge from
+// a held one. An empty binding replaces nothing. send runs inside the
+// transaction and must not use the store.
+func (s *Store) CreateEmailChallenge(c EmailChallenge, now time.Time, send func() bool) (link, code string, sent bool, err error) {
tx, err := s.db.Begin()
if err != nil {
- return "", "", err
+ return "", "", false, err
}
defer tx.Rollback()
+ if send != nil {
+ if col, ok := challengeBinding(c.Purpose); ok && bindingOf(c) != "" {
+ var addr string
+ var created int64
+ err := tx.QueryRow(`SELECT address, created_at FROM email_challenges
+WHERE purpose = ? AND `+col+` = ? AND expires_at >= ?
+ORDER BY created_at DESC, rowid DESC LIMIT 1`, c.Purpose, bindingOf(c), now.Unix()).Scan(&addr, &created)
+ if err == nil && addr == c.Address && created > now.Add(-emailResendGap).Unix() {
+ return "", "", false, nil
+ }
+ if err != nil && err != sql.ErrNoRows {
+ return "", "", false, err
+ }
+ }
+ }
+ sent = send == nil || send()
if err := deleteBound(tx, c.Purpose, bindingOf(c)); err != nil {
- return "", "", err
+ return "", "", false, err
}
- if link, code, err = s.insertEmailChallenge(tx, c, false, now); err != nil {
- return "", "", err
+ if link, code, err = s.insertEmailChallenge(tx, c, !sent, now); err != nil {
+ return "", "", false, err
}
if err := tx.Commit(); err != nil {
- return "", "", err
- }
- return link, code, nil
-}
-
-// HoldEmailChallenge is a refused request's challenge (spec §15, rev 6): when
-// c's binding already has a live challenge of c's purpose it changes nothing,
-// so the email already sent keeps working; otherwise it stores c with a link
-// and code nobody is ever told, so a typed code reads exactly as it would
-// against a sent one, and nothing the mailbox could redeem exists. The row is
-// marked held: no code ever redeems it (TakeEmailCode), so guessing at it is
-// worthless, and only sent challenges count toward the guessing bound
-// (reserveCodeGuess).
-func (s *Store) HoldEmailChallenge(c EmailChallenge, now time.Time) error {
- col, ok := challengeBinding(c.Purpose)
- if !ok {
- return fmt.Errorf("console: no binding for challenge purpose %q", c.Purpose)
+ return "", "", false, err
}
- tx, err := s.db.Begin()
- if err != nil {
- return err
- }
- defer tx.Rollback()
- var live int
- if err := tx.QueryRow(`SELECT COUNT(*) FROM email_challenges WHERE purpose = ? AND `+col+` = ? AND expires_at >= ?`,
- c.Purpose, bindingOf(c), now.Unix()).Scan(&live); err != nil {
- return err
- }
- if live > 0 {
- return nil
- }
- if err := deleteBound(tx, c.Purpose, bindingOf(c)); err != nil {
- return err
- }
- if _, _, err := s.insertEmailChallenge(tx, c, true, now); err != nil {
- return err
+ if !sent {
+ return "", "", false, nil
}
- return tx.Commit()
+ return link, code, true, nil
}
// deleteBound deletes every challenge of purpose bound to bind; an empty bind
@@ -206,7 +208,7 @@ func deleteBound(tx *sql.Tx, purpose, bind string) error {
}
// insertEmailChallenge mints a challenge's row key, link and code and stores
-// c under them, marked held when it is HoldEmailChallenge's. The row key is
+// c under them, marked held when its code is not sent. The row key is
// internal: no browser is given it.
func (s *Store) insertEmailChallenge(tx *sql.Tx, c EmailChallenge, held bool, now time.Time) (link, code string, err error) {
row, err := randomToken()
diff --git a/internal/console/emailsignin_store_test.go b/internal/console/emailsignin_store_test.go
index f8f535571..4fb5ac2ad 100644
--- a/internal/console/emailsignin_store_test.go
+++ b/internal/console/emailsignin_store_test.go
@@ -16,10 +16,10 @@ var testFlow = hashToken("a-test-flow-token-of-some-length-000000")
func newSignInChallenge(t *testing.T, s *Store, now time.Time, flowHash string) (link, code string) {
t.Helper()
- link, code, err := s.CreateEmailChallenge(EmailChallenge{
+ link, code, _, err := s.CreateEmailChallenge(EmailChallenge{
Purpose: ChallengeSignIn, Address: "bob@example.com", Next: "/auth/cli", FlowHash: flowHash,
ExpiresAt: now.Add(ConfirmationTTL),
- }, now)
+ }, now, nil)
if err != nil {
t.Fatal(err)
}
@@ -96,9 +96,9 @@ func TestEmailChallengeLiveByFlow(t *testing.T) {
t.Fatal("a taken challenge is still live")
}
// A step-up is found by its session's hash.
- if _, _, err := s.CreateEmailChallenge(EmailChallenge{
+ if _, _, _, err := s.CreateEmailChallenge(EmailChallenge{
Purpose: ChallengeStepUp, Address: "bob@example.com", SessionHash: "sh", PendingHash: "ph",
- }, now); err != nil {
+ }, now, nil); err != nil {
t.Fatal(err)
}
if c, ok := s.LiveEmailChallenge(ChallengeStepUp, "sh", now); !ok || c.PendingHash != "ph" {
@@ -282,45 +282,64 @@ func TestEmailChallengeReplace(t *testing.T) {
}
}
-// A refused request's challenge is recorded only when the flow has no live
-// one, and never displaces the email already sent.
-func TestEmailChallengeHold(t *testing.T) {
+// One rule for sent and unsent (H4-M5/M6 review 2): a requester's request
+// replaces the flow's challenge and resets attempts whether or not its code
+// goes out; an unsent one is held and redeems nothing; a same-address repeat
+// inside the resend gap changes nothing and asks nothing.
+func TestEmailChallengeOneRule(t *testing.T) {
s := openTestStore(t)
now := time.Now()
- link, code := newSignInChallenge(t, s, now, testFlow)
- held := EmailChallenge{Purpose: ChallengeSignIn, Address: "carol@example.com", FlowHash: testFlow}
- if err := s.HoldEmailChallenge(held, now); err != nil {
- t.Fatal(err)
- }
- if n := countChallenges(t, s); n != 1 {
- t.Fatalf("%d challenges after a hold beside a live one, want 1", n)
+ asks := 0
+ send := func(ok bool) func() bool { return func() bool { asks++; return ok } }
+ bob := EmailChallenge{Purpose: ChallengeSignIn, Address: "bob@example.com", FlowHash: testFlow}
+ carol := EmailChallenge{Purpose: ChallengeSignIn, Address: "carol@example.com", FlowHash: testFlow}
+
+ link, code, sent, err := s.CreateEmailChallenge(bob, now, send(true))
+ if err != nil || !sent || link == "" || code == "" {
+ t.Fatalf("sent create = %q %q %v %v", link, code, sent, err)
}
- if c := live(t, s, testFlow, now); c.Address != "bob@example.com" {
- t.Fatalf("the hold displaced the sent challenge: %+v", c)
+ // A repeat inside the gap: nothing changes, send not asked.
+ if _, _, sent, err := s.CreateEmailChallenge(bob, now.Add(emailResendGap-2*time.Second), send(false)); err != nil || sent || asks != 1 {
+ t.Fatalf("repeat = sent %v, %v, asks %d; want a no-op", sent, err, asks)
}
if _, ok := s.PeekEmailLink(link, now); !ok {
- t.Fatal("the hold ended the sent link")
+ t.Fatal("a repeat ended the email already sent")
}
- if _, res := s.TakeEmailCode(live(t, s, testFlow, now), code, now); res != CodeOK {
- t.Fatalf("the sent code after a hold = %v", res)
+ // Spend four attempts, then ask for another address, unsent: replaced,
+ // held, attempts reset to five fresh ones.
+ for i := 0; i < emailCodeAttempts-1; i++ {
+ if _, res := s.TakeEmailCode(live(t, s, testFlow, now), wrongCode(code), now); res != CodeWrong {
+ t.Fatalf("wrong code %d = %v", i+1, res)
+ }
}
- // A flow with none gets an unsent challenge for the refused address.
- if err := s.HoldEmailChallenge(held, now); err != nil {
- t.Fatal(err)
+ if _, _, sent, err := s.CreateEmailChallenge(carol, now, send(false)); err != nil || sent {
+ t.Fatalf("unsent create = %v %v", sent, err)
}
c := live(t, s, testFlow, now)
- if c.Address != "carol@example.com" {
- t.Fatalf("held challenge = %+v", c)
+ if c.Address != "carol@example.com" || !c.held || countChallenges(t, s) != 1 {
+ t.Fatalf("after an unsent create: %+v, %d rows", c, countChallenges(t, s))
}
- if _, res := s.TakeEmailCode(c, "000000", now); res == CodeGone {
- t.Fatal("a code against the held challenge found nothing, unlike a sent one")
+ if _, ok := s.PeekEmailLink(link, now); ok {
+ t.Fatal("the replaced challenge's link still works")
+ }
+ for i := 1; i <= emailCodeAttempts; i++ {
+ want := CodeWrong
+ if i == emailCodeAttempts {
+ want = CodeBurned
+ }
+ if _, res := s.TakeEmailCode(live(t, s, testFlow, now), "000000", now); res != want {
+ t.Fatalf("held attempt %d = %v, want %v", i, res, want)
+ }
}
- // An expired one counts as none.
- if err := s.HoldEmailChallenge(held, now.Add(ConfirmationTTL+time.Second)); err != nil {
+ // Past the gap, the same address is a new request again.
+ if _, _, sent, err := s.CreateEmailChallenge(carol, now, send(false)); err != nil || sent {
t.Fatal(err)
}
- if n := countChallenges(t, s); n != 1 {
- t.Fatalf("%d challenges after holding past an expired one, want 1", n)
+ if _, _, _, err := s.CreateEmailChallenge(carol, now.Add(emailResendGap+time.Second), send(true)); err != nil {
+ t.Fatal(err)
+ }
+ if c := live(t, s, testFlow, now.Add(emailResendGap+time.Second)); c.held || countChallenges(t, s) != 1 {
+ t.Fatalf("a sent create past the gap = %+v, %d rows", c, countChallenges(t, s))
}
}
@@ -490,14 +509,14 @@ func TestHeldChallengeNeverRedeemsACode(t *testing.T) {
t.Fatalf("held challenge's own code = %v, %v; want CodeWrong", got, res)
}
- // HoldEmailChallenge marks its row held; a sent one is not.
- if err := st.HoldEmailChallenge(EmailChallenge{Purpose: ChallengeSignIn, Address: "bob@example.com", FlowHash: hashToken("other")}, now); err != nil {
+ // An unsent create marks its row held; a sent one is not.
+ if _, _, _, err := st.CreateEmailChallenge(EmailChallenge{Purpose: ChallengeSignIn, Address: "bob@example.com", FlowHash: hashToken("other")}, now, func() bool { return false }); err != nil {
t.Fatal(err)
}
if h, ok := st.LiveEmailChallenge(ChallengeSignIn, hashToken("other"), now); !ok || !h.held {
- t.Fatalf("HoldEmailChallenge row = %+v, %v; want held", h, ok)
+ t.Fatalf("unsent row = %+v, %v; want held", h, ok)
}
- if _, _, err := st.CreateEmailChallenge(EmailChallenge{Purpose: ChallengeSignIn, Address: "bob@example.com", FlowHash: hashToken("sent")}, now); err != nil {
+ if _, _, _, err := st.CreateEmailChallenge(EmailChallenge{Purpose: ChallengeSignIn, Address: "bob@example.com", FlowHash: hashToken("sent")}, now, nil); err != nil {
t.Fatal(err)
}
if s, ok := st.LiveEmailChallenge(ChallengeSignIn, hashToken("sent"), now); !ok || s.held {
diff --git a/internal/console/emailsignin_test.go b/internal/console/emailsignin_test.go
index cfb5d3973..c8a82f306 100644
--- a/internal/console/emailsignin_test.go
+++ b/internal/console/emailsignin_test.go
@@ -935,7 +935,7 @@ func TestEmailCodeGuessCap(t *testing.T) {
c.Jar.SetCookies(u, []*http.Cookie{{Name: flowCookie, Value: flow, Path: "/"}})
// Each new challenge in the flow replaces the one before.
fresh := func() (link, code string) {
- link, code, err := fx.st.CreateEmailChallenge(EmailChallenge{Purpose: ChallengeSignIn, Address: addr, FlowHash: hashToken(flow)}, time.Now())
+ link, code, _, err := fx.st.CreateEmailChallenge(EmailChallenge{Purpose: ChallengeSignIn, Address: addr, FlowHash: hashToken(flow)}, time.Now(), nil)
if err != nil {
t.Fatal(err)
}
diff --git a/internal/console/perfwalk_test.go b/internal/console/perfwalk_test.go
index ccf86426e..77e5f21bd 100644
--- a/internal/console/perfwalk_test.go
+++ b/internal/console/perfwalk_test.go
@@ -192,8 +192,8 @@ func perfSeed(t *testing.T, fx *consoleFixture, seeds *perfSeeds) {
}
seeds.invite = tok
// /auth/email/link?t=: a live sign-in link; its GET never spends it.
- link, _, err := fx.st.CreateEmailChallenge(EmailChallenge{Purpose: ChallengeSignIn, Address: "paul@keymail.dev",
- FlowHash: hashToken("perf-walk-flow")}, now)
+ link, _, _, err := fx.st.CreateEmailChallenge(EmailChallenge{Purpose: ChallengeSignIn, Address: "paul@keymail.dev",
+ FlowHash: hashToken("perf-walk-flow")}, now, nil)
if err != nil {
t.Fatal(err)
}
diff --git a/internal/console/server.go b/internal/console/server.go
index 28cbfd69d..b4fd01c29 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -3716,7 +3716,9 @@ func (s *Server) handleContinue(w http.ResponseWriter, r *http.Request) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return
}
- now := time.Now()
+ // The send limits' clock, so one clock decides both the sends and the
+ // challenge's age (CreateEmailChallenge's repeat rule) and expiry.
+ now := s.limits.clock()
s.store.PurgeExpired(now) // housekeeping on the write path
flow := s.requestFlow(r)
if flow == "" {
@@ -3798,15 +3800,15 @@ func (s *Server) signinChallenge(flow, addr, next, ip string, underCap bool, now
if err != nil {
return "", "", false, err
}
- if !s.limits.signinSendTo(addr, ip, known) {
+ asked, allowed := false, false
+ link, code, sent, err = s.store.CreateEmailChallenge(c, now, func() bool {
+ asked, allowed = true, s.limits.signinSendTo(addr, ip, known)
+ return allowed
+ })
+ if asked && !allowed {
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)
- }
- link, code, err = s.store.CreateEmailChallenge(c, now)
- if err != nil {
- return "", "", false, err
}
- return link, code, true, nil
+ return link, code, sent, err
}
// ValidAddress is the console's one shape check on a keymail address: