carlos / platform Public

console: email challenge store and session method

Co-Authored-By: Claude <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 9407420b0e963707254ebedcf63baa8f4fe399d9 parent dc23feb
4 files changed, +586 −5
  • internal/console/emailsignin_store.go +247 −0
  • internal/console/emailsignin_store_test.go +290 −0
  • internal/console/store.go +48 −5
  • internal/console/store_gate.go +1 −0
diff --git a/internal/console/emailsignin_store.go b/internal/console/emailsignin_store.go
new file mode 100644
index 000000000..983a3a3b6
--- /dev/null
+++ b/internal/console/emailsignin_store.go
@@ -0,0 +1,247 @@
+package console
+
+// The email sign-in challenge (spec §5): one emailed link + code, for one
+// purpose, bound to the browser that asked. Its own file, with its own
+// migration, in the authstore/step-up precedent.
+//
+// Only hashes are stored, so a database read is not a sign-in. The six-digit
+// code is stored as an HMAC under a key that lives only in this process
+// (Store.codeKey): six digits under an id the requester knows would fall to an
+// offline search in a blink if they were merely hashed. The price is that a
+// console restart invalidates codes in flight; links still work, and asking
+// again sends a fresh code.
+
+import (
+ "crypto/hmac"
+ "crypto/rand"
+ "crypto/sha256"
+ "database/sql"
+ "encoding/hex"
+ "fmt"
+ "math/big"
+ "strings"
+ "time"
+)
+
+const (
+ // ChallengeSignIn and ChallengeStepUp are the two purposes of a challenge.
+ ChallengeSignIn = "signin"
+ ChallengeStepUp = "stepup"
+
+ // MethodKeymail and MethodEmail are how a session was proved (spec §5.4).
+ MethodKeymail = "keymail"
+ MethodEmail = "email"
+
+ // emailCodeAttempts is how many wrong codes burn a challenge.
+ emailCodeAttempts = 5
+)
+
+// EmailChallenge is what a caller supplies to create a challenge and what a
+// successful take hands back. SessionHash and PendingHash are step-up only;
+// Next is sign-in only.
+type EmailChallenge struct {
+ Purpose, Address, SessionHash, PendingHash, Next string
+ ExpiresAt time.Time
+}
+
+// CodeResult is the verdict of TakeEmailCode.
+type CodeResult int
+
+const (
+ // CodeOK: the code matched; the challenge is spent.
+ CodeOK CodeResult = iota
+ // CodeWrong: it did not match and the challenge still stands.
+ CodeWrong
+ // CodeGone: there is no usable challenge (unknown, expired, wrong
+ // purpose, or burned by too many wrong codes).
+ CodeGone
+)
+
+func (s *Store) migrateEmailSignin() error {
+ _, err := s.db.Exec(`CREATE TABLE IF NOT EXISTS email_challenges (
+ id_hash TEXT PRIMARY KEY,
+ link_hash TEXT UNIQUE,
+ code_mac TEXT NOT NULL,
+ purpose TEXT NOT NULL,
+ address TEXT NOT NULL,
+ session_hash TEXT NOT NULL DEFAULT '',
+ pending TEXT NOT NULL DEFAULT '',
+ next TEXT NOT NULL DEFAULT '',
+ attempts INTEGER NOT NULL DEFAULT 0,
+ created_at INTEGER NOT NULL,
+ expires_at INTEGER NOT NULL
+);`)
+ 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 {
+ m := hmac.New(sha256.New, s.codeKey)
+ m.Write([]byte(id + ":" + code))
+ return s.codeEpoch + ":" + hex.EncodeToString(m.Sum(nil))
+}
+
+// CreateEmailChallenge stores a challenge and returns the browser-held id, the
+// emailed link token and the six-digit code. A zero ExpiresAt means
+// ConfirmationTTL from now. A non-empty replaceID names the browser's earlier
+// challenge, which is deleted wholly in the same transaction, so only the
+// newest email's link and code work.
+func (s *Store) CreateEmailChallenge(c EmailChallenge, replaceID string, now time.Time) (id, link, code string, err error) {
+ if id, err = randomToken(); err != nil {
+ return "", "", "", err
+ }
+ if link, err = randomToken(); err != nil {
+ return "", "", "", err
+ }
+ n, err := rand.Int(rand.Reader, big.NewInt(1_000_000))
+ if err != nil {
+ return "", "", "", err
+ }
+ code = fmt.Sprintf("%06d", n.Int64())
+ exp := c.ExpiresAt
+ if exp.IsZero() {
+ exp = now.Add(ConfirmationTTL)
+ }
+ tx, err := s.db.Begin()
+ if err != nil {
+ return "", "", "", err
+ }
+ defer tx.Rollback()
+ if replaceID != "" {
+ if _, err := tx.Exec(`DELETE FROM email_challenges WHERE id_hash = ?`, hashToken(replaceID)); err != nil {
+ return "", "", "", err
+ }
+ }
+ 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,
+ c.SessionHash, c.PendingHash, c.Next, now.Unix(), exp.Unix()); err != nil {
+ return "", "", "", err
+ }
+ if err := tx.Commit(); err != nil {
+ return "", "", "", err
+ }
+ return id, link, code, nil
+}
+
+// PeekEmailLink reads a challenge by its emailed link without spending it, so
+// a mail scanner's GET leaves the link good for the person's own click. It
+// reports false for unknown or expired links and deletes nothing.
+func (s *Store) PeekEmailLink(link string, now time.Time) (*EmailChallenge, bool) {
+ c, exp, err := scanEmailChallenge(s.db.QueryRow(`SELECT purpose, address, session_hash, pending, next, expires_at
+FROM email_challenges WHERE link_hash = ?`, hashToken(link)))
+ if err != nil || now.Unix() > exp {
+ return nil, false
+ }
+ return c, true
+}
+
+// TakeEmailLink spends a challenge by its emailed link. The row is deleted
+// before the expiry verdict (burn-then-check, as TakeConfirmation), so a link
+// can never be retried into validity.
+func (s *Store) TakeEmailLink(link string, now time.Time) (*EmailChallenge, bool) {
+ tx, err := s.db.Begin()
+ if err != nil {
+ return nil, false
+ }
+ defer tx.Rollback()
+ c, exp, err := scanEmailChallenge(tx.QueryRow(`SELECT purpose, address, session_hash, pending, next, expires_at
+FROM email_challenges WHERE link_hash = ?`, hashToken(link)))
+ if err != nil {
+ return nil, false
+ }
+ if _, err := tx.Exec(`DELETE FROM email_challenges WHERE link_hash = ?`, hashToken(link)); err != nil {
+ return nil, false
+ }
+ if err := tx.Commit(); err != nil {
+ return nil, false
+ }
+ if now.Unix() > exp {
+ return nil, false
+ }
+ return c, true
+}
+
+// TakeEmailCode checks a typed code against the challenge named by id, which
+// must be of the given purpose. One transaction: a missing, expired or
+// wrong-purpose challenge is deleted and reported CodeGone; a wrong code adds
+// an attempt, and the fifth burns the challenge (CodeGone); a right code
+// deletes it and reports CodeOK.
+func (s *Store) TakeEmailCode(id, code, purpose string, now time.Time) (*EmailChallenge, CodeResult) {
+ if id == "" {
+ return nil, CodeGone
+ }
+ tx, err := s.db.Begin()
+ if err != nil {
+ return nil, CodeGone
+ }
+ defer tx.Rollback()
+ idHash := hashToken(id)
+ var mac string
+ var attempts int
+ row := tx.QueryRow(`SELECT purpose, address, session_hash, pending, next, expires_at, code_mac, 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 {
+ return nil, CodeGone
+ }
+ 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 {
+ return nil, CodeGone
+ }
+ if err := tx.Commit(); err != nil {
+ return nil, CodeGone
+ }
+ return nil, CodeGone
+ }
+ // A code minted under an earlier process's key can never match: report it
+ // used up, but leave the row and its attempts alone so the link still works.
+ if !strings.HasPrefix(mac, s.codeEpoch+":") {
+ return nil, CodeGone
+ }
+ if !hmac.Equal([]byte(mac), []byte(s.codeMAC(id, code))) {
+ attempts++
+ res := CodeWrong
+ if attempts >= emailCodeAttempts {
+ res = CodeGone
+ _, err = tx.Exec(`DELETE FROM email_challenges WHERE id_hash = ?`, idHash)
+ } else {
+ _, err = tx.Exec(`UPDATE email_challenges SET attempts = ? WHERE id_hash = ?`, attempts, idHash)
+ }
+ if err != nil {
+ return nil, CodeGone
+ }
+ if err := tx.Commit(); err != nil {
+ return nil, CodeGone
+ }
+ return nil, res
+ }
+ if _, err := tx.Exec(`DELETE FROM email_challenges WHERE id_hash = ?`, idHash); err != nil {
+ return nil, CodeGone
+ }
+ if err := tx.Commit(); err != nil {
+ return nil, CodeGone
+ }
+ return &c, CodeOK
+}
+
+// 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))
+ return err
+}
+
+func scanEmailChallenge(row *sql.Row) (*EmailChallenge, int64, error) {
+ var c EmailChallenge
+ var exp int64
+ if err := row.Scan(&c.Purpose, &c.Address, &c.SessionHash, &c.PendingHash, &c.Next, &exp); err != nil {
+ return nil, 0, err
+ }
+ c.ExpiresAt = time.Unix(exp, 0)
+ return &c, exp, nil
+}
diff --git a/internal/console/emailsignin_store_test.go b/internal/console/emailsignin_store_test.go
new file mode 100644
index 000000000..498704c26
--- /dev/null
+++ b/internal/console/emailsignin_store_test.go
@@ -0,0 +1,290 @@
+package console
+
+import (
+ "crypto/sha256"
+ "database/sql"
+ "encoding/hex"
+ "path/filepath"
+ "testing"
+ "time"
+)
+
+func newSignInChallenge(t *testing.T, s *Store, now time.Time, replaceID string) (id, link, code string) {
+ t.Helper()
+ id, link, code, err := s.CreateEmailChallenge(EmailChallenge{
+ Purpose: ChallengeSignIn, Address: "bob@example.com", Next: "/auth/cli",
+ ExpiresAt: now.Add(ConfirmationTTL),
+ }, replaceID, now)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return id, link, code
+}
+
+// wrongCode returns a six-digit code that is not code.
+func wrongCode(code string) string {
+ if code == "000000" {
+ return "000001"
+ }
+ return "000000"
+}
+
+func TestEmailChallengeLinkPeekDoesNotConsume(t *testing.T) {
+ s := openTestStore(t)
+ now := time.Now()
+ _, link, _ := newSignInChallenge(t, s, now, "")
+ for i := 0; i < 2; i++ {
+ c, ok := s.PeekEmailLink(link, now)
+ if !ok || c.Address != "bob@example.com" || c.Next != "/auth/cli" || c.Purpose != ChallengeSignIn {
+ t.Fatalf("peek %d = %+v, %v", i, c, ok)
+ }
+ }
+ if c, ok := s.TakeEmailLink(link, now); !ok || c.Address != "bob@example.com" || c.Next != "/auth/cli" {
+ t.Fatalf("take = %+v, %v", c, ok)
+ }
+ if _, ok := s.TakeEmailLink(link, now); ok {
+ t.Fatal("a link was taken twice")
+ }
+ if _, ok := s.PeekEmailLink(link, now); ok {
+ t.Fatal("a taken link still peeks")
+ }
+}
+
+func TestEmailChallengeCode(t *testing.T) {
+ s := openTestStore(t)
+ now := time.Now()
+
+ id, link, code := newSignInChallenge(t, s, now, "")
+ if c, res := s.TakeEmailCode(id, code, ChallengeSignIn, now); res != CodeOK || c == nil || c.Address != "bob@example.com" {
+ t.Fatalf("right code = %+v, %v", c, res)
+ }
+ if _, ok := s.TakeEmailLink(link, now); ok {
+ t.Fatal("the link outlived a successful code")
+ }
+ if _, res := s.TakeEmailCode(id, code, ChallengeSignIn, now); res != CodeGone {
+ t.Fatalf("a code was taken twice: %v", res)
+ }
+
+ id, link, code = newSignInChallenge(t, s, now, "")
+ bad := wrongCode(code)
+ for i := 1; i <= 4; i++ {
+ if _, res := s.TakeEmailCode(id, bad, ChallengeSignIn, now); res != CodeWrong {
+ t.Fatalf("wrong code %d = %v, want CodeWrong", i, res)
+ }
+ }
+ if _, res := s.TakeEmailCode(id, bad, ChallengeSignIn, now); res != CodeGone {
+ t.Fatalf("5th wrong code = %v, want CodeGone", res)
+ }
+ if _, res := s.TakeEmailCode(id, code, ChallengeSignIn, now); res != CodeGone {
+ t.Fatalf("right code after burn = %v, want CodeGone", res)
+ }
+ if _, ok := s.TakeEmailLink(link, now); ok {
+ t.Fatal("the link outlived a burned challenge")
+ }
+
+ id, _, code = newSignInChallenge(t, s, now, "")
+ if _, res := s.TakeEmailCode(id, code, ChallengeStepUp, now); res != CodeGone {
+ t.Fatalf("wrong purpose = %v, want CodeGone", res)
+ }
+ if _, res := s.TakeEmailCode(id, code, ChallengeSignIn, now); res != CodeGone {
+ t.Fatalf("a wrong-purpose attempt left the challenge standing: %v", res)
+ }
+}
+
+func countChallenges(t *testing.T, s *Store) int {
+ t.Helper()
+ var n int
+ if err := s.db.QueryRow(`SELECT COUNT(*) FROM email_challenges`).Scan(&n); err != nil {
+ t.Fatal(err)
+ }
+ return n
+}
+
+func TestEmailChallengeExpiry(t *testing.T) {
+ s := openTestStore(t)
+ now := time.Now()
+ late := now.Add(ConfirmationTTL + time.Second)
+
+ id, link, code := newSignInChallenge(t, s, now, "")
+ if _, ok := s.PeekEmailLink(link, late); ok {
+ t.Fatal("an expired link peeks")
+ }
+ if _, ok := s.TakeEmailLink(link, late); ok {
+ t.Fatal("an expired link was taken")
+ }
+ if n := countChallenges(t, s); n != 0 {
+ t.Fatalf("expired link attempt left %d rows", n)
+ }
+ if _, res := s.TakeEmailCode(id, code, ChallengeSignIn, late); res != CodeGone {
+ t.Fatalf("code after expiry = %v", res)
+ }
+
+ id, link, code = newSignInChallenge(t, s, now, "")
+ if _, res := s.TakeEmailCode(id, code, ChallengeSignIn, late); res != CodeGone {
+ t.Fatalf("expired code = %v, want CodeGone", res)
+ }
+ if n := countChallenges(t, s); n != 0 {
+ t.Fatalf("expired code attempt left %d rows", n)
+ }
+ if _, ok := s.TakeEmailLink(link, now); ok {
+ t.Fatal("the link survived an expired code attempt")
+ }
+}
+
+func TestEmailChallengeCodeKeyIsProcessLocal(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "console.db")
+ s, err := Open(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ now := time.Now()
+ id, link, code := newSignInChallenge(t, s, now, "")
+
+ var mac string
+ if err := s.db.QueryRow(`SELECT code_mac FROM email_challenges WHERE id_hash = ?`, hashToken(id)).Scan(&mac); err != nil {
+ t.Fatal(err)
+ }
+ plain := sha256.Sum256([]byte(id + code))
+ if mac == hex.EncodeToString(plain[:]) {
+ t.Fatal("code_mac is a plain hash of id and code, recoverable from a database read")
+ }
+ if err := s.Close(); err != nil {
+ t.Fatal(err)
+ }
+
+ s2, err := Open(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer s2.Close()
+ // The link is 32 random bytes hashed in the database, so it survives.
+ if c, ok := s2.PeekEmailLink(link, now); !ok || c.Address != "bob@example.com" {
+ t.Fatalf("link after restart = %+v, %v", c, ok)
+ }
+ // The code's key died with the first process: the code reads as used up.
+ if _, res := s2.TakeEmailCode(id, code, ChallengeSignIn, now); res != CodeGone {
+ t.Fatalf("code after restart = %v, want CodeGone (used up)", res)
+ }
+ if _, ok := s2.TakeEmailLink(link, now); !ok {
+ t.Fatal("the link did not survive a restart")
+ }
+}
+
+func TestEmailChallengeReplace(t *testing.T) {
+ s := openTestStore(t)
+ now := time.Now()
+ idA, linkA, codeA := newSignInChallenge(t, s, now, "")
+ idB, linkB, codeB := newSignInChallenge(t, s, now, idA)
+ if _, ok := s.PeekEmailLink(linkA, now); ok {
+ t.Fatal("the replaced link still works")
+ }
+ if _, res := s.TakeEmailCode(idA, codeA, ChallengeSignIn, now); res != CodeGone {
+ t.Fatalf("the replaced code = %v, want CodeGone", res)
+ }
+ if n := countChallenges(t, s); n != 1 {
+ t.Fatalf("%d challenges after a replace, want 1", n)
+ }
+ if _, res := s.TakeEmailCode(idB, codeB, ChallengeSignIn, now); res != CodeOK {
+ t.Fatalf("the new code = %v, want CodeOK", res)
+ }
+ _, linkC, _ := newSignInChallenge(t, s, now, "")
+ _ = linkB
+ if _, ok := s.TakeEmailLink(linkC, now); !ok {
+ t.Fatal("the new link does not work")
+ }
+}
+
+func TestEmailChallengeDelete(t *testing.T) {
+ s := openTestStore(t)
+ now := time.Now()
+ id, link, _ := newSignInChallenge(t, s, now, "")
+ if err := s.DeleteEmailChallenge(id); err != nil {
+ t.Fatal(err)
+ }
+ if _, ok := s.PeekEmailLink(link, now); ok {
+ t.Fatal("a deleted challenge still peeks")
+ }
+}
+
+func TestEmailChallengePurgedWithExpired(t *testing.T) {
+ s := openTestStore(t)
+ now := time.Now()
+ newSignInChallenge(t, s, now, "")
+ if err := s.PurgeExpired(now); err != nil {
+ t.Fatal(err)
+ }
+ if n := countChallenges(t, s); n != 1 {
+ t.Fatalf("PurgeExpired removed a live challenge (%d left)", n)
+ }
+ if err := s.PurgeExpired(now.Add(ConfirmationTTL + time.Second)); err != nil {
+ t.Fatal(err)
+ }
+ if n := countChallenges(t, s); n != 0 {
+ t.Fatalf("PurgeExpired left %d expired challenges", n)
+ }
+}
+
+func TestSessionMethod(t *testing.T) {
+ s := openTestStore(t)
+ now := time.Now()
+
+ raw, err := s.CreateSession("bob@example.com", "tok", now)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if a, m, ok := s.SessionInfo(raw, now); !ok || a != "bob@example.com" || m != MethodKeymail {
+ t.Fatalf("CreateSession info = %q %q %v", a, m, ok)
+ }
+ raw, err = s.CreateSessionMethod("bob@example.com", "", MethodEmail, now)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if a, m, ok := s.SessionInfo(raw, now); !ok || a != "bob@example.com" || m != MethodEmail {
+ t.Fatalf("email info = %q %q %v", a, m, ok)
+ }
+ if _, _, ok := s.SessionInfo(raw, now.Add(SessionTTL+time.Second)); ok {
+ t.Fatal("an expired session resolved")
+ }
+ if _, _, ok := s.SessionInfo("nope", now); ok {
+ t.Fatal("an unknown session resolved")
+ }
+}
+
+func TestSessionMethodPreMigrationRowReadsKeymail(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "console.db")
+ old, err := sql.Open("sqlite", path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ now := time.Now()
+ raw := "an-old-session-token"
+ for _, q := range []string{
+ `CREATE TABLE sessions (
+ token_hash TEXT PRIMARY KEY,
+ address TEXT NOT NULL,
+ keymail_token TEXT NOT NULL DEFAULT '',
+ created_at INTEGER NOT NULL,
+ expires_at INTEGER NOT NULL
+)`,
+ } {
+ if _, err := old.Exec(q); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if _, err := old.Exec(`INSERT INTO sessions (token_hash, address, keymail_token, created_at, expires_at) VALUES (?, ?, '', ?, ?)`,
+ hashToken(raw), "old@example.com", now.Unix(), now.Add(time.Hour).Unix()); err != nil {
+ t.Fatal(err)
+ }
+ if err := old.Close(); err != nil {
+ t.Fatal(err)
+ }
+
+ s, err := Open(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer s.Close()
+ if a, m, ok := s.SessionInfo(raw, now); !ok || a != "old@example.com" || m != MethodKeymail {
+ t.Fatalf("pre-migration session = %q %q %v, want keymail", a, m, ok)
+ }
+}
diff --git a/internal/console/store.go b/internal/console/store.go
index 21523c90e..4b6680f3a 100644
--- a/internal/console/store.go
+++ b/internal/console/store.go
@@ -64,10 +64,24 @@ type Store struct {
mailEventsPruned *atomic.Int64
// mailPushPruned is the same stamp for the push queue (mailpush.go).
mailPushPruned *atomic.Int64
+
+ // codeKey is the in-memory HMAC key for emailed sign-in codes
+ // (emailsignin_store.go). Minted per process and never written down, so a
+ // database read cannot recover a code. A Store view shares it.
+ codeKey []byte
+ // codeEpoch is a random per-process label stored in front of each
+ // code_mac, so a code minted by an earlier process is recognised as such.
+ codeEpoch string
}
func newStore(db *sql.DB) *Store {
- return &Store{db: db, rawPool: db, rawBoot: db, mailEventsPruned: new(atomic.Int64), mailPushPruned: new(atomic.Int64)}
+ key := make([]byte, 32)
+ // crypto/rand.Read does not return an error (it aborts the process if the
+ // system source fails), so there is no weaker key to fall back to.
+ _, _ = rand.Read(key)
+ ep := make([]byte, 8)
+ _, _ = rand.Read(ep)
+ return &Store{codeEpoch: hex.EncodeToString(ep), db: db, rawPool: db, rawBoot: db, mailEventsPruned: new(atomic.Int64), mailPushPruned: new(atomic.Int64), codeKey: key}
}
// Open opens (creating if needed) the console DB at path.
@@ -491,6 +505,10 @@ func (s *Store) migrate() error {
// predates the feature). No timezone, IP or coordinate is stored.
`ALTER TABLE apps ADD COLUMN region TEXT NOT NULL DEFAULT '';`,
`ALTER TABLE apps ADD COLUMN region_source TEXT NOT NULL DEFAULT '';`,
+ // How a session was proved (email sign-in spec §5.4). Every session
+ // that predates the column was made through Keymail, so the default
+ // is the backfill.
+ `ALTER TABLE sessions ADD COLUMN method TEXT NOT NULL DEFAULT 'keymail';`,
} {
if _, err := s.db.Exec(stmt); err != nil && !strings.Contains(err.Error(), "duplicate column") {
return err
@@ -518,6 +536,10 @@ func (s *Store) migrate() error {
if err := s.migrateStepUp(); err != nil {
return err
}
+ // Email sign-in's challenge table (emailsignin_store.go), for the same reason.
+ if err := s.migrateEmailSignin(); err != nil {
+ return err
+ }
// Pending-change quorum's own tables (pending.go), for the same reason.
if err := s.migratePendingChanges(); err != nil {
return err
@@ -2402,13 +2424,19 @@ func randomToken() (string, error) {
// CreateSession mints a console session for address, returning the raw
// token the cookie carries. Only the sha256 of it is stored.
func (s *Store) CreateSession(address, keymailToken string, now time.Time) (string, error) {
+ return s.CreateSessionMethod(address, keymailToken, MethodKeymail, now)
+}
+
+// CreateSessionMethod is CreateSession with the way the session was proved
+// recorded: MethodKeymail or MethodEmail.
+func (s *Store) CreateSessionMethod(address, keymailToken, method string, now time.Time) (string, error) {
raw, err := randomToken()
if err != nil {
return "", err
}
- _, err = s.db.Exec(`INSERT INTO sessions (token_hash, address, keymail_token, created_at, expires_at)
-VALUES (?, ?, ?, ?, ?)`,
- hashToken(raw), address, keymailToken, now.Unix(), now.Add(SessionTTL).Unix())
+ _, err = s.db.Exec(`INSERT INTO sessions (token_hash, address, keymail_token, method, created_at, expires_at)
+VALUES (?, ?, ?, ?, ?, ?)`,
+ hashToken(raw), address, keymailToken, method, now.Unix(), now.Add(SessionTTL).Unix())
if err != nil {
return "", err
}
@@ -2428,13 +2456,25 @@ func (s *Store) SessionAddress(rawToken string, now time.Time) (string, bool) {
return addr, true
}
+// SessionInfo resolves a raw session token to its address and the method that
+// proved it; ok is false for unknown or expired tokens.
+func (s *Store) SessionInfo(rawToken string, now time.Time) (address, method string, ok bool) {
+ var exp int64
+ err := s.db.QueryRow(`SELECT address, method, expires_at FROM sessions WHERE token_hash = ?`,
+ hashToken(rawToken)).Scan(&address, &method, &exp)
+ if err != nil || now.Unix() > exp {
+ return "", "", false
+ }
+ return address, method, true
+}
+
// DeleteSession removes a session by its raw token.
func (s *Store) DeleteSession(rawToken string) error {
_, err := s.db.Exec(`DELETE FROM sessions WHERE token_hash = ?`, hashToken(rawToken))
return err
}
-// PurgeExpired drops expired sessions and confirmation tokens — and, on the
+// PurgeExpired drops expired sessions, confirmation tokens and email challenges — and, on the
// same pass, the CLI login requests and tokens that have aged out (throttled
// inside PurgeCLIAuth, which is also called from the login path).
func (s *Store) PurgeExpired(now time.Time) error {
@@ -2444,6 +2484,9 @@ func (s *Store) PurgeExpired(now time.Time) error {
if _, err := s.db.Exec(`DELETE FROM confirmations WHERE expires_at < ?`, now.Unix()); err != nil {
return err
}
+ if _, err := s.db.Exec(`DELETE FROM email_challenges WHERE expires_at < ?`, now.Unix()); err != nil {
+ return err
+ }
s.PurgeCLIAuth(now)
return nil
}
diff --git a/internal/console/store_gate.go b/internal/console/store_gate.go
index 6fe9ae657..679c3a742 100644
--- a/internal/console/store_gate.go
+++ b/internal/console/store_gate.go
@@ -218,6 +218,7 @@ var claimSQLTables = map[string]claimSQLTable{
"step_ups": {NonApp: "passkey step-up marks, keyed by session hash"},
"claim_sql_identity": {NonApp: "private receipt database identity"},
"claim_sql_receipts": {NonApp: "private SQL effect receipts and fences"},
+ "email_challenges": {NonApp: "emailed sign-in and step-up links and codes in flight, keyed by id hash; carries no app column"},
"pending_actions": {NonApp: "replay-by-token actions, keyed by token hash; carries no app column and re-enters the ordinary handlers"},
}