console: one sign-in flow per browser; a refused send sends nothing
The whole-branch review found three ways the per-challenge browser id failed: over the per-IP submit cap discovery was skipped but email still went out (F1); a throttled request's decoy id answered a wrong code with "expired" where a real one said "doesn't match" (F2); and two overlapping first submissions could leave the browser holding the refused one's id, so the emailed code failed (F3). One model replaces the id, its re-keying and the decoys: - A sign-in flow cookie (carlos_console_flow), set whenever a sign-in form or the check page renders, and by /auth/continue when missing. Sign-in challenges store the flow's hash; the code box checks the flow's newest live challenge. Its value never depends on the outcome. - /auth/continue takes a per-flow lock around the limits and the challenge write. Accepted: a new challenge replacing the flow's earlier ones. Refused (over the submit cap or the send limits): no mail, the flow's live challenge left alone, or, with none, a challenge nobody is told the link or code of, so a typed code reads the same. - Over the submit cap there is no lookup and no send; the Keymail host's own addresses still go to Keymail. - The code page shows the address and next the form carried, so its state is identical for sent and refused requests. - Step-up challenges are found by the session's hash, not a cookie. - A successful link or code ends the flow's other challenges. RekeyEmailChallenge, the alias ids, PeekEmailChallenge and DeleteEmailChallenge are gone; flow_hash is an additive column.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
8 files changed,
+814
−521
internal/console/authcli.go+1 −1internal/console/claim_invariant_probes_nonapp_test.go+10 −6internal/console/emailsignin.go+94 −71internal/console/emailsignin_store.go+168 −133internal/console/emailsignin_store_test.go+177 −187internal/console/emailsignin_test.go+297 −63internal/console/emailstepup_test.go+2 −6internal/console/server.go+65 −54
diff --git a/internal/console/authcli.go b/internal/console/authcli.go| index ea21aab8f..f70397288 100644 |
| --- a/internal/console/authcli.go |
| +++ b/internal/console/authcli.go |
| @@ -1415,7 +1415,7 @@ func (s *Server) handleCLIApprovePage(w http.ResponseWriter, r *http.Request) { |
| if c := NormalizeUserCode(r.URL.Query().Get("code")); len(c) == userCodeLen+1 { |
| next += "?code=" + url.QueryEscape(c) |
| } |
| - s.renderHome(w, homeForm{Next: next, Banner: copyText("home.cli_prompt")}) |
| + s.renderHome(w, r, homeForm{Next: next, Banner: copyText("home.cli_prompt")}) |
| return |
| } |
| p := cliPage{page: page{Title: "Approve a terminal", Address: addr, CSRF: raw}, |
diff --git a/internal/console/claim_invariant_probes_nonapp_test.go b/internal/console/claim_invariant_probes_nonapp_test.go| index f8e30cf95..7bd9fda53 100644 |
| --- a/internal/console/claim_invariant_probes_nonapp_test.go |
| +++ b/internal/console/claim_invariant_probes_nonapp_test.go |
| @@ -141,15 +141,19 @@ func claimConfirmProbe() claimProbe { |
| } |
| } |
| -// claimEmailChallengeWorld is a sign-in challenge for the case's owner, its |
| -// browser-held id, link token and code kept in vars. |
| +// claimEmailChallengeWorld is a sign-in challenge for the case's owner in a |
| +// browser's sign-in flow, the flow token, link token and code kept in vars. |
| func claimEmailChallengeWorld(t *testing.T, cx *claimCase) { |
| t.Helper() |
| - id, link, code, err := cx.st.CreateEmailChallenge(EmailChallenge{Purpose: ChallengeSignIn, Address: claimFxOwner}, "", time.Now()) |
| + flow, err := randomToken() |
| if err != nil { |
| t.Fatal(err) |
| } |
| - cx.vars["challenge"], cx.vars["link"], cx.vars["code"] = id, link, code |
| + link, code, err := cx.st.CreateEmailChallenge(EmailChallenge{Purpose: ChallengeSignIn, Address: claimFxOwner, FlowHash: hashToken(flow)}, time.Now()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + cx.vars["flow"], cx.vars["link"], cx.vars["code"] = flow, link, code |
| } |
| // claimBrowserWithCookie is a fresh browser already holding one console |
| @@ -192,7 +196,7 @@ func claimEmailCodeProbe() claimProbe { |
| return claimProbe{ |
| setup: claimEmailChallengeWorld, |
| do: func(t *testing.T, cx *claimCase) claimReply { |
| - c = claimBrowserWithCookie(t, cx, challengeCookie, cx.vars["challenge"]) |
| + c = claimBrowserWithCookie(t, cx, flowCookie, cx.vars["flow"]) |
| status, loc, body := postForm(t, c, cx.ts.URL+"/auth/email/code", url.Values{"code": {cx.vars["code"]}}) |
| return cx.browserReply(c, status, loc, body) |
| }, |
| @@ -201,7 +205,7 @@ func claimEmailCodeProbe() claimProbe { |
| if !cx.signedInAs(c, claimFxOwner) { |
| return "the emailed code opened no session" |
| } |
| - if _, ok := cx.st.PeekEmailChallenge(cx.vars["challenge"], time.Now()); ok { |
| + if _, ok := cx.st.LiveEmailChallenge(ChallengeSignIn, hashToken(cx.vars["flow"]), time.Now()); ok { |
| return "the challenge is still standing after its code was used" |
| } |
| return "" |
diff --git a/internal/console/emailsignin.go b/internal/console/emailsignin.go| index 78747f294..3c42c4286 100644 |
| --- a/internal/console/emailsignin.go |
| +++ b/internal/console/emailsignin.go |
| @@ -2,12 +2,14 @@ package console |
| import ( |
| "context" |
| + "crypto/sha256" |
| "crypto/subtle" |
| "log" |
| "net/http" |
| netmail "net/mail" |
| "net/url" |
| "strings" |
| + "sync" |
| "time" |
| ) |
| @@ -15,9 +17,12 @@ import ( |
| // the auth cookie. (An email sign-in keeps its next on the challenge row.) |
| const nextCookie = "carlos_console_next" |
| -// challengeCookie names this browser's email challenge (its id), so a code |
| -// typed here finds it and a second request from here replaces it. |
| -const challengeCookie = "carlos_console_email" |
| +// flowCookie holds this browser's sign-in flow: a random token, set whenever |
| +// a sign-in form renders and kept for ConfirmationTTL from the last one. A |
| +// sign-in challenge stores the flow's hash, so a code typed here is checked |
| +// against this flow's newest live challenge and a second request from here |
| +// replaces it. Its value never depends on how /auth/continue answered. |
| +const flowCookie = "carlos_console_flow" |
| // linkConfirmCookie holds the nonce the emailed link's confirm page also puts |
| // in its form (spec 5.1). A cross-site POST carries no Lax cookie, so an |
| @@ -151,30 +156,71 @@ func (s *Server) sendChallengeAsync(to, subject, body string) { |
| }() |
| } |
| -// homeForm is what the front page's one form starts with. |
| +// requestFlow is this browser's sign-in flow token, or a fresh one when it |
| +// sent none we could have minted. It is "" only when no randomness was to be |
| +// had. |
| +func (s *Server) requestFlow(r *http.Request) string { |
| + if c, err := r.Cookie(flowCookie); err == nil && len(c.Value) >= 32 && len(c.Value) <= 128 { |
| + return c.Value |
| + } |
| + t, err := randomToken() |
| + if err != nil { |
| + log.Printf("console: sign-in flow token: %v", err) |
| + return "" |
| + } |
| + return t |
| +} |
| + |
| +// setFlow (re)sets the flow cookie for another ConfirmationTTL. |
| +func (s *Server) setFlow(w http.ResponseWriter, flow string) { |
| + if flow != "" { |
| + s.setCookie(w, flowCookie, flow, int(ConfirmationTTL.Seconds())) |
| + } |
| +} |
| + |
| +// flowLock serialises /auth/continue's limits and challenge writes for one |
| +// flow, so overlapping submissions from one browser (a double-clicked |
| +// Continue) cannot both see "no challenge yet". Striped by the flow's hash: |
| +// bounded memory, and two flows rarely share a stripe. |
| +func (s *Server) flowLock(flow string) *sync.Mutex { |
| + sum := sha256.Sum256([]byte(flow)) |
| + return &s.flowLocks[sum[0]] |
| +} |
| + |
| +// homeForm is what the front page's one form starts with. flow, when set, is |
| +// the flow the caller already holds for this request. |
| type homeForm struct { |
| Prefill, Next, Banner, Error string |
| NoMail bool |
| + flow string |
| } |
| -// renderHome renders the signed-out front page. |
| -func (s *Server) renderHome(w http.ResponseWriter, f homeForm) { |
| +// renderHome renders the signed-out front page and (re)sets the browser's |
| +// sign-in flow. |
| +func (s *Server) renderHome(w http.ResponseWriter, r *http.Request, f homeForm) { |
| + if f.flow == "" { |
| + f.flow = s.requestFlow(r) |
| + } |
| + s.setFlow(w, f.flow) |
| s.render(w, http.StatusOK, "home", page{ |
| Title: "Sign in", Prefill: f.Prefill, Next: safeNext(f.Next), |
| Banner: f.Banner, Error: f.Error, NoMail: f.NoMail, |
| }) |
| } |
| -// renderCheck renders "Check your email" for addr. Every email-bound outcome |
| -// of the front door renders exactly this, so the page never says whether a |
| -// message was sent, throttled or refused. |
| -func (s *Server) renderCheck(w http.ResponseWriter, addr, next string) { |
| - s.renderCheckError(w, addr, next, "") |
| +// renderCheck renders "Check your email" for addr and (re)sets the flow |
| +// cookie. Every email-bound outcome of the front door renders exactly this, |
| +// so the page never says whether a message was sent, throttled or refused. |
| +func (s *Server) renderCheck(w http.ResponseWriter, flow, addr, next string) { |
| + s.renderCheckError(w, flow, addr, next, "") |
| } |
| // renderCheckError is the same page with a refusal of a typed code under the |
| -// code box. |
| -func (s *Server) renderCheckError(w http.ResponseWriter, addr, next, codeErr string) { |
| +// code box. Its address and next are what the request carried, never the |
| +// stored challenge's, so a refused request's page and a sent one's stay the |
| +// same through every later code. |
| +func (s *Server) renderCheckError(w http.ResponseWriter, flow, addr, next, codeErr string) { |
| + s.setFlow(w, flow) |
| sent := "" |
| if addr != "" { |
| sent = copyText("check.sent", "address", addr) |
| @@ -321,47 +367,36 @@ func (s *Server) handleEmailLink(w http.ResponseWriter, r *http.Request) { |
| s.renderLinkExpired(w, r) |
| return |
| } |
| + // Spending it also ends the flow's other sign-in challenges. |
| c, ok := s.store.TakeEmailLink(link, now) |
| if !ok || c.Purpose != ChallengeSignIn { |
| s.renderLinkExpired(w, r) |
| return |
| } |
| - s.clearSpentChallengeCookie(w, r, now) |
| s.finishSignin(w, r, c.Address, "", MethodEmail, c.Next) |
| } |
| -// clearSpentChallengeCookie follows a spent link: a challenge cookie that now |
| -// names nothing named the spent challenge (or something already gone), so it |
| -// is cleared. One naming a newer, live challenge is left alone. |
| -func (s *Server) clearSpentChallengeCookie(w http.ResponseWriter, r *http.Request, now time.Time) { |
| - if cc, err := r.Cookie(challengeCookie); err == nil { |
| - if _, live := s.store.PeekEmailChallenge(cc.Value, now); !live { |
| - s.clearCookie(w, challengeCookie) |
| - } |
| - } |
| -} |
| - |
| // handleEmailCode is POST /auth/email/code (spec 5.2): the typed code is |
| -// checked only against the challenge this browser's cookie names. Wrong codes |
| -// count against the address and the client IP across every challenge |
| -// (spec 5); past either cap the code is refused unchecked and nothing is |
| -// burned, so the emailed link still works. |
| +// checked only against the newest live sign-in challenge of this browser's |
| +// flow. A challenge that was sent and one a refused request recorded unsent |
| +// answer alike, so the code box says nothing about throttling. Wrong codes |
| +// count against the challenge's address and the client IP across every |
| +// challenge (spec 5); past either cap the code is refused unchecked and |
| +// nothing is burned, so the emailed link still works. |
| func (s *Server) handleEmailCode(w http.ResponseWriter, r *http.Request) { |
| if !s.sameOrigin(r) { |
| s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.") |
| return |
| } |
| now := time.Now() |
| - id := "" |
| - if ck, err := r.Cookie(challengeCookie); err == nil { |
| - id = ck.Value |
| - } |
| - c, ok := s.store.PeekEmailChallenge(id, now) |
| - if !ok || c.Purpose != ChallengeSignIn { |
| - // No challenge to check against: the page again, for the address the |
| - // form carried (shown only, never used as a key). |
| - addr, _ := canonicalAddress(r.PostFormValue("address")) |
| - s.renderCheckError(w, addr, r.PostFormValue("next"), copyText("check.code_used_up")) |
| + 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. |
| + addr, _ := canonicalAddress(r.PostFormValue("address")) |
| + next := r.PostFormValue("next") |
| + c, ok := s.store.LiveEmailChallenge(ChallengeSignIn, hashToken(flow), now) |
| + if flow == "" || !ok { |
| + s.renderCheckError(w, flow, addr, next, copyText("check.code_used_up")) |
| return |
| } |
| // The cap is keyed by the stored challenge's address, never by the form. |
| @@ -371,21 +406,20 @@ func (s *Server) handleEmailCode(w http.ResponseWriter, r *http.Request) { |
| done, allowed := s.limits.reserveGuess(c.Address, ip) |
| if !allowed { |
| log.Printf("console: code for %s from %s refused: too many wrong codes", c.Address, ip) |
| - s.renderCheckError(w, c.Address, c.Next, copyText("check.code_throttled")) |
| + s.renderCheckError(w, flow, addr, next, copyText("check.code_throttled")) |
| return |
| } |
| - got, res := s.store.TakeEmailCode(id, strings.TrimSpace(r.PostFormValue("code")), ChallengeSignIn, now) |
| + got, res := s.store.TakeEmailCode(c, strings.TrimSpace(r.PostFormValue("code")), now) |
| done(res == CodeOK) |
| switch res { |
| case CodeOK: |
| - s.clearCookie(w, challengeCookie) |
| s.finishSignin(w, r, got.Address, "", MethodEmail, got.Next) |
| case CodeWrong: |
| - s.renderCheckError(w, c.Address, c.Next, copyText("check.code_wrong")) |
| + s.renderCheckError(w, flow, addr, next, copyText("check.code_wrong")) |
| default: |
| // CodeBurned (this wrong code was the last) or CodeGone (the challenge |
| // went meanwhile, or predates a restart); both keep the reservation. |
| - s.renderCheckError(w, c.Address, c.Next, copyText("check.code_used_up")) |
| + s.renderCheckError(w, flow, addr, next, copyText("check.code_used_up")) |
| } |
| } |
| @@ -401,9 +435,9 @@ func (s *Server) handleEmailCode(w http.ResponseWriter, r *http.Request) { |
| // emailStepUp is requireFreshAuth's answer for an email session that is not |
| // fresh: hold the action, email a link and code bound to this session and |
| // that action, and show "Confirm it's you". With no mailer ready it fails |
| -// closed, holding nothing. Over the send limit, a browser already holding a |
| -// live step-up challenge for this session sees that one's page again (the |
| -// earlier email still works); any other fails closed. |
| +// closed, holding nothing. Over the send limit, a session that already has a |
| +// live step-up challenge sees that one's page again (the earlier email still |
| +// works); any other fails closed. |
| func (s *Server) emailStepUp(w http.ResponseWriter, r *http.Request, addr, raw string, now time.Time) { |
| if !s.mailReady(r.Context()) { |
| log.Printf("console: step-up for %s: the console mailer is not ready", addr) |
| @@ -411,7 +445,7 @@ func (s *Server) emailStepUp(w http.ResponseWriter, r *http.Request, addr, raw s |
| return |
| } |
| if !s.limits.stepUpSend(addr) { |
| - if _, c, ok := s.liveStepUp(r, raw, now); ok { |
| + if c, ok := s.liveStepUp(raw, now); ok { |
| s.renderStepUp(w, r, c.Address, "") |
| return |
| } |
| @@ -423,23 +457,19 @@ func (s *Server) emailStepUp(w http.ResponseWriter, r *http.Request, addr, raw s |
| if !ok { |
| return |
| } |
| - replace := "" |
| - if id, _, ok := s.liveStepUp(r, raw, now); ok { |
| - replace = id |
| - } |
| - id, link, code, err := s.store.CreateEmailChallenge(EmailChallenge{ |
| + // It replaces this session's earlier step-up challenge, if any. |
| + link, code, err := s.store.CreateEmailChallenge(EmailChallenge{ |
| Purpose: ChallengeStepUp, |
| Address: addr, |
| SessionHash: hashToken(raw), |
| PendingHash: hashToken(pending), |
| ExpiresAt: now.Add(stepUpFlowTTL), |
| - }, replace, now) |
| + }, now) |
| 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.") |
| return |
| } |
| - s.setCookie(w, challengeCookie, id, int(stepUpFlowTTL.Seconds())) |
| console := s.consoleName() |
| s.sendChallengeAsync(addr, |
| copyText("email.stepup.subject", "console", console), |
| @@ -454,18 +484,13 @@ func stepUpFor(c *EmailChallenge, raw string) bool { |
| subtle.ConstantTimeCompare([]byte(c.SessionHash), []byte(hashToken(raw))) == 1 |
| } |
| -// liveStepUp is the live step-up challenge this browser's challengeCookie |
| -// names, with its id, when it was made for the session raw. |
| -func (s *Server) liveStepUp(r *http.Request, raw string, now time.Time) (string, *EmailChallenge, bool) { |
| - ck, err := r.Cookie(challengeCookie) |
| - if err != nil || ck.Value == "" { |
| - return "", nil, false |
| - } |
| - c, ok := s.store.PeekEmailChallenge(ck.Value, now) |
| +// liveStepUp is the newest live step-up challenge made for the session raw. |
| +func (s *Server) liveStepUp(raw string, now time.Time) (*EmailChallenge, bool) { |
| + c, ok := s.store.LiveEmailChallenge(ChallengeStepUp, hashToken(raw), now) |
| if !ok || !stepUpFor(c, raw) { |
| - return "", nil, false |
| + return nil, false |
| } |
| - return ck.Value, c, true |
| + return c, true |
| } |
| // renderStepUp renders "Confirm it's you" for addr, with a refusal of a typed |
| @@ -529,13 +554,12 @@ func (s *Server) stepUpLink(w http.ResponseWriter, r *http.Request, link string, |
| s.renderStepUpExpired(w, r) |
| return |
| } |
| - s.clearSpentChallengeCookie(w, r, now) |
| s.finishStepUp(w, r, addr, raw, c, now) |
| } |
| // handleStepUpEmailCode is POST /auth/email/stepup/code: the typed code is |
| -// checked only against the step-up challenge this browser's cookie names, and |
| -// only for the session it was made for. Wrong codes count against the |
| +// checked only against the newest live step-up challenge made for this |
| +// browser's session. Wrong codes count against the |
| // challenge's address and the client IP, as for sign-in codes. |
| func (s *Server) handleStepUpEmailCode(w http.ResponseWriter, r *http.Request) { |
| addr, raw, ok := s.session(r) |
| @@ -548,7 +572,7 @@ func (s *Server) handleStepUpEmailCode(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| now := time.Now() |
| - id, c, ok := s.liveStepUp(r, raw, now) |
| + c, ok := s.liveStepUp(raw, now) |
| if !ok { |
| s.renderStepUpExpired(w, r) |
| return |
| @@ -560,11 +584,10 @@ func (s *Server) handleStepUpEmailCode(w http.ResponseWriter, r *http.Request) { |
| s.renderStepUp(w, r, c.Address, copyText("check.code_throttled")) |
| return |
| } |
| - got, res := s.store.TakeEmailCode(id, strings.TrimSpace(r.PostFormValue("code")), ChallengeStepUp, now) |
| + got, res := s.store.TakeEmailCode(c, strings.TrimSpace(r.PostFormValue("code")), now) |
| done(res == CodeOK) |
| switch res { |
| case CodeOK: |
| - s.clearCookie(w, challengeCookie) |
| s.finishStepUp(w, r, addr, raw, got, now) |
| case CodeWrong: |
| s.renderStepUp(w, r, c.Address, copyText("check.code_wrong")) |
diff --git a/internal/console/emailsignin_store.go b/internal/console/emailsignin_store.go| index 974227908..8788b6bcd 100644 |
| --- a/internal/console/emailsignin_store.go |
| +++ b/internal/console/emailsignin_store.go |
| @@ -1,13 +1,16 @@ |
| 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 |
| +// purpose. A sign-in challenge belongs to the browser's sign-in flow (its |
| +// flow cookie's hash), a step-up challenge to the session that asked; the |
| +// code box finds the newest live challenge of either by that binding, so no |
| +// browser ever holds a challenge's own id. 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 |
| +// (Store.codeKey): six digits bound to a row anyone reading the database can |
| +// see 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. |
| @@ -37,11 +40,15 @@ const ( |
| ) |
| // 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. |
| +// read or a successful take hands back. FlowHash and Next are sign-in only; |
| +// SessionHash and PendingHash are step-up only. |
| type EmailChallenge struct { |
| - Purpose, Address, SessionHash, PendingHash, Next string |
| - ExpiresAt time.Time |
| + Purpose, Address, SessionHash, PendingHash, Next, FlowHash string |
| + ExpiresAt time.Time |
| + |
| + // row is the challenge's row key (id_hash), set by LiveEmailChallenge, so |
| + // TakeEmailCode checks the very challenge that was read. |
| + row string |
| } |
| // CodeResult is the verdict of TakeEmailCode. |
| @@ -73,91 +80,153 @@ func (s *Store) migrateEmailSignin() error { |
| attempts INTEGER NOT NULL DEFAULT 0, |
| created_at INTEGER NOT NULL, |
| expires_at INTEGER NOT NULL, |
| - alias_hashes TEXT NOT NULL DEFAULT '' |
| + flow_hash TEXT NOT NULL DEFAULT '' |
| );`) |
| 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 && |
| + // Additive: the sign-in flow a challenge belongs to. Forgiving "duplicate |
| + // column", so re-running is always safe. (An earlier build's alias_hashes |
| + // column, where one exists, is no longer read or written.) |
| + if _, err := s.db.Exec(`ALTER TABLE email_challenges ADD COLUMN flow_hash 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 |
| -) |
| +// challengeBinding is the column that ties together the challenges of one |
| +// purpose: a sign-in flow's (flow_hash) or a session's step-ups |
| +// (session_hash). Fixed names only, so it is safe to build into SQL. |
| +func challengeBinding(purpose string) (column string, ok bool) { |
| + switch purpose { |
| + case ChallengeSignIn: |
| + return "flow_hash", true |
| + case ChallengeStepUp: |
| + return "session_hash", true |
| + } |
| + return "", false |
| +} |
| + |
| +// bindingOf is c's value in its purpose's binding column. |
| +func bindingOf(c EmailChallenge) string { |
| + if c.Purpose == ChallengeStepUp { |
| + return c.SessionHash |
| + } |
| + return c.FlowHash |
| +} |
| // 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. |
| +// row's link hash binds the code to its challenge. 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(linkHash + ":" + 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 |
| +// 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) { |
| + tx, err := s.db.Begin() |
| + if err != nil { |
| + return "", "", err |
| + } |
| + defer tx.Rollback() |
| + if err := deleteBound(tx, c.Purpose, bindingOf(c)); err != nil { |
| + return "", "", err |
| + } |
| + if link, code, err = s.insertEmailChallenge(tx, c, now); err != nil { |
| + return "", "", 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. |
| +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) |
| + } |
| + 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, now); err != nil { |
| + return err |
| + } |
| + return tx.Commit() |
| +} |
| + |
| +// deleteBound deletes every challenge of purpose bound to bind; an empty bind |
| +// deletes nothing. |
| +func deleteBound(tx *sql.Tx, purpose, bind string) error { |
| + col, ok := challengeBinding(purpose) |
| + if !ok || bind == "" { |
| + return nil |
| + } |
| + _, err := tx.Exec(`DELETE FROM email_challenges WHERE purpose = ? AND `+col+` = ?`, purpose, bind) |
| + return err |
| +} |
| + |
| +// insertEmailChallenge mints a challenge's row key, link and code and stores |
| +// c under them. The row key is internal: no browser is given it. |
| +func (s *Store) insertEmailChallenge(tx *sql.Tx, c EmailChallenge, now time.Time) (link, code string, err error) { |
| + row, err := randomToken() |
| + if err != nil { |
| + return "", "", err |
| } |
| if link, err = randomToken(); err != nil { |
| - return "", "", "", err |
| + return "", "", err |
| } |
| n, err := rand.Int(rand.Reader, big.NewInt(1_000_000)) |
| if err != nil { |
| - return "", "", "", err |
| + 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 != "" { |
| - h := hashToken(replaceID) |
| - if _, err := tx.Exec(`DELETE FROM email_challenges WHERE `+challengeByID, h, h); 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(hashToken(link), 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 |
| +(id_hash, link_hash, code_mac, purpose, address, session_hash, pending, next, flow_hash, attempts, created_at, expires_at) |
| +VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?)`, |
| + hashToken(row), hashToken(link), s.codeMAC(hashToken(link), code), c.Purpose, c.Address, |
| + c.SessionHash, c.PendingHash, c.Next, c.FlowHash, now.Unix(), exp.Unix()); err != nil { |
| + return "", "", err |
| } |
| - return id, link, code, nil |
| + return link, code, nil |
| } |
| +const challengeColumns = `purpose, address, session_hash, pending, next, flow_hash, expires_at` |
| + |
| // 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 |
| + c, exp, err := scanEmailChallenge(s.db.QueryRow(`SELECT `+challengeColumns+` |
| FROM email_challenges WHERE link_hash = ?`, hashToken(link))) |
| if err != nil || now.Unix() > exp { |
| return nil, false |
| @@ -165,32 +234,41 @@ FROM email_challenges WHERE link_hash = ?`, hashToken(link))) |
| return c, true |
| } |
| -// PeekEmailChallenge reads a challenge by its browser-held id without |
| -// spending it or counting an attempt. It reports false for an empty, unknown |
| -// or expired id and deletes nothing. |
| -func (s *Store) PeekEmailChallenge(id string, now time.Time) (*EmailChallenge, bool) { |
| - if id == "" { |
| +// LiveEmailChallenge is the newest live challenge of purpose bound to bind |
| +// (a sign-in flow's hash, or a session's hash for a step-up), without |
| +// spending it or counting an attempt. It reports false for an empty binding |
| +// or when there is none. |
| +func (s *Store) LiveEmailChallenge(purpose, bind string, now time.Time) (*EmailChallenge, bool) { |
| + col, ok := challengeBinding(purpose) |
| + if !ok || bind == "" { |
| 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 `+challengeByID, h, h)) |
| - if err != nil || now.Unix() > exp { |
| + var row string |
| + var c EmailChallenge |
| + var exp int64 |
| + err := s.db.QueryRow(`SELECT id_hash, `+challengeColumns+` FROM email_challenges |
| +WHERE purpose = ? AND `+col+` = ? AND expires_at >= ? |
| +ORDER BY created_at DESC, rowid DESC LIMIT 1`, purpose, bind, now.Unix()). |
| + Scan(&row, &c.Purpose, &c.Address, &c.SessionHash, &c.PendingHash, &c.Next, &c.FlowHash, &exp) |
| + if err != nil { |
| return nil, false |
| } |
| - return c, true |
| + c.ExpiresAt = time.Unix(exp, 0) |
| + c.row = row |
| + 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. |
| +// can never be retried into validity. A live one also takes its binding's |
| +// other challenges with it: a successful sign-in ends the flow's others. |
| 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 |
| + c, exp, err := scanEmailChallenge(tx.QueryRow(`SELECT `+challengeColumns+` |
| FROM email_challenges WHERE link_hash = ?`, hashToken(link))) |
| if err != nil { |
| return nil, false |
| @@ -198,22 +276,28 @@ FROM email_challenges WHERE link_hash = ?`, hashToken(link))) |
| if _, err := tx.Exec(`DELETE FROM email_challenges WHERE link_hash = ?`, hashToken(link)); err != nil { |
| return nil, false |
| } |
| - if err := tx.Commit(); err != nil { |
| + if now.Unix() > exp { |
| + if err := tx.Commit(); err != nil { |
| + return nil, false |
| + } |
| return nil, false |
| } |
| - if now.Unix() > exp { |
| + if err := deleteBound(tx, c.Purpose, bindingOf(*c)); err != nil { |
| + return nil, false |
| + } |
| + if err := tx.Commit(); err != nil { |
| 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 (CodeBurned); a right code |
| -// deletes it and reports CodeOK. |
| -func (s *Store) TakeEmailCode(id, code, purpose string, now time.Time) (*EmailChallenge, CodeResult) { |
| - if id == "" { |
| +// TakeEmailCode checks a typed code against the challenge read by |
| +// LiveEmailChallenge. One transaction: a challenge gone, expired or changed |
| +// meanwhile is reported CodeGone (an expired one is deleted); a wrong code |
| +// adds an attempt, and the fifth burns the challenge (CodeBurned); a right |
| +// code deletes it, with its binding's other challenges, and reports CodeOK. |
| +func (s *Store) TakeEmailCode(read *EmailChallenge, code string, now time.Time) (*EmailChallenge, CodeResult) { |
| + if read == nil || read.row == "" { |
| return nil, CodeGone |
| } |
| tx, err := s.db.Begin() |
| @@ -221,18 +305,17 @@ func (s *Store) TakeEmailCode(id, code, purpose string, now time.Time) (*EmailCh |
| return nil, CodeGone |
| } |
| defer tx.Rollback() |
| - idHash := hashToken(id) |
| 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 `+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 { |
| + if err := tx.QueryRow(`SELECT `+challengeColumns+`, code_mac, link_hash, attempts |
| +FROM email_challenges WHERE id_hash = ?`, read.row). |
| + Scan(&c.Purpose, &c.Address, &c.SessionHash, &c.PendingHash, &c.Next, &c.FlowHash, &exp, &mac, &linkHash, &attempts); err != nil { |
| return nil, CodeGone |
| } |
| c.ExpiresAt = time.Unix(exp, 0) |
| - if now.Unix() > exp || c.Purpose != purpose { |
| + if now.Unix() > exp || c.Purpose != read.Purpose { |
| if _, err := tx.Exec(`DELETE FROM email_challenges WHERE link_hash = ?`, linkHash); err != nil { |
| return nil, CodeGone |
| } |
| @@ -266,67 +349,19 @@ FROM email_challenges WHERE `+challengeByID, idHash, idHash) |
| if _, err := tx.Exec(`DELETE FROM email_challenges WHERE link_hash = ?`, linkHash); err != nil { |
| return nil, CodeGone |
| } |
| - if err := tx.Commit(); err != nil { |
| + if err := deleteBound(tx, c.Purpose, bindingOf(c)); err != nil { |
| return nil, CodeGone |
| } |
| - return &c, CodeOK |
| -} |
| - |
| -// RekeyEmailChallenge gives a live sign-in challenge for address a new |
| -// 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 |
| - } |
| - newID, err := randomToken() |
| - if err != nil { |
| - return "", false |
| - } |
| - tx, err := s.db.Begin() |
| - if err != nil { |
| - return "", false |
| - } |
| - defer tx.Rollback() |
| - 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 |
| - } |
| - 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 { |
| - return "", false |
| + return nil, CodeGone |
| } |
| - 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 { |
| - h := hashToken(id) |
| - _, err := s.db.Exec(`DELETE FROM email_challenges WHERE `+challengeByID, h, h) |
| - return err |
| + return &c, CodeOK |
| } |
| 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 { |
| + if err := row.Scan(&c.Purpose, &c.Address, &c.SessionHash, &c.PendingHash, &c.Next, &c.FlowHash, &exp); err != nil { |
| return nil, 0, err |
| } |
| c.ExpiresAt = time.Unix(exp, 0) |
diff --git a/internal/console/emailsignin_store_test.go b/internal/console/emailsignin_store_test.go| index 40b4a742c..ae85bd099 100644 |
| --- a/internal/console/emailsignin_store_test.go |
| +++ b/internal/console/emailsignin_store_test.go |
| @@ -1,6 +1,7 @@ |
| package console |
| import ( |
| + "crypto/hmac" |
| "crypto/sha256" |
| "database/sql" |
| "encoding/hex" |
| @@ -9,16 +10,30 @@ import ( |
| "time" |
| ) |
| -func newSignInChallenge(t *testing.T, s *Store, now time.Time, replaceID string) (id, link, code string) { |
| +// testFlow is the flow hash the store tests' sign-in challenges belong to. |
| +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() |
| - id, link, code, err := s.CreateEmailChallenge(EmailChallenge{ |
| - Purpose: ChallengeSignIn, Address: "bob@example.com", Next: "/auth/cli", |
| + link, code, err := s.CreateEmailChallenge(EmailChallenge{ |
| + Purpose: ChallengeSignIn, Address: "bob@example.com", Next: "/auth/cli", FlowHash: flowHash, |
| ExpiresAt: now.Add(ConfirmationTTL), |
| - }, replaceID, now) |
| + }, now) |
| if err != nil { |
| t.Fatal(err) |
| } |
| - return id, link, code |
| + return link, code |
| +} |
| + |
| +// live is the flow's newest live sign-in challenge, failing the test when |
| +// there is none. |
| +func live(t *testing.T, s *Store, flowHash string, now time.Time) *EmailChallenge { |
| + t.Helper() |
| + c, ok := s.LiveEmailChallenge(ChallengeSignIn, flowHash, now) |
| + if !ok { |
| + t.Fatal("the flow has no live sign-in challenge") |
| + } |
| + return c |
| } |
| // wrongCode returns a six-digit code that is not code. |
| @@ -32,10 +47,10 @@ func wrongCode(code string) string { |
| func TestEmailChallengeLinkPeekDoesNotConsume(t *testing.T) { |
| s := openTestStore(t) |
| now := time.Now() |
| - _, link, _ := newSignInChallenge(t, s, now, "") |
| + link, _ := newSignInChallenge(t, s, now, testFlow) |
| 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 { |
| + if !ok || c.Address != "bob@example.com" || c.Next != "/auth/cli" || c.Purpose != ChallengeSignIn || c.FlowHash != testFlow { |
| t.Fatalf("peek %d = %+v, %v", i, c, ok) |
| } |
| } |
| @@ -50,27 +65,43 @@ func TestEmailChallengeLinkPeekDoesNotConsume(t *testing.T) { |
| } |
| } |
| -func TestEmailChallengePeekByID(t *testing.T) { |
| +func TestEmailChallengeLiveByFlow(t *testing.T) { |
| s := openTestStore(t) |
| now := time.Now() |
| - id, _, code := newSignInChallenge(t, s, now, "") |
| + _, code := newSignInChallenge(t, s, now, testFlow) |
| for i := 0; i < 2; i++ { |
| - c, ok := s.PeekEmailChallenge(id, now) |
| - if !ok || c.Address != "bob@example.com" || c.Next != "/auth/cli" || c.Purpose != ChallengeSignIn { |
| - t.Fatalf("peek %d = %+v, %v", i, c, ok) |
| + c := live(t, s, testFlow, now) |
| + if c.Address != "bob@example.com" || c.Next != "/auth/cli" || c.Purpose != ChallengeSignIn { |
| + t.Fatalf("live read %d = %+v", i, c) |
| } |
| } |
| - if _, ok := s.PeekEmailChallenge(id, now.Add(ConfirmationTTL+time.Minute)); ok { |
| - t.Fatal("an expired challenge peeks") |
| + for _, tc := range []struct { |
| + why, purpose, flow string |
| + at time.Time |
| + }{ |
| + {"expired", ChallengeSignIn, testFlow, now.Add(ConfirmationTTL + time.Minute)}, |
| + {"empty flow", ChallengeSignIn, "", now}, |
| + {"another flow", ChallengeSignIn, hashToken("other"), now}, |
| + {"another purpose", ChallengeStepUp, testFlow, now}, |
| + } { |
| + if _, ok := s.LiveEmailChallenge(tc.purpose, tc.flow, tc.at); ok { |
| + t.Errorf("%s: a challenge was found", tc.why) |
| + } |
| + } |
| + if _, res := s.TakeEmailCode(live(t, s, testFlow, now), code, now); res != CodeOK { |
| + t.Fatalf("reading spent the challenge: %v", res) |
| } |
| - if _, ok := s.PeekEmailChallenge("", now); ok { |
| - t.Fatal("an empty id peeks") |
| + if _, ok := s.LiveEmailChallenge(ChallengeSignIn, testFlow, now); ok { |
| + t.Fatal("a taken challenge is still live") |
| } |
| - if _, res := s.TakeEmailCode(id, code, ChallengeSignIn, now); res != CodeOK { |
| - t.Fatalf("peeking spent the challenge: %v", res) |
| + // A step-up is found by its session's hash. |
| + if _, _, err := s.CreateEmailChallenge(EmailChallenge{ |
| + Purpose: ChallengeStepUp, Address: "bob@example.com", SessionHash: "sh", PendingHash: "ph", |
| + }, now); err != nil { |
| + t.Fatal(err) |
| } |
| - if _, ok := s.PeekEmailChallenge(id, now); ok { |
| - t.Fatal("a taken challenge still peeks") |
| + if c, ok := s.LiveEmailChallenge(ChallengeStepUp, "sh", now); !ok || c.PendingHash != "ph" { |
| + t.Fatalf("step-up by session = %+v, %v", c, ok) |
| } |
| } |
| @@ -78,39 +109,47 @@ 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) |
| + link, code := newSignInChallenge(t, s, now, testFlow) |
| + c := live(t, s, testFlow, now) |
| + if got, res := s.TakeEmailCode(c, code, now); res != CodeOK || got == nil || got.Address != "bob@example.com" { |
| + t.Fatalf("right code = %+v, %v", got, 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 { |
| + if _, res := s.TakeEmailCode(c, code, now); res != CodeGone { |
| t.Fatalf("a code was taken twice: %v", res) |
| } |
| + if _, res := s.TakeEmailCode(nil, code, now); res != CodeGone { |
| + t.Fatalf("no challenge = %v, want CodeGone", res) |
| + } |
| - id, link, code = newSignInChallenge(t, s, now, "") |
| + link, code = newSignInChallenge(t, s, now, testFlow) |
| + c = live(t, s, testFlow, now) |
| bad := wrongCode(code) |
| for i := 1; i <= 4; i++ { |
| - if _, res := s.TakeEmailCode(id, bad, ChallengeSignIn, now); res != CodeWrong { |
| + if _, res := s.TakeEmailCode(c, bad, now); res != CodeWrong { |
| t.Fatalf("wrong code %d = %v, want CodeWrong", i, res) |
| } |
| } |
| - if _, res := s.TakeEmailCode(id, bad, ChallengeSignIn, now); res != CodeBurned { |
| + if _, res := s.TakeEmailCode(c, bad, now); res != CodeBurned { |
| t.Fatalf("5th wrong code = %v, want CodeBurned", res) |
| } |
| - if _, res := s.TakeEmailCode(id, code, ChallengeSignIn, now); res != CodeGone { |
| + if _, res := s.TakeEmailCode(c, code, 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 { |
| + _, code = newSignInChallenge(t, s, now, testFlow) |
| + c = live(t, s, testFlow, now) |
| + other := *c |
| + other.Purpose = ChallengeStepUp |
| + if _, res := s.TakeEmailCode(&other, code, now); res != CodeGone { |
| t.Fatalf("wrong purpose = %v, want CodeGone", res) |
| } |
| - if _, res := s.TakeEmailCode(id, code, ChallengeSignIn, now); res != CodeGone { |
| + if _, res := s.TakeEmailCode(c, code, now); res != CodeGone { |
| t.Fatalf("a wrong-purpose attempt left the challenge standing: %v", res) |
| } |
| } |
| @@ -129,7 +168,8 @@ func TestEmailChallengeExpiry(t *testing.T) { |
| now := time.Now() |
| late := now.Add(ConfirmationTTL + time.Second) |
| - id, link, code := newSignInChallenge(t, s, now, "") |
| + link, code := newSignInChallenge(t, s, now, testFlow) |
| + c := live(t, s, testFlow, now) |
| if _, ok := s.PeekEmailLink(link, late); ok { |
| t.Fatal("an expired link peeks") |
| } |
| @@ -139,12 +179,13 @@ func TestEmailChallengeExpiry(t *testing.T) { |
| 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 { |
| + if _, res := s.TakeEmailCode(c, code, 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 { |
| + link, code = newSignInChallenge(t, s, now, testFlow) |
| + c = live(t, s, testFlow, now) |
| + if _, res := s.TakeEmailCode(c, code, late); res != CodeGone { |
| t.Fatalf("expired code = %v, want CodeGone", res) |
| } |
| if n := countChallenges(t, s); n != 0 { |
| @@ -162,15 +203,30 @@ func TestEmailChallengeCodeKeyIsProcessLocal(t *testing.T) { |
| t.Fatal(err) |
| } |
| now := time.Now() |
| - id, link, code := newSignInChallenge(t, s, now, "") |
| + link, code := newSignInChallenge(t, s, now, testFlow) |
| + // The stored MAC is exactly HMAC-SHA256 under this process's key over the |
| + // challenge's binding (its link hash) and the code, behind the epoch. |
| var mac string |
| - if err := s.db.QueryRow(`SELECT code_mac FROM email_challenges WHERE id_hash = ?`, hashToken(id)).Scan(&mac); err != nil { |
| + if err := s.db.QueryRow(`SELECT code_mac FROM email_challenges WHERE link_hash = ?`, hashToken(link)).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") |
| + macUnder := func(key []byte) string { |
| + m := hmac.New(sha256.New, key) |
| + m.Write([]byte(hashToken(link) + ":" + code)) |
| + return s.codeEpoch + ":" + hex.EncodeToString(m.Sum(nil)) |
| + } |
| + if want := macUnder(s.codeKey); mac != want { |
| + t.Fatalf("code_mac = %q, want HMAC under the process key %q", mac, want) |
| + } |
| + otherKey := append([]byte(nil), s.codeKey...) |
| + otherKey[0] ^= 0xff |
| + if mac == macUnder(otherKey) { |
| + t.Fatal("a different key gives the same code_mac: the key does not bind it") |
| + } |
| + plain := sha256.Sum256([]byte(hashToken(link) + ":" + code)) |
| + if mac == s.codeEpoch+":"+hex.EncodeToString(plain[:]) { |
| + t.Fatal("code_mac is a plain hash of the binding and code, recoverable from a database read") |
| } |
| if err := s.Close(); err != nil { |
| t.Fatal(err) |
| @@ -186,7 +242,7 @@ func TestEmailChallengeCodeKeyIsProcessLocal(t *testing.T) { |
| 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 { |
| + if _, res := s2.TakeEmailCode(live(t, s2, testFlow, now), code, now); res != CodeGone { |
| t.Fatalf("code after restart = %v, want CodeGone (used up)", res) |
| } |
| if _, ok := s2.TakeEmailLink(link, now); !ok { |
| @@ -194,46 +250,109 @@ func TestEmailChallengeCodeKeyIsProcessLocal(t *testing.T) { |
| } |
| } |
| +// A new challenge replaces the flow's earlier one, link and code alike, and |
| +// leaves other flows alone. |
| 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) |
| + linkA, codeA := newSignInChallenge(t, s, now, testFlow) |
| + cA := live(t, s, testFlow, now) |
| + otherFlow := hashToken("another-browser") |
| + linkOther, _ := newSignInChallenge(t, s, now, otherFlow) |
| + linkB, _ := newSignInChallenge(t, s, now, testFlow) |
| if _, ok := s.PeekEmailLink(linkA, now); ok { |
| t.Fatal("the replaced link still works") |
| } |
| - if _, res := s.TakeEmailCode(idA, codeA, ChallengeSignIn, now); res != CodeGone { |
| + if _, res := s.TakeEmailCode(cA, codeA, 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 n := countChallenges(t, s); n != 2 { |
| + t.Fatalf("%d challenges after a replace, want 2 (this flow's newest and the other flow's)", n) |
| + } |
| + if _, ok := s.PeekEmailLink(linkOther, now); !ok { |
| + t.Fatal("a replace in one flow ended another flow's challenge") |
| } |
| - if _, res := s.TakeEmailCode(idB, codeB, ChallengeSignIn, now); res != CodeOK { |
| - t.Fatalf("the new code = %v, want CodeOK", res) |
| + // B's own link signs in, once. |
| + if c, ok := s.TakeEmailLink(linkB, now); !ok || c.Address != "bob@example.com" { |
| + t.Fatalf("the new link = %+v, %v", c, ok) |
| } |
| - _, linkC, _ := newSignInChallenge(t, s, now, "") |
| - _ = linkB |
| - if _, ok := s.TakeEmailLink(linkC, now); !ok { |
| - t.Fatal("the new link does not work") |
| + if _, ok := s.LiveEmailChallenge(ChallengeSignIn, testFlow, now); ok { |
| + t.Fatal("B's challenge is still live after its link was used") |
| } |
| } |
| -func TestEmailChallengeDelete(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) { |
| s := openTestStore(t) |
| now := time.Now() |
| - id, link, _ := newSignInChallenge(t, s, now, "") |
| - if err := s.DeleteEmailChallenge(id); err != nil { |
| + 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 _, ok := s.PeekEmailLink(link, now); ok { |
| - t.Fatal("a deleted challenge still peeks") |
| + if n := countChallenges(t, s); n != 1 { |
| + t.Fatalf("%d challenges after a hold beside a live one, want 1", n) |
| + } |
| + if c := live(t, s, testFlow, now); c.Address != "bob@example.com" { |
| + t.Fatalf("the hold displaced the sent challenge: %+v", c) |
| + } |
| + if _, ok := s.PeekEmailLink(link, now); !ok { |
| + t.Fatal("the hold ended the sent link") |
| + } |
| + if _, res := s.TakeEmailCode(live(t, s, testFlow, now), code, now); res != CodeOK { |
| + t.Fatalf("the sent code after a hold = %v", res) |
| + } |
| + // A flow with none gets an unsent challenge for the refused address. |
| + if err := s.HoldEmailChallenge(held, now); err != nil { |
| + t.Fatal(err) |
| + } |
| + c := live(t, s, testFlow, now) |
| + if c.Address != "carol@example.com" { |
| + t.Fatalf("held challenge = %+v", c) |
| + } |
| + if _, res := s.TakeEmailCode(c, "000000", now); res == CodeGone { |
| + t.Fatal("a code against the held challenge found nothing, unlike a sent one") |
| + } |
| + // An expired one counts as none. |
| + if err := s.HoldEmailChallenge(held, now.Add(ConfirmationTTL+time.Second)); err != nil { |
| + t.Fatal(err) |
| + } |
| + if n := countChallenges(t, s); n != 1 { |
| + t.Fatalf("%d challenges after holding past an expired one, want 1", n) |
| + } |
| +} |
| + |
| +// A successful link or code ends every other challenge of the same flow. |
| +func TestEmailChallengeTakeEndsFlow(t *testing.T) { |
| + s := openTestStore(t) |
| + now := time.Now() |
| + for _, by := range []string{"link", "code"} { |
| + t.Run(by, func(t *testing.T) { |
| + link, code := newSignInChallenge(t, s, now, testFlow) |
| + // A second row in the same flow, as an older build might leave. |
| + if _, err := s.db.Exec(`INSERT INTO email_challenges (id_hash, link_hash, code_mac, purpose, address, flow_hash, created_at, expires_at) |
| +VALUES (?, ?, 'x', ?, 'old@example.com', ?, ?, ?)`, hashToken(by+"-row"), hashToken(by+"-link"), ChallengeSignIn, testFlow, now.Unix()-1, now.Add(time.Minute).Unix()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if by == "link" { |
| + if _, ok := s.TakeEmailLink(link, now); !ok { |
| + t.Fatal("link refused") |
| + } |
| + } else if _, res := s.TakeEmailCode(live(t, s, testFlow, now), code, now); res != CodeOK { |
| + t.Fatalf("code = %v", res) |
| + } |
| + if n := countChallenges(t, s); n != 0 { |
| + t.Fatalf("%d of the flow's challenges outlived a sign-in", n) |
| + } |
| + }) |
| } |
| } |
| func TestEmailChallengePurgedWithExpired(t *testing.T) { |
| s := openTestStore(t) |
| now := time.Now() |
| - newSignInChallenge(t, s, now, "") |
| + newSignInChallenge(t, s, now, testFlow) |
| if err := s.PurgeExpired(now); err != nil { |
| t.Fatal(err) |
| } |
| @@ -312,132 +431,3 @@ 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 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" { |
| - 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") |
| - } |
| -} |
| - |
| -// 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 92e125c99..c4d5ef393 100644 |
| --- a/internal/console/emailsignin_test.go |
| +++ b/internal/console/emailsignin_test.go |
| @@ -6,7 +6,9 @@ import ( |
| "net/http/httptest" |
| "net/url" |
| "regexp" |
| + "sort" |
| "strings" |
| + "sync" |
| "testing" |
| "time" |
| ) |
| @@ -315,8 +317,8 @@ func checkEmailSent(t *testing.T, fx *consoleFixture, m *fakeConsoleMail, c *htt |
| if !ok || ch.Address != addr || ch.Purpose != ChallengeSignIn || ch.Next != next { |
| t.Fatalf("challenge = %+v %v, want a sign-in for %s with next %q", ch, ok, addr, next) |
| } |
| - if browserCookie(t, fx, c, challengeCookie) == "" { |
| - t.Fatal("no challenge cookie set on the browser that asked") |
| + if flow := browserCookie(t, fx, c, flowCookie); flow == "" || ch.FlowHash != hashToken(flow) { |
| + t.Fatalf("challenge flow %q is not the asking browser's flow %q", ch.FlowHash, flow) |
| } |
| } |
| @@ -419,8 +421,7 @@ 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 spends no lookup; the send limits |
| - // still refuse bob. |
| + // And an IP over its submission cap spends no lookup and sends nothing. |
| for fx.srv.limits.submit("127.0.0.1") { |
| } |
| lookupsBefore := lookupCount(fx) |
| @@ -432,16 +433,17 @@ func TestContinuePageIdentical(t *testing.T) { |
| if n := len(m.sentCopy()); n != 2 { |
| t.Fatalf("mailer got %d messages, want 2 (the throttled and capped ones send nothing)", n) |
| } |
| - if n := challengeRows(t, fx); n != 2 { |
| - t.Fatalf("%d challenges stored, want 2", n) |
| + // Two sent, and one never-sent challenge for each refused fresh browser. |
| + if n := challengeRows(t, fx); n != 4 { |
| + t.Fatalf("%d challenges stored, want 4", n) |
| } |
| if lookupCount(fx) != lookupsBefore { |
| t.Fatal("a capped submission still asked Keymail") |
| } |
| - // The headers match too: every outcome sets the challenge cookie. |
| + // The headers match too: every outcome sets a flow cookie. |
| for i, c := range browsers { |
| - if browserCookie(t, fx, c, challengeCookie) == "" { |
| - t.Errorf("outcome %d set no challenge cookie", i) |
| + if browserCookie(t, fx, c, flowCookie) == "" { |
| + t.Errorf("outcome %d set no flow cookie", i) |
| } |
| } |
| for _, want := range []string{ |
| @@ -893,8 +895,8 @@ func TestEmailCodeCrossDevice(t *testing.T) { |
| t.Fatalf("code on the asking browser = %d -> %q", status, loc) |
| } |
| emailSession(t, fx, a, addr) |
| - if browserCookie(t, fx, a, challengeCookie) != "" { |
| - t.Fatal("the challenge cookie outlived the sign-in") |
| + if challengeRows(t, fx) != 0 { |
| + t.Fatal("the challenge outlived the sign-in") |
| } |
| // Used once. |
| if status, _, body := postCode(t, fx, a, code); status != http.StatusOK || !strings.Contains(body, esc(copyText("check.code_used_up"))) { |
| @@ -907,15 +909,17 @@ func TestEmailCodeCrossDevice(t *testing.T) { |
| func TestEmailCodeGuessCap(t *testing.T) { |
| fx := newConsoleFixture(t) |
| const addr = "bob@example.com" |
| + const flow = "a-flow-token-of-at-least-thirty-two-characters" |
| c := newBrowser(t) |
| u, _ := url.Parse(fx.ts.URL) |
| - fresh := func(replace string) (id, link, code string) { |
| - id, link, code, err := fx.st.CreateEmailChallenge(EmailChallenge{Purpose: ChallengeSignIn, Address: addr}, replace, time.Now()) |
| + 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()) |
| if err != nil { |
| t.Fatal(err) |
| } |
| - c.Jar.SetCookies(u, []*http.Cookie{{Name: challengeCookie, Value: id, Path: "/"}}) |
| - return id, link, code |
| + return link, code |
| } |
| wrong := func(n int, code string) { |
| t.Helper() |
| @@ -930,11 +934,11 @@ func TestEmailCodeGuessCap(t *testing.T) { |
| } |
| } |
| } |
| - id, _, code := fresh("") |
| + _, code := fresh() |
| wrong(5, code) |
| - id, _, code = fresh(id) |
| + _, code = fresh() |
| wrong(5, code) |
| - _, link, code := fresh(id) |
| + link, code := fresh() |
| // The eleventh wrong code, and even the right one, is throttled unchecked. |
| for _, try := range []string{wrongCode(code), code} { |
| @@ -1033,69 +1037,299 @@ func TestLegacyConfirmRetired(t *testing.T) { |
| } |
| } |
| -// 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) { |
| +// The sign-in forms and every answer of the front door set the flow cookie. |
| +// Its value comes only from what the browser sent: an accepted send, a |
| +// refused one, a capped one and a Keymail redirect all answer a browser with |
| +// the flow it already had, and the one email's code still signs in. |
| +func TestContinueFlowCookie(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 { |
| + tok, err := fx.st.CreateInvite(OpsAccountID, addr, "paul@keymail.dev", time.Now()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, path := range []string{"/", "/invite/" + tok, "/invite/no-such-invite", "/auth/cli"} { |
| c := newBrowser(t) |
| - c.Jar.SetCookies(u, []*http.Cookie{{Name: challengeCookie, Value: v, Path: "/"}}) |
| - return c |
| + if status, _, _ := get(t, c, fx.ts.URL+path); status != http.StatusOK || browserCookie(t, fx, c, flowCookie) == "" { |
| + t.Fatalf("signed-out %s = %d, flow cookie %q", path, status, browserCookie(t, fx, c, flowCookie)) |
| + } |
| } |
| - |
| - // 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) |
| + // A browser with no flow is given one by the front door itself. |
| + bare := newBrowser(t) |
| + postContinue(t, fx, bare, url.Values{"address": {"carol@example.com"}}) |
| + if browserCookie(t, fx, bare, flowCookie) == "" { |
| + t.Fatal("continue with no flow set none") |
| } |
| + waitChallengeSent(t, fx, 1) |
| - // 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") |
| + c := newBrowser(t) |
| + get(t, c, fx.ts.URL+"/") |
| + flow := browserCookie(t, fx, c, flowCookie) |
| + same := func(what string) { |
| + t.Helper() |
| + if got := browserCookie(t, fx, c, flowCookie); got != flow { |
| + t.Fatalf("%s changed the flow cookie: %q, want %q", what, got, flow) |
| + } |
| } |
| + code, _ := askSignin(t, fx, m, c, addr, "") |
| + same("an accepted send") |
| + postContinue(t, fx, c, url.Values{"address": {addr}}) |
| + same("a refused send") |
| + postContinue(t, fx, c, url.Values{"address": {"kim@" + fx.srv.km.Host()}}) |
| + same("a Keymail redirect") |
| + for fx.srv.limits.submit("127.0.0.1") { |
| + } |
| + postContinue(t, fx, c, url.Values{"address": {addr}}) |
| + same("a capped submission") |
| - // 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 n := len(m.sentCopy()); n != 2 { |
| + t.Fatalf("mailer got %d messages, want 2 (carol's and bob's one)", n) |
| } |
| - if _, ok := fx.st.PeekEmailChallenge(rekeyed, time.Now()); !ok { |
| - t.Fatal("the re-keyed id names nothing") |
| + if status, _, body := postCode(t, fx, c, code); status != http.StatusSeeOther { |
| + t.Fatalf("code after refused requests = %d:\n%s", status, body) |
| } |
| + emailSession(t, fx, c, addr) |
| +} |
| - // Over the submission cap too, both kinds of incoming cookie. |
| - for fx.srv.limits.submit("127.0.0.1") { |
| +// postCheckCode submits the check page's code form as the page renders it: |
| +// the code with the page's address and next. |
| +func postCheckCode(t *testing.T, fx *consoleFixture, c *http.Client, code, addr, next string) (int, http.Header, string) { |
| + t.Helper() |
| + form := url.Values{"code": {code}, "address": {addr}} |
| + if next != "" { |
| + form.Set("next", next) |
| } |
| - 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) |
| + req, err := http.NewRequest(http.MethodPost, fx.ts.URL+"/auth/email/code", strings.NewReader(form.Encode())) |
| + if err != nil { |
| + t.Fatal(err) |
| } |
| - 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) |
| + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| + req.Header.Set("Origin", fx.ts.URL) |
| + res, err := c.Do(req) |
| + if err != nil { |
| + t.Fatal(err) |
| } |
| + defer res.Body.Close() |
| + raw, err := io.ReadAll(res.Body) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return res.StatusCode, res.Header, string(raw) |
| +} |
| +// setCookieNames is the sorted names a response sets. |
| +func setCookieNames(h http.Header) string { |
| + var names []string |
| + for _, c := range (&http.Response{Header: h}).Cookies() { |
| + names = append(names, c.Name) |
| + } |
| + sort.Strings(names) |
| + return strings.Join(names, ",") |
| +} |
| + |
| +// F2 (final review): a wrong code typed after a refused request reads exactly |
| +// as one typed after a sent email, so the code box is no throttling oracle. |
| +func TestEmailCodeRefusedReadsAsSent(t *testing.T) { |
| + fx, m := newEmailFixture(t, true) |
| + const addr, next = "bob@example.com", "/auth/cli" |
| + lookupAnswers(fx, addr, http.StatusNotFound) |
| + |
| + sent := newBrowser(t) |
| + code, _ := askSignin(t, fx, m, sent, addr, next) |
| + // At once, from a fresh browser: the per-address gap refuses the send. |
| + refused := newBrowser(t) |
| + if status, _, body := postContinue(t, fx, refused, url.Values{"address": {addr}, "next": {next}}); status != http.StatusOK || |
| + !strings.Contains(body, esc(copyText("check.sent", "address", addr))) { |
| + t.Fatalf("refused continue = %d:\n%s", status, body) |
| + } |
| 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) |
| + for _, try := range []string{wrongCode(code), "abcdef"} { |
| + sStatus, sHdr, sBody := postCheckCode(t, fx, sent, try, addr, next) |
| + rStatus, rHdr, rBody := postCheckCode(t, fx, refused, try, addr, next) |
| + if sStatus != http.StatusOK || !strings.Contains(sBody, esc(copyText("check.code_wrong"))) { |
| + t.Fatalf("wrong code %q after a sent email = %d:\n%s", try, sStatus, sBody) |
| + } |
| + if rStatus != sStatus || rBody != sBody { |
| + t.Fatalf("wrong code %q: refused answered %d, sent %d; bodies:\nrefused:\n%s\nsent:\n%s", try, rStatus, sStatus, rBody, sBody) |
| + } |
| + if setCookieNames(rHdr) != setCookieNames(sHdr) { |
| + t.Fatalf("wrong code %q set cookies %q after a refusal, %q after a send", try, setCookieNames(rHdr), setCookieNames(sHdr)) |
| + } |
| + } |
| + // The refused browser's challenge can never sign in: nobody has its code |
| + // or link, and the five attempts burn it as they would a sent one. |
| + for i := 3; i <= emailCodeAttempts; i++ { |
| + _, _, sBody := postCheckCode(t, fx, sent, wrongCode(code), addr, next) |
| + _, _, rBody := postCheckCode(t, fx, refused, wrongCode(code), addr, next) |
| + if rBody != sBody { |
| + t.Fatalf("attempt %d differs:\nrefused:\n%s\nsent:\n%s", i, rBody, sBody) |
| + } |
| + } |
| + if !signedOut(t, fx, refused) || !signedOut(t, fx, sent) { |
| + t.Fatal("a wrong code signed in") |
| + } |
| + |
| + // A refusal in a flow that already has a live challenge, for another |
| + // address, leaves that challenge in place; the code page still shows what |
| + // this request asked for, exactly as a sent one does. |
| + const a, b = "ann@example.com", "ben@example.com" |
| + lookupAnswers(fx, a, http.StatusNotFound) |
| + lookupAnswers(fx, b, http.StatusNotFound) |
| + asker := newBrowser(t) |
| + askSignin(t, fx, m, asker, a, "") |
| + sentB := newBrowser(t) |
| + codeB, _ := askSignin(t, fx, m, sentB, b, "") |
| + // ben was just sent one, so asker's request for ben is refused. |
| + before := len(m.sentCopy()) |
| + postContinue(t, fx, asker, url.Values{"address": {b}}) |
| + if len(m.sentCopy()) != before { |
| + t.Fatal("the refused request for ben sent mail") |
| + } |
| + _, _, sBody := postCheckCode(t, fx, sentB, wrongCode(codeB), b, "") |
| + _, _, rBody := postCheckCode(t, fx, asker, wrongCode(codeB), b, "") |
| + if rBody != sBody || !strings.Contains(sBody, esc(copyText("check.sent", "address", b))) { |
| + t.Fatalf("a wrong code after a refusal beside a live challenge differs:\nrefused:\n%s\nsent:\n%s", rBody, sBody) |
| + } |
| +} |
| + |
| +// F3 (final review): two submissions leave one browser before either answer |
| +// arrives, with no challenge yet. One is sent, the other refused; whichever |
| +// answer the browser keeps, the emailed code signs in. |
| +func TestContinueOverlappingFirstSubmissions(t *testing.T) { |
| + const addr = "bob@example.com" |
| + // submit posts the front door's form with the browser's flow cookie set by |
| + // hand (two requests that left before either answer carry the same |
| + // cookies) and returns the flow cookie the answer sets. |
| + submit := func(t *testing.T, fx *consoleFixture, flow string) string { |
| + t.Helper() |
| + req, err := http.NewRequest(http.MethodPost, fx.ts.URL+"/auth/continue", strings.NewReader(url.Values{"address": {addr}}.Encode())) |
| + if err != nil { |
| + t.Error(err) |
| + return "" |
| + } |
| + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| + req.Header.Set("Origin", fx.ts.URL) |
| + req.AddCookie(&http.Cookie{Name: flowCookie, Value: flow}) |
| + res, err := http.DefaultTransport.RoundTrip(req) |
| + if err != nil { |
| + t.Error(err) |
| + return "" |
| + } |
| + defer res.Body.Close() |
| + io.Copy(io.Discard, res.Body) |
| + for _, c := range res.Cookies() { |
| + if c.Name == flowCookie { |
| + return c.Value |
| + } |
| + } |
| + t.Error("an answer set no flow cookie") |
| + return "" |
| + } |
| + // world is a fresh console and a browser that has loaded the front page. |
| + world := func(t *testing.T) (*consoleFixture, *fakeConsoleMail, *http.Client, string) { |
| + fx, m := newEmailFixture(t, true) |
| + lookupAnswers(fx, addr, http.StatusNotFound) |
| + c := newBrowser(t) |
| + get(t, c, fx.ts.URL+"/") |
| + flow := browserCookie(t, fx, c, flowCookie) |
| + if flow == "" { |
| + t.Fatal("the front page set no flow") |
| + } |
| + return fx, m, c, flow |
| + } |
| + // finish keeps the answers' cookies in the given order, the last one |
| + // winning as in a browser, and signs in with the one email's code. |
| + finish := func(t *testing.T, fx *consoleFixture, m *fakeConsoleMail, c *http.Client, answers []string) { |
| + t.Helper() |
| + u, _ := url.Parse(fx.ts.URL) |
| + for _, v := range answers { |
| + c.Jar.SetCookies(u, []*http.Cookie{{Name: flowCookie, Value: v, Path: "/"}}) |
| + } |
| + waitChallengeSent(t, fx, 1) |
| + _, code, _ := sentSignin(t, m) |
| + if status, loc, body := postCode(t, fx, c, code); status != http.StatusSeeOther || !strings.HasPrefix(loc, "/a/") { |
| + t.Fatalf("the emailed code = %d -> %q:\n%s", status, loc, body) |
| + } |
| + emailSession(t, fx, c, addr) |
| + } |
| + |
| + t.Run("concurrent", func(t *testing.T) { |
| + fx, m, c, flow := world(t) |
| + var ( |
| + start = make(chan struct{}) |
| + wg sync.WaitGroup |
| + mu sync.Mutex |
| + order []string |
| + ) |
| + for i := 0; i < 2; i++ { |
| + wg.Add(1) |
| + go func() { |
| + defer wg.Done() |
| + <-start |
| + v := submit(t, fx, flow) |
| + mu.Lock() |
| + order = append(order, v) |
| + mu.Unlock() |
| + }() |
| + } |
| + close(start) |
| + wg.Wait() |
| + if len(m.sentCopy()) > 1 { |
| + t.Fatalf("two overlapping submissions sent %d emails", len(m.sentCopy())) |
| + } |
| + finish(t, fx, m, c, order) |
| + }) |
| + for _, last := range []string{"sent answer last", "refused answer last"} { |
| + t.Run(last, func(t *testing.T) { |
| + fx, m, c, flow := world(t) |
| + first, second := submit(t, fx, flow), submit(t, fx, flow) |
| + answers := []string{second, first} // the sent (first) answer lands last |
| + if last == "refused answer last" { |
| + answers = []string{first, second} |
| + } |
| + finish(t, fx, m, c, answers) |
| + }) |
| + } |
| +} |
| + |
| +// F1 (final review): an IP that has spent its submissions on the Keymail |
| +// host's own addresses (no lookup, no email slot) gets no email for an |
| +// address it can no longer have looked up, here one Keymail serves. |
| +func TestContinueSubmitCapSendsNothing(t *testing.T) { |
| + fx, m := newEmailFixture(t, true) |
| + const addr = "kim@example.com" |
| + lookupAnswers(fx, addr, http.StatusOK) |
| + for i := 0; i < submitsPerIPHour; i++ { |
| + 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 submission %d = %d -> %q", i+1, status, loc) |
| + } |
| + } |
| + c := newBrowser(t) |
| + status, _, body := postContinue(t, fx, c, url.Values{"address": {addr}}) |
| + if status != http.StatusOK || !strings.Contains(body, esc(copyText("check.sent", "address", addr))) { |
| + t.Fatalf("capped continue = %d, want the ordinary check page:\n%s", status, body) |
| + } |
| + if n := lookupCount(fx); n != 0 { |
| + t.Fatalf("over the cap Keymail was asked %d times", n) |
| + } |
| + // The send runs off the request: give a stray one time to land. |
| + select { |
| + case <-fx.srv.challengeSent: |
| + t.Fatal("a capped submission started a send") |
| + case <-time.After(200 * time.Millisecond): |
| + } |
| + if sent := m.sentCopy(); len(sent) != 0 { |
| + t.Fatalf("a capped submission sent %q", sent) |
| + } |
| + // Its challenge is the never-sent kind: no link was ever minted for the |
| + // mailbox, and the code box treats it as any other. |
| + if n := challengeRows(t, fx); n != 1 { |
| + t.Fatalf("%d challenges, want the one unsent", n) |
| + } |
| + if status, _, body := postCode(t, fx, c, "000000"); status != http.StatusOK || !signedOut(t, fx, c) { |
| + t.Fatalf("a code against the unsent challenge = %d:\n%s", status, body) |
| } |
| - emailSession(t, fx, junk, addr) |
| } |
diff --git a/internal/console/emailstepup_test.go b/internal/console/emailstepup_test.go| index c115c61bb..e12257250 100644 |
| --- a/internal/console/emailstepup_test.go |
| +++ b/internal/console/emailstepup_test.go |
| @@ -140,9 +140,6 @@ func TestEmailSessionStepUpByCode(t *testing.T) { |
| if !fx.st.FreshStepUp(raw, "bob@example.com", time.Now(), StepUpWindow) { |
| t.Fatal("no presence recorded after the step-up code") |
| } |
| - if browserCookie(t, fx, c, challengeCookie) != "" { |
| - t.Fatal("the challenge cookie outlived the step-up") |
| - } |
| if challengeRows(t, fx) != 0 { |
| t.Fatal("the step-up challenge is still standing") |
| } |
| @@ -226,9 +223,8 @@ func TestStepUpLinkOtherBrowser(t *testing.T) { |
| t.Fatalf("%s: step-up link POST = %d:\n%s", name, status, body) |
| } |
| } |
| - // The code, typed in the other session with this browser's challenge id, |
| - // is refused without being checked. |
| - otherB.Jar.SetCookies(u, []*http.Cookie{{Name: challengeCookie, Value: browserCookie(t, fx, c, challengeCookie), Path: "/"}}) |
| + // The code, typed in the other session, finds no step-up of that session |
| + // and is refused without being checked. |
| if status, _, body := postStepUpCode(t, fx, otherB, code); status != http.StatusGone || !strings.Contains(body, esc(copyText("stepup.expired"))) { |
| t.Fatalf("step-up code from another session = %d:\n%s", status, body) |
| } |
diff --git a/internal/console/server.go b/internal/console/server.go| index a2dac6423..745c5f5e0 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -960,6 +960,8 @@ type Server struct { |
| // limits are email sign-in's rate limits (emailsignin_limits.go): in |
| // memory, one console process per deployment. |
| limits emailLimits |
| + // flowLocks serialise /auth/continue per sign-in flow (flowLock). |
| + flowLocks [256]sync.Mutex |
| // challengeSem bounds the sign-in and step-up sends in flight |
| // (sendChallengeAsync). challengeSent, when non-nil, is signalled after |
| // each one finishes or is dropped. Tests only, as cliNotified. |
| @@ -1193,6 +1195,11 @@ func (s *Server) consoleName() string { |
| return "the CARLOS platform" |
| } |
| +// dnsTargets is what every custom-domain guidance string in this console is |
| +// built from (view.go's domainGuidance): the deployment's edge addresses and |
| +// its steering hostname, read from ONE place so the app page, the Settings |
| +// page and the /domains API can never disagree about where a member should |
| +// point DNS. |
| func (s *Server) dnsTargets() DNSTargets { |
| return DNSTargets{EdgeIPs: s.edgeIPs(), SteeringHost: s.steeringHost} |
| } |
| @@ -2216,7 +2223,7 @@ func (s *Server) handleHome(w http.ResponseWriter, r *http.Request) { |
| s.redirectToCurrentAccount(w, r, addr, http.StatusFound) |
| return |
| } |
| - s.renderHome(w, homeForm{Next: r.URL.Query().Get("next")}) |
| + s.renderHome(w, r, homeForm{Next: r.URL.Query().Get("next")}) |
| } |
| // redirectToCurrentAccount sends a signed-in user to the account they were |
| @@ -2692,10 +2699,10 @@ func (s *Server) handleInvitePage(w http.ResponseWriter, r *http.Request) { |
| if !ok { |
| invited, found := s.store.PendingInviteAddress(token, time.Now()) |
| if !found { |
| - s.renderHome(w, homeForm{}) |
| + s.renderHome(w, r, homeForm{}) |
| return |
| } |
| - s.renderHome(w, homeForm{ |
| + s.renderHome(w, r, homeForm{ |
| Prefill: invited, |
| Next: "/invite/" + url.PathEscape(token), |
| Banner: copyText("home.invite_prompt", "address", invited), |
| @@ -2762,8 +2769,16 @@ func (s *Server) handleAcceptInvite(w http.ResponseWriter, r *http.Request) { |
| // handleContinue is the front page's one form (spec 4): it finds the door |
| // from the address alone. A Keymail address goes to Keymail's sign-in; any |
| // other gets an emailed link and code. Every email-bound outcome renders the |
| -// same "Check your email" page, whether a message was sent, throttled or |
| -// refused, so the page reveals neither an account nor a rate limit. |
| +// same "Check your email" page and sets the same flow cookie, whether a |
| +// message was sent or the request was refused, so neither the page nor any |
| +// later code typed on it reveals an account or a rate limit. |
| +// |
| +// The order is load-bearing: the per-IP submission cap is noted first; the |
| +// Keymail host's own addresses go to Keymail whatever the cap (that costs no |
| +// lookup); Keymail's lookup is asked only under the cap; an email-bound |
| +// address with no ready mailer is told so before any send limit (spec 4.2); |
| +// and a request over the submission cap or the send limits is refused: no |
| +// email, and no challenge the mailbox could redeem. |
| func (s *Server) handleContinue(w http.ResponseWriter, r *http.Request) { |
| if !s.sameOrigin(r) { |
| s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.") |
| @@ -2771,22 +2786,25 @@ func (s *Server) handleContinue(w http.ResponseWriter, r *http.Request) { |
| } |
| now := time.Now() |
| s.store.PurgeExpired(now) // housekeeping on the write path |
| + flow := s.requestFlow(r) |
| + if flow == "" { |
| + s.renderMessage(w, r, http.StatusInternalServerError, "Error", "Could not start the sign-in flow. Please try again.") |
| + return |
| + } |
| typed := strings.TrimSpace(r.FormValue("address")) |
| next := safeNext(r.FormValue("next")) |
| addr, ok := canonicalAddress(typed) |
| if !ok { |
| - s.renderHome(w, homeForm{Prefill: typed, Next: next, Error: copyText("home.bad_address")}) |
| + s.renderHome(w, r, homeForm{Prefill: typed, Next: next, Error: copyText("home.bad_address"), flow: flow}) |
| return |
| } |
| ip := s.clientIP(r) |
| - // 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) { |
| + underCap := s.limits.submit(ip) |
| + if !underCap { |
| + log.Printf("console: sign-in submissions from %s over the hourly cap; no lookup, no send", ip) |
| + } |
| + if s.keymailAddress(r.Context(), addr, underCap) { |
| + s.setFlow(w, flow) |
| target := "/auth/signin" |
| if next != "" { |
| target += "?next=" + url.QueryEscape(next) |
| @@ -2794,55 +2812,49 @@ func (s *Server) handleContinue(w http.ResponseWriter, r *http.Request) { |
| http.Redirect(w, r, target, http.StatusSeeOther) |
| return |
| } |
| - // Before the send limits (spec 4.2), so throttling stays invisible. |
| if !s.mailReady(r.Context()) { |
| - s.renderHome(w, homeForm{Prefill: addr, Next: next, NoMail: true}) |
| - return |
| - } |
| - if !s.limits.signinSend(addr, ip) { |
| - log.Printf("console: sign-in email to %s from %s over its limits; not sent", addr, ip) |
| - s.rotateChallengeCookie(w, r, addr, now) |
| - s.renderCheck(w, addr, next) |
| + s.renderHome(w, r, homeForm{Prefill: addr, Next: next, NoMail: true, flow: flow}) |
| return |
| } |
| - replace := "" |
| - if c, err := r.Cookie(challengeCookie); err == nil { |
| - replace = c.Value |
| - } |
| - id, link, code, err := s.store.CreateEmailChallenge(EmailChallenge{ |
| - Purpose: ChallengeSignIn, Address: addr, Next: next, |
| - }, replace, now) |
| + link, code, sent, err := s.signinChallenge(flow, addr, next, ip, underCap, now) |
| if err != nil { |
| log.Printf("console: sign-in challenge for %s: %v", addr, err) |
| s.renderMessage(w, r, http.StatusInternalServerError, "Error", "Could not start the sign-in flow. Please try again.") |
| return |
| } |
| - s.setCookie(w, challengeCookie, id, int(ConfirmationTTL.Seconds())) |
| - console := s.consoleName() |
| - s.sendChallengeAsync(addr, |
| - copyText("email.signin.subject", "console", console), |
| - copyText("email.signin.body", "console", console, "address", addr, |
| - "link", s.cfg.Origin+"/auth/email/link?t="+link, "code", code)) |
| - s.renderCheck(w, addr, next) |
| + if sent { |
| + console := s.consoleName() |
| + s.sendChallengeAsync(addr, |
| + copyText("email.signin.subject", "console", console), |
| + copyText("email.signin.body", "console", console, "address", addr, |
| + "link", s.cfg.Origin+"/auth/email/link?t="+link, "code", code)) |
| + } |
| + s.renderCheck(w, flow, addr, next) |
| } |
| -// 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 { |
| - id, _ = s.store.RekeyEmailChallenge(c.Value, addr, now) |
| - } |
| - if id == "" { |
| - var err error |
| - if id, err = randomToken(); err != nil { |
| - return |
| - } |
| +// signinChallenge is the front door's limits and challenge write for one |
| +// flow, under that flow's lock, so overlapping submissions from one browser |
| +// take turns. Accepted (under the submission cap and every send limit), it |
| +// records a new sign-in challenge for the flow, replacing the flow's earlier |
| +// ones, and returns its link and code to send. Refused, it sends nothing: |
| +// the flow's live challenge, if it has one, is left untouched so the email |
| +// already sent keeps working; otherwise a challenge nobody is ever told the |
| +// link or code of is recorded, so a code typed next answers exactly as it |
| +// would against a sent one. |
| +func (s *Server) signinChallenge(flow, addr, next, ip string, underCap bool, now time.Time) (link, code string, sent bool, err error) { |
| + mu := s.flowLock(flow) |
| + mu.Lock() |
| + defer mu.Unlock() |
| + c := EmailChallenge{Purpose: ChallengeSignIn, Address: addr, Next: next, FlowHash: hashToken(flow)} |
| + if !underCap || !s.limits.signinSend(addr, ip) { |
| + 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 |
| } |
| - s.setCookie(w, challengeCookie, id, int(ConfirmationTTL.Seconds())) |
| + return link, code, true, nil |
| } |
| // ValidAddress is the console's one shape check on a keymail address: |
| @@ -2890,8 +2902,7 @@ func (s *Server) handleSignin(w http.ResponseWriter, r *http.Request) { |
| func (s *Server) handleCallback(w http.ResponseWriter, r *http.Request) { |
| q := r.URL.Query() |
| if e := q.Get("error"); e != "" { |
| - p := page{Title: "Sign in", Error: "Sign-in was cancelled at Keymail (" + e + ")."} |
| - s.render(w, http.StatusOK, "home", p) |
| + s.renderHome(w, r, homeForm{Error: "Sign-in was cancelled at Keymail (" + e + ")."}) |
| return |
| } |
| c, err := r.Cookie(authCookie) |