carlos / platform Public

console: sign in by emailed link or code

GET /auth/email/link shows a confirm page and never spends the link;
POST spends it after the login-CSRF checks (same origin, nonce cookie
equal to the form's). POST /auth/email/code checks a code only against
this browser's challenge, with wrong codes counted per address and IP
across challenges (a fifth wrong code is CodeBurned, and counts). The
old /auth/confirm link is retired to the expired message.
Co-Authored-By: Claude <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev b2c238436b003e92752b7b80b777c5d4f9558041 parent 4f3ecc1
10 files changed, +721 −33
  • internal/console/claim_invariant_fixtures_test.go +4 −1
  • internal/console/claim_invariant_probes_nonapp_test.go +99 −7
  • internal/console/emailsignin.go +147 −1
  • internal/console/emailsignin_store.go +21 −3
  • internal/console/emailsignin_store_test.go +26 −2
  • internal/console/emailsignin_test.go +397 −0
  • internal/console/server.go +14 −19
  • internal/console/templates/check.html +2 −0
  • internal/console/templates/email_link.html +8 −0
  • internal/console/testdata/claim-routes.txt +3 −0
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go
index 3caf30288..ff4977fa8 100644
--- a/internal/console/claim_invariant_fixtures_test.go
+++ b/internal/console/claim_invariant_fixtures_test.go
@@ -812,7 +812,8 @@ var claimFixtures = map[string]claimFixture{
"route GET /auth/cli": claimRead("renders the device-code approval page"),
"route GET /auth/cli/tokens": claimRead("redirects to /settings"),
"route GET /auth/cli/whoami": claimRead("names the bearer's principal"),
- "route GET /auth/confirm": claimNonApp("consumes a sign-in confirmation link: confirmations and sessions"),
+ "route GET /auth/confirm": claimRead("the retired confirmation link: renders the expired message for any token"),
+ "route GET /auth/email/link": claimNonApp("an emailed link's confirm page: sets the login-CSRF nonce cookie; spends nothing"),
"route GET /auth/signin": claimNonApp("starts an OAuth flow: the auth cookie and its PKCE state"),
"route GET /fleet": claimRead("operator fleet view"),
"route GET /fleet/economics": claimRead("operator economics view"),
@@ -1217,6 +1218,8 @@ var claimFixtures = map[string]claimFixture{
// the same handler's other branch; service credentials are refused.
"route POST /auth/cli/tokens/revoke": {door: claimLegacyAppTokenRevokeDoor("/auth/cli/tokens/revoke")},
"route POST /auth/continue": claimNonApp("starts sign-in: email challenges"),
+ "route POST /auth/email/code": claimNonApp("signs in by an emailed code: email challenges, user, session and step-up"),
+ "route POST /auth/email/link": claimNonApp("signs in by an emailed link: email challenges, user, session and step-up"),
"route POST /auth/signout": claimNonApp("ends the session"),
"route POST /fleet/store/{account}/{decision}": claimNonApp("operator entitlement decision for an account"),
"route POST /invite/{token}": claimNonApp("accepts an invitation: membership"),
diff --git a/internal/console/claim_invariant_probes_nonapp_test.go b/internal/console/claim_invariant_probes_nonapp_test.go
index d905e8458..612374176 100644
--- a/internal/console/claim_invariant_probes_nonapp_test.go
+++ b/internal/console/claim_invariant_probes_nonapp_test.go
@@ -116,6 +116,8 @@ func claimCallbackProbe() claimProbe {
}
func claimConfirmProbe() claimProbe {
+ // Retired (spec 11): the old Apps-inbox link only explains itself now,
+ // even for a token the old table still holds.
var c *http.Client
return claimProbe{
setup: func(t *testing.T, cx *claimCase) {
@@ -129,13 +131,100 @@ func claimConfirmProbe() claimProbe {
c = newBrowser(t)
return cx.pageReplyAs(t, c, "/auth/confirm?token=<confirm>")
},
+ body: []string{esc(copyText("link.expired"))},
+ effect: func(t *testing.T, cx *claimCase, r claimReply) string {
+ if cx.signedInAs(c, claimFxOwner) {
+ return "the retired confirmation link opened a session"
+ }
+ return ""
+ },
+ }
+}
+
+// claimEmailChallengeWorld is a sign-in challenge for the case's owner, its
+// browser-held id, 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())
+ if err != nil {
+ t.Fatal(err)
+ }
+ cx.vars["challenge"], cx.vars["link"], cx.vars["code"] = id, link, code
+}
+
+// claimBrowserWithCookie is a fresh browser already holding one console
+// cookie.
+func claimBrowserWithCookie(t *testing.T, cx *claimCase, name, value string) *http.Client {
+ t.Helper()
+ c := newBrowser(t)
+ u, err := url.Parse(cx.ts.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ c.Jar.SetCookies(u, []*http.Cookie{{Name: name, Value: value, Path: "/"}})
+ return c
+}
+
+func claimEmailLinkPageProbe() claimProbe {
+ var c *http.Client
+ return claimProbe{
+ setup: claimEmailChallengeWorld,
+ do: func(t *testing.T, cx *claimCase) claimReply {
+ c = newBrowser(t)
+ return cx.pageReplyAs(t, c, "/auth/email/link?t=<link>")
+ },
+ body: []string{esc(copyText("link.title", "address", claimFxOwner)), `name="t" value="<link>"`},
+ effect: func(t *testing.T, cx *claimCase, r claimReply) string {
+ nonce := cx.cookieOf(c, linkConfirmCookie)
+ if nonce == "" || !strings.Contains(r.Body, `name="nonce" value="`+nonce+`"`) {
+ return "the confirm page set no nonce cookie matching its form"
+ }
+ if _, ok := cx.st.PeekEmailLink(cx.vars["link"], time.Now()); !ok {
+ return "the GET spent the link"
+ }
+ return ""
+ },
+ }
+}
+
+func claimEmailLinkProbe() claimProbe {
+ var c *http.Client
+ return claimProbe{
+ setup: claimEmailChallengeWorld,
+ do: func(t *testing.T, cx *claimCase) claimReply {
+ c = claimBrowserWithCookie(t, cx, linkConfirmCookie, "claim-probe-nonce")
+ status, loc, body := postForm(t, c, cx.ts.URL+"/auth/email/link", url.Values{"t": {cx.vars["link"]}, "nonce": {"claim-probe-nonce"}})
+ return cx.browserReply(c, status, loc, body)
+ },
+ status: http.StatusSeeOther, loc: "/a/",
+ effect: func(t *testing.T, cx *claimCase, r claimReply) string {
+ if !cx.signedInAs(c, claimFxOwner) {
+ return "the emailed link opened no session"
+ }
+ if _, ok := cx.st.PeekEmailLink(cx.vars["link"], time.Now()); ok {
+ return "the emailed link is still good after it was used"
+ }
+ return ""
+ },
+ }
+}
+
+func claimEmailCodeProbe() claimProbe {
+ var c *http.Client
+ return claimProbe{
+ setup: claimEmailChallengeWorld,
+ do: func(t *testing.T, cx *claimCase) claimReply {
+ c = claimBrowserWithCookie(t, cx, challengeCookie, cx.vars["challenge"])
+ 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)
+ },
status: http.StatusSeeOther, loc: "/a/",
effect: func(t *testing.T, cx *claimCase, r claimReply) string {
if !cx.signedInAs(c, claimFxOwner) {
- return "the confirmation link opened no session"
+ return "the emailed code opened no session"
}
- if _, ok := cx.st.TakeConfirmation(cx.vars["confirm"], time.Now()); ok {
- return "the confirmation link is still good after it was used"
+ if _, ok := cx.st.PeekEmailChallenge(cx.vars["challenge"], time.Now()); ok {
+ return "the challenge is still standing after its code was used"
}
return ""
},
@@ -268,10 +357,13 @@ var claimNonAppProbes = map[string]claimProbe{
},
// ---- sign-in and session ----
- "route GET /auth/signin": claimSigninProbe(),
- "route GET /auth/callback": claimCallbackProbe(),
- "route GET /auth/confirm": claimConfirmProbe(),
- "route POST /auth/continue": claimContinueProbe(),
+ "route GET /auth/signin": claimSigninProbe(),
+ "route GET /auth/callback": claimCallbackProbe(),
+ "route GET /auth/confirm": claimConfirmProbe(),
+ "route POST /auth/continue": claimContinueProbe(),
+ "route GET /auth/email/link": claimEmailLinkPageProbe(),
+ "route POST /auth/email/link": claimEmailLinkProbe(),
+ "route POST /auth/email/code": claimEmailCodeProbe(),
"route POST /auth/signout": {
do: claimFormReply("/auth/signout"),
status: http.StatusSeeOther, loc: "/",
diff --git a/internal/console/emailsignin.go b/internal/console/emailsignin.go
index 814bd9276..0c5a68d56 100644
--- a/internal/console/emailsignin.go
+++ b/internal/console/emailsignin.go
@@ -2,6 +2,7 @@ package console
import (
"context"
+ "crypto/subtle"
"log"
"net/http"
netmail "net/mail"
@@ -18,6 +19,11 @@ const nextCookie = "carlos_console_next"
// typed here finds it and a second request from here replaces it.
const challengeCookie = "carlos_console_email"
+// 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
+// attacker cannot submit their own link into someone else's browser.
+const linkConfirmCookie = "carlos_console_linkconfirm"
+
// Sign-in sends run off the request (spec 4.2): at most challengeSendSlots at
// once, each with challengeSendTimeout to get a slot and finish.
const (
@@ -30,6 +36,7 @@ const (
type signinView struct {
EmailLabel, EmailPlaceholder, EmailButton, Small, NoMail string
CheckTitle, CodeLabel, CodeButton, Nothing, AgainButton string
+ LinkButton string
}
var approvedSigninView = signinView{
@@ -43,6 +50,7 @@ var approvedSigninView = signinView{
CodeButton: copyText("check.code_button"),
Nothing: copyText("check.nothing"),
AgainButton: copyText("check.again_button"),
+ LinkButton: copyText("link.button"),
}
// sameOrigin reports whether a form POST came from this console's own pages:
@@ -153,11 +161,22 @@ func (s *Server) renderHome(w http.ResponseWriter, f homeForm) {
// 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, "")
+}
+
+// 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) {
+ sent := ""
+ if addr != "" {
+ sent = copyText("check.sent", "address", addr)
+ }
s.render(w, http.StatusOK, "check", page{
Title: copyText("check.title"),
- CheckSent: copyText("check.sent", "address", addr),
+ CheckSent: sent,
Prefill: addr,
Next: safeNext(next),
+ CodeError: codeErr,
})
}
@@ -223,3 +242,130 @@ func (s *Server) finishSignin(w http.ResponseWriter, r *http.Request, addr, keym
}
s.redirectToCurrentAccount(w, r, addr, http.StatusSeeOther)
}
+
+// renderLinkExpired is the answer to an unknown, expired or spent link.
+func (s *Server) renderLinkExpired(w http.ResponseWriter, r *http.Request) {
+ s.renderMessage(w, r, http.StatusGone, "Link expired", copyText("link.expired"))
+}
+
+// handleEmailLinkPage is GET /auth/email/link?t= (spec 5.1). It never spends
+// the link, so a mail scanner's fetch leaves it good: it renders a confirm
+// page naming the address, whose form POSTs the token with a fresh nonce that
+// is also set in linkConfirmCookie.
+func (s *Server) handleEmailLinkPage(w http.ResponseWriter, r *http.Request) {
+ link := r.URL.Query().Get("t")
+ c, ok := s.store.PeekEmailLink(link, time.Now())
+ if link == "" || !ok {
+ s.renderLinkExpired(w, r)
+ return
+ }
+ switch c.Purpose {
+ case ChallengeSignIn:
+ default:
+ // A step-up link (spec 6) is not a sign-in; until its door exists it
+ // reads as expired.
+ s.renderLinkExpired(w, r)
+ return
+ }
+ nonce, err := randomToken()
+ if err != nil {
+ s.renderMessage(w, r, http.StatusInternalServerError, "Error", "Could not start the sign-in flow. Please try again.")
+ return
+ }
+ s.setCookie(w, linkConfirmCookie, nonce, int(ConfirmationTTL.Seconds()))
+ s.render(w, http.StatusOK, "email_link", page{
+ Title: copyText("link.title", "address", c.Address),
+ LinkToken: link,
+ LinkNonce: nonce,
+ })
+}
+
+// handleEmailLink is POST /auth/email/link (spec 5.1): it spends the link and
+// signs this browser in, whichever browser it is. Login CSRF is refused
+// first, before anything is spent, so a refused POST leaves the link good: the
+// request must be same-origin and carry linkConfirmCookie equal to the form's
+// nonce.
+func (s *Server) handleEmailLink(w http.ResponseWriter, r *http.Request) {
+ nonce := r.PostFormValue("nonce")
+ ck, err := r.Cookie(linkConfirmCookie)
+ if !s.sameOrigin(r) || err != nil || ck.Value == "" || nonce == "" ||
+ subtle.ConstantTimeCompare([]byte(ck.Value), []byte(nonce)) != 1 {
+ s.renderMessage(w, r, http.StatusForbidden, "Refused", copyText("link.wrong_site"))
+ return
+ }
+ s.clearCookie(w, linkConfirmCookie)
+ now := time.Now()
+ link := r.PostFormValue("t")
+ peek, ok := s.store.PeekEmailLink(link, now)
+ if link == "" || !ok {
+ s.renderLinkExpired(w, r)
+ return
+ }
+ switch peek.Purpose {
+ case ChallengeSignIn:
+ default:
+ // A step-up link (spec 6) is not a sign-in; until its door exists it
+ // reads as expired, and is not spent here.
+ s.renderLinkExpired(w, r)
+ return
+ }
+ c, ok := s.store.TakeEmailLink(link, now)
+ if !ok || c.Purpose != ChallengeSignIn {
+ s.renderLinkExpired(w, r)
+ return
+ }
+ // The take deleted this challenge, so a challenge cookie that now names
+ // nothing named it (or something already gone): clear it. One naming a
+ // newer, live challenge is left alone.
+ if cc, err := r.Cookie(challengeCookie); err == nil {
+ if _, live := s.store.PeekEmailChallenge(cc.Value, now); !live {
+ s.clearCookie(w, challengeCookie)
+ }
+ }
+ s.finishSignin(w, r, c.Address, "", MethodEmail, c.Next)
+}
+
+// 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.
+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"))
+ return
+ }
+ ip := s.clientIP(r)
+ if !s.limits.codeAllowed(c.Address, ip) {
+ 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"))
+ return
+ }
+ got, res := s.store.TakeEmailCode(id, strings.TrimSpace(r.PostFormValue("code")), ChallengeSignIn, now)
+ switch res {
+ case CodeOK:
+ s.clearCookie(w, challengeCookie)
+ s.finishSignin(w, r, got.Address, "", MethodEmail, got.Next)
+ case CodeWrong:
+ s.limits.codeFailed(c.Address, ip)
+ s.renderCheckError(w, c.Address, c.Next, copyText("check.code_wrong"))
+ case CodeBurned:
+ s.limits.codeFailed(c.Address, ip)
+ s.renderCheckError(w, c.Address, c.Next, copyText("check.code_used_up"))
+ default:
+ s.renderCheckError(w, c.Address, c.Next, copyText("check.code_used_up"))
+ }
+}
diff --git a/internal/console/emailsignin_store.go b/internal/console/emailsignin_store.go
index 983a3a3b6..60c22c766 100644
--- a/internal/console/emailsignin_store.go
+++ b/internal/console/emailsignin_store.go
@@ -53,8 +53,11 @@ const (
// CodeWrong: it did not match and the challenge still stands.
CodeWrong
// CodeGone: there is no usable challenge (unknown, expired, wrong
- // purpose, or burned by too many wrong codes).
+ // purpose, burned earlier, or minted under an earlier process's key).
CodeGone
+ // CodeBurned: the code did not match and that was the last attempt, so
+ // the challenge is gone. It is a wrong code for the guessing budget.
+ CodeBurned
)
func (s *Store) migrateEmailSignin() error {
@@ -138,6 +141,21 @@ 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 == "" {
+ return nil, false
+ }
+ c, exp, err := scanEmailChallenge(s.db.QueryRow(`SELECT purpose, address, session_hash, pending, next, expires_at
+FROM email_challenges WHERE id_hash = ?`, hashToken(id)))
+ if err != nil || now.Unix() > exp {
+ return nil, false
+ }
+ return c, true
+}
+
// TakeEmailLink spends a challenge by its emailed link. The row is deleted
// before the expiry verdict (burn-then-check, as TakeConfirmation), so a link
// can never be retried into validity.
@@ -167,7 +185,7 @@ FROM email_challenges WHERE link_hash = ?`, hashToken(link)))
// TakeEmailCode checks a typed code against the challenge named by id, which
// must be of the given purpose. One transaction: a missing, expired or
// wrong-purpose challenge is deleted and reported CodeGone; a wrong code adds
-// an attempt, and the fifth burns the challenge (CodeGone); a right code
+// 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 == "" {
@@ -207,7 +225,7 @@ FROM email_challenges WHERE id_hash = ?`, idHash)
attempts++
res := CodeWrong
if attempts >= emailCodeAttempts {
- res = CodeGone
+ res = CodeBurned
_, err = tx.Exec(`DELETE FROM email_challenges WHERE id_hash = ?`, idHash)
} else {
_, err = tx.Exec(`UPDATE email_challenges SET attempts = ? WHERE id_hash = ?`, attempts, idHash)
diff --git a/internal/console/emailsignin_store_test.go b/internal/console/emailsignin_store_test.go
index 498704c26..8225ff388 100644
--- a/internal/console/emailsignin_store_test.go
+++ b/internal/console/emailsignin_store_test.go
@@ -50,6 +50,30 @@ func TestEmailChallengeLinkPeekDoesNotConsume(t *testing.T) {
}
}
+func TestEmailChallengePeekByID(t *testing.T) {
+ s := openTestStore(t)
+ now := time.Now()
+ id, _, code := newSignInChallenge(t, s, now, "")
+ 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)
+ }
+ }
+ if _, ok := s.PeekEmailChallenge(id, now.Add(ConfirmationTTL+time.Minute)); ok {
+ t.Fatal("an expired challenge peeks")
+ }
+ if _, ok := s.PeekEmailChallenge("", now); ok {
+ t.Fatal("an empty id peeks")
+ }
+ if _, res := s.TakeEmailCode(id, code, ChallengeSignIn, now); res != CodeOK {
+ t.Fatalf("peeking spent the challenge: %v", res)
+ }
+ if _, ok := s.PeekEmailChallenge(id, now); ok {
+ t.Fatal("a taken challenge still peeks")
+ }
+}
+
func TestEmailChallengeCode(t *testing.T) {
s := openTestStore(t)
now := time.Now()
@@ -72,8 +96,8 @@ func TestEmailChallengeCode(t *testing.T) {
t.Fatalf("wrong code %d = %v, want CodeWrong", i, res)
}
}
- if _, res := s.TakeEmailCode(id, bad, ChallengeSignIn, now); res != CodeGone {
- t.Fatalf("5th wrong code = %v, want CodeGone", res)
+ if _, res := s.TakeEmailCode(id, bad, ChallengeSignIn, now); res != CodeBurned {
+ t.Fatalf("5th wrong code = %v, want CodeBurned", res)
}
if _, res := s.TakeEmailCode(id, code, ChallengeSignIn, now); res != CodeGone {
t.Fatalf("right code after burn = %v, want CodeGone", res)
diff --git a/internal/console/emailsignin_test.go b/internal/console/emailsignin_test.go
index ff42ed6c4..ce331121a 100644
--- a/internal/console/emailsignin_test.go
+++ b/internal/console/emailsignin_test.go
@@ -617,3 +617,400 @@ func TestHomeCarriesSafeNext(t *testing.T) {
t.Fatal("home still links the Keymail ceremony directly")
}
}
+
+// ---- signing in by the emailed link or code ---------------------------------
+
+// postFrom posts form to path on browser c with the given Origin ("" sends
+// none).
+func postFrom(t *testing.T, fx *consoleFixture, c *http.Client, path, origin string, form url.Values) (status int, location, body string) {
+ t.Helper()
+ req, err := http.NewRequest(http.MethodPost, fx.ts.URL+path, strings.NewReader(form.Encode()))
+ if err != nil {
+ t.Fatal(err)
+ }
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ if origin != "" {
+ req.Header.Set("Origin", origin)
+ }
+ 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.Get("Location"), string(raw)
+}
+
+// askSignin submits addr (with next) at the front door from browser c and
+// returns the code and link token of the email that went out.
+func askSignin(t *testing.T, fx *consoleFixture, m *fakeConsoleMail, c *http.Client, addr, next string) (code, link string) {
+ t.Helper()
+ before := len(m.sentCopy())
+ form := url.Values{"address": {addr}}
+ if next != "" {
+ form.Set("next", next)
+ }
+ if status, _, body := postContinue(t, fx, c, form); status != http.StatusOK || !strings.Contains(body, esc(copyText("check.sent", "address", addr))) {
+ t.Fatalf("continue for %s = %d:\n%s", addr, status, body)
+ }
+ waitChallengeSent(t, fx, 1)
+ sent := m.sentCopy()
+ if len(sent) != before+1 {
+ t.Fatalf("console mailer has %d messages, want %d", len(sent), before+1)
+ }
+ _, body, _ := strings.Cut(sent[len(sent)-1], "|")
+ cm, lm := signinCodeRe.FindStringSubmatch(body), signinLinkRe.FindStringSubmatch(body)
+ if cm == nil || lm == nil {
+ t.Fatalf("sign-in email has no code or link:\n%s", body)
+ }
+ return cm[1], lm[1]
+}
+
+// advanceLimits moves the rate limits' clock d past the wall clock, so one
+// address may be sent another email.
+func advanceLimits(fx *consoleFixture, d time.Duration) {
+ fx.srv.limits.mu.Lock()
+ defer fx.srv.limits.mu.Unlock()
+ fx.srv.limits.now = func() time.Time { return time.Now().Add(d) }
+}
+
+var linkNonceRe = regexp.MustCompile(`name="nonce" value="([^"]+)"`)
+
+// openLink GETs the emailed link on browser c and returns the status, the
+// page and the form's nonce ("" when there is none).
+func openLink(t *testing.T, fx *consoleFixture, c *http.Client, link string) (int, string, string) {
+ t.Helper()
+ status, _, body := get(t, c, fx.ts.URL+"/auth/email/link?t="+url.QueryEscape(link))
+ nonce := ""
+ if m := linkNonceRe.FindStringSubmatch(body); m != nil {
+ nonce = m[1]
+ }
+ return status, body, nonce
+}
+
+// postLink submits the confirm page's form from the console's own origin.
+func postLink(t *testing.T, fx *consoleFixture, c *http.Client, link, nonce string) (int, string, string) {
+ t.Helper()
+ return postFrom(t, fx, c, "/auth/email/link", fx.ts.URL, url.Values{"t": {link}, "nonce": {nonce}})
+}
+
+// postCode submits the check page's code form from the console's own origin.
+func postCode(t *testing.T, fx *consoleFixture, c *http.Client, code string) (int, string, string) {
+ t.Helper()
+ return postFrom(t, fx, c, "/auth/email/code", fx.ts.URL, url.Values{"code": {code}})
+}
+
+// emailSession asserts browser c holds a live email-method session for addr
+// with a fresh step-up, and returns the raw token.
+func emailSession(t *testing.T, fx *consoleFixture, c *http.Client, addr string) string {
+ t.Helper()
+ raw := browserCookie(t, fx, c, sessionCookie)
+ got, method, ok := fx.st.SessionInfo(raw, time.Now())
+ if raw == "" || !ok || got != addr || method != MethodEmail {
+ t.Fatalf("session = %q %q %v, want an email session for %s", got, method, ok, addr)
+ }
+ if !fx.st.FreshStepUp(raw, addr, time.Now(), StepUpWindow) {
+ t.Fatal("an email sign-in recorded no step-up")
+ }
+ return raw
+}
+
+func signedOut(t *testing.T, fx *consoleFixture, c *http.Client) bool {
+ t.Helper()
+ raw := browserCookie(t, fx, c, sessionCookie)
+ if raw == "" {
+ return true
+ }
+ _, ok := fx.st.SessionAddress(raw, time.Now())
+ return !ok
+}
+
+// Review Focus 2: a mail scanner's GET (twice) leaves the link good; the
+// person's POST signs them in once.
+func TestEmailLinkGetDoesNotConsume(t *testing.T) {
+ fx, m := newEmailFixture(t, true)
+ const addr = "bob@example.com"
+ lookupAnswers(fx, addr, http.StatusNotFound)
+ asker := newBrowser(t)
+ _, link := askSignin(t, fx, m, asker, addr, "")
+
+ scanner := newBrowser(t)
+ for i := 0; i < 2; i++ {
+ status, body, _ := openLink(t, fx, scanner, link)
+ if status != http.StatusOK || !strings.Contains(body, esc(copyText("link.title", "address", addr))) {
+ t.Fatalf("scanner GET %d = %d:\n%s", i, status, body)
+ }
+ }
+ if !signedOut(t, fx, scanner) {
+ t.Fatal("a GET signed the scanner in")
+ }
+
+ // The person, in another browser (a forwarded link opens there too).
+ c := newBrowser(t)
+ status, body, nonce := openLink(t, fx, c, link)
+ if status != http.StatusOK || nonce == "" {
+ t.Fatalf("GET = %d, nonce %q:\n%s", status, nonce, body)
+ }
+ for _, want := range []string{
+ esc(copyText("link.title", "address", addr)), esc(copyText("link.button")),
+ `action="/auth/email/link"`, `name="t" value="` + link + `"`,
+ } {
+ if !strings.Contains(body, want) {
+ t.Errorf("confirm page is missing %q:\n%s", want, body)
+ }
+ }
+ if browserCookie(t, fx, c, linkConfirmCookie) != nonce {
+ t.Fatal("the GET did not set the nonce cookie to the form's nonce")
+ }
+ status, loc, _ := postLink(t, fx, c, link, nonce)
+ if status != http.StatusSeeOther || !strings.HasPrefix(loc, "/a/") {
+ t.Fatalf("POST = %d -> %q, want 303 into an account", status, loc)
+ }
+ emailSession(t, fx, c, addr)
+ if browserCookie(t, fx, c, linkConfirmCookie) != "" {
+ t.Fatal("the nonce cookie outlived the sign-in")
+ }
+
+ // Spent: a second POST and a GET both say expired.
+ c2 := newBrowser(t)
+ if status, body, _ := openLink(t, fx, c2, link); status != http.StatusGone || !strings.Contains(body, esc(copyText("link.expired"))) {
+ t.Fatalf("GET after use = %d:\n%s", status, body)
+ }
+ // The nonce went with the sign-in, so a replay from this browser is refused
+ // as foreign; one that does hold a nonce finds the link spent.
+ if status, _, _ := postLink(t, fx, c, link, nonce); status != http.StatusForbidden {
+ t.Fatalf("second POST from the same browser = %d, want 403", status)
+ }
+ u, _ := url.Parse(fx.ts.URL)
+ c2.Jar.SetCookies(u, []*http.Cookie{{Name: linkConfirmCookie, Value: "n2", Path: "/"}})
+ if status, _, body := postLink(t, fx, c2, link, "n2"); status != http.StatusGone || !strings.Contains(body, esc(copyText("link.expired"))) {
+ t.Fatalf("second POST = %d:\n%s", status, body)
+ }
+ if !signedOut(t, fx, c2) {
+ t.Fatal("a spent link signed a second browser in")
+ }
+ if status, body, _ := openLink(t, fx, newBrowser(t), "no-such-link"); status != http.StatusGone || !strings.Contains(body, esc(copyText("link.expired"))) {
+ t.Fatalf("unknown link = %d:\n%s", status, body)
+ }
+}
+
+// Login CSRF (codex 1): a valid token POSTed without this browser's nonce, or
+// from another site, is refused before anything is spent.
+func TestEmailLinkLoginCSRF(t *testing.T) {
+ fx, m := newEmailFixture(t, true)
+ const addr = "mallory@example.com"
+ lookupAnswers(fx, addr, http.StatusNotFound)
+ _, link := askSignin(t, fx, m, newBrowser(t), addr, "")
+
+ refused := func(status int, body string) bool {
+ return status == http.StatusForbidden && strings.Contains(body, esc(copyText("link.wrong_site")))
+ }
+ // The victim's browser has no nonce cookie: an auto-submitted form from
+ // the attacker's page (no Origin, as old browsers send) carries only the
+ // token and a nonce of the attacker's choosing.
+ victim := newBrowser(t)
+ for _, nonce := range []string{"", "attacker-nonce"} {
+ status, _, body := postFrom(t, fx, victim, "/auth/email/link", "", url.Values{"t": {link}, "nonce": {nonce}})
+ if !refused(status, body) {
+ t.Fatalf("POST with nonce %q and no cookie = %d:\n%s", nonce, status, body)
+ }
+ }
+ // A nonce cookie from another link page does not match a forged form.
+ if _, _, n := openLink(t, fx, victim, link); n == "" {
+ t.Fatal("no nonce on the confirm page")
+ }
+ if status, _, body := postFrom(t, fx, victim, "/auth/email/link", "", url.Values{"t": {link}, "nonce": {"attacker-nonce"}}); !refused(status, body) {
+ t.Fatalf("mismatched nonce = %d:\n%s", status, body)
+ }
+ // A foreign Origin is refused even with a matching nonce.
+ _, _, nonce := openLink(t, fx, victim, link)
+ if status, _, body := postFrom(t, fx, victim, "/auth/email/link", "https://evil.example", url.Values{"t": {link}, "nonce": {nonce}}); !refused(status, body) {
+ t.Fatalf("foreign Origin = %d:\n%s", status, body)
+ }
+ if !signedOut(t, fx, victim) {
+ t.Fatal("a refused POST signed the victim in")
+ }
+ // Nothing was spent: the link still signs its owner in.
+ if _, ok := fx.st.PeekEmailLink(link, time.Now()); !ok {
+ t.Fatal("a refused POST spent the link")
+ }
+ owner := newBrowser(t)
+ _, _, nonce = openLink(t, fx, owner, link)
+ if status, loc, _ := postLink(t, fx, owner, link, nonce); status != http.StatusSeeOther || !strings.HasPrefix(loc, "/a/") {
+ t.Fatalf("owner's POST after the refusals = %d -> %q", status, loc)
+ }
+ emailSession(t, fx, owner, addr)
+}
+
+// The code is the cross-device path, but only on the browser that asked: a
+// second browser with the code and no challenge cookie gets nowhere.
+func TestEmailCodeCrossDevice(t *testing.T) {
+ fx, m := newEmailFixture(t, true)
+ const addr = "bob@example.com"
+ lookupAnswers(fx, addr, http.StatusNotFound)
+ a := newBrowser(t)
+ code, _ := askSignin(t, fx, m, a, addr, "")
+
+ b := newBrowser(t)
+ status, _, body := postCode(t, fx, b, code)
+ if status != http.StatusOK || !strings.Contains(body, esc(copyText("check.code_used_up"))) || !signedOut(t, fx, b) {
+ t.Fatalf("code from a browser that never asked = %d:\n%s", status, body)
+ }
+ // The page keeps the address its form carried, so "Send a new link" works.
+ _, _, body = postFrom(t, fx, b, "/auth/email/code", fx.ts.URL, url.Values{"code": {code}, "address": {addr}, "next": {"/auth/cli"}})
+ for _, want := range []string{esc(copyText("check.sent", "address", addr)), `name="address" value="bob@example.com"`, `name="next" value="/auth/cli"`, esc(copyText("check.code_used_up"))} {
+ if !strings.Contains(body, want) {
+ t.Fatalf("used-up page is missing %q:\n%s", want, body)
+ }
+ }
+ // Cross-site posts are refused before the code is looked at.
+ if status, _, _ := postFrom(t, fx, a, "/auth/email/code", "https://evil.example", url.Values{"code": {code}}); status != http.StatusForbidden {
+ t.Fatalf("cross-site code POST = %d, want 403", status)
+ }
+ status, loc, _ := postCode(t, fx, a, code)
+ if status != http.StatusSeeOther || !strings.HasPrefix(loc, "/a/") {
+ 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")
+ }
+ // Used once.
+ if status, _, body := postCode(t, fx, a, code); status != http.StatusOK || !strings.Contains(body, esc(copyText("check.code_used_up"))) {
+ t.Fatalf("the code a second time = %d:\n%s", status, body)
+ }
+}
+
+// Spec r2-2: wrong codes count per address across fresh challenges. Past the
+// cap the code box refuses without checking, while a link still signs in.
+func TestEmailCodeGuessCap(t *testing.T) {
+ fx := newConsoleFixture(t)
+ const addr = "bob@example.com"
+ 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())
+ if err != nil {
+ t.Fatal(err)
+ }
+ c.Jar.SetCookies(u, []*http.Cookie{{Name: challengeCookie, Value: id, Path: "/"}})
+ return id, link, code
+ }
+ wrong := func(n int, code string) {
+ t.Helper()
+ for i := 1; i <= n; i++ {
+ status, _, body := postCode(t, fx, c, wrongCode(code))
+ want := "check.code_wrong"
+ if i == emailCodeAttempts {
+ want = "check.code_used_up" // the fifth burns the challenge
+ }
+ if status != http.StatusOK || !strings.Contains(body, esc(copyText(want))) {
+ t.Fatalf("wrong code %d = %d, want %s:\n%s", i, status, want, body)
+ }
+ }
+ }
+ id, _, code := fresh("")
+ wrong(5, code)
+ id, _, code = fresh(id)
+ wrong(5, code)
+ _, link, code := fresh(id)
+
+ // The eleventh wrong code, and even the right one, is throttled unchecked.
+ for _, try := range []string{wrongCode(code), code} {
+ status, _, body := postCode(t, fx, c, try)
+ if status != http.StatusOK || !strings.Contains(body, esc(copyText("check.code_throttled"))) {
+ t.Fatalf("code past the cap = %d:\n%s", status, body)
+ }
+ }
+ if !signedOut(t, fx, c) {
+ t.Fatal("a throttled code signed in")
+ }
+ // The throttle burned nothing: this challenge's link still signs in.
+ if challengeRows(t, fx) != 1 {
+ t.Fatalf("%d challenges stand, want the third", challengeRows(t, fx))
+ }
+ other := newBrowser(t)
+ _, _, nonce := openLink(t, fx, other, link)
+ if status, loc, _ := postLink(t, fx, other, link, nonce); status != http.StatusSeeOther || !strings.HasPrefix(loc, "/a/") {
+ t.Fatalf("link past the code cap = %d -> %q", status, loc)
+ }
+ emailSession(t, fx, other, addr)
+}
+
+// A brand-new address signed in by code from the CLI's page lands back there,
+// already holding a personal account.
+func TestNewEmailUserGetsAccount(t *testing.T) {
+ fx, m := newEmailFixture(t, true)
+ const addr = "newbie@example.com"
+ lookupAnswers(fx, addr, http.StatusNotFound)
+ c := newBrowser(t)
+ code, _ := askSignin(t, fx, m, c, addr, "/auth/cli")
+ if userRows(t, fx, addr) != 0 {
+ t.Fatal("asking for a sign-in email created a user")
+ }
+ status, loc, _ := postCode(t, fx, c, code)
+ if status != http.StatusSeeOther || loc != "/auth/cli" {
+ t.Fatalf("code = %d -> %q, want 303 -> /auth/cli", status, loc)
+ }
+ emailSession(t, fx, c, addr)
+ if accts, err := fx.st.AccountsFor(addr); err != nil || len(accts) == 0 {
+ t.Fatalf("accounts for a new email user = %v, %v; want a personal account", accts, err)
+ }
+ if browserCookie(t, fx, c, welcomeCookie) == "" {
+ t.Fatal("no welcome for a brand-new user")
+ }
+}
+
+// Review Focus 5: asking twice from one browser leaves only the newest email
+// working, link and code alike.
+func TestReplacedChallenge(t *testing.T) {
+ fx, m := newEmailFixture(t, true)
+ const addr = "bob@example.com"
+ lookupAnswers(fx, addr, http.StatusNotFound)
+ c := newBrowser(t)
+ code1, link1 := askSignin(t, fx, m, c, addr, "")
+ advanceLimits(fx, 2*time.Minute)
+ code2, link2 := askSignin(t, fx, m, c, addr, "")
+
+ if status, body, _ := openLink(t, fx, newBrowser(t), link1); status != http.StatusGone || !strings.Contains(body, esc(copyText("link.expired"))) {
+ t.Fatalf("first link = %d:\n%s", status, body)
+ }
+ if code1 != code2 {
+ if status, _, body := postCode(t, fx, c, code1); status != http.StatusOK || !strings.Contains(body, esc(copyText("check.code_wrong"))) {
+ t.Fatalf("first code = %d:\n%s", status, body)
+ }
+ }
+ if !signedOut(t, fx, c) {
+ t.Fatal("the first email signed in")
+ }
+ if status, _, _ := openLink(t, fx, newBrowser(t), link2); status != http.StatusOK {
+ t.Fatalf("second link = %d, want its confirm page", status)
+ }
+ if status, loc, _ := postCode(t, fx, c, code2); status != http.StatusSeeOther || !strings.HasPrefix(loc, "/a/") {
+ t.Fatalf("second code = %d -> %q", status, loc)
+ }
+ emailSession(t, fx, c, addr)
+}
+
+// Spec 11: the old Apps-inbox link is retired. Any token, even one the old
+// table still holds, gets the expired message and no session.
+func TestLegacyConfirmRetired(t *testing.T) {
+ fx := newConsoleFixture(t)
+ raw, err := fx.st.CreateConfirmation("bob@example.com", time.Now())
+ if err != nil {
+ t.Fatal(err)
+ }
+ c := newBrowser(t)
+ for _, tok := range []string{raw, "made-up"} {
+ status, _, body := get(t, c, fx.ts.URL+"/auth/confirm?token="+url.QueryEscape(tok))
+ if status != http.StatusOK || !strings.Contains(body, "Link expired") || !strings.Contains(body, esc(copyText("link.expired"))) {
+ t.Fatalf("legacy confirm %q = %d:\n%s", tok, status, body)
+ }
+ }
+ if !signedOut(t, fx, c) {
+ t.Fatal("the retired confirm link opened a session")
+ }
+}
diff --git a/internal/console/server.go b/internal/console/server.go
index 7e265d66b..c29cdc348 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -1388,6 +1388,9 @@ func NewServer(cfg Config, st *Store) (*Server, error) {
// test that constructs a Server gets a Server and nothing else.
s.registerRoute("GET /{$}", s.handleHome)
s.registerRoute("POST /auth/continue", s.handleContinue)
+ s.registerRoute("GET /auth/email/link", s.handleEmailLinkPage)
+ s.registerRoute("POST /auth/email/link", s.handleEmailLink)
+ s.registerRoute("POST /auth/email/code", s.handleEmailCode)
s.registerRoute("GET /auth/signin", s.handleSignin)
s.registerRoute("GET /auth/callback", s.handleCallback)
// Passkey step-up (stepup.go): where a re-authentication lands, on its own
@@ -1793,6 +1796,9 @@ type page struct {
NoMail bool
CheckSent, CodeError string
SigninCopy signinView
+ // The emailed link's confirm page: the token and the login-CSRF nonce
+ // its form POSTs.
+ LinkToken, LinkNonce string
Msg string // generic message page body
@@ -2913,26 +2919,15 @@ func (s *Server) handleCallback(w http.ResponseWriter, r *http.Request) {
s.finishSignin(w, r, address, token, MethodKeymail, next)
}
-// handleConfirm consumes a returning-sign-in confirmation link. The token is
-// burned before the expiry verdict (store.TakeConfirmation), so a link works
-// exactly once.
+// handleConfirm is the retired Apps-inbox confirmation link (spec 11):
+// nothing mints those links any more, so every token gets the expired
+// message and nothing is read or spent. The route stays so an old email still
+// lands somewhere that explains itself.
+//
+// It answers 200, not the 410 of an expired email link: the claim census
+// accepts only a success from a read's probe, and this route is now a read.
func (s *Server) handleConfirm(w http.ResponseWriter, r *http.Request) {
- addr, ok := s.store.TakeConfirmation(r.URL.Query().Get("token"), time.Now())
- if !ok {
- s.renderMessage(w, r, http.StatusGone, "Link expired",
- "That sign-in link has expired or was already used. Ask for a fresh one from the front page.")
- return
- }
- now := time.Now()
- s.store.EnsureUser(addr, now) // belt and braces; confirmations only exist for known users
- tok, _ := s.store.GrantToken(addr)
- raw, err := s.store.CreateSession(addr, tok, now)
- if err != nil {
- s.renderMessage(w, r, http.StatusInternalServerError, "Error", "Could not create your session. Please try again.")
- return
- }
- s.setCookie(w, sessionCookie, raw, int(SessionTTL.Seconds()))
- s.redirectToCurrentAccount(w, r, addr, http.StatusSeeOther)
+ s.renderMessage(w, r, http.StatusOK, "Link expired", copyText("link.expired"))
}
// handleSignout deletes the console session. The Keymail grant deliberately
diff --git a/internal/console/templates/check.html b/internal/console/templates/check.html
index 08e856886..adafdcccb 100644
--- a/internal/console/templates/check.html
+++ b/internal/console/templates/check.html
@@ -2,6 +2,8 @@
<h1>{{.SigninCopy.CheckTitle}}</h1>
<p>{{.CheckSent}}</p>
<form class="signin" method="post" action="/auth/email/code">
+ <input type="hidden" name="address" value="{{.Prefill}}">
+ {{if .Next}}<input type="hidden" name="next" value="{{.Next}}">{{end}}
<label for="code">{{.SigninCopy.CodeLabel}}</label>
<input id="code" type="text" name="code" inputmode="numeric" autocomplete="one-time-code" required autofocus>
<button type="submit">{{.SigninCopy.CodeButton}}</button>
diff --git a/internal/console/templates/email_link.html b/internal/console/templates/email_link.html
new file mode 100644
index 000000000..6c5b9256d
--- /dev/null
+++ b/internal/console/templates/email_link.html
@@ -0,0 +1,8 @@
+{{define "email_link"}}{{template "top" .}}
+<h1>{{.Title}}</h1>
+<form class="signin" method="post" action="/auth/email/link">
+ <input type="hidden" name="t" value="{{.LinkToken}}">
+ <input type="hidden" name="nonce" value="{{.LinkNonce}}">
+ <button type="submit">{{.SigninCopy.LinkButton}}</button>
+</form>
+{{template "bottom" .}}{{end}}
diff --git a/internal/console/testdata/claim-routes.txt b/internal/console/testdata/claim-routes.txt
index 932579962..2676371f1 100644
--- a/internal/console/testdata/claim-routes.txt
+++ b/internal/console/testdata/claim-routes.txt
@@ -98,6 +98,7 @@ route GET /auth/cli
route GET /auth/cli/tokens
route GET /auth/cli/whoami
route GET /auth/confirm
+route GET /auth/email/link
route GET /auth/signin
route GET /auth/stepup/callback
route GET /fleet
@@ -265,6 +266,8 @@ route POST /auth/cli/revoke
route POST /auth/cli/start
route POST /auth/cli/tokens/revoke
route POST /auth/continue
+route POST /auth/email/code
+route POST /auth/email/link
route POST /auth/signout
route POST /fleet/store/{account}/{decision}
route POST /invite/{token}