Merge main (Keymail step-up) into fix/connect-item-when-linked
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
7 files changed,
+519
−26
implementation/fresh-assertion.md+25 −0internal/home/exchange.go+12 −1internal/home/keymail_fresh_test.go+351 −0internal/home/keymailstub_test.go+23 −2internal/home/signin.go+104 −21internal/home/signin_return_test.go+3 −1internal/home/templates/signin.html+1 −1
diff --git a/implementation/fresh-assertion.md b/implementation/fresh-assertion.md| index ae38981..4b487c8 100644 |
| --- a/implementation/fresh-assertion.md |
| +++ b/implementation/fresh-assertion.md |
| @@ -18,3 +18,28 @@ Acceptance: normal exchange retains old AuthTime; max_age with stale session pro |
| Implementation decisions after review: resolve the standing session explicitly with a.sessions.From at authorize because this router has no sessions.Middleware. A completed Keymail first factor plus recovery-code redemption qualifies as fresh within five minutes: recovery is a current credential and requires the gated first factor, while a half-session alone never qualifies. This is covered separately from stale-session forced mail. MaxAge=0 never forces mail. During rollback an old binary rejects a new nonzero-age sealed intent as an unknown field; the user must restart that in-flight exchange. No persistent data format changes. |
| + |
| + |
| +## Keymail step-up — 2026-10-24 |
| + |
| +Supersedes the forced-mail paragraph above for Keymail addresses whose server can demand a gesture; for every other address that paragraph still holds. |
| + |
| +keymaildev/signin v0.1.1 sends prompt=login when the federation server's /.well-known/keymail advertises "reauth": true (keymail serve answers prompt=login with 403 otherwise), and returns Identity.AuthTime, Keymail's report of the authenticator gesture, zero when none was reported. A forced login with a reported gesture time is a fresh gesture, which is what the forced mail existed to obtain, so a fresh intent no longer has to email a Keymail address on such a server. |
| + |
| +Begin. A fresh-intent begin classifies as usual. If the result is a Keymail continuation whose authorize URL carries exactly prompt=login, Home starts Keymail and sends no mail. If it is a Keymail continuation without prompt=login (a server that does not advertise reauth), Home discards it unsent and calls Begin again with the magic link forced: today's behaviour. A non-Keymail address gets the magic link, as before. The check is on the URL actually handed to the browser rather than on a separate classification, so it tests the fact that matters instead of predicting it, and classification still runs after the per-IP budget. The cost is a second address-budget token on the no-reauth path only. |
| + |
| +Callback. During a fresh flow (a valid sealed intent with MaxAge set) the Keymail return is credited only if AuthTime is non-zero, no later than now, and now - AuthTime <= MaxAge (300 s). Otherwise no session is minted and the browser goes to /signin?force=1, the existing Keymail fallback, with the intent and the /authorize/resume navigation cookie untouched. The form rendered at /signin?force=1 posts to /signin?force=1, because the browser submits the form's action and not the URL that rendered it. Before this, every Keymail fallback, ordinary ones included, classified again on submit and went straight back to Keymail; the existing tests posted to /signin?force=1 directly and hid it. The flag is convenience, not security: dropping it buys another Keymail round trip held to the same checks. The plain /signin form still posts to /signin. |
| + |
| +This check cannot be left to resume. Resume reads a zero AuthTime as the session's At, which is the callback's own clock, so a standing Keymail approval with no reported gesture would pass resume's freshness test. Resume's existing checks (sessions.Fresh, verified <= now, subject binding) still run afterwards, unchanged. |
| + |
| +No clock-skew allowance. A future AuthTime is refused outright. rastrillo's assertion validation refuses auth_time > iat, and the issued assertion must carry Keymail's AuthTime unaltered, so no future value can ever be issued. Allowing skew at the callback would only mint a session that resume bounces back to sign-in. Keymail's auth_time is whole seconds, truncated, and the gesture precedes the callback by at least one redirect, so synchronised clocks never trip it. A Keymail clock running ahead of Home's degrades to the email link, which is the safe direction. |
| + |
| +Unchanged: ordinary SSO and ordinary Keymail sign-in, including whatever prompt the library chooses there, with no gesture check on the return; subject binding (a different person's fresh Keymail gesture still gets 400 at resume); the passkey and recovery gates, which run in completeSignIn on both doors; and every sealed-intent bound. AuthTime is never advanced: the assertion carries Keymail's gesture time, tested to the second. |
| + |
| +Acceptance (keymail_fresh_test.go, against the existing keymail stub with "reauth" added): fresh intent plus a reauth server gives an authorize URL with exactly prompt=login and no mail; a gesture 90 s old yields an assertion whose auth_time equals Keymail's; zero, 301 s, one hour, +5 s and +1 h AuthTime give no session and fall back to email, and that email link completes the step-up through the form a browser would submit; a server without reauth gets forced mail; a non-Keymail address gets mail; ordinary Keymail with zero AuthTime still signs in; subject switching through Keymail is refused. Mutation: replacing the window with true fails all five fallback cases, as do removing the future bound or the age bound alone; dropping the prompt=login requirement fails the no-reauth tests; dropping the form's override fails the fresh fallback, the ordinary fallback and TestCredentialReturnKeymailAndFallback. Removing only the zero check survives, because a zero time is also more than 300 s old; the explicit check stays as documentation of the case Keymail defines. |
| + |
| +A Keymail session with no gesture time never satisfies a step-up. Resume refuses a session whose Method is exactly "keymail" and whose AuthTime is zero, even inside the window: sessions.Fresh would fall back to At, which is when Home minted the session, not anything the person did. The step-up then goes to sign-in, where the rules above apply (Keymail with prompt=login, or email). A completed second factor ("keymail+passkey", "keymail+recovery") sets AuthTime itself and is unaffected; magic-link sessions keep the At fallback, because the click is the gesture. Tested with a control (the same flow with a reported gesture mints) and mutation-checked: removing the guard fails the no-gesture case. |
| + |
| +Error re-renders (unparseable form, bad address, rate limit, internal error) draw the form through the same helper as the first GET, so a forced form keeps posting to /signin?force=1 after an error (TestForcedFormErrorsKeepTheOverride, failing first). |
| + |
| +Open, blocked on rastrillo (Astra review of #83 at 1f18405, P1): the guard above runs only when max_age is present. Without max_age, resume still substitutes session At for a Keymail session's missing AuthTime and signs it as auth_time, and a consumer that persisted its own five-minute requirement (handoff StartFresh) accepts it at age 0. The honest assertion for such a session carries no auth_time, which handoff's fresh check (age > freshAuthLifetime) and connect/linkstore's fresh() (at > 0) would both refuse. But rastrillo's assertion.validate, run by Sign and Verify alike, rejects AuthTime <= 0, so Home cannot issue one, and ordinary SSO for these sessions would break if it refused instead. Closing it needs rastrillo to let an assertion carry absent (unknown) auth_time, with every freshness consumer refusing that. Home then falls back to At only for the magic link. Not changed on this branch. |
diff --git a/internal/home/exchange.go b/internal/home/exchange.go| index bf87bb1..32b23a3 100644 |
| --- a/internal/home/exchange.go |
| +++ b/internal/home/exchange.go |
| @@ -10,6 +10,7 @@ import ( |
| "amadan.net/rastrillo/rastrillo/assertion" |
| "amadan.net/rastrillo/rastrillo/sessions" |
| json "github.com/go-json-experiment/json" |
| + "github.com/keymaildev/signin" |
| ) |
| const assertionIntentCookie = "__Host-oficina-assertion-intent" |
| @@ -92,7 +93,7 @@ func (a *App) handleAssertion(w http.ResponseWriter, r *http.Request) { |
| a.failAssertion(w, r, assertionSubject) |
| return |
| } |
| - if intent.MaxAge != 0 && (!sessions.Fresh(session, time.Duration(intent.MaxAge)*time.Second, now) || authTime.After(now)) { |
| + if intent.MaxAge != 0 && (!sessions.Fresh(session, time.Duration(intent.MaxAge)*time.Second, now) || authTime.After(now) || keymailWithoutGesture(session)) { |
| http.Redirect(w, r, "/signin?return_to=%2Fauthorize%2Fresume", http.StatusSeeOther) |
| return |
| } |
| @@ -109,3 +110,13 @@ func (a *App) handleAssertion(w http.ResponseWriter, r *http.Request) { |
| http.SetCookie(w, &http.Cookie{Name: assertionIntentCookie, Value: "", Path: "/", MaxAge: -1, Secure: true, HttpOnly: true, SameSite: http.SameSiteLaxMode}) |
| a.render(w, r, http.StatusOK, "assertion.html", map[string]any{"Action": target + handoff.CallbackPath, "Token": token}) |
| } |
| + |
| +// keymailWithoutGesture reports a session whose only factor is a Keymail |
| +// approval that reported no gesture time. sessions.Fresh falls back to |
| +// At for such a session, and At is when Home minted it, not when the |
| +// person did anything: a standing Keymail inbox session would pass a |
| +// step-up for being new. A second factor (Method "keymail+passkey", |
| +// "keymail+recovery") sets AuthTime itself, so it is not caught here. |
| +func keymailWithoutGesture(session sessions.Session) bool { |
| + return session.Method == string(signin.MethodKeymail) && session.AuthTime.IsZero() |
| +} |
diff --git a/internal/home/keymail_fresh_test.go b/internal/home/keymail_fresh_test.go| new file mode 100644 |
| index 0000000..08dfc1e |
| --- /dev/null |
| +++ b/internal/home/keymail_fresh_test.go |
| @@ -0,0 +1,351 @@ |
| +package home |
| + |
| +import ( |
| + "html" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/url" |
| + "regexp" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/home/internal/home/sealtest" |
| + "amadan.net/rastrillo/rastrillo/assertion" |
| +) |
| + |
| +// The fresh step-up through Keymail (implementation/fresh-assertion.md, |
| +// "Keymail step-up"). A fresh intent may take the Keymail door only |
| +// when the server can be told to demand a new gesture (prompt=login, |
| +// advertised as "reauth": true) and only counts when the gesture time |
| +// Keymail reports is inside the window. Everything else is the email |
| +// link, as before. |
| + |
| +const freshKeymailAddress = "person@keymail.invalid" |
| + |
| +// freshSignInForm walks a fresh, unauthenticated intent to the sign-in |
| +// form the way a browser does, and returns the intent and the |
| +// navigation cookie that carries /authorize/resume. |
| +func freshSignInForm(t *testing.T, p exchangePair, session *http.Cookie) (intent, navigation *http.Cookie) { |
| + t.Helper() |
| + _, intent = p.startFresh(t, session) |
| + resume := exchangeRequest(p.credential.App, "GET", Origin+"/authorize/resume", "", nil, intent, session) |
| + if resume.Code != 303 || resume.Header().Get("Location") != "/signin?return_to=%2Fauthorize%2Fresume" { |
| + t.Fatal("fresh intent did not ask for sign-in", resume.Code, resume.Header().Get("Location")) |
| + } |
| + form := exchangeRequest(p.credential.App, "GET", Origin+resume.Header().Get("Location"), "", nil, intent, session) |
| + return intent, namedCookie(t, form, returnCookie) |
| +} |
| + |
| +// freshBegin POSTs the address under a fresh intent. It forgets earlier |
| +// mail first, so what the mailer holds afterwards is this begin's. |
| +func freshBegin(t *testing.T, p exchangePair, path, address string, cookies ...*http.Cookie) *httptest.ResponseRecorder { |
| + t.Helper() |
| + p.credential.mailer.mu.Lock() |
| + p.credential.mailer.sent = nil |
| + p.credential.mailer.mu.Unlock() |
| + return exchangeRequest(p.credential.App, "POST", Origin+path, Origin, url.Values{"address": {address}}, cookies...) |
| +} |
| + |
| +// keymailContinuation returns the authorize URL a begin handed the |
| +// browser, the pending cookie and the sealed state; it fails the test |
| +// if the begin did anything else, mail included. |
| +func keymailContinuation(t *testing.T, p exchangePair, begin *httptest.ResponseRecorder) (*url.URL, *http.Cookie) { |
| + t.Helper() |
| + _, links := continuationTargets(t, begin.Body.String()) |
| + if begin.Code != 200 || len(links) != 1 || !strings.Contains(links[0], "/oauth/authorize?") { |
| + t.Fatal("fresh Keymail begin did not continue to Keymail", begin.Code, begin.Header().Get("Location")) |
| + } |
| + assertContinuationPage(t, begin, links[0]) |
| + if _, sent := p.credential.mailer.last(); sent { |
| + t.Fatal("fresh Keymail begin also sent mail") |
| + } |
| + u, err := url.Parse(links[0]) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return u, namedCookie(t, begin, pendingCookie) |
| +} |
| + |
| +func TestFreshIntentStartsKeymailWithForcedLogin(t *testing.T) { |
| + p := newExchangePair(t) |
| + stub := newKeymailStub(t, p.credential, freshKeymailAddress) |
| + stub.reauth = true |
| + intent, navigation := freshSignInForm(t, p, nil) |
| + |
| + u, _ := keymailContinuation(t, p, freshBegin(t, p, "/signin", freshKeymailAddress, intent, navigation)) |
| + if got := u.Query()["prompt"]; len(got) != 1 || got[0] != "login" { |
| + t.Fatalf("fresh Keymail authorize URL carries prompt=%q, want exactly login", got) |
| + } |
| +} |
| + |
| +func TestFreshKeymailGestureYieldsAssertionWithKeymailAuthTime(t *testing.T) { |
| + p := newExchangePair(t) |
| + stub := newKeymailStub(t, p.credential, freshKeymailAddress) |
| + stub.reauth = true |
| + // Inside the window but well away from now, so an implementation |
| + // that stamped issuance time over Keymail's report would be seen. |
| + stub.authTime = time.Now().Add(-90 * time.Second).Truncate(time.Second) |
| + intent, navigation := freshSignInForm(t, p, nil) |
| + |
| + u, pending := keymailContinuation(t, p, freshBegin(t, p, "/signin", freshKeymailAddress, intent, navigation)) |
| + back := callback(t, p.credential, "code-1", u.Query().Get("state"), pending, intent, navigation) |
| + if back.Code != 303 || back.Header().Get("Location") != "/authorize/resume" || sessionCookie(back) == nil { |
| + t.Fatal("fresh Keymail gesture was not credited", back.Code, back.Header().Get("Location")) |
| + } |
| + token, _ := p.mint(t, intent, sessionCookie(back)) |
| + verifier, err := assertion.NewVerifier(Origin, directoryOrigin, p.credential.runtime.keys) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + claims, err := verifier.Verify(token, time.Now()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if claims.AuthTime != stub.authTime.Unix() { |
| + t.Fatalf("assertion auth_time=%d, want Keymail's %d", claims.AuthTime, stub.authTime.Unix()) |
| + } |
| +} |
| + |
| +// A gesture Keymail did not report (zero), one older than the window, |
| +// and one from the future must not become a session in a fresh flow. |
| +// Each falls back to the email link with the intent intact, and that |
| +// link — taken through the form a browser would actually submit — |
| +// completes the step-up. |
| +// |
| +// Zero is the case with teeth: resume reads a zero AuthTime as the |
| +// session's At, which is the callback's own clock, so without the |
| +// callback's check a standing Keymail approval would pass as fresh. |
| +func TestFreshKeymailWithoutAFreshGestureFallsBackToEmail(t *testing.T) { |
| + for name, at := range map[string]func() time.Time{ |
| + "zero": func() time.Time { return time.Time{} }, |
| + "stale": func() time.Time { return time.Now().Add(-301 * time.Second) }, |
| + "hour": func() time.Time { return time.Now().Add(-time.Hour) }, |
| + "future": func() time.Time { return time.Now().Add(5 * time.Second) }, |
| + "far": func() time.Time { return time.Now().Add(time.Hour) }, |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + p := newExchangePair(t) |
| + stub := newKeymailStub(t, p.credential, freshKeymailAddress) |
| + stub.reauth = true |
| + stub.authTime = at() |
| + intent, navigation := freshSignInForm(t, p, nil) |
| + |
| + u, pending := keymailContinuation(t, p, freshBegin(t, p, "/signin", freshKeymailAddress, intent, navigation)) |
| + back := callback(t, p.credential, "code-1", u.Query().Get("state"), pending, intent, navigation) |
| + if back.Code != 303 || back.Header().Get("Location") != "/signin?force=1" || sessionCookie(back) != nil { |
| + t.Fatal("Keymail approval without a fresh gesture was credited", back.Code, back.Header().Get("Location")) |
| + } |
| + if intentCleared(back) { |
| + t.Fatal("fallback discarded the assertion intent") |
| + } |
| + |
| + // The form the fallback renders must itself carry the |
| + // override: the browser submits its action, not the URL it |
| + // was reached by. |
| + form := exchangeRequest(p.credential.App, "GET", Origin+"/signin?force=1", "", nil, intent, navigation) |
| + if form.Code != 200 { |
| + t.Fatal("fallback form", form.Code) |
| + } |
| + if c := intentFrom(form); c != nil { |
| + navigation = c |
| + } |
| + sent := freshBegin(t, p, formAction(t, form), freshKeymailAddress, intent, navigation) |
| + if sent.Code != 303 || sent.Header().Get("Location") != "/signin/sent" { |
| + t.Fatal("fallback did not email", sent.Code) |
| + } |
| + verified := exchangeRequest(p.credential.App, "POST", Origin+linkPath, Origin, url.Values{"token": {capturedLink(t, p.credential)}}, intent, navigation) |
| + if verified.Code != 303 || verified.Header().Get("Location") != "/authorize/resume" { |
| + t.Fatal("email fallback lost the step-up continuation", verified.Code) |
| + } |
| + p.mint(t, intent, sessionCookie(verified)) |
| + }) |
| + } |
| +} |
| + |
| +// formAction is the sign-in form's own action, which is what a browser |
| +// submits — not the URL that rendered the form. Tests that POST to a URL |
| +// of their own choosing are how the ordinary fallback's lost override |
| +// survived. |
| +func formAction(t *testing.T, r *httptest.ResponseRecorder) string { |
| + t.Helper() |
| + m := regexp.MustCompile(`<form method="post" action="([^"]*)"`).FindStringSubmatch(r.Body.String()) |
| + if len(m) != 2 { |
| + t.Fatal("no sign-in form") |
| + } |
| + return html.UnescapeString(m[1]) |
| +} |
| + |
| +func intentCleared(r *httptest.ResponseRecorder) bool { |
| + for _, c := range r.Result().Cookies() { |
| + if c.Name == assertionIntentCookie { |
| + return true |
| + } |
| + } |
| + return false |
| +} |
| + |
| +func TestFreshKeymailWithoutReauthStillEmails(t *testing.T) { |
| + p := newExchangePair(t) |
| + newKeymailStub(t, p.credential, freshKeymailAddress) // reauth: false |
| + intent, navigation := freshSignInForm(t, p, nil) |
| + begin := freshBegin(t, p, "/signin", freshKeymailAddress, intent, navigation) |
| + if begin.Code != 303 || begin.Header().Get("Location") != "/signin/sent" { |
| + t.Fatal("fresh flow took Keymail on a server that cannot force a gesture", begin.Code) |
| + } |
| + if m, sent := p.credential.mailer.last(); !sent || m.To != freshKeymailAddress { |
| + t.Fatal("no email was sent") |
| + } |
| +} |
| + |
| +func TestFreshNonKeymailAddressEmails(t *testing.T) { |
| + p := newExchangePair(t) |
| + stub := newKeymailStub(t, p.credential, freshKeymailAddress) |
| + stub.reauth = true |
| + const other = "nobody@keymail.invalid" // the stub's lookup answers 404 |
| + intent, navigation := freshSignInForm(t, p, nil) |
| + begin := freshBegin(t, p, "/signin", other, intent, navigation) |
| + if begin.Code != 303 || begin.Header().Get("Location") != "/signin/sent" { |
| + t.Fatal("non-Keymail address did not get email", begin.Code) |
| + } |
| + if m, sent := p.credential.mailer.last(); !sent || m.To != other { |
| + t.Fatal("no email was sent") |
| + } |
| +} |
| + |
| +// The ordinary path keeps what it had: Keymail, and whatever prompt the |
| +// library's own classification chose, with no new check on the return. |
| +func TestOrdinaryKeymailIgnoresGestureTime(t *testing.T) { |
| + p := newExchangePair(t) |
| + stub := newKeymailStub(t, p.credential, freshKeymailAddress) |
| + stub.reauth = true |
| + stub.authTime = time.Time{} |
| + _, intent := p.start(t) |
| + pending, state := beginKeymail(t, p.credential, freshKeymailAddress) |
| + back := callback(t, p.credential, "code-1", state, pending, intent) |
| + if sessionCookie(back) == nil { |
| + t.Fatal("ordinary Keymail sign-in now depends on gesture time", back.Code, back.Header().Get("Location")) |
| + } |
| +} |
| + |
| +func TestFreshKeymailCannotSwitchSubject(t *testing.T) { |
| + p := newExchangePair(t) |
| + original := signInFully(t, p.credential, sealtest.CanaryAddress) |
| + backdateCredential(t, p, time.Now().Add(-time.Hour)) |
| + stub := newKeymailStub(t, p.credential, freshKeymailAddress) |
| + stub.reauth = true |
| + intent, navigation := freshSignInForm(t, p, original) |
| + |
| + u, pending := keymailContinuation(t, p, freshBegin(t, p, "/signin", freshKeymailAddress, intent, original, navigation)) |
| + back := callback(t, p.credential, "code-1", u.Query().Get("state"), pending, intent, navigation) |
| + other := sessionCookie(back) |
| + if other == nil || back.Header().Get("Location") != "/authorize/resume" { |
| + t.Fatal("fresh Keymail sign-in did not complete", back.Code) |
| + } |
| + r := exchangeRequest(p.credential.App, "GET", Origin+"/authorize/resume", "", nil, intent, other) |
| + if r.Code != 400 || strings.Contains(r.Body.String(), `name="assertion"`) { |
| + t.Fatal("a different person's fresh Keymail gesture satisfied the original step-up", r.Code) |
| + } |
| +} |
| + |
| +// The ordinary Keymail fallback, driven as a browser drives it: a failed |
| +// return lands on /signin?force=1, and the person submits the form that |
| +// page renders. The override has to be in that form's action, or the |
| +// next attempt classifies again and goes straight back to Keymail. |
| +func TestOrdinaryKeymailFallbackFormEmails(t *testing.T) { |
| + app := newTestApp(t) |
| + newKeymailStub(t, app, freshKeymailAddress) |
| + pending, _ := beginKeymail(t, app, freshKeymailAddress) |
| + back := callback(t, app, "code-1", "invalid-state", pending) |
| + if back.Header().Get("Location") != "/signin?force=1" || sessionCookie(back) != nil { |
| + t.Fatal("failed Keymail return did not fall back", back.Code) |
| + } |
| + form := returnRequest(app, "GET", back.Header().Get("Location"), nil) |
| + sent := returnRequest(app, "POST", formAction(t, form), url.Values{"address": {freshKeymailAddress}}) |
| + if sent.Code != 303 || sent.Header().Get("Location") != "/signin/sent" { |
| + t.Fatal("the fallback form went back to Keymail instead of emailing", sent.Code) |
| + } |
| + if m, ok := app.mailer.last(); !ok || m.To != freshKeymailAddress { |
| + t.Fatal("no email was sent") |
| + } |
| + // And the plain form stays plain. |
| + if got := formAction(t, returnRequest(app, "GET", "/signin", nil)); got != "/signin" { |
| + t.Fatalf("plain form action=%q", got) |
| + } |
| +} |
| + |
| +// A Keymail session that reported no gesture time has nothing a step-up |
| +// can credit: its At is when Home minted it, not when the person did |
| +// anything. It must not pass a later fresh intent just for being new. |
| +// The control is the same flow with a reported gesture, which passes. |
| +func TestKeymailSessionWithoutGestureTimeIsNotFresh(t *testing.T) { |
| + for name, gesture := range map[string]bool{"no gesture": false, "gesture": true} { |
| + t.Run(name, func(t *testing.T) { |
| + p := newExchangePair(t) |
| + stub := newKeymailStub(t, p.credential, freshKeymailAddress) // reauth: false |
| + if !gesture { |
| + stub.authTime = time.Time{} |
| + } |
| + pending, state := beginKeymail(t, p.credential, freshKeymailAddress) |
| + session := sessionCookie(callback(t, p.credential, "code-1", state, pending)) |
| + if session == nil { |
| + t.Fatal("ordinary Keymail sign-in failed") |
| + } |
| + _, intent := p.startFresh(t, session) |
| + resume := exchangeRequest(p.credential.App, "GET", Origin+"/authorize/resume", "", nil, intent, session) |
| + if gesture { |
| + if resume.Code != 200 || !strings.Contains(resume.Body.String(), `name="assertion"`) { |
| + t.Fatal("a Keymail session with a fresh gesture was refused", resume.Code) |
| + } |
| + return |
| + } |
| + if resume.Code != 303 || resume.Header().Get("Location") != "/signin?return_to=%2Fauthorize%2Fresume" || strings.Contains(resume.Body.String(), `name="assertion"`) { |
| + t.Fatal("a Keymail session with no gesture time satisfied a step-up", resume.Code) |
| + } |
| + form := exchangeRequest(p.credential.App, "GET", Origin+resume.Header().Get("Location"), "", nil, intent, session) |
| + navigation := namedCookie(t, form, returnCookie) |
| + begin := freshBegin(t, p, formAction(t, form), freshKeymailAddress, intent, session, navigation) |
| + if begin.Code != 303 || begin.Header().Get("Location") != "/signin/sent" { |
| + t.Fatal("step-up did not fall back to email", begin.Code) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// An error re-render of the form must keep the override too. Each of |
| +// these renders the form again, and the person resubmits that form: if |
| +// its action is plain /signin, the retry goes back to Keymail. |
| +func TestForcedFormErrorsKeepTheOverride(t *testing.T) { |
| + t.Run("bad address", func(t *testing.T) { |
| + app := newTestApp(t) |
| + newKeymailStub(t, app, freshKeymailAddress) |
| + bad := returnRequest(app, "POST", "/signin?force=1", url.Values{"address": {"person@localhost"}}) |
| + if bad.Code != 400 { |
| + t.Fatal("single-label domain accepted", bad.Code) |
| + } |
| + retry := returnRequest(app, "POST", formAction(t, bad), url.Values{"address": {freshKeymailAddress}}) |
| + if retry.Code != 303 || retry.Header().Get("Location") != "/signin/sent" { |
| + t.Fatal("retry after an error went back to Keymail", retry.Code) |
| + } |
| + }) |
| + t.Run("rate limited", func(t *testing.T) { |
| + app := newTestApp(t) |
| + var last *httptest.ResponseRecorder |
| + for range 6 { |
| + last = returnRequest(app, "POST", "/signin?force=1", url.Values{"address": {"person@example.invalid"}}) |
| + } |
| + if last.Code != 429 { |
| + t.Fatal("address budget not reached", last.Code) |
| + } |
| + if got := formAction(t, last); got != "/signin?force=1" { |
| + t.Fatalf("rate-limited form action=%q", got) |
| + } |
| + }) |
| + t.Run("plain stays plain", func(t *testing.T) { |
| + app := newTestApp(t) |
| + bad := returnRequest(app, "POST", "/signin", url.Values{"address": {"person@localhost"}}) |
| + if got := formAction(t, bad); got != "/signin" { |
| + t.Fatalf("plain error form action=%q", got) |
| + } |
| + }) |
| +} |
diff --git a/internal/home/keymailstub_test.go b/internal/home/keymailstub_test.go| index b3f82ba..9bfec0a 100644 |
| --- a/internal/home/keymailstub_test.go |
| +++ b/internal/home/keymailstub_test.go |
| @@ -32,6 +32,12 @@ type keymailStub struct { |
| // authenticator gesture happened. Zero means "no gesture", which |
| // callers must treat as the weaker of the two methods. |
| authTime time.Time |
| + // reauth is what /.well-known/keymail advertises. keymail serve |
| + // answers prompt=login with 403 unless it says "reauth": true, so |
| + // Home may only ask for a forced gesture when this is set. Set it |
| + // before the first classification: the classifier caches it per |
| + // domain. |
| + reauth bool |
| mu sync.Mutex |
| spent map[string]bool |
| @@ -54,7 +60,10 @@ func newKeymailStub(t *testing.T, app *testApp, address string) *keymailStub { |
| mux := http.NewServeMux() |
| mux.HandleFunc("/.well-known/keymail", func(w http.ResponseWriter, r *http.Request) { |
| - writeJSON(t, w, map[string]any{"version": "1", "reauth": false}) |
| + k.mu.Lock() |
| + reauth := k.reauth |
| + k.mu.Unlock() |
| + writeJSON(t, w, map[string]any{"version": "1", "reauth": reauth}) |
| }) |
| mux.HandleFunc("/api/federation/lookup", func(w http.ResponseWriter, r *http.Request) { |
| // A claimed inbox is a 200; anything else is "not keymail". |
| @@ -81,6 +90,7 @@ func newKeymailStub(t *testing.T, app *testApp, address string) *keymailStub { |
| k.mu.Lock() |
| used := k.spent[body.Code] |
| k.spent[body.Code] = true |
| + authTime := k.authTime |
| k.mu.Unlock() |
| if used { |
| http.Error(w, "code already redeemed", http.StatusBadRequest) |
| @@ -90,7 +100,7 @@ func newKeymailStub(t *testing.T, app *testApp, address string) *keymailStub { |
| "access_token": "stub-access-token", |
| "token_type": "bearer", |
| "address": k.address, |
| - "auth_time": k.authTime.Unix(), |
| + "auth_time": unixOrZero(authTime), |
| }) |
| }) |
| @@ -121,6 +131,17 @@ func newKeymailStub(t *testing.T, app *testApp, address string) *keymailStub { |
| return k |
| } |
| +// unixOrZero is what keymail sends: 0 when no gesture backed the |
| +// approval, never a plausible invented time. time.Time{}.Unix() is a |
| +// large negative number, which the library would also read as absent, |
| +// but the stub should say what the server says. |
| +func unixOrZero(t time.Time) int64 { |
| + if t.IsZero() { |
| + return 0 |
| + } |
| + return t.Unix() |
| +} |
| + |
| func writeJSON(t *testing.T, w http.ResponseWriter, v any) { |
| t.Helper() |
| w.Header().Set("Content-Type", "application/json") |
diff --git a/internal/home/signin.go b/internal/home/signin.go| index adee4bc..61ff83c 100644 |
| --- a/internal/home/signin.go |
| +++ b/internal/home/signin.go |
| @@ -160,9 +160,32 @@ func clientIP(r *http.Request) string { |
| } |
| // handleSigninForm renders the address form. |
| +// |
| +// The email override (force=1) has to survive into the POST, because the |
| +// browser submits the form's action and not the URL that rendered it. |
| +// Every failed Keymail return lands on /signin?force=1; without this the |
| +// next attempt classified the address again and went straight back to |
| +// Keymail, so "not a dead end" was not true in a browser. Dropping the |
| +// flag from the action is harmless: it buys another Keymail round trip, |
| +// held to the same checks. |
| func (a *App) handleSigninForm(w http.ResponseWriter, r *http.Request) { |
| rememberReturn(w, r) |
| - a.render(w, r, http.StatusOK, "signin.html", map[string]any{}) |
| + a.renderSigninForm(w, r, http.StatusOK, "") |
| +} |
| + |
| +// renderSigninForm is the one way the address form is drawn: the first |
| +// GET and every error re-render alike. The person resubmits whatever |
| +// form is on screen, so an error page that dropped the override would |
| +// send a forced retry straight back to Keymail. |
| +func (a *App) renderSigninForm(w http.ResponseWriter, r *http.Request, status int, msg string) { |
| + data := map[string]any{} |
| + if msg != "" { |
| + data["Error"] = msg |
| + } |
| + if r.URL.Query().Get("force") == "1" { |
| + data["Action"] = "/signin?force=1" |
| + } |
| + a.render(w, r, status, "signin.html", data) |
| } |
| // handleSigninSent is the check-your-mail page. It is reached by |
| @@ -192,8 +215,7 @@ func againHref(r *http.Request) string { |
| // neither discloses whether that person has an account here. |
| func (a *App) handleSigninBegin(w http.ResponseWriter, r *http.Request) { |
| if err := r.ParseForm(); err != nil { |
| - a.render(w, r, http.StatusBadRequest, "signin.html", |
| - map[string]any{"Error": "That did not look like a form."}) |
| + a.renderSigninForm(w, r, http.StatusBadRequest, "That did not look like a form.") |
| return |
| } |
| address := strings.TrimSpace(r.PostFormValue("address")) |
| @@ -201,30 +223,33 @@ func (a *App) handleSigninBegin(w http.ResponseWriter, r *http.Request) { |
| // The force override carries a failed keymail round trip back to the |
| // magic link, so a failed approval is not a dead end. |
| var force signin.Method |
| - intent, freshIntent := a.readAssertionIntent(r, time.Now()) |
| - if r.URL.Query().Get("force") == "1" || (freshIntent && intent.MaxAge == 300) { |
| + if r.URL.Query().Get("force") == "1" { |
| force = signin.MethodMagicLink |
| } |
| - |
| next, err := a.flow.Begin(r.Context(), address, clientIP(r), force) |
| - switch { |
| - case errors.Is(err, signin.ErrBadAddress): |
| - a.render(w, r, http.StatusBadRequest, "signin.html", |
| - map[string]any{"Error": "That does not look like an email address."}) |
| - return |
| - case errors.Is(err, signin.ErrRateLimited): |
| - // 429 without saying which budget: which one was hit is itself |
| - // information about whether that address has been tried. |
| - a.render(w, r, http.StatusTooManyRequests, "signin.html", |
| - map[string]any{"Error": "Too many attempts. Try again shortly."}) |
| - return |
| - case err != nil: |
| - a.logger.Error("signin begin", "err", err) |
| - a.render(w, r, http.StatusInternalServerError, "signin.html", |
| - map[string]any{"Error": "Something went wrong. Try again."}) |
| + if a.beginFailed(w, r, err) { |
| return |
| } |
| + // A fresh step-up (max_age, implementation/fresh-assertion.md) may |
| + // take the Keymail door only when Keymail will demand a new gesture. |
| + // A standing Keymail inbox session approves without one, so a plain |
| + // authorize URL proves nothing about freshness. The test is on the |
| + // URL actually handed to the browser: the library adds prompt=login |
| + // exactly when the server advertised "reauth": true (keymail serve |
| + // answers it with 403 otherwise), so its presence is the fact that |
| + // matters, not a prediction of it. Without it, nothing has been sent |
| + // yet and the email link is what runs, as it always did here. That |
| + // second Begin spends a second rate-limit token for the address; it |
| + // happens only for a Keymail server that cannot step up. |
| + intent, freshIntent := a.readAssertionIntent(r, time.Now()) |
| + if freshIntent && intent.MaxAge != 0 && next.Kind == signin.NextKeymail && !forcesLogin(next.Redirect) { |
| + next, err = a.flow.Begin(r.Context(), address, clientIP(r), signin.MethodMagicLink) |
| + if a.beginFailed(w, r, err) { |
| + return |
| + } |
| + } |
| + |
| if next.Kind == signin.NextKeymail { |
| a.setPending(w, next.Pending) |
| a.renderContinuation(w, r, next.Redirect, "Continue to Keymail") |
| @@ -233,6 +258,24 @@ func (a *App) handleSigninBegin(w http.ResponseWriter, r *http.Request) { |
| http.Redirect(w, r, "/signin/sent", http.StatusSeeOther) |
| } |
| +// beginFailed answers a failed Begin and reports whether it did. |
| +func (a *App) beginFailed(w http.ResponseWriter, r *http.Request, err error) bool { |
| + switch { |
| + case err == nil: |
| + return false |
| + case errors.Is(err, signin.ErrBadAddress): |
| + a.renderSigninForm(w, r, http.StatusBadRequest, "That does not look like an email address.") |
| + case errors.Is(err, signin.ErrRateLimited): |
| + // 429 without saying which budget: which one was hit is itself |
| + // information about whether that address has been tried. |
| + a.renderSigninForm(w, r, http.StatusTooManyRequests, "Too many attempts. Try again shortly.") |
| + default: |
| + a.logger.Error("signin begin", "err", err) |
| + a.renderSigninForm(w, r, http.StatusInternalServerError, "Something went wrong. Try again.") |
| + } |
| + return true |
| +} |
| + |
| // handleVerifyForm renders the confirmation page for a magic link. It |
| // TOUCHES NO STATE, and that is the whole point. |
| // |
| @@ -303,9 +346,49 @@ func (a *App) handleCallback(w http.ResponseWriter, r *http.Request) { |
| http.Redirect(w, r, "/signin?force=1", http.StatusSeeOther) |
| return |
| } |
| + // In a fresh step-up the approval counts only if Keymail reports a |
| + // gesture inside the window. Otherwise no session is minted and the |
| + // person takes the email link instead, the intent cookie untouched. |
| + // The check has to be here rather than left to resume: resume reads |
| + // a zero AuthTime as the session's At, which is this request's own |
| + // clock, so a standing Keymail approval would pass as fresh. |
| + now := time.Now() |
| + if intent, ok := a.readAssertionIntent(r, now); ok && intent.MaxAge != 0 && |
| + !freshGesture(id.AuthTime, now, time.Duration(intent.MaxAge)*time.Second) { |
| + http.Redirect(w, r, "/signin?force=1", http.StatusSeeOther) |
| + return |
| + } |
| a.completeSignIn(w, r, id) |
| } |
| +// freshGesture reports whether Keymail's gesture time proves a gesture |
| +// within maxAge of now. |
| +// |
| +// Zero is Keymail saying no gesture backed the approval. A time after |
| +// now is refused with NO clock-skew allowance, deliberately: the |
| +// assertion format refuses auth_time later than iat, and the issued |
| +// assertion must carry Keymail's real AuthTime unaltered, so a future |
| +// value can never be issued — crediting it here would only mint a |
| +// session that resume then bounces back to sign-in. Keymail's |
| +// auth_time is whole seconds, truncated, and the gesture precedes this |
| +// request by at least the redirect, so synchronised clocks never trip |
| +// this; a Keymail clock running ahead of Home's sends the person to the |
| +// email link, which is the safe direction to fail in. |
| +func freshGesture(at, now time.Time, maxAge time.Duration) bool { |
| + return !at.IsZero() && !at.After(now) && now.Sub(at) <= maxAge |
| +} |
| + |
| +// forcesLogin reports whether a Keymail authorize URL demands a new |
| +// gesture: exactly one prompt parameter, and it is login. |
| +func forcesLogin(authorize string) bool { |
| + u, err := url.Parse(authorize) |
| + if err != nil { |
| + return false |
| + } |
| + prompt := u.Query()["prompt"] |
| + return len(prompt) == 1 && prompt[0] == "login" |
| +} |
| + |
| // completeSignIn turns a verified identity into a session. |
| // |
| // The session's subject is the person ref, never the address. |
diff --git a/internal/home/signin_return_test.go b/internal/home/signin_return_test.go| index 16cc2e8..a940518 100644 |
| --- a/internal/home/signin_return_test.go |
| +++ b/internal/home/signin_return_test.go |
| @@ -82,7 +82,9 @@ func TestCredentialReturnKeymailAndFallback(t *testing.T) { |
| if changed := intentFrom(form); changed != nil { |
| intent = changed |
| } |
| - returnRequest(app, "POST", "/signin?force=1", url.Values{"address": {"person@keymail.invalid"}}, intent) |
| + // The form's own action, as a browser submits it: posting |
| + // to /signin?force=1 directly hid that the form dropped it. |
| + returnRequest(app, "POST", formAction(t, form), url.Values{"address": {"person@keymail.invalid"}}, intent) |
| got = returnRequest(app, "POST", linkPath, url.Values{"token": {capturedLink(t, app)}}, intent) |
| } |
| if got.Header().Get("Location") != "/passkey/codes" || sessionCookie(got) == nil { |
diff --git a/internal/home/templates/signin.html b/internal/home/templates/signin.html| index b871679..2c2f816 100644 |
| --- a/internal/home/templates/signin.html |
| +++ b/internal/home/templates/signin.html |
| @@ -2,7 +2,7 @@ |
| {{define "content"}}{{with signinDoor}} |
| <h1>{{.Heading}}</h1> |
| {{if $.Data.Error}}<p role="alert" rst-callout rst-tone="negative"><span rst-callout-body>{{$.Data.Error}}</span></p>{{end}} |
| -<form method="post" action="/signin" rst-form estilo-signin-form> |
| +<form method="post" action="{{with $.Data.Action}}{{.}}{{else}}/signin{{end}}" rst-form estilo-signin-form> |
| <div rst-field> |
| <label rst-field-label for="address">{{.AddressLabel}}</label> |
| <input id="address" name="address" type="email" autocomplete="email" required autofocus rst-input aria-describedby="address-help"> |