carlos / platform Public

console: a re-keyed challenge keeps its earlier ids until it expires

Co-Authored-By: Claude <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 29ad958ad7a67abfa825c6a74733a0fdae4e80b8 parent ab84265
3 files changed, +133 −22
  • internal/console/emailsignin_store.go +51 −18
  • internal/console/emailsignin_store_test.go +80 −2
  • internal/console/emailsignin_test.go +2 −2
diff --git a/internal/console/emailsignin_store.go b/internal/console/emailsignin_store.go
index 1fa768316..974227908 100644
--- a/internal/console/emailsignin_store.go
+++ b/internal/console/emailsignin_store.go
@@ -72,11 +72,31 @@ func (s *Store) migrateEmailSignin() error {
next TEXT NOT NULL DEFAULT '',
attempts INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL,
- expires_at INTEGER NOT NULL
+ expires_at INTEGER NOT NULL,
+ alias_hashes TEXT NOT NULL DEFAULT ''
);`)
- return err
+ if err != nil {
+ return err
+ }
+ // Additive: the re-keyed ids (RekeyEmailChallenge). Forgiving "duplicate
+ // column", so re-running is always safe.
+ if _, err := s.db.Exec(`ALTER TABLE email_challenges ADD COLUMN alias_hashes TEXT NOT NULL DEFAULT ''`); err != nil &&
+ !strings.Contains(err.Error(), "duplicate column") {
+ return err
+ }
+ return nil
}
+// A challenge answers to its first browser-held id (id_hash) and to every id
+// RekeyEmailChallenge has since given it (alias_hashes, space-separated, at
+// most maxChallengeAliases, newest last), all until it expires. Hashes are
+// fixed-length hex, so a substring match is a whole-entry match.
+// challengeByID is the WHERE clause for that; it takes the id's hash twice.
+const (
+ challengeByID = `(id_hash = ? OR instr(alias_hashes, ?) > 0)`
+ maxChallengeAliases = 8
+)
+
// 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
@@ -115,7 +135,8 @@ func (s *Store) CreateEmailChallenge(c EmailChallenge, replaceID string, now tim
}
defer tx.Rollback()
if replaceID != "" {
- if _, err := tx.Exec(`DELETE FROM email_challenges WHERE id_hash = ?`, hashToken(replaceID)); err != nil {
+ h := hashToken(replaceID)
+ if _, err := tx.Exec(`DELETE FROM email_challenges WHERE `+challengeByID, h, h); err != nil {
return "", "", "", err
}
}
@@ -151,8 +172,9 @@ func (s *Store) PeekEmailChallenge(id string, now time.Time) (*EmailChallenge, b
if id == "" {
return nil, false
}
+ h := hashToken(id)
c, exp, err := scanEmailChallenge(s.db.QueryRow(`SELECT purpose, address, session_hash, pending, next, expires_at
-FROM email_challenges WHERE id_hash = ?`, hashToken(id)))
+FROM email_challenges WHERE `+challengeByID, h, h))
if err != nil || now.Unix() > exp {
return nil, false
}
@@ -203,7 +225,7 @@ func (s *Store) TakeEmailCode(id, code, purpose string, now time.Time) (*EmailCh
var mac, linkHash string
var attempts int
row := tx.QueryRow(`SELECT purpose, address, session_hash, pending, next, expires_at, code_mac, link_hash, attempts
-FROM email_challenges WHERE id_hash = ?`, idHash)
+FROM email_challenges WHERE `+challengeByID, idHash, idHash)
var c EmailChallenge
var exp int64
if err := row.Scan(&c.Purpose, &c.Address, &c.SessionHash, &c.PendingHash, &c.Next, &exp, &mac, &linkHash, &attempts); err != nil {
@@ -211,7 +233,7 @@ FROM email_challenges WHERE id_hash = ?`, idHash)
}
c.ExpiresAt = time.Unix(exp, 0)
if now.Unix() > exp || c.Purpose != purpose {
- if _, err := tx.Exec(`DELETE FROM email_challenges WHERE id_hash = ?`, idHash); err != nil {
+ if _, err := tx.Exec(`DELETE FROM email_challenges WHERE link_hash = ?`, linkHash); err != nil {
return nil, CodeGone
}
if err := tx.Commit(); err != nil {
@@ -229,9 +251,9 @@ FROM email_challenges WHERE id_hash = ?`, idHash)
res := CodeWrong
if attempts >= emailCodeAttempts {
res = CodeBurned
- _, err = tx.Exec(`DELETE FROM email_challenges WHERE id_hash = ?`, idHash)
+ _, err = tx.Exec(`DELETE FROM email_challenges WHERE link_hash = ?`, linkHash)
} else {
- _, err = tx.Exec(`UPDATE email_challenges SET attempts = ? WHERE id_hash = ?`, attempts, idHash)
+ _, err = tx.Exec(`UPDATE email_challenges SET attempts = ? WHERE link_hash = ?`, attempts, linkHash)
}
if err != nil {
return nil, CodeGone
@@ -241,7 +263,7 @@ FROM email_challenges WHERE id_hash = ?`, idHash)
}
return nil, res
}
- if _, err := tx.Exec(`DELETE FROM email_challenges WHERE id_hash = ?`, idHash); err != nil {
+ if _, err := tx.Exec(`DELETE FROM email_challenges WHERE link_hash = ?`, linkHash); err != nil {
return nil, CodeGone
}
if err := tx.Commit(); err != nil {
@@ -251,10 +273,13 @@ FROM email_challenges WHERE id_hash = ?`, idHash)
}
// 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).
+// browser-held id, in one transaction, and returns it. The id it was asked
+// with, and every earlier one, keep working until the challenge expires, so
+// two overlapping retries from one browser each get an id that works,
+// whichever response lands last; only the newest maxChallengeAliases re-keyed
+// ids are kept. The emailed link and code are unchanged. 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
@@ -268,13 +293,20 @@ func (s *Store) RekeyEmailChallenge(oldID, address string, now time.Time) (strin
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())
+ h := hashToken(oldID)
+ var linkHash, aliases string
+ err = tx.QueryRow(`SELECT link_hash, alias_hashes FROM email_challenges
+WHERE `+challengeByID+` AND purpose = ? AND address = ? AND expires_at >= ?`,
+ h, h, ChallengeSignIn, address, now.Unix()).Scan(&linkHash, &aliases)
if err != nil {
return "", false
}
- if n, err := res.RowsAffected(); err != nil || n != 1 {
+ list := append(strings.Fields(aliases), hashToken(newID))
+ if len(list) > maxChallengeAliases {
+ list = list[len(list)-maxChallengeAliases:]
+ }
+ if _, err := tx.Exec(`UPDATE email_challenges SET alias_hashes = ? WHERE link_hash = ?`,
+ strings.Join(list, " "), linkHash); err != nil {
return "", false
}
if err := tx.Commit(); err != nil {
@@ -286,7 +318,8 @@ WHERE id_hash = ? AND purpose = ? AND address = ? AND expires_at >= ?`,
// 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 {
- _, err := s.db.Exec(`DELETE FROM email_challenges WHERE id_hash = ?`, hashToken(id))
+ h := hashToken(id)
+ _, err := s.db.Exec(`DELETE FROM email_challenges WHERE `+challengeByID, h, h)
return err
}
diff --git a/internal/console/emailsignin_store_test.go b/internal/console/emailsignin_store_test.go
index c81b8daa3..40b4a742c 100644
--- a/internal/console/emailsignin_store_test.go
+++ b/internal/console/emailsignin_store_test.go
@@ -335,8 +335,11 @@ func TestEmailChallengeRekey(t *testing.T) {
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")
+ if _, ok := s.PeekEmailChallenge(id, now); !ok {
+ t.Fatal("the old id stopped naming the challenge before it expired")
+ }
+ if _, ok := s.PeekEmailChallenge(newID, now); !ok {
+ t.Fatal("the new id names nothing")
}
// 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" {
@@ -363,3 +366,78 @@ func TestEmailChallengeRekey(t *testing.T) {
t.Fatal("re-keyed a step-up challenge")
}
}
+
+// Two overlapping retries from one browser re-key from the same id. Whichever
+// response the browser keeps, its id redeems the code (once), and the id both
+// started from works too until the challenge expires.
+func TestEmailChallengeRekeyOverlapping(t *testing.T) {
+ for _, redeem := range []string{"first", "second", "old"} {
+ t.Run(redeem, func(t *testing.T) {
+ s := openTestStore(t)
+ now := time.Now()
+ old, _, code := newSignInChallenge(t, s, now, "")
+ a, okA := s.RekeyEmailChallenge(old, "bob@example.com", now)
+ b, okB := s.RekeyEmailChallenge(old, "bob@example.com", now)
+ if !okA || !okB || a == b || a == old || b == old {
+ t.Fatalf("rekeys = %q %v, %q %v; want two fresh ids", a, okA, b, okB)
+ }
+ // A rekey from an alias gives a fresh id too.
+ c, okC := s.RekeyEmailChallenge(a, "bob@example.com", now)
+ if !okC || c == a || c == b || c == old {
+ t.Fatalf("rekey from an alias = %q %v", c, okC)
+ }
+ ids := map[string]string{"first": a, "second": b, "old": old}
+ for name, id := range map[string]string{"first": a, "second": b, "old": old, "third": c} {
+ if _, ok := s.PeekEmailChallenge(id, now); !ok {
+ t.Fatalf("the %s id names nothing", name)
+ }
+ }
+ // Each id answers for the same row: a wrong code under one counts
+ // against them all.
+ if _, res := s.TakeEmailCode(b, wrongCode(code), ChallengeSignIn, now); res != CodeWrong {
+ t.Fatalf("wrong code = %v", res)
+ }
+ if got, res := s.TakeEmailCode(ids[redeem], code, ChallengeSignIn, now); res != CodeOK || got.Address != "bob@example.com" {
+ t.Fatalf("code under the %s id = %v", redeem, res)
+ }
+ for name, id := range ids {
+ if _, res := s.TakeEmailCode(id, code, ChallengeSignIn, now); res == CodeOK {
+ t.Fatalf("the code redeemed twice (again under the %s id)", name)
+ }
+ }
+ })
+ }
+ // The old id lasts only as long as the challenge.
+ s := openTestStore(t)
+ now := time.Now()
+ old, _, _ := newSignInChallenge(t, s, now, "")
+ if _, ok := s.RekeyEmailChallenge(old, "bob@example.com", now); !ok {
+ t.Fatal("rekey failed")
+ }
+ if _, ok := s.PeekEmailChallenge(old, now.Add(ConfirmationTTL+time.Second)); ok {
+ t.Fatal("the old id outlived the challenge")
+ }
+}
+
+// Replacing or deleting by any of a challenge's ids removes it wholly.
+func TestEmailChallengeAliasReplaceAndDelete(t *testing.T) {
+ s := openTestStore(t)
+ now := time.Now()
+ old, link, _ := newSignInChallenge(t, s, now, "")
+ alias, _ := s.RekeyEmailChallenge(old, "bob@example.com", now)
+ newSignInChallenge(t, s, now, alias)
+ if _, ok := s.PeekEmailChallenge(old, now); ok {
+ t.Fatal("replacing by an alias left the challenge under its first id")
+ }
+ if _, ok := s.PeekEmailLink(link, now); ok {
+ t.Fatal("replacing by an alias left the old link working")
+ }
+ id2, _, _ := newSignInChallenge(t, s, now, "")
+ alias2, _ := s.RekeyEmailChallenge(id2, "bob@example.com", now)
+ if err := s.DeleteEmailChallenge(alias2); err != nil {
+ t.Fatal(err)
+ }
+ if _, ok := s.PeekEmailChallenge(id2, now); ok {
+ t.Fatal("deleting by an alias left the challenge")
+ }
+}
diff --git a/internal/console/emailsignin_test.go b/internal/console/emailsignin_test.go
index 8a355765c..92e125c99 100644
--- a/internal/console/emailsignin_test.go
+++ b/internal/console/emailsignin_test.go
@@ -1072,8 +1072,8 @@ func TestContinueChallengeCookieAlwaysFresh(t *testing.T) {
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")
+ if _, ok := fx.st.PeekEmailChallenge(rekeyed, time.Now()); !ok {
+ t.Fatal("the re-keyed id names nothing")
}
// Over the submission cap too, both kinds of incoming cookie.