console: email sessions re-confirm by emailed link or code
A session that signed in by email re-confirms a sensitive action by an emailed link or code (spec 6); a Keymail session keeps the passkey path and never gets an email. requireFreshAuth branches on the session's method; the step-up challenge is bound to the session hash and the held action's hash, lives stepUpFlowTTL, and is redeemed through takePendingActionByHash then resume. New route POST /auth/email/stepup/code; the link GET/POST serve step-up challenges to the asking session only. The team page's note is team.confirm_note.
Co-Authored-By: Claude <noreply@anthropic.com>
11 files changed,
+798
−30
internal/console/claim_invariant_fixtures_test.go+2 −1internal/console/claim_invariant_probes_nonapp_test.go+61 −7internal/console/emailsignin.go+228 −8internal/console/emailstepup_test.go+441 −0internal/console/server.go+8 −1internal/console/server_test.go+1 −0internal/console/stepup.go+44 −10internal/console/templates/email_link.html+1 −1internal/console/templates/stepup_email.html+10 −0internal/console/templates/team.html+1 −2internal/console/testdata/claim-routes.txt+1 −0
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go| index ff4977fa8..474b09e68 100644 |
| --- a/internal/console/claim_invariant_fixtures_test.go |
| +++ b/internal/console/claim_invariant_fixtures_test.go |
| @@ -1219,7 +1219,8 @@ var claimFixtures = map[string]claimFixture{ |
| "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/email/link": claimNonApp("signs in by an emailed link: email challenges, user, session and step-up; or re-confirms a session and resumes its held action through the router"), |
| + "route POST /auth/email/stepup/code": claimNonApp("re-confirms a session by an emailed code: email challenges and step-up, then resumes its held action through the router"), |
| "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 612374176..7362d5250 100644 |
| --- a/internal/console/claim_invariant_probes_nonapp_test.go |
| +++ b/internal/console/claim_invariant_probes_nonapp_test.go |
| @@ -231,6 +231,59 @@ func claimEmailCodeProbe() claimProbe { |
| } |
| } |
| +// claimStepUpCodeProbe: an email session's held removal of kim, and the |
| +// step-up challenge emailed for it, its session, id and code kept in vars; |
| +// the right code resumes the removal. |
| +func claimStepUpCodeProbe() claimProbe { |
| + var c *http.Client |
| + return claimProbe{ |
| + setup: func(t *testing.T, cx *claimCase) { |
| + claimMemberWorld(t, cx) |
| + now := time.Now() |
| + raw, err := cx.st.CreateSessionMethod(claimFxOwner, "", MethodEmail, now) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + pending, err := cx.st.StashPendingAction(raw, claimFxOwner, http.MethodPost, "/a/bab/members/remove", |
| + url.Values{"address": {"kim@keymail.dev"}}.Encode(), now) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + id, _, code, err := cx.st.CreateEmailChallenge(EmailChallenge{ |
| + Purpose: ChallengeStepUp, Address: claimFxOwner, SessionHash: hashToken(raw), |
| + PendingHash: hashToken(pending), ExpiresAt: now.Add(stepUpFlowTTL), |
| + }, "", now) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + cx.vars["stepupsession"], cx.vars["challenge"], cx.vars["code"] = raw, id, code |
| + }, |
| + do: func(t *testing.T, cx *claimCase) claimReply { |
| + c = claimBrowserWithCookie(t, cx, sessionCookie, cx.vars["stepupsession"]) |
| + u, err := url.Parse(cx.ts.URL) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + c.Jar.SetCookies(u, []*http.Cookie{{Name: challengeCookie, Value: cx.vars["challenge"], Path: "/"}}) |
| + status, loc, body := postForm(t, c, cx.ts.URL+"/auth/email/stepup/code", url.Values{"code": {cx.vars["code"]}}) |
| + return cx.browserReply(c, status, loc, body) |
| + }, |
| + status: http.StatusSeeOther, loc: "/a/bab/team", |
| + effect: func(t *testing.T, cx *claimCase, r claimReply) string { |
| + if role, _ := cx.st.Role(OpsAccountID, "kim@keymail.dev"); role != "" { |
| + return `the held removal did not resume: kim@keymail.dev still holds role "` + role + `"` |
| + } |
| + if !cx.st.FreshStepUp(cx.vars["stepupsession"], claimFxOwner, time.Now(), StepUpWindow) { |
| + return "the step-up code recorded no presence" |
| + } |
| + if _, ok := cx.st.PeekEmailChallenge(cx.vars["challenge"], time.Now()); ok { |
| + return "the step-up challenge is still standing after its code was used" |
| + } |
| + return "" |
| + }, |
| + } |
| +} |
| + |
| func claimContinueProbe() claimProbe { |
| // An address Keymail's lookup does not know: the email door, which |
| // records a challenge and answers with the check page. |
| @@ -357,13 +410,14 @@ 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/email/link": claimEmailLinkPageProbe(), |
| - "route POST /auth/email/link": claimEmailLinkProbe(), |
| - "route POST /auth/email/code": claimEmailCodeProbe(), |
| + "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/email/stepup/code": claimStepUpCodeProbe(), |
| "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 2661d0755..78747f294 100644 |
| --- a/internal/console/emailsignin.go |
| +++ b/internal/console/emailsignin.go |
| @@ -37,6 +37,8 @@ type signinView struct { |
| EmailLabel, EmailPlaceholder, EmailButton, Small, NoMail string |
| CheckTitle, CodeLabel, CodeButton, Nothing, AgainButton string |
| LinkButton string |
| + // The email step-up's code box and its link's confirm button. |
| + StepUpCodeLabel, StepUpCodeButton, StepUpLinkButton string |
| } |
| var approvedSigninView = signinView{ |
| @@ -51,6 +53,9 @@ var approvedSigninView = signinView{ |
| Nothing: copyText("check.nothing"), |
| AgainButton: copyText("check.again_button"), |
| LinkButton: copyText("link.button"), |
| + StepUpCodeLabel: copyText("stepup.code_label"), |
| + StepUpCodeButton: copyText("stepup.code_button"), |
| + StepUpLinkButton: copyText("stepup.link_button"), |
| } |
| // sameOrigin reports whether a form POST came from this console's own pages: |
| @@ -264,9 +269,10 @@ func (s *Server) handleEmailLinkPage(w http.ResponseWriter, r *http.Request) { |
| } |
| switch c.Purpose { |
| case ChallengeSignIn: |
| + case ChallengeStepUp: |
| + s.stepUpLinkPage(w, r, link, c) |
| + return |
| 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 |
| } |
| @@ -306,9 +312,12 @@ func (s *Server) handleEmailLink(w http.ResponseWriter, r *http.Request) { |
| } |
| switch peek.Purpose { |
| case ChallengeSignIn: |
| + case ChallengeStepUp: |
| + // Never a sign-in: a step-up link only confirms the session it was |
| + // sent for. |
| + s.stepUpLink(w, r, link, peek, now) |
| + return |
| 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 |
| } |
| @@ -317,15 +326,19 @@ func (s *Server) handleEmailLink(w http.ResponseWriter, r *http.Request) { |
| 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. |
| + 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) |
| } |
| } |
| - s.finishSignin(w, r, c.Address, "", MethodEmail, c.Next) |
| } |
| // handleEmailCode is POST /auth/email/code (spec 5.2): the typed code is |
| @@ -375,3 +388,210 @@ func (s *Server) handleEmailCode(w http.ResponseWriter, r *http.Request) { |
| s.renderCheckError(w, c.Address, c.Next, copyText("check.code_used_up")) |
| } |
| } |
| + |
| +// ---- re-confirmation by email (spec 6) -------------------------------------- |
| +// |
| +// A session that signed in by email proves it is still there the way it |
| +// signed in: an emailed link or code. The step-up gate's properties hold as |
| +// for Keymail (stepup.go): the challenge is bound to the session that asked |
| +// and to the held action's hash, the held action is redeemed only through |
| +// takePendingActionByHash, and requireFreshAuth still runs after every |
| +// membership and CSRF gate. A step-up challenge never signs anyone in. |
| + |
| +// 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. |
| +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) |
| + s.renderMessage(w, r, http.StatusServiceUnavailable, "Error", stepUpHoldFailed) |
| + return |
| + } |
| + if !s.limits.stepUpSend(addr) { |
| + if _, c, ok := s.liveStepUp(r, raw, now); ok { |
| + s.renderStepUp(w, r, c.Address, "") |
| + return |
| + } |
| + log.Printf("console: step-up email to %s over its limits; not sent", addr) |
| + s.renderMessage(w, r, http.StatusServiceUnavailable, "Error", stepUpHoldFailed) |
| + return |
| + } |
| + pending, ok := s.stashRequest(w, r, addr, raw, now) |
| + if !ok { |
| + return |
| + } |
| + replace := "" |
| + if id, _, ok := s.liveStepUp(r, raw, now); ok { |
| + replace = id |
| + } |
| + id, link, code, err := s.store.CreateEmailChallenge(EmailChallenge{ |
| + Purpose: ChallengeStepUp, |
| + Address: addr, |
| + SessionHash: hashToken(raw), |
| + PendingHash: hashToken(pending), |
| + ExpiresAt: now.Add(stepUpFlowTTL), |
| + }, replace, 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), |
| + copyText("email.stepup.body", "console", console, "address", addr, |
| + "link", s.cfg.Origin+"/auth/email/link?t="+link, "code", code)) |
| + s.renderStepUp(w, r, addr, "") |
| +} |
| + |
| +// stepUpFor reports whether c is a step-up challenge made for the session raw. |
| +func stepUpFor(c *EmailChallenge, raw string) bool { |
| + return c != nil && c.Purpose == ChallengeStepUp && c.SessionHash != "" && |
| + 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) |
| + if !ok || !stepUpFor(c, raw) { |
| + return "", nil, false |
| + } |
| + return ck.Value, c, true |
| +} |
| + |
| +// renderStepUp renders "Confirm it's you" for addr, with a refusal of a typed |
| +// code under the code box when codeErr is set. |
| +func (s *Server) renderStepUp(w http.ResponseWriter, r *http.Request, addr, codeErr string) { |
| + p := s.basePage(r) |
| + p.Title = copyText("stepup.title") |
| + p.CheckSent = copyText("stepup.sent", "address", addr) |
| + p.CodeError = codeErr |
| + s.render(w, http.StatusOK, "stepup_email", p) |
| +} |
| + |
| +// renderStepUpExpired answers a step-up that has expired, was used, or has no |
| +// held action left to resume. |
| +func (s *Server) renderStepUpExpired(w http.ResponseWriter, r *http.Request) { |
| + s.renderMessage(w, r, http.StatusGone, "Confirmation expired", copyText("stepup.expired")) |
| +} |
| + |
| +// renderStepUpWrongBrowser answers a step-up link opened anywhere but the |
| +// session that asked for it. |
| +func (s *Server) renderStepUpWrongBrowser(w http.ResponseWriter, r *http.Request) { |
| + s.renderMessage(w, r, http.StatusForbidden, copyText("stepup.link_title"), copyText("stepup.wrong_browser")) |
| +} |
| + |
| +// stepUpLinkPage is GET /auth/email/link for a step-up challenge. It spends |
| +// nothing. Only the session the challenge was made for gets the confirm page |
| +// (with its login-CSRF nonce, as for sign-in); anyone else is told to use the |
| +// browser where they started. |
| +func (s *Server) stepUpLinkPage(w http.ResponseWriter, r *http.Request, link string, c *EmailChallenge) { |
| + _, raw, ok := s.session(r) |
| + if !ok || !stepUpFor(c, raw) { |
| + s.renderStepUpWrongBrowser(w, r) |
| + return |
| + } |
| + nonce, err := randomToken() |
| + if err != nil { |
| + s.renderMessage(w, r, http.StatusInternalServerError, "Error", "Could not start the confirmation. Please try again.") |
| + return |
| + } |
| + s.setCookie(w, linkConfirmCookie, nonce, int(ConfirmationTTL.Seconds())) |
| + p := s.basePage(r) |
| + p.Title = copyText("stepup.link_title") |
| + p.LinkToken = link |
| + p.LinkNonce = nonce |
| + p.StepUpLink = true |
| + s.render(w, http.StatusOK, "email_link", p) |
| +} |
| + |
| +// stepUpLink is POST /auth/email/link for a step-up challenge, after the |
| +// nonce and origin checks: a session other than the one the challenge was |
| +// made for is refused with the link unspent; the right one spends it and |
| +// finishes the step-up. |
| +func (s *Server) stepUpLink(w http.ResponseWriter, r *http.Request, link string, peek *EmailChallenge, now time.Time) { |
| + addr, raw, ok := s.session(r) |
| + if !ok || !stepUpFor(peek, raw) { |
| + s.renderStepUpWrongBrowser(w, r) |
| + return |
| + } |
| + c, ok := s.store.TakeEmailLink(link, now) |
| + if !ok { |
| + 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 |
| +// 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) |
| + if !ok { |
| + http.Redirect(w, r, "/", http.StatusFound) |
| + return |
| + } |
| + if !s.sameOrigin(r) { |
| + s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.") |
| + return |
| + } |
| + now := time.Now() |
| + id, c, ok := s.liveStepUp(r, raw, now) |
| + if !ok { |
| + s.renderStepUpExpired(w, r) |
| + return |
| + } |
| + ip := s.clientIP(r) |
| + done, allowed := s.limits.reserveGuess(c.Address, ip) |
| + if !allowed { |
| + log.Printf("console: step-up code for %s from %s refused: too many wrong codes", c.Address, ip) |
| + s.renderStepUp(w, r, c.Address, copyText("check.code_throttled")) |
| + return |
| + } |
| + got, res := s.store.TakeEmailCode(id, strings.TrimSpace(r.PostFormValue("code")), ChallengeStepUp, 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")) |
| + default: |
| + s.renderStepUpExpired(w, r) |
| + } |
| +} |
| + |
| +// finishStepUp is the tail both step-up doors share, the same as |
| +// handleStepUpCallback's: record presence at the moment the link or code was |
| +// used, redeem the held action this challenge names, and resume it through |
| +// the router. A spent challenge that was not this session's, or names another |
| +// address, records nothing. |
| +func (s *Server) finishStepUp(w http.ResponseWriter, r *http.Request, addr, raw string, c *EmailChallenge, now time.Time) { |
| + if !stepUpFor(c, raw) || c.Address != addr { |
| + s.renderStepUpExpired(w, r) |
| + return |
| + } |
| + if err := s.store.RecordStepUp(raw, addr, now, now); err != nil { |
| + log.Printf("console: record step-up: %v", err) |
| + s.renderMessage(w, r, http.StatusInternalServerError, "Error", "Could not record your confirmation. Please try the action again.") |
| + return |
| + } |
| + pending, ok := s.store.takePendingActionByHash(c.PendingHash, raw, now) |
| + if !ok { |
| + s.renderStepUpExpired(w, r) |
| + return |
| + } |
| + s.resume(w, r, pending) |
| +} |
diff --git a/internal/console/emailstepup_test.go b/internal/console/emailstepup_test.go| new file mode 100644 |
| index 000000000..6d0024052 |
| --- /dev/null |
| +++ b/internal/console/emailstepup_test.go |
| @@ -0,0 +1,441 @@ |
| +package console |
| + |
| +// Re-confirmation by email (spec 6): a session that signed in by email proves |
| +// it is still there by an emailed link or code; a Keymail session keeps its |
| +// passkey and never gets an email instead (anti-goal: no downgrade). |
| + |
| +import ( |
| + "net/http" |
| + "net/url" |
| + "regexp" |
| + "strings" |
| + "testing" |
| + "time" |
| +) |
| + |
| +var ( |
| + stepUpCodeRe = regexp.MustCompile(`type this code there: (\d{6})\b`) |
| + stepUpLinkRe = regexp.MustCompile(`/auth/email/link\?t=([A-Za-z0-9_-]+)`) |
| +) |
| + |
| +// emailOwnerWorld is bob@example.com signed in by an emailed code on browser |
| +// c, owning his personal account with kim@keymail.dev as a second member, |
| +// and with the sign-in's own step-up gone stale, so the next sensitive action |
| +// asks for a fresh one. It returns the session token and the account's |
| +// path base ("/a/<sqid>"). |
| +func emailOwnerWorld(t *testing.T, fx *consoleFixture, m *fakeConsoleMail, c *http.Client) (raw, base string) { |
| + t.Helper() |
| + const addr = "bob@example.com" |
| + lookupAnswers(fx, addr, http.StatusNotFound) |
| + code, _ := askSignin(t, fx, m, c, addr, "") |
| + if status, loc, _ := postCode(t, fx, c, code); status != http.StatusSeeOther { |
| + t.Fatalf("sign-in code = %d -> %q", status, loc) |
| + } |
| + raw = emailSession(t, fx, c, addr) |
| + accts, err := fx.st.AccountsFor(addr) |
| + if err != nil || len(accts) == 0 { |
| + t.Fatalf("bob's accounts = %v, %v", accts, err) |
| + } |
| + if err := fx.st.AddMember(accts[0].ID, "kim@keymail.dev", RoleMember, time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := fx.st.ClearStepUp(raw); err != nil { |
| + t.Fatal(err) |
| + } |
| + return raw, "/a/" + accts[0].Sqid |
| +} |
| + |
| +// kimRole is kim's role in bob's account ("" once removed). |
| +func kimRole(t *testing.T, fx *consoleFixture) string { |
| + t.Helper() |
| + role, _ := fx.st.Role(bobAccount(t, fx).ID, "kim@keymail.dev") |
| + return role |
| +} |
| + |
| +// askStepUp POSTs the removal of kim from browser c and expects the "Confirm |
| +// it's you" page; it returns the code and link token of the step-up email |
| +// that went out. |
| +func askStepUp(t *testing.T, fx *consoleFixture, m *fakeConsoleMail, c *http.Client, raw, base string) (code, link string) { |
| + t.Helper() |
| + before := len(m.sentCopy()) |
| + status, _, body := postForm(t, c, fx.ts.URL+base+"/members/remove", |
| + url.Values{"csrf": {raw}, "address": {"kim@keymail.dev"}}) |
| + for _, want := range []string{esc(copyText("stepup.title")), esc(copyText("stepup.sent", "address", "bob@example.com")), |
| + `action="/auth/email/stepup/code"`, esc(copyText("stepup.code_label")), esc(copyText("stepup.code_button"))} { |
| + if status != http.StatusOK || !strings.Contains(body, want) { |
| + t.Fatalf("gated removal = %d, missing %q:\n%s", status, want, body) |
| + } |
| + } |
| + if kimRole(t, fx) != RoleMember { |
| + t.Fatal("kim was removed before the confirmation") |
| + } |
| + 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) |
| + } |
| + to, body, _ := strings.Cut(sent[len(sent)-1], "|") |
| + cm, lm := stepUpCodeRe.FindStringSubmatch(body), stepUpLinkRe.FindStringSubmatch(body) |
| + if to != "bob@example.com" || cm == nil || lm == nil { |
| + t.Fatalf("step-up email to %q has no code or link:\n%s", to, body) |
| + } |
| + return cm[1], lm[1] |
| +} |
| + |
| +func postStepUpCode(t *testing.T, fx *consoleFixture, c *http.Client, code string) (int, string, string) { |
| + t.Helper() |
| + return postFrom(t, fx, c, "/auth/email/stepup/code", fx.ts.URL, url.Values{"code": {code}}) |
| +} |
| + |
| +func TestEmailSessionStepUpByCode(t *testing.T) { |
| + fx, m := newEmailFixture(t, true) |
| + c := newBrowser(t) |
| + raw, base := emailOwnerWorld(t, fx, m, c) |
| + code, _ := askStepUp(t, fx, m, c, raw, base) |
| + |
| + // The held action is parked server-side, without the session token. |
| + var stashed, leaked int |
| + fx.st.db.QueryRow(`SELECT COUNT(*) FROM pending_actions`).Scan(&stashed) |
| + fx.st.db.QueryRow(`SELECT COUNT(*) FROM pending_actions WHERE form LIKE ?`, "%"+raw+"%").Scan(&leaked) |
| + if stashed != 1 || leaked != 0 { |
| + t.Fatalf("pending actions: %d parked, %d holding the session token", stashed, leaked) |
| + } |
| + |
| + // Cross-site posts are refused before the code is looked at. |
| + if status, _, _ := postFrom(t, fx, c, "/auth/email/stepup/code", "https://evil.example", url.Values{"code": {code}}); status != http.StatusForbidden { |
| + t.Fatalf("cross-site step-up code = %d, want 403", status) |
| + } |
| + // A signed-out browser is sent to the front page. |
| + if status, loc, _ := postStepUpCode(t, fx, newBrowser(t), code); status != http.StatusFound || loc != "/" { |
| + t.Fatalf("signed-out step-up code = %d -> %q, want 302 -> /", status, loc) |
| + } |
| + status, _, body := postStepUpCode(t, fx, c, wrongCode(code)) |
| + if status != http.StatusOK || !strings.Contains(body, esc(copyText("check.code_wrong"))) || |
| + !strings.Contains(body, `action="/auth/email/stepup/code"`) { |
| + t.Fatalf("wrong step-up code = %d:\n%s", status, body) |
| + } |
| + if kimRole(t, fx) != RoleMember { |
| + t.Fatal("a wrong code removed kim") |
| + } |
| + |
| + status, loc, body := postStepUpCode(t, fx, c, code) |
| + if status != http.StatusSeeOther || loc != base+"/team" { |
| + t.Fatalf("right step-up code = %d -> %q, want the resumed removal's 303 to the team page:\n%s", status, loc, body) |
| + } |
| + if kimRole(t, fx) != "" { |
| + t.Fatal("kim is still a member after a confirmed removal") |
| + } |
| + 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") |
| + } |
| + // Used once. |
| + if status, _, body := postStepUpCode(t, fx, c, code); status != http.StatusGone || !strings.Contains(body, esc(copyText("stepup.expired"))) { |
| + t.Fatalf("the step-up code a second time = %d:\n%s", status, body) |
| + } |
| + // A step-up never signs anyone in: the session is the one that asked. |
| + if got := browserCookie(t, fx, c, sessionCookie); got != raw { |
| + t.Fatal("the step-up replaced the session") |
| + } |
| +} |
| + |
| +func TestEmailSessionStepUpByLink(t *testing.T) { |
| + fx, m := newEmailFixture(t, true) |
| + c := newBrowser(t) |
| + raw, base := emailOwnerWorld(t, fx, m, c) |
| + _, link := askStepUp(t, fx, m, c, raw, base) |
| + |
| + // A GET (twice, as a scanner might from this same browser) spends nothing. |
| + var nonce string |
| + for i := 0; i < 2; i++ { |
| + status, body, n := openLink(t, fx, c, link) |
| + if status != http.StatusOK || n == "" || !strings.Contains(body, esc(copyText("stepup.link_title"))) || |
| + !strings.Contains(body, esc(copyText("stepup.link_button"))) { |
| + t.Fatalf("step-up link GET %d = %d:\n%s", i+1, status, body) |
| + } |
| + nonce = n |
| + } |
| + if _, ok := fx.st.PeekEmailLink(link, time.Now()); !ok || kimRole(t, fx) != RoleMember { |
| + t.Fatal("opening the step-up link spent it or acted") |
| + } |
| + // The confirm page's form still needs its nonce. |
| + if status, _, _ := postLink(t, fx, c, link, "forged"); status != http.StatusForbidden { |
| + t.Fatalf("step-up link POST without its nonce = %d, want 403", status) |
| + } |
| + _, _, nonce = openLink(t, fx, c, link) |
| + status, loc, body := postLink(t, fx, c, link, nonce) |
| + if status != http.StatusSeeOther || loc != base+"/team" { |
| + t.Fatalf("step-up link POST = %d -> %q:\n%s", status, loc, body) |
| + } |
| + if kimRole(t, fx) != "" { |
| + t.Fatal("kim is still a member after a confirmed removal") |
| + } |
| + if !fx.st.FreshStepUp(raw, "bob@example.com", time.Now(), StepUpWindow) { |
| + t.Fatal("no presence recorded after the step-up link") |
| + } |
| + if got := browserCookie(t, fx, c, sessionCookie); got != raw { |
| + t.Fatal("the step-up link replaced the session") |
| + } |
| + if status, body, _ := openLink(t, fx, c, link); status != http.StatusGone || !strings.Contains(body, esc(copyText("link.expired"))) { |
| + t.Fatalf("a used step-up link = %d:\n%s", status, body) |
| + } |
| +} |
| + |
| +func TestStepUpLinkOtherBrowser(t *testing.T) { |
| + fx, m := newEmailFixture(t, true) |
| + c := newBrowser(t) |
| + raw, base := emailOwnerWorld(t, fx, m, c) |
| + code, link := askStepUp(t, fx, m, c, raw, base) |
| + u, _ := url.Parse(fx.ts.URL) |
| + |
| + // Signed out, and signed in as bob in another session: both get the |
| + // wrong-browser page, no confirm form, and nothing is spent. |
| + signedOutB := newBrowser(t) |
| + otherSession, err := fx.st.CreateSessionMethod("bob@example.com", "", MethodEmail, time.Now()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + otherB := newBrowser(t) |
| + otherB.Jar.SetCookies(u, []*http.Cookie{{Name: sessionCookie, Value: otherSession, Path: "/"}}) |
| + for name, b := range map[string]*http.Client{"signed out": signedOutB, "another session": otherB} { |
| + status, body, nonce := openLink(t, fx, b, link) |
| + if status != http.StatusForbidden || nonce != "" || !strings.Contains(body, esc(copyText("stepup.wrong_browser"))) { |
| + t.Fatalf("%s: step-up link GET = %d (nonce %q):\n%s", name, status, nonce, body) |
| + } |
| + // Even a POST carrying a matching nonce of its own is refused unspent. |
| + b.Jar.SetCookies(u, []*http.Cookie{{Name: linkConfirmCookie, Value: "n", Path: "/"}}) |
| + status, _, body = postLink(t, fx, b, link, "n") |
| + if status != http.StatusForbidden || !strings.Contains(body, esc(copyText("stepup.wrong_browser"))) { |
| + 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: "/"}}) |
| + 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) |
| + } |
| + if kimRole(t, fx) != RoleMember { |
| + t.Fatal("another browser's step-up attempt removed kim") |
| + } |
| + if _, ok := fx.st.PeekEmailLink(link, time.Now()); !ok { |
| + t.Fatal("another browser spent the step-up link") |
| + } |
| + if fx.st.FreshStepUp(otherSession, "bob@example.com", time.Now(), StepUpWindow) { |
| + t.Fatal("another session gained presence") |
| + } |
| + // The right browser still can. |
| + _, _, nonce := openLink(t, fx, c, link) |
| + if status, loc, _ := postLink(t, fx, c, link, nonce); status != http.StatusSeeOther || loc != base+"/team" { |
| + t.Fatalf("step-up link in the right browser = %d -> %q", status, loc) |
| + } |
| + if kimRole(t, fx) != "" { |
| + t.Fatal("the right browser's confirmation did not remove kim") |
| + } |
| +} |
| + |
| +// Review Focus 1: a Keymail session re-confirms with its passkey only, even |
| +// with a mailer ready, and even when Keymail cannot do it. |
| +func TestKeymailSessionNeverEmailStepUp(t *testing.T) { |
| + fx, m := newEmailFixture(t, true) |
| + c := newBrowser(t) |
| + signUp(t, fx, c, "code-keymail-stepup") |
| + if err := fx.st.AddMember(OpsAccountID, "kim@keymail.dev", RoleMember, time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + csrf := sessionToken(t, fx, c) |
| + if _, method, _ := fx.st.SessionInfo(csrf, time.Now()); method != MethodKeymail { |
| + t.Fatalf("session method = %q, want keymail", method) |
| + } |
| + status, loc, _ := postForm(t, c, fx.u("/members/remove"), url.Values{"csrf": {csrf}, "address": {"kim@keymail.dev"}}) |
| + if status != http.StatusSeeOther || !strings.HasPrefix(loc, fx.fk.srv.URL) { |
| + t.Fatalf("keymail session's gated removal = %d -> %q, want a redirect into Keymail", status, loc) |
| + } |
| + fx.fk.mu.Lock() |
| + fx.fk.reauth = false |
| + fx.fk.mu.Unlock() |
| + if status, _, _ := postForm(t, c, fx.u("/members/remove"), url.Values{"csrf": {csrf}, "address": {"kim@keymail.dev"}}); status != http.StatusServiceUnavailable { |
| + t.Fatalf("keymail session with no Keymail step-up = %d, want 503", status) |
| + } |
| + if n := len(m.sentCopy()); n != 0 || challengeRows(t, fx) != 0 { |
| + t.Fatalf("a keymail session's step-up sent %d emails and left %d challenges", n, challengeRows(t, fx)) |
| + } |
| + if role, _ := fx.st.Role(OpsAccountID, "kim@keymail.dev"); role != RoleMember { |
| + t.Fatal("kim was removed without a passkey") |
| + } |
| +} |
| + |
| +func TestStepUpChallengeExpiresWithPendingAction(t *testing.T) { |
| + fx, m := newEmailFixture(t, true) |
| + c := newBrowser(t) |
| + raw, base := emailOwnerWorld(t, fx, m, c) |
| + code, link := askStepUp(t, fx, m, c, raw, base) |
| + |
| + // The challenge lives exactly as long as the action it holds: 10 minutes. |
| + var cCreated, cExp, pCreated, pExp int64 |
| + if err := fx.st.db.QueryRow(`SELECT created_at, expires_at FROM email_challenges`).Scan(&cCreated, &cExp); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := fx.st.db.QueryRow(`SELECT created_at, expires_at FROM pending_actions`).Scan(&pCreated, &pExp); err != nil { |
| + t.Fatal(err) |
| + } |
| + if cExp-cCreated != int64(stepUpFlowTTL.Seconds()) || cExp != pExp { |
| + t.Fatalf("challenge lives %ds to %d, pending action to %d; want %ds, together", |
| + cExp-cCreated, cExp, pExp, int64(stepUpFlowTTL.Seconds())) |
| + } |
| + // Eleven minutes on. |
| + shift := int64((11 * time.Minute).Seconds()) |
| + for _, table := range []string{"email_challenges", "pending_actions"} { |
| + if _, err := fx.st.db.Exec(`UPDATE `+table+` SET created_at = created_at - ?, expires_at = expires_at - ?`, shift, shift); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if status, _, body := postStepUpCode(t, fx, c, code); status != http.StatusGone || !strings.Contains(body, esc(copyText("stepup.expired"))) { |
| + t.Fatalf("step-up code after 11 minutes = %d:\n%s", status, body) |
| + } |
| + if status, body, _ := openLink(t, fx, c, link); status != http.StatusGone || !strings.Contains(body, esc(copyText("link.expired"))) { |
| + t.Fatalf("step-up link after 11 minutes = %d:\n%s", status, body) |
| + } |
| + if kimRole(t, fx) != RoleMember || fx.st.FreshStepUp(raw, "bob@example.com", time.Now(), StepUpWindow) { |
| + t.Fatal("an expired step-up acted or recorded presence") |
| + } |
| + |
| + // A live challenge whose held action has gone: confirmed, but nothing to |
| + // resume, and the page says so. |
| + advanceLimits(fx, 2*time.Minute) |
| + code, _ = askStepUp(t, fx, m, c, raw, base) |
| + if _, err := fx.st.db.Exec(`DELETE FROM pending_actions`); err != nil { |
| + t.Fatal(err) |
| + } |
| + if status, _, body := postStepUpCode(t, fx, c, code); status != http.StatusGone || !strings.Contains(body, esc(copyText("stepup.expired"))) { |
| + t.Fatalf("step-up code with its action gone = %d:\n%s", status, body) |
| + } |
| + if kimRole(t, fx) != RoleMember { |
| + t.Fatal("kim was removed with no held action") |
| + } |
| +} |
| + |
| +// The mailer down, and the impatient second click: neither stashes a second |
| +// action or sends a second email. |
| +func TestEmailSessionStepUpFailsClosed(t *testing.T) { |
| + t.Run("no mailer", func(t *testing.T) { |
| + fx, m := newEmailFixture(t, true) |
| + c := newBrowser(t) |
| + raw, base := emailOwnerWorld(t, fx, m, c) |
| + m.mu.Lock() |
| + m.ready = false |
| + m.mu.Unlock() |
| + status, _, body := postForm(t, c, fx.ts.URL+base+"/members/remove", |
| + url.Values{"csrf": {raw}, "address": {"kim@keymail.dev"}}) |
| + if status != http.StatusServiceUnavailable || !strings.Contains(body, "Could not hold on to that action. Please try again.") { |
| + t.Fatalf("step-up with the mailer down = %d:\n%s", status, body) |
| + } |
| + var stashed int |
| + fx.st.db.QueryRow(`SELECT COUNT(*) FROM pending_actions`).Scan(&stashed) |
| + if stashed != 0 || challengeRows(t, fx) != 0 || len(m.sentCopy()) != 1 || kimRole(t, fx) != RoleMember { |
| + t.Fatalf("mailer down: %d stashed, %d challenges, %d emails", stashed, challengeRows(t, fx), len(m.sentCopy())) |
| + } |
| + }) |
| + t.Run("asked twice", func(t *testing.T) { |
| + fx, m := newEmailFixture(t, true) |
| + c := newBrowser(t) |
| + raw, base := emailOwnerWorld(t, fx, m, c) |
| + code, _ := askStepUp(t, fx, m, c, raw, base) |
| + status, _, body := postForm(t, c, fx.ts.URL+base+"/members/remove", |
| + url.Values{"csrf": {raw}, "address": {"kim@keymail.dev"}}) |
| + if status != http.StatusOK || !strings.Contains(body, esc(copyText("stepup.sent", "address", "bob@example.com"))) { |
| + t.Fatalf("second ask inside the minute = %d:\n%s", status, body) |
| + } |
| + var stashed int |
| + fx.st.db.QueryRow(`SELECT COUNT(*) FROM pending_actions`).Scan(&stashed) |
| + if stashed != 1 || challengeRows(t, fx) != 1 || len(m.sentCopy()) != 2 { |
| + t.Fatalf("second ask: %d stashed, %d challenges, %d emails", stashed, challengeRows(t, fx), len(m.sentCopy())) |
| + } |
| + // The first email's code still finishes the action. |
| + if status, loc, _ := postStepUpCode(t, fx, c, code); status != http.StatusSeeOther || loc != base+"/team" || kimRole(t, fx) != "" { |
| + t.Fatalf("first code after a second ask = %d -> %q", status, loc) |
| + } |
| + // Still inside the minute, with no live step-up challenge left in this |
| + // browser, the throttle fails closed. |
| + if err := fx.st.ClearStepUp(raw); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := fx.st.AddMember(bobAccount(t, fx).ID, "kim@keymail.dev", RoleMember, time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + status, _, body = postForm(t, c, fx.ts.URL+base+"/members/remove", |
| + url.Values{"csrf": {raw}, "address": {"kim@keymail.dev"}}) |
| + if status != http.StatusServiceUnavailable || !strings.Contains(body, "Could not hold on to that action. Please try again.") { |
| + t.Fatalf("throttled with no live challenge = %d:\n%s", status, body) |
| + } |
| + }) |
| +} |
| + |
| +func bobAccount(t *testing.T, fx *consoleFixture) Account { |
| + t.Helper() |
| + accts, err := fx.st.AccountsFor("bob@example.com") |
| + if err != nil || len(accts) == 0 { |
| + t.Fatalf("bob's accounts = %v, %v", accts, err) |
| + } |
| + return accts[0] |
| +} |
| + |
| +// The headline: a signed-out new email user logs a terminal in with exactly |
| +// one email, because the sign-in itself is a fresh step-up. |
| +func TestCLILoginByEmailUserOneEmail(t *testing.T) { |
| + fx, m := newEmailFixture(t, true) |
| + fx.srv.cliNotified = make(chan struct{}, 1) |
| + const addr = "newbie@example.com" |
| + lookupAnswers(fx, addr, http.StatusNotFound) |
| + c := newBrowser(t) |
| + |
| + status, _, body := get(t, c, fx.ts.URL+"/auth/cli") |
| + if status != http.StatusOK || !strings.Contains(body, esc(copyText("home.cli_prompt"))) || |
| + !strings.Contains(body, `name="next" value="/auth/cli"`) { |
| + t.Fatalf("signed-out /auth/cli = %d:\n%s", status, body) |
| + } |
| + code, _ := askSignin(t, fx, m, c, addr, "/auth/cli") |
| + if status, loc, _ := postCode(t, fx, c, code); status != http.StatusSeeOther || loc != "/auth/cli" { |
| + t.Fatalf("sign-in code = %d -> %q, want 303 -> /auth/cli", status, loc) |
| + } |
| + csrf := emailSession(t, fx, c, addr) |
| + if status, _, _ := get(t, c, fx.ts.URL+"/auth/cli"); status != http.StatusOK { |
| + t.Fatalf("signed-in /auth/cli = %d", status) |
| + } |
| + |
| + status, start := postJSON(t, fx.ts.URL+"/auth/cli/start", map[string]string{"label": "newbie@laptop"}, "") |
| + if status != http.StatusOK { |
| + t.Fatalf("start = %d %v", status, start) |
| + } |
| + userCode, deviceCode := str(t, start, "user_code"), str(t, start, "device_code") |
| + status, _, body = postForm(t, c, fx.ts.URL+"/auth/cli/approve", |
| + url.Values{"code": {userCode}, "action": {"continue"}, "csrf": {csrf}}) |
| + if status != http.StatusOK || !strings.Contains(body, "newbie@laptop") { |
| + t.Fatalf("continue = %d:\n%s", status, body) |
| + } |
| + status, loc, body := postForm(t, c, fx.ts.URL+"/auth/cli/approve", |
| + url.Values{"code": {userCode}, "action": {"approve"}, "csrf": {csrf}}) |
| + if status != http.StatusOK || !strings.Contains(body, "Approved") { |
| + t.Fatalf("approve = %d -> %q, want approved at once:\n%s", status, loc, body) |
| + } |
| + _, poll := postJSON(t, fx.ts.URL+"/auth/cli/poll", map[string]string{"device_code": deviceCode}, "") |
| + if str(t, poll, "status") != CLIAuthApproved || str(t, poll, "address") != addr || str(t, poll, "token") == "" { |
| + t.Fatalf("poll after approval = %v", poll) |
| + } |
| + select { |
| + case <-fx.srv.cliNotified: |
| + case <-time.After(5 * time.Second): |
| + t.Fatal("no issuance notice attempt") |
| + } |
| + if sent := m.sentCopy(); len(sent) != 1 { |
| + t.Fatalf("console mailer got %d messages, want exactly the sign-in email: %q", len(sent), sent) |
| + } |
| + if challengeRows(t, fx) != 0 { |
| + t.Fatal("a step-up challenge was created") |
| + } |
| +} |
diff --git a/internal/console/server.go b/internal/console/server.go| index 3d24bc139..562f6a594 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -1391,6 +1391,7 @@ func NewServer(cfg Config, st *Store) (*Server, error) { |
| 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("POST /auth/email/stepup/code", s.handleStepUpEmailCode) |
| 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 |
| @@ -1797,8 +1798,13 @@ type page struct { |
| CheckSent, CodeError string |
| SigninCopy signinView |
| // The emailed link's confirm page: the token and the login-CSRF nonce |
| - // its form POSTs. |
| + // its form POSTs; StepUpLink when the link re-confirms a session |
| + // rather than signing in. |
| LinkToken, LinkNonce string |
| + StepUpLink bool |
| + // ConfirmNote is the team page's note on actions that ask you to |
| + // confirm it's you (team.confirm_note). |
| + ConfirmNote string |
| Msg string // generic message page body |
| @@ -3169,6 +3175,7 @@ func (s *Server) handleTeam(w http.ResponseWriter, r *http.Request) { |
| p := s.accountPage(w, r, addr, raw, acct, role) |
| p.Title = "Team" |
| p.ActiveNav = "team" |
| + p.ConfirmNote = copyText("team.confirm_note") |
| if members, err := s.store.Members(acct.ID); err != nil { |
| log.Printf("console: members: %v", err) |
| } else { |
diff --git a/internal/console/server_test.go b/internal/console/server_test.go| index a323bf16f..b5be130b6 100644 |
| --- a/internal/console/server_test.go |
| +++ b/internal/console/server_test.go |
| @@ -682,6 +682,7 @@ func TestTeamPage(t *testing.T) { |
| for _, want := range []string{ |
| "Team", "people who can see and ship", |
| `action="` + fx.path("/invite") + `"`, |
| + esc(copyText("team.confirm_note")), |
| } { |
| if !strings.Contains(body, want) { |
| t.Fatalf("team page missing %q", want) |
diff --git a/internal/console/stepup.go b/internal/console/stepup.go| index b8869d37e..f062f4791 100644 |
| --- a/internal/console/stepup.go |
| +++ b/internal/console/stepup.go |
| @@ -96,6 +96,10 @@ const stepUpUnavailable = "This action needs you to confirm it's really you with |
| "if this keeps happening, this deployment's Keymail does not support re-authentication " + |
| "and these actions stay blocked until it does." |
| +// stepUpHoldFailed is the message when the console cannot hold on to the |
| +// action, or (an email session) cannot send the confirmation for it. |
| +const stepUpHoldFailed = "Could not hold on to that action. Please try again." |
| + |
| // ---- storage ---------------------------------------------------------------- |
| // migrateStepUp adds this feature's two tables. Additive and idempotent, and |
| @@ -203,6 +207,17 @@ func (s *Store) TakePendingAction(rawToken, rawSession string, now time.Time) (* |
| if rawToken == "" { |
| return nil, false |
| } |
| + return s.takePendingActionByHash(hashToken(rawToken), rawSession, now) |
| +} |
| + |
| +// takePendingActionByHash is TakePendingAction for a caller that holds only |
| +// the token's hash (an email step-up challenge stores the hash, never the |
| +// token): the same transaction, single-use delete, session binding and expiry |
| +// check. |
| +func (s *Store) takePendingActionByHash(hash, rawSession string, now time.Time) (*pendingAction, bool) { |
| + if hash == "" { |
| + return nil, false |
| + } |
| tx, err := s.db.Begin() |
| if err != nil { |
| return nil, false |
| @@ -212,7 +227,7 @@ func (s *Store) TakePendingAction(rawToken, rawSession string, now time.Time) (* |
| var expires int64 |
| var p pendingAction |
| err = tx.QueryRow(`SELECT session_hash, method, path, form, expires_at |
| -FROM pending_actions WHERE token_hash = ?`, hashToken(rawToken)). |
| +FROM pending_actions WHERE token_hash = ?`, hash). |
| Scan(&sessionHash, &p.Method, &p.Path, &p.Form, &expires) |
| if err == sql.ErrNoRows { |
| return nil, false |
| @@ -220,7 +235,7 @@ FROM pending_actions WHERE token_hash = ?`, hashToken(rawToken)). |
| if err != nil { |
| return nil, false |
| } |
| - if _, err := tx.Exec(`DELETE FROM pending_actions WHERE token_hash = ?`, hashToken(rawToken)); err != nil { |
| + if _, err := tx.Exec(`DELETE FROM pending_actions WHERE token_hash = ?`, hash); err != nil { |
| return nil, false |
| } |
| if err := tx.Commit(); err != nil { |
| @@ -239,7 +254,8 @@ FROM pending_actions WHERE token_hash = ?`, hashToken(rawToken)). |
| // requireFreshAuth is the step-up gate. It returns true only when this session |
| // has proved presence inside StepUpWindow; otherwise it has ALREADY written the |
| -// response (a redirect into Keymail's re-authentication, or a fail-closed |
| +// response (a redirect into Keymail's re-authentication, for an email session |
| +// the "Confirm it's you" page of an emailed link and code, or a fail-closed |
| // message) and the caller must simply return. |
| // |
| // Call it LAST — after the membership/ownership gate and after the CSRF check. |
| @@ -251,6 +267,13 @@ func (s *Server) requireFreshAuth(w http.ResponseWriter, r *http.Request, addr, |
| if s.store.FreshStepUp(raw, addr, now, StepUpWindow) { |
| return true |
| } |
| + // A session that signed in by email re-confirms by email (spec 6). Only |
| + // that method does: a Keymail session, or one whose method cannot be |
| + // read, takes the passkey path below and never an email instead. |
| + if _, method, ok := s.store.SessionInfo(raw, now); ok && method == MethodEmail { |
| + s.emailStepUp(w, r, addr, raw, now) |
| + return false |
| + } |
| // Ask the identity provider whether it can do this at all before sending a |
| // human off to try. Unreachable and "no" are the same answer here — see |
| // stepUpUnavailable. |
| @@ -276,18 +299,31 @@ func (s *Server) requireFreshAuth(w http.ResponseWriter, r *http.Request, addr, |
| s.renderMessage(w, r, http.StatusInternalServerError, "Error", "Could not start the confirmation. Please try again.") |
| return false |
| } |
| + pending, ok := s.stashRequest(w, r, addr, raw, now) |
| + if !ok { |
| + return false |
| + } |
| + s.setCookie(w, stepUpCookie, state+"."+verifier+"."+pending, int(stepUpFlowTTL.Seconds())) |
| + http.Redirect(w, r, s.km.StepUpURL(state, ChallengeS256(verifier), StepUpWindow), http.StatusSeeOther) |
| + return false |
| +} |
| + |
| +// stashRequest parks the request the gate interrupted (StashPendingAction) |
| +// and returns the token that redeems it. On false it has already written the |
| +// response. |
| +func (s *Server) stashRequest(w http.ResponseWriter, r *http.Request, addr, raw string, now time.Time) (string, bool) { |
| // The handler has already read fields off this request, so PostForm is |
| // parsed and cached; Encode gives back exactly what it will be re-fed. |
| if err := r.ParseForm(); err != nil { |
| s.renderMessage(w, r, http.StatusBadRequest, "Refused", "That request could not be read.") |
| - return false |
| + return "", false |
| } |
| // The csrf field is deliberately NOT stored. It is the raw session token, |
| // and sessions are kept hashed here precisely so a database read is not a |
| // session; parking a live one in a form blob would quietly undo that. The |
| // resume re-injects it from the cookie the resuming request carries — which |
| // costs nothing in safety, because the cross-site question was already |
| - // answered above, before this stash was ever created. |
| + // answered before this stash was ever created. |
| form := url.Values{} |
| for k, v := range r.PostForm { |
| if k != "csrf" { |
| @@ -297,12 +333,10 @@ func (s *Server) requireFreshAuth(w http.ResponseWriter, r *http.Request, addr, |
| pending, err := s.store.StashPendingAction(raw, addr, r.Method, r.URL.Path, form.Encode(), now) |
| if err != nil { |
| log.Printf("console: stash pending action: %v", err) |
| - s.renderMessage(w, r, http.StatusInternalServerError, "Error", "Could not hold on to that action. Please try again.") |
| - return false |
| + s.renderMessage(w, r, http.StatusInternalServerError, "Error", stepUpHoldFailed) |
| + return "", false |
| } |
| - s.setCookie(w, stepUpCookie, state+"."+verifier+"."+pending, int(stepUpFlowTTL.Seconds())) |
| - http.Redirect(w, r, s.km.StepUpURL(state, ChallengeS256(verifier), StepUpWindow), http.StatusSeeOther) |
| - return false |
| + return pending, true |
| } |
| // handleStepUpCallback is where a re-authentication lands. It trusts nothing |
diff --git a/internal/console/templates/email_link.html b/internal/console/templates/email_link.html| index 6c5b9256d..e21ab2a0d 100644 |
| --- a/internal/console/templates/email_link.html |
| +++ b/internal/console/templates/email_link.html |
| @@ -3,6 +3,6 @@ |
| <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> |
| + <button type="submit">{{if .StepUpLink}}{{.SigninCopy.StepUpLinkButton}}{{else}}{{.SigninCopy.LinkButton}}{{end}}</button> |
| </form> |
| {{template "bottom" .}}{{end}} |
diff --git a/internal/console/templates/stepup_email.html b/internal/console/templates/stepup_email.html| new file mode 100644 |
| index 000000000..a12ef55f7 |
| --- /dev/null |
| +++ b/internal/console/templates/stepup_email.html |
| @@ -0,0 +1,10 @@ |
| +{{define "stepup_email"}}{{template "top" .}} |
| +<h1>{{.Title}}</h1> |
| +<p>{{.CheckSent}}</p> |
| +<form class="signin" method="post" action="/auth/email/stepup/code"> |
| + <label for="code">{{.SigninCopy.StepUpCodeLabel}}</label> |
| + <input id="code" type="text" name="code" inputmode="numeric" autocomplete="one-time-code" required autofocus> |
| + <button type="submit">{{.SigninCopy.StepUpCodeButton}}</button> |
| +</form> |
| +{{if .CodeError}}<p class="error">{{.CodeError}}</p>{{end}} |
| +{{template "bottom" .}}{{end}} |
diff --git a/internal/console/templates/team.html b/internal/console/templates/team.html| index c835842a6..c961bfc74 100644 |
| --- a/internal/console/templates/team.html |
| +++ b/internal/console/templates/team.html |
| @@ -30,8 +30,7 @@ |
| </table> |
| </div> |
| {{if .IsOwner}} |
| -<p class="small">Removing a member, handing over ownership and deleting the account each ask |
| - you to confirm with your passkey — a signed-in browser on its own isn't enough.</p> |
| +<p class="small">{{.ConfirmNote}}</p> |
| <h2>Invite a teammate</h2> |
| <form class="signin" method="post" action="{{.Base}}/invite"> |
| <input type="hidden" name="csrf" value="{{.CSRF}}"> |
diff --git a/internal/console/testdata/claim-routes.txt b/internal/console/testdata/claim-routes.txt| index 2676371f1..3a3c4ada4 100644 |
| --- a/internal/console/testdata/claim-routes.txt |
| +++ b/internal/console/testdata/claim-routes.txt |
| @@ -268,6 +268,7 @@ route POST /auth/cli/tokens/revoke |
| route POST /auth/continue |
| route POST /auth/email/code |
| route POST /auth/email/link |
| +route POST /auth/email/stepup/code |
| route POST /auth/signout |
| route POST /fleet/store/{account}/{decision} |
| route POST /invite/{token} |