oficina / home Public

Home: tests for the Keymail fresh step-up (failing first)

A fresh intent with a Keymail server that advertises reauth should
start Keymail with prompt=login and send no mail; the callback should
credit only a reported gesture inside the 300 s window, and fall back
to the email link otherwise. The stub learns to advertise reauth and
to report a zero auth_time.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 5c9b4575e3de9147ebbcc5f36435bba39865090f parent ba81936
2 files changed, +257 −2
  • internal/home/keymail_fresh_test.go +234 −0
  • internal/home/keymailstub_test.go +23 −2
diff --git a/internal/home/keymail_fresh_test.go b/internal/home/keymail_fresh_test.go
new file mode 100644
index 0000000..740ace2
--- /dev/null
+++ b/internal/home/keymail_fresh_test.go
@@ -0,0 +1,234 @@
+package home
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "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 || !strings.Contains(form.Body.String(), `action="/signin?force=1"`) {
+ t.Fatal("fallback form does not keep the email override", form.Code)
+ }
+ if c := intentFrom(form); c != nil {
+ navigation = c
+ }
+ sent := freshBegin(t, p, "/signin?force=1", 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))
+ })
+ }
+}
+
+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)
+ }
+}
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")