carlos / platform Public

console: a fresh challenge id on every front-door answer; the submit cap spends no lookup

Co-Authored-By: Claude <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev d3696e0637bfe4680678d321f68f8b522fbad011 parent b2c2384
5 files changed, +208 −31
  • internal/console/emailsignin.go +6 −3
  • internal/console/emailsignin_store.go +45 −9
  • internal/console/emailsignin_store_test.go +51 −0
  • internal/console/emailsignin_test.go +86 −1
  • internal/console/server.go +20 −18
diff --git a/internal/console/emailsignin.go b/internal/console/emailsignin.go
index 0c5a68d56..b003cac28 100644
--- a/internal/console/emailsignin.go
+++ b/internal/console/emailsignin.go
@@ -89,15 +89,18 @@ func canonicalAddress(raw string) (string, bool) {
}
// keymailAddress is discovery (spec 4.1): the configured Keymail host's own
-// addresses, or any address Keymail's public lookup says is a mailbox. Only
-// those public answers decide; any lookup failure means email.
-func (s *Server) keymailAddress(ctx context.Context, addr string) bool {
+// addresses, or, when mayLookup, any address Keymail's public lookup says is
+// a mailbox. Only those public answers decide; any lookup failure means email.
+func (s *Server) keymailAddress(ctx context.Context, addr string, mayLookup bool) bool {
if s.km == nil {
return false
}
if h := s.km.Host(); h != "" && addr[strings.LastIndex(addr, "@")+1:] == h {
return true
}
+ if !mayLookup {
+ return false
+ }
ok, err := s.km.HasMailbox(ctx, addr)
if err != nil {
log.Printf("console: keymail lookup for %s: %v (sending email)", addr, err)
diff --git a/internal/console/emailsignin_store.go b/internal/console/emailsignin_store.go
index 60c22c766..1fa768316 100644
--- a/internal/console/emailsignin_store.go
+++ b/internal/console/emailsignin_store.go
@@ -77,11 +77,14 @@ func (s *Store) migrateEmailSignin() error {
return err
}
-// codeMAC is epoch ":" hex(HMAC-SHA256(process key, id ":" code)). The epoch
-// is a random per-process label, not secret; see TakeEmailCode.
-func (s *Store) codeMAC(id, code string) string {
+// codeMAC is epoch ":" hex(HMAC-SHA256(process key, link_hash ":" code)). The
+// row's link hash binds the code to its challenge and, unlike the
+// browser-held id, never changes, so RekeyEmailChallenge can rotate the id
+// without the code. The epoch is a random per-process label, not secret; see
+// TakeEmailCode.
+func (s *Store) codeMAC(linkHash, code string) string {
m := hmac.New(sha256.New, s.codeKey)
- m.Write([]byte(id + ":" + code))
+ m.Write([]byte(linkHash + ":" + code))
return s.codeEpoch + ":" + hex.EncodeToString(m.Sum(nil))
}
@@ -119,7 +122,7 @@ func (s *Store) CreateEmailChallenge(c EmailChallenge, replaceID string, now tim
if _, err := tx.Exec(`INSERT INTO email_challenges
(id_hash, link_hash, code_mac, purpose, address, session_hash, pending, next, attempts, created_at, expires_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?)`,
- hashToken(id), hashToken(link), s.codeMAC(id, code), c.Purpose, c.Address,
+ hashToken(id), hashToken(link), s.codeMAC(hashToken(link), code), c.Purpose, c.Address,
c.SessionHash, c.PendingHash, c.Next, now.Unix(), exp.Unix()); err != nil {
return "", "", "", err
}
@@ -197,13 +200,13 @@ func (s *Store) TakeEmailCode(id, code, purpose string, now time.Time) (*EmailCh
}
defer tx.Rollback()
idHash := hashToken(id)
- var mac string
+ var mac, linkHash string
var attempts int
- row := tx.QueryRow(`SELECT purpose, address, session_hash, pending, next, expires_at, code_mac, attempts
+ row := tx.QueryRow(`SELECT purpose, address, session_hash, pending, next, expires_at, code_mac, link_hash, attempts
FROM email_challenges WHERE id_hash = ?`, idHash)
var c EmailChallenge
var exp int64
- if err := row.Scan(&c.Purpose, &c.Address, &c.SessionHash, &c.PendingHash, &c.Next, &exp, &mac, &attempts); err != nil {
+ if err := row.Scan(&c.Purpose, &c.Address, &c.SessionHash, &c.PendingHash, &c.Next, &exp, &mac, &linkHash, &attempts); err != nil {
return nil, CodeGone
}
c.ExpiresAt = time.Unix(exp, 0)
@@ -221,7 +224,7 @@ FROM email_challenges WHERE id_hash = ?`, idHash)
if !strings.HasPrefix(mac, s.codeEpoch+":") {
return nil, CodeGone
}
- if !hmac.Equal([]byte(mac), []byte(s.codeMAC(id, code))) {
+ if !hmac.Equal([]byte(mac), []byte(s.codeMAC(linkHash, code))) {
attempts++
res := CodeWrong
if attempts >= emailCodeAttempts {
@@ -247,6 +250,39 @@ FROM email_challenges WHERE id_hash = ?`, idHash)
return &c, CodeOK
}
+// RekeyEmailChallenge gives a live sign-in challenge for address a new
+// browser-held id, in one transaction, and returns it. The emailed link and
+// code are unchanged and keep working. It reports false, changing nothing,
+// when oldID names no such challenge (unknown, expired, another purpose or
+// another address).
+func (s *Store) RekeyEmailChallenge(oldID, address string, now time.Time) (string, bool) {
+ if oldID == "" {
+ return "", false
+ }
+ newID, err := randomToken()
+ if err != nil {
+ return "", false
+ }
+ tx, err := s.db.Begin()
+ if err != nil {
+ return "", false
+ }
+ defer tx.Rollback()
+ res, err := tx.Exec(`UPDATE email_challenges SET id_hash = ?
+WHERE id_hash = ? AND purpose = ? AND address = ? AND expires_at >= ?`,
+ hashToken(newID), hashToken(oldID), ChallengeSignIn, address, now.Unix())
+ if err != nil {
+ return "", false
+ }
+ if n, err := res.RowsAffected(); err != nil || n != 1 {
+ return "", false
+ }
+ if err := tx.Commit(); err != nil {
+ return "", false
+ }
+ return newID, true
+}
+
// DeleteEmailChallenge removes a challenge by its browser-held id (for
// example when the email it belongs to could not be sent).
func (s *Store) DeleteEmailChallenge(id string) error {
diff --git a/internal/console/emailsignin_store_test.go b/internal/console/emailsignin_store_test.go
index 8225ff388..c81b8daa3 100644
--- a/internal/console/emailsignin_store_test.go
+++ b/internal/console/emailsignin_store_test.go
@@ -312,3 +312,54 @@ func TestSessionMethodPreMigrationRowReadsKeymail(t *testing.T) {
t.Fatalf("pre-migration session = %q %q %v, want keymail", a, m, ok)
}
}
+
+func TestEmailChallengeRekey(t *testing.T) {
+ s := openTestStore(t)
+ now := time.Now()
+ id, _, code := newSignInChallenge(t, s, now, "")
+
+ for _, tc := range []struct{ id, addr, why string }{
+ {"", "bob@example.com", "empty id"},
+ {"probe", "bob@example.com", "unknown id"},
+ {id, "carol@example.com", "another address"},
+ } {
+ if _, ok := s.RekeyEmailChallenge(tc.id, tc.addr, now); ok {
+ t.Fatalf("re-keyed with %s", tc.why)
+ }
+ }
+ if _, ok := s.RekeyEmailChallenge(id, "bob@example.com", now.Add(ConfirmationTTL+time.Second)); ok {
+ t.Fatal("re-keyed an expired challenge")
+ }
+
+ newID, ok := s.RekeyEmailChallenge(id, "bob@example.com", now)
+ if !ok || newID == "" || newID == id {
+ t.Fatalf("rekey = %q %v, want a fresh id", newID, ok)
+ }
+ if _, ok := s.PeekEmailChallenge(id, now); ok {
+ t.Fatal("the old id still names the challenge")
+ }
+ // The emailed code still works, now under the new id.
+ if c, res := s.TakeEmailCode(newID, code, ChallengeSignIn, now); res != CodeOK || c.Address != "bob@example.com" {
+ t.Fatalf("code after rekey = %v %+v, want CodeOK for bob", res, c)
+ }
+
+ // And the link of a re-keyed challenge still works.
+ id2, link2, _ := newSignInChallenge(t, s, now, "")
+ if _, ok := s.RekeyEmailChallenge(id2, "bob@example.com", now); !ok {
+ t.Fatal("rekey of a second challenge failed")
+ }
+ if _, ok := s.TakeEmailLink(link2, now); !ok {
+ t.Fatal("the link stopped working after a rekey")
+ }
+
+ // A step-up challenge is never re-keyed by the sign-in door.
+ stepID, _, _, err := s.CreateEmailChallenge(EmailChallenge{
+ Purpose: ChallengeStepUp, Address: "bob@example.com", SessionHash: "sh", PendingHash: "ph",
+ }, "", now)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, ok := s.RekeyEmailChallenge(stepID, "bob@example.com", now); ok {
+ t.Fatal("re-keyed a step-up challenge")
+ }
+}
diff --git a/internal/console/emailsignin_test.go b/internal/console/emailsignin_test.go
index ce331121a..8a355765c 100644
--- a/internal/console/emailsignin_test.go
+++ b/internal/console/emailsignin_test.go
@@ -419,7 +419,8 @@ func TestContinuePageIdentical(t *testing.T) {
// At once again: the per-address gap refuses the send.
_, _, throttled := postContinue(t, fx, browsers[2], form)
- // And an IP over its submission cap is refused before anything else.
+ // And an IP over its submission cap spends no lookup; the send limits
+ // still refuse bob.
for fx.srv.limits.submit("127.0.0.1") {
}
lookupsBefore := lookupCount(fx)
@@ -476,9 +477,26 @@ func TestContinueNoMailer(t *testing.T) {
t.Fatalf("request %d differs from the first:\n%s\nvs\n%s", i, body, first)
}
}
+ // Over the IP's submission cap: no lookup, and still the same answer.
+ for fx.srv.limits.submit("127.0.0.1") {
+ }
+ lookups := lookupCount(fx)
+ if _, _, body := postContinue(t, fx, newBrowser(t), form); body != first {
+ t.Fatalf("over the submission cap the answer differs:\n%s\nvs\n%s", body, first)
+ }
+ if lookupCount(fx) != lookups {
+ t.Fatal("a capped submission still asked Keymail")
+ }
if sent := m.sentCopy(); len(sent) != 0 || challengeRows(t, fx) != 0 {
t.Fatalf("no mailer, yet sent %q and stored %d challenges", sent, challengeRows(t, fx))
}
+ // The Keymail host's own addresses need no lookup and still go there.
+ if status, loc, _ := postContinue(t, fx, newBrowser(t), url.Values{"address": {"kim@" + fx.srv.km.Host()}}); status != http.StatusSeeOther || loc != "/auth/signin" {
+ t.Fatalf("Keymail-host address over the cap = %d -> %q", status, loc)
+ }
+ fx.srv.limits.mu.Lock()
+ fx.srv.limits.submits = keyedWindow{}
+ fx.srv.limits.mu.Unlock()
// A Keymail address still signs in.
lookupAnswers(fx, "kim@example.com", http.StatusOK)
if status, loc, _ := postContinue(t, fx, newBrowser(t), url.Values{"address": {"kim@example.com"}}); status != http.StatusSeeOther || loc != "/auth/signin" {
@@ -1014,3 +1032,70 @@ func TestLegacyConfirmRetired(t *testing.T) {
t.Fatal("the retired confirm link opened a session")
}
}
+
+// Every email-bound answer sets a fresh challenge id, whatever cookie came
+// in, so the cookie never tells a sent request from a refused one. A refusal
+// re-keys this browser's live challenge for the same address, so the email
+// already sent still works.
+func TestContinueChallengeCookieAlwaysFresh(t *testing.T) {
+ fx, m := newEmailFixture(t, true)
+ const addr = "bob@example.com"
+ lookupAnswers(fx, addr, http.StatusNotFound)
+ form := url.Values{"address": {addr}}
+ u, _ := url.Parse(fx.ts.URL)
+ withCookie := func(v string) *http.Client {
+ c := newBrowser(t)
+ c.Jar.SetCookies(u, []*http.Cookie{{Name: challengeCookie, Value: v, Path: "/"}})
+ return c
+ }
+
+ // Accepted, with a junk cookie in: a new id.
+ junk := withCookie("probe")
+ code, _ := askSignin(t, fx, m, junk, addr, "")
+ live := browserCookie(t, fx, junk, challengeCookie)
+ if live == "" || live == "probe" {
+ t.Fatalf("accepted send kept the incoming cookie %q", live)
+ }
+
+ // Refused by the per-address gap, junk cookie: a decoy naming nothing.
+ other := withCookie("probe")
+ postContinue(t, fx, other, form)
+ if v := browserCookie(t, fx, other, challengeCookie); v == "" || v == "probe" {
+ t.Fatalf("refused send with a junk cookie answered %q", v)
+ } else if _, ok := fx.st.PeekEmailChallenge(v, time.Now()); ok {
+ t.Fatal("the decoy id names a challenge")
+ }
+
+ // Refused, with the live challenge's id: re-keyed, not repeated.
+ postContinue(t, fx, junk, form)
+ rekeyed := browserCookie(t, fx, junk, challengeCookie)
+ if rekeyed == "" || rekeyed == live {
+ t.Fatalf("refused send with a live cookie answered %q (incoming %q)", rekeyed, live)
+ }
+ if _, ok := fx.st.PeekEmailChallenge(live, time.Now()); ok {
+ t.Fatal("the old id still names the challenge")
+ }
+
+ // Over the submission cap too, both kinds of incoming cookie.
+ for fx.srv.limits.submit("127.0.0.1") {
+ }
+ postContinue(t, fx, junk, form)
+ capped := browserCookie(t, fx, junk, challengeCookie)
+ if capped == "" || capped == rekeyed {
+ t.Fatalf("capped send with a live cookie answered %q (incoming %q)", capped, rekeyed)
+ }
+ capJunk := withCookie("probe")
+ postContinue(t, fx, capJunk, form)
+ if v := browserCookie(t, fx, capJunk, challengeCookie); v == "" || v == "probe" {
+ t.Fatalf("capped send with a junk cookie answered %q", v)
+ }
+
+ if n := len(m.sentCopy()); n != 1 {
+ t.Fatalf("mailer got %d messages, want 1", n)
+ }
+ // The one email's code still signs in, in the browser that asked.
+ if status, _, body := postCode(t, fx, junk, code); status != http.StatusSeeOther {
+ t.Fatalf("code after re-keys = %d:\n%s", status, body)
+ }
+ emailSession(t, fx, junk, addr)
+}
diff --git a/internal/console/server.go b/internal/console/server.go
index c29cdc348..3d24bc139 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -2771,13 +2771,14 @@ func (s *Server) handleContinue(w http.ResponseWriter, r *http.Request) {
return
}
ip := s.clientIP(r)
- if !s.limits.submit(ip) {
- log.Printf("console: sign-in submissions from %s over the hourly cap", ip)
- s.keepChallengeCookie(w, r)
- s.renderCheck(w, addr, next)
- return
- }
- if s.keymailAddress(r.Context(), addr) {
+ // Over the per-IP submission cap no lookup is spent: only the Keymail
+ // host's own addresses still go to Keymail, and the rest take the email
+ // path below, where readiness and the send limits answer as usual.
+ mayLookup := s.limits.submit(ip)
+ if !mayLookup {
+ log.Printf("console: sign-in submissions from %s over the hourly cap; no lookup", ip)
+ }
+ if s.keymailAddress(r.Context(), addr, mayLookup) {
target := "/auth/signin"
if next != "" {
target += "?next=" + url.QueryEscape(next)
@@ -2792,7 +2793,7 @@ func (s *Server) handleContinue(w http.ResponseWriter, r *http.Request) {
}
if !s.limits.signinSend(addr, ip) {
log.Printf("console: sign-in email to %s from %s over its limits; not sent", addr, ip)
- s.keepChallengeCookie(w, r)
+ s.rotateChallengeCookie(w, r, addr, now)
s.renderCheck(w, addr, next)
return
}
@@ -2817,22 +2818,23 @@ func (s *Server) handleContinue(w http.ResponseWriter, r *http.Request) {
s.renderCheck(w, addr, next)
}
-// keepChallengeCookie re-sets this browser's challenge cookie (or, with none,
-// a random stand-in that names nothing) when the front door sends nothing, so
-// the response carries the same Set-Cookie as one that sent. The earlier
-// challenge, if any, keeps working.
-func (s *Server) keepChallengeCookie(w http.ResponseWriter, r *http.Request) {
- v := ""
+// rotateChallengeCookie answers a refused send with a fresh challenge id, as
+// an accepted one does, so the cookie never says which happened. When this
+// browser's cookie names a live sign-in challenge for addr, that challenge is
+// re-keyed and its email's link and code keep working; otherwise the new id
+// is a random stand-in that names nothing.
+func (s *Server) rotateChallengeCookie(w http.ResponseWriter, r *http.Request, addr string, now time.Time) {
+ id := ""
if c, err := r.Cookie(challengeCookie); err == nil {
- v = c.Value
+ id, _ = s.store.RekeyEmailChallenge(c.Value, addr, now)
}
- if v == "" {
+ if id == "" {
var err error
- if v, err = randomToken(); err != nil {
+ if id, err = randomToken(); err != nil {
return
}
}
- s.setCookie(w, challengeCookie, v, int(ConfirmationTTL.Seconds()))
+ s.setCookie(w, challengeCookie, id, int(ConfirmationTTL.Seconds()))
}
// ValidAddress is the console's one shape check on a keymail address: