Merge remote-tracking branch 'origin/main' into feat/consolidated-dashboard
20 files changed,
+975
−62
connect/README.md+10 −0connect/api.go+9 −0connect/bridge.go+7 −0connect/bridge_test.go+20 −3connect/go.mod+1 −1connect/go.sum+2 −2connect/link_handlers.go+89 −7connect/linked_test.go+202 −0connect/linkstore/store.go+19 −0connect/navigation.go+70 −18connect/navigation_test.go+2 −2connect/routes.go+2 −0connect/view.go+23 −3implementation/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/connect/README.md b/connect/README.md| index 02d4491..c258ad4 100644 |
| --- a/connect/README.md |
| +++ b/connect/README.md |
| @@ -69,6 +69,16 @@ admits that hop only from an origin registered in its `HOME_CONSUMERS`, by |
| `Referrer-Policy: no-referrer` (use `strict-origin`), and a custom policy must keep |
| the issuer in `form-action`. |
| +Offer "Connect your Oficina account" in the account menu only when |
| +`Bridge.Linked` reports no stored link for the signed-in local person, however |
| +the session signed in: one indexed lookup per render. Render the shared pages |
| +with `PageFor(r, ...)` so "Accounts connected" leads back to the page the link |
| +began from. An assertion with no link here leaves a sealed, ten-minute |
| +navigation marker: the next fresh local sign-in begins the link at once and |
| +lands, after Home's freshness check, on the confirm step. An expired marker is |
| +ignored. The confirm POST ends on `GET /account/home/confirm?connected=1`, |
| +which shows "Accounts connected" only to a person whose link is stored. |
| + |
| Wrap the trusted local plugin's Begin handler with `OAuthContinuation` when it |
| can redirect to Keymail. Render the supplied destination with `OAuthPage` and the |
| shared `home-oauth-head` and `home-oauth` templates inside your existing layout. |
diff --git a/connect/api.go b/connect/api.go| index 91aee15..17f7f94 100644 |
| --- a/connect/api.go |
| +++ b/connect/api.go |
| @@ -48,6 +48,15 @@ func (b *Bridge) Resolve(ctx context.Context, subject string) (Person, error) { |
| id, label, err := b.links.Resolve(ctx, b.issuer, subject) |
| return Person{ID: id, Label: label}, err |
| } |
| + |
| +// Linked reports whether the local person already has a stored link to an |
| +// Oficina identity. The account menu offers "Connect your Oficina account" |
| +// only when it does not, however this session signed in: someone linked who |
| +// signed in with the app's own email link is still linked. One indexed |
| +// lookup; an error means "unknown", and callers should offer nothing. |
| +func (b *Bridge) Linked(ctx context.Context, person int64) (bool, error) { |
| + return b.links.Linked(ctx, person) |
| +} |
| func (b *Bridge) ResolveSession(r *http.Request) (Person, error) { |
| session, err := b.actualSession(r) |
| if err != nil || session == nil { |
diff --git a/connect/bridge.go b/connect/bridge.go| index 245a441..40deb82 100644 |
| --- a/connect/bridge.go |
| +++ b/connect/bridge.go |
| @@ -33,6 +33,10 @@ type Bridge struct { |
| mintSession func(http.ResponseWriter, *http.Request, Session) error |
| localPerson func(context.Context, Session) (Person, error) |
| render func(http.ResponseWriter, *http.Request, string, string, int) |
| + // rememberUnknown is set by NewRoutes: an assertion with no link here |
| + // leaves the sealed navigation marker that resumes linking after the |
| + // person signs in locally. |
| + rememberUnknown func(http.ResponseWriter) |
| } |
| type homeFinishKey struct{} |
| type homeFinishResult struct { |
| @@ -207,6 +211,9 @@ func (b *Bridge) complete(w http.ResponseWriter, r *http.Request, claims asserti |
| } |
| id, _, err := b.links.Resolve(r.Context(), claims.Issuer, claims.Subject) |
| if errors.Is(err, linkstore.ErrRefused) { |
| + if b.rememberUnknown != nil { |
| + b.rememberUnknown(w) |
| + } |
| return rejectHome(r, "unknown", http.StatusForbidden) |
| } |
| if err != nil { |
diff --git a/connect/bridge_test.go b/connect/bridge_test.go| index ffa0569..c97ff6a 100644 |
| --- a/connect/bridge_test.go |
| +++ b/connect/bridge_test.go |
| @@ -236,8 +236,8 @@ func (f *bridgeFixture) link(t *testing.T, local *http.Cookie, subject string) { |
| } |
| w := httptest.NewRecorder() |
| f.b.ConfirmPost(w, bridgeRequest(http.MethodPost, "/account/home/confirm", cookies)) |
| - if w.Code != 303 || w.Header().Get("Location") != "/" { |
| - t.Fatalf("confirm=%d", w.Code) |
| + if w.Code != 303 || w.Header().Get("Location") != connectedURL("/") { |
| + t.Fatalf("confirm=%d %q", w.Code, w.Header().Get("Location")) |
| } |
| bridgeNoSession(t, f.b, w) |
| } |
| @@ -479,9 +479,26 @@ func TestHomeBridgeReturnPathCallbackRemainsSafe(t *testing.T) { |
| proof, cookies := f.linkProof(t, local, "opaque") |
| w := httptest.NewRecorder() |
| f.b.ConfirmPost(w, bridgeRequest(http.MethodPost, "/account/home/confirm", append(cookies, proof))) |
| - if w.Code != 303 || w.Header().Get("Location") != tc.want { |
| + if w.Code != 303 || w.Header().Get("Location") != connectedURL(tc.want) { |
| t.Fatalf("return location=%q status=%d", w.Header().Get("Location"), w.Code) |
| } |
| + // The success page's way back is that same safe path, even |
| + // when the query is hand-edited to something else. |
| + var back string |
| + f.b.render = func(w http.ResponseWriter, r *http.Request, state, label string, status int) { |
| + back = PageFor(r, state, label).Action |
| + w.WriteHeader(status) |
| + } |
| + for location, want := range map[string]string{w.Header().Get("Location"): tc.want, connectedURL(tc.input): "/"} { |
| + if tc.input == tc.want { |
| + want = tc.want |
| + } |
| + done := httptest.NewRecorder() |
| + f.b.ConfirmPage(done, bridgeRequest(http.MethodGet, location, []*http.Cookie{local})) |
| + if done.Code != 200 || back != want { |
| + t.Fatalf("%s: success way back=%q status=%d want %q", location, back, done.Code, want) |
| + } |
| + } |
| }) |
| } |
| } |
diff --git a/connect/go.mod b/connect/go.mod| index de1fbd8..debab6d 100644 |
| --- a/connect/go.mod |
| +++ b/connect/go.mod |
| @@ -3,7 +3,7 @@ module amadan.net/oficina/home/connect |
| go 1.25.0 |
| require ( |
| - amadan.net/oficina/estilo.git v0.0.0-20260909234655-dec3908b237c |
| + amadan.net/oficina/estilo.git v0.0.0-20261024225503-1817c1c6c7ef |
| amadan.net/oficina/home/handoff v0.0.0-20260908102137-481d2d57f489 |
| amadan.net/rastrillo/rastrillo v0.26.1-0.20260908075707-29e4491631bd |
| github.com/go-json-experiment/json v0.0.0-20250725192818-e39067aee2d2 |
diff --git a/connect/go.sum b/connect/go.sum| index db96826..06717e6 100644 |
| --- a/connect/go.sum |
| +++ b/connect/go.sum |
| @@ -1,5 +1,5 @@ |
| -amadan.net/oficina/estilo.git v0.0.0-20260909234655-dec3908b237c h1:LgE7WLm6zMG/qZScoAHb4X2gguzorctB4XGjPYavXts= |
| -amadan.net/oficina/estilo.git v0.0.0-20260909234655-dec3908b237c/go.mod h1:0R45/vCUAT+kpS7S6K/ZxBdE8f7YxFN4HT3HyDJ3nPY= |
| +amadan.net/oficina/estilo.git v0.0.0-20261024225503-1817c1c6c7ef h1:c+0jDD33fLLQ0L4lOF7mYjEC6dbcIq1d3RGAAxGtXWo= |
| +amadan.net/oficina/estilo.git v0.0.0-20261024225503-1817c1c6c7ef/go.mod h1:4u0jNBtIdMLOsJyrScfqoEuYDJF7BBM3qM9YWbzt6aw= |
| amadan.net/oficina/home/handoff v0.0.0-20260908102137-481d2d57f489 h1:RPKtyry/71i06o8L+gjAaUyexbmG56kO1YPs601URAM= |
| amadan.net/oficina/home/handoff v0.0.0-20260908102137-481d2d57f489/go.mod h1:YISpzFJ+iMgrM0rUL032OSzsAQbP4/nozvXLCCOcn1k= |
| amadan.net/rastrillo/rastrillo v0.26.1-0.20260908075707-29e4491631bd h1:jlFSt95M1ontOg+VePU+kIJpChtWqDQAbnmlxqCnbgc= |
diff --git a/connect/link_handlers.go b/connect/link_handlers.go| index bdbd5f1..ac8999b 100644 |
| --- a/connect/link_handlers.go |
| +++ b/connect/link_handlers.go |
| @@ -1,8 +1,11 @@ |
| package connect |
| import ( |
| + "context" |
| "errors" |
| "net/http" |
| + "net/url" |
| + "strings" |
| "amadan.net/oficina/home/connect/linkstore" |
| "amadan.net/oficina/home/handoff" |
| @@ -30,18 +33,37 @@ func (b *Bridge) LinkStart(w http.ResponseWriter, r *http.Request) { |
| if !b.guard(w, r, http.MethodPost, "/account/home") { |
| return |
| } |
| + if status, err := b.startLink(w, r); err != nil { |
| + if status == 0 { |
| + b.linkFailure(w, r, err) |
| + } else { |
| + b.fail(w, r, status) |
| + } |
| + } |
| +} |
| + |
| +// resumeLink is LinkStart for a person who just signed in locally after an |
| +// Oficina assertion with no link arrived: the same checks, the same flow. |
| +// It reports false having written nothing when the link cannot begin. |
| +func (b *Bridge) resumeLink(w http.ResponseWriter, r *http.Request) bool { |
| + _, err := b.startLink(w, r) |
| + return err == nil |
| +} |
| + |
| +// startLink begins a link for the actual fresh local session and sends the |
| +// browser to the Home freshness check. It writes nothing unless it succeeds; |
| +// on failure it returns the status to show, or 0 for linkFailure's. |
| +func (b *Bridge) startLink(w http.ResponseWriter, r *http.Request) (int, error) { |
| for _, name := range []string{homeInitCookie, homeProofCookie} { |
| if _, _, ok := homeCookie(r, name); !ok { |
| - b.fail(w, r, http.StatusBadRequest) |
| - return |
| + return http.StatusBadRequest, errIdentityRefused |
| } |
| } |
| local, _, err := b.localBinding(r) |
| // The reviewed local reauthentication continuation is wired separately. |
| // Stale local authentication cannot begin or reuse a linking initiation. |
| if err != nil { |
| - b.fail(w, r, http.StatusForbidden) |
| - return |
| + return http.StatusForbidden, err |
| } |
| path := "/" |
| if b.returnPath != nil { |
| @@ -51,14 +73,32 @@ func (b *Bridge) LinkStart(w http.ResponseWriter, r *http.Request) { |
| } |
| secret, err := b.links.Start(r.Context(), local, path, b.now()) |
| if err != nil { |
| - b.linkFailure(w, r, err) |
| - return |
| + return 0, err |
| } |
| setHomeCookie(w, homeInitCookie, secret, 300) |
| setHomeCookie(w, homeProofCookie, "", -1) |
| http.Redirect(w, r, "/auth/start?return_to=%2Faccount%2Fhome%2Fconfirm", http.StatusSeeOther) |
| + return 0, nil |
| } |
| + |
| +// connectedQuery marks the confirm page's GET after a successful confirm. |
| +// It shows "Accounts connected" only to a person whose link is stored, so |
| +// a crafted URL can show nothing that is not already true. return_to is |
| +// the page the link began from, revalidated before it becomes the page's |
| +// way back. |
| +const connectedQuery = "connected" |
| + |
| +type successReturnKey struct{} |
| + |
| +func connectedURL(path string) string { |
| + return "/account/home/confirm?" + url.Values{connectedQuery: {"1"}, "return_to": {path}}.Encode() |
| +} |
| + |
| func (b *Bridge) ConfirmPage(w http.ResponseWriter, r *http.Request) { |
| + if q, err := url.ParseQuery(r.URL.RawQuery); err == nil && q.Has(connectedQuery) { |
| + b.connectedPage(w, r, q) |
| + return |
| + } |
| if !b.guard(w, r, http.MethodGet, "/account/home/confirm") { |
| return |
| } |
| @@ -103,7 +143,49 @@ func (b *Bridge) ConfirmPost(w http.ResponseWriter, r *http.Request) { |
| b.linkFailure(w, r, err) |
| return |
| } |
| - http.Redirect(w, r, pending.ReturnPath, http.StatusSeeOther) |
| + // Say that it worked (Paul, 2026-10-24: landing back on the page with |
| + // nothing changed left him unable to tell). A GET, so a reload repeats |
| + // the page rather than the POST. |
| + http.Redirect(w, r, connectedURL(pending.ReturnPath), http.StatusSeeOther) |
| +} |
| + |
| +// connectedPage is "Accounts connected", for the signed-in person whose |
| +// account now has a stored link. |
| +func (b *Bridge) connectedPage(w http.ResponseWriter, r *http.Request, q url.Values) { |
| + w.Header().Set("Cache-Control", "no-store") |
| + if r.Host != strings.TrimPrefix(b.origin, "https://") || r.URL.Path != "/account/home/confirm" { |
| + b.fail(w, r, http.StatusNotFound) |
| + return |
| + } |
| + if r.Method != http.MethodGet { |
| + w.Header().Set("Allow", http.MethodGet) |
| + b.fail(w, r, http.StatusMethodNotAllowed) |
| + return |
| + } |
| + session, err := b.actualSession(r) |
| + if err != nil || session == nil { |
| + b.fail(w, r, http.StatusForbidden) |
| + return |
| + } |
| + person, err := b.existingPerson(r, *session) |
| + if err != nil { |
| + b.fail(w, r, http.StatusForbidden) |
| + return |
| + } |
| + linked, err := b.links.Linked(r.Context(), person.ID) |
| + if err != nil { |
| + b.fail(w, r, http.StatusServiceUnavailable) |
| + return |
| + } |
| + if !linked { |
| + b.fail(w, r, http.StatusForbidden) |
| + return |
| + } |
| + back := "/" |
| + if v, ok := q["return_to"]; ok && len(v) == 1 && handoff.SafePath(v[0]) { |
| + back = v[0] |
| + } |
| + b.render(w, r.WithContext(context.WithValue(r.Context(), successReturnKey{}, back)), "success", person.Label, http.StatusOK) |
| } |
| func (b *Bridge) linkFailure(w http.ResponseWriter, r *http.Request, err error) { |
| status := http.StatusServiceUnavailable |
diff --git a/connect/linked_test.go b/connect/linked_test.go| new file mode 100644 |
| index 0000000..30c3b25 |
| --- /dev/null |
| +++ b/connect/linked_test.go |
| @@ -0,0 +1,202 @@ |
| +package connect |
| + |
| +import ( |
| + "bytes" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/url" |
| + "testing" |
| + "time" |
| +) |
| + |
| +func (f *bridgeFixture) personID(t *testing.T, address string) int64 { |
| + t.Helper() |
| + var id int64 |
| + if err := f.db.QueryRow("SELECT id FROM people WHERE email=?", address).Scan(&id); err != nil { |
| + t.Fatal(err) |
| + } |
| + return id |
| +} |
| + |
| +// routes wires NewRoutes over the fixture's bridge, as an app does, so the |
| +// navigation marker and the bridge share their hooks. |
| +func (f *bridgeFixture) routes(t *testing.T) *Routes { |
| + t.Helper() |
| + h, err := NewRoutes(f.b, RoutesConfig{Namespace: "oficina/docs", Origin: bridgeOrigin, Issuer: bridgeIssuer, SessionCookie: f.sessions.cookie, DEK: bytes.Repeat([]byte{41}, 32), |
| + ReadSession: func(r *http.Request) (*Session, error) { |
| + s, ok := f.sessions.From(r) |
| + if !ok { |
| + return nil, nil |
| + } |
| + return &s, nil |
| + }, |
| + SignOut: func(http.ResponseWriter, *http.Request) {}, |
| + LocalSignin: func(http.ResponseWriter, *http.Request) {}, |
| + Protect: func(next http.Handler) http.Handler { return next }, |
| + Render: f.b.render}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return h |
| +} |
| + |
| +// TestLinkedIsTheStoredLinkNotTheSessionMethod is the menu bug: someone |
| +// linked who signs in with the app's own email link is still linked. |
| +func TestLinkedIsTheStoredLinkNotTheSessionMethod(t *testing.T) { |
| + f := newBridgeFixture(t) |
| + local := f.local(t, "one@example.com", "magiclink", time.Time{}) |
| + f.local(t, "two@example.com", "magiclink", time.Time{}) |
| + one, two := f.personID(t, "one@example.com"), f.personID(t, "two@example.com") |
| + ctx := t.Context() |
| + if linked, err := f.b.Linked(ctx, one); err != nil || linked { |
| + t.Fatal("unlinked person reported linked", linked, err) |
| + } |
| + f.link(t, local, "opaque-one") |
| + if linked, err := f.b.Linked(ctx, one); err != nil || !linked { |
| + t.Fatal("linked person reported unlinked", linked, err) |
| + } |
| + if linked, err := f.b.Linked(ctx, two); err != nil || linked { |
| + t.Fatal("another person's link leaked", linked, err) |
| + } |
| + if linked, err := f.b.Linked(ctx, 0); err != nil || linked { |
| + t.Fatal("no person reported linked", linked, err) |
| + } |
| +} |
| + |
| +// TestConfirmEndsOnAccountsConnected: after "Connect accounts" the person |
| +// sees that it worked, on a GET, and only once the link is stored. |
| +func TestConfirmEndsOnAccountsConnected(t *testing.T) { |
| + f := newBridgeFixture(t) |
| + local := f.local(t, "one@example.com", "magiclink", time.Time{}) |
| + proof, cookies := f.linkProof(t, local, "opaque-one") |
| + w := httptest.NewRecorder() |
| + f.b.ConfirmPost(w, bridgeRequest(http.MethodPost, "/account/home/confirm", append(cookies, proof))) |
| + if w.Code != 303 || w.Header().Get("Location") != connectedURL("/") { |
| + t.Fatalf("confirm=%d %q", w.Code, w.Header().Get("Location")) |
| + } |
| + var links int |
| + if err := f.db.QueryRow("SELECT COUNT(*) FROM home_identity_links WHERE subject='opaque-one' AND person_id=?", f.personID(t, "one@example.com")).Scan(&links); err != nil || links != 1 { |
| + t.Fatal("confirm did not store the link", links, err) |
| + } |
| + done := httptest.NewRecorder() |
| + f.b.ConfirmPage(done, bridgeRequest(http.MethodGet, connectedURL("/"), []*http.Cookie{local})) |
| + if done.Code != 200 || done.Body.String() != "success" { |
| + t.Fatalf("connected page=%d %q", done.Code, done.Body.String()) |
| + } |
| + other := f.local(t, "two@example.com", "magiclink", time.Time{}) |
| + crafted := httptest.NewRecorder() |
| + f.b.ConfirmPage(crafted, bridgeRequest(http.MethodGet, connectedURL("/"), []*http.Cookie{other})) |
| + if crafted.Code != 403 || crafted.Body.String() == "success" { |
| + t.Fatalf("unlinked person shown success: %d", crafted.Code) |
| + } |
| + anonymous := httptest.NewRecorder() |
| + f.b.ConfirmPage(anonymous, bridgeRequest(http.MethodGet, connectedURL("/"), nil)) |
| + if anonymous.Code != 403 { |
| + t.Fatalf("signed-out success page=%d", anonymous.Code) |
| + } |
| +} |
| + |
| +// unknownArrival runs an ordinary exchange for a subject with no link and |
| +// returns the navigation marker it left. |
| +func (f *bridgeFixture) unknownArrival(t *testing.T, subject string) *http.Cookie { |
| + t.Helper() |
| + pending, nonce := f.start(t, nil, "/d/existing") |
| + inbox := f.callback(t, subject, nonce, time.Now().Add(-time.Hour)) |
| + w := httptest.NewRecorder() |
| + f.b.Finish(w, bridgeRequest(http.MethodGet, "/auth/finish", []*http.Cookie{pending, inbox})) |
| + if w.Code != 403 || w.Body.String() != "unknown" { |
| + t.Fatalf("unknown arrival=%d %q", w.Code, w.Body.String()) |
| + } |
| + bridgeNoSession(t, f.b, w) |
| + return bridgeCookie(t, w, localLinkNavigationCookie) |
| +} |
| + |
| +// TestUnknownAssertionResumesLinkAfterLocalSignIn: an Oficina assertion |
| +// with no link, then a local sign-in, lands on the confirm step for a |
| +// fresh Oficina assertion, with no menu to hunt for. Every existing rule |
| +// still holds: fresh local auth, a fresh Home assertion bound to this |
| +// session, and an explicit confirm before anything is stored. |
| +func TestUnknownAssertionResumesLinkAfterLocalSignIn(t *testing.T) { |
| + f := newBridgeFixture(t) |
| + h := f.routes(t) |
| + marker := f.unknownArrival(t, "opaque-one") |
| + local := f.local(t, "one@example.com", "magiclink", time.Time{}) |
| + w := httptest.NewRecorder() |
| + h.LocalComplete(w, bridgeRequest(http.MethodGet, LocalCompletePath, []*http.Cookie{marker, local})) |
| + if w.Code != 303 || w.Header().Get("Location") != "/auth/start?return_to=%2Faccount%2Fhome%2Fconfirm" { |
| + t.Fatalf("local sign-in did not resume the link: %d %q", w.Code, w.Header().Get("Location")) |
| + } |
| + init := bridgeCookie(t, w, homeInitCookie) |
| + cookies := []*http.Cookie{local, init} |
| + start := httptest.NewRecorder() |
| + f.b.Start(start, bridgeRequest(http.MethodGet, w.Header().Get("Location"), cookies)) |
| + target, _ := url.Parse(start.Header().Get("Location")) |
| + if start.Code != 303 || target.Query().Get("max_age") != "300" { |
| + t.Fatal("resumed link did not ask Oficina for fresh authentication", start.Code) |
| + } |
| + pending := bridgeCookie(t, start, "__Host-oficina-assertion-pending") |
| + inbox := f.callback(t, "opaque-one", target.Query().Get("nonce"), time.Now().Add(-30*time.Second)) |
| + finish := httptest.NewRecorder() |
| + f.b.Finish(finish, bridgeRequest(http.MethodGet, "/auth/finish", append(cookies, pending, inbox))) |
| + if finish.Code != 303 || finish.Header().Get("Location") != "/account/home/confirm" { |
| + t.Fatalf("finish=%d %q", finish.Code, finish.Header().Get("Location")) |
| + } |
| + proof := bridgeCookie(t, finish, homeProofCookie) |
| + var links int |
| + if err := f.db.QueryRow("SELECT COUNT(*) FROM home_identity_links").Scan(&links); err != nil || links != 0 { |
| + t.Fatal("linked before the explicit confirm", links, err) |
| + } |
| + page := httptest.NewRecorder() |
| + f.b.ConfirmPage(page, bridgeRequest(http.MethodGet, "/account/home/confirm", []*http.Cookie{local, proof})) |
| + if page.Code != 200 || page.Body.String() != "confirm" { |
| + t.Fatalf("confirm page=%d %q", page.Code, page.Body.String()) |
| + } |
| + post := httptest.NewRecorder() |
| + f.b.ConfirmPost(post, bridgeRequest(http.MethodPost, "/account/home/confirm", []*http.Cookie{local, proof})) |
| + if post.Code != 303 { |
| + t.Fatalf("confirm=%d", post.Code) |
| + } |
| + if id, err := f.b.Resolve(t.Context(), "opaque-one"); err != nil || id.ID != f.personID(t, "one@example.com") { |
| + t.Fatal("resumed link not stored", id, err) |
| + } |
| +} |
| + |
| +// TestUnknownMarkerExpiresToTheMenuPath: a remembered arrival older than |
| +// the marker's lifetime is ignored, and the person lands as from any sign |
| +// in, with the menu item still on offer. A stale local sign-in never |
| +// resumes, and the menu's own marker still goes to the Connect page. |
| +func TestUnknownMarkerExpiresToTheMenuPath(t *testing.T) { |
| + f := newBridgeFixture(t) |
| + h := f.routes(t) |
| + marker := f.unknownArrival(t, "opaque-one") |
| + later := time.Now().Add(time.Duration(localLinkNavigationLifetime+1) * time.Second) |
| + // The local sign-in is fresh at the later time too, so only the |
| + // marker's own expiry can decide. |
| + local := f.local(t, "one@example.com", "magiclink", later.Add(-time.Minute)) |
| + h.navigation.now = func() time.Time { return later } |
| + w := httptest.NewRecorder() |
| + h.LocalComplete(w, bridgeRequest(http.MethodGet, LocalCompletePath, []*http.Cookie{marker, local})) |
| + if w.Code != 303 || w.Header().Get("Location") != "/" { |
| + t.Fatalf("expired marker still resumed: %d %q", w.Code, w.Header().Get("Location")) |
| + } |
| + for _, c := range w.Result().Cookies() { |
| + if c.Name == homeInitCookie && c.MaxAge > 0 { |
| + t.Fatal("expired marker began a link") |
| + } |
| + } |
| + h.navigation.now = time.Now |
| + local = f.local(t, "one@example.com", "magiclink", time.Time{}) |
| + stale := f.local(t, "one@example.com", "keymail", time.Now().Add(-10*time.Minute)) |
| + w = httptest.NewRecorder() |
| + h.LocalComplete(w, bridgeRequest(http.MethodGet, LocalCompletePath, []*http.Cookie{f.unknownArrival(t, "opaque-one"), stale})) |
| + if w.Header().Get("Location") != "/" { |
| + t.Fatalf("stale local sign-in resumed: %q", w.Header().Get("Location")) |
| + } |
| + begin := httptest.NewRecorder() |
| + h.navigation.Begin(begin, bridgeRequest(http.MethodGet, "/account/home", nil)) |
| + w = httptest.NewRecorder() |
| + h.LocalComplete(w, bridgeRequest(http.MethodGet, LocalCompletePath, []*http.Cookie{bridgeCookie(t, begin, localLinkNavigationCookie), local})) |
| + if w.Header().Get("Location") != "/account/home" { |
| + t.Fatalf("menu marker changed: %q", w.Header().Get("Location")) |
| + } |
| +} |
diff --git a/connect/linkstore/store.go b/connect/linkstore/store.go| index 544c1ff..e0422ca 100644 |
| --- a/connect/linkstore/store.go |
| +++ b/connect/linkstore/store.go |
| @@ -203,6 +203,25 @@ func (s *Store) Resolve(ctx context.Context, issuer, subject string) (int64, str |
| return id, address, nil |
| } |
| +// Linked reports whether the person has a stored link to an identity at |
| +// this issuer, whichever way the current session signed in. It is one |
| +// lookup on the UNIQUE (issuer, person_id) index, cheap enough for every |
| +// page that draws the account menu. |
| +func (s *Store) Linked(ctx context.Context, person int64) (bool, error) { |
| + if person <= 0 { |
| + return false, nil |
| + } |
| + var one int |
| + err := s.db.QueryRowContext(ctx, "SELECT 1 FROM home_identity_links WHERE issuer = ? AND person_id = ?", s.issuer, person).Scan(&one) |
| + if errors.Is(err, sql.ErrNoRows) { |
| + return false, nil |
| + } |
| + if err != nil { |
| + return false, ErrStorage |
| + } |
| + return true, nil |
| +} |
| + |
| func safePath(v string) string { |
| if handoff.SafePath(v) { |
| return v |
diff --git a/connect/navigation.go b/connect/navigation.go| index c3adc89..bae5b39 100644 |
| --- a/connect/navigation.go |
| +++ b/connect/navigation.go |
| @@ -4,6 +4,7 @@ import ( |
| "bytes" |
| "encoding/base64" |
| "encoding/json" |
| + "errors" |
| "math" |
| "net/http" |
| "net/url" |
| @@ -33,8 +34,22 @@ type localLinkNavigation struct { |
| fail func(http.ResponseWriter, *http.Request, int) |
| origin, host string |
| now func() time.Time |
| + // resume begins the link for the actual fresh local session and |
| + // redirects to the Home freshness check, or reports false having |
| + // written nothing (Bridge.resumeLink). |
| + resume func(http.ResponseWriter, *http.Request) bool |
| } |
| +// The marker's two actions. linkStart is the account menu's: after local |
| +// sign-in, show the Connect page. linkResume is remembered when an Oficina |
| +// assertion arrived that this app has no link for: after local sign-in, |
| +// begin the link at once, so the person lands on the confirm step rather |
| +// than hunting for the menu item. |
| +const ( |
| + linkStart = "link-start" |
| + linkResume = "link-resume" |
| +) |
| + |
| func newLocalLinkNavigation(sealer handoff.Sealer, c RoutesConfig) *localLinkNavigation { |
| u, err := url.Parse(c.Origin) |
| if err != nil || u.Scheme != "https" || u.Host == "" || u.User != nil || u.Path != "" || u.RawQuery != "" || u.Fragment != "" || sealer == nil || c.ReadSession == nil { |
| @@ -82,27 +97,54 @@ func (n *localLinkNavigation) Begin(w http.ResponseWriter, r *http.Request) { |
| } |
| localNavigationCookie(w, homeInitCookie, "", -1) |
| localNavigationCookie(w, homeProofCookie, "", -1) |
| - now := n.now().Unix() |
| - if now <= 0 || now > math.MaxInt64-localLinkNavigationLifetime { |
| + encoded, err := n.seal(linkStart) |
| + if errors.Is(err, errNavigationClock) { |
| http.Redirect(w, r, "/", http.StatusSeeOther) |
| return |
| } |
| - payload, _ := json.Marshal(localLinkMarker{Version: 1, Action: "link-start", Issued: now, Expires: now + localLinkNavigationLifetime}) |
| - sealed, err := n.sealer.Seal(n.purpose(), payload) |
| if err != nil { |
| n.fail(w, r, http.StatusServiceUnavailable) |
| return |
| } |
| + localNavigationCookie(w, localLinkNavigationCookie, encoded, int(localLinkNavigationLifetime)) |
| + http.Redirect(w, r, "/signin/local", http.StatusSeeOther) |
| +} |
| + |
| +var ( |
| + errNavigationClock = errors.New("home connect: navigation clock unusable") |
| + errNavigationSeal = errors.New("home connect: navigation marker unavailable") |
| +) |
| + |
| +// seal returns the encoded marker for action. |
| +func (n *localLinkNavigation) seal(action string) (string, error) { |
| + now := n.now().Unix() |
| + if now <= 0 || now > math.MaxInt64-localLinkNavigationLifetime { |
| + return "", errNavigationClock |
| + } |
| + payload, _ := json.Marshal(localLinkMarker{Version: 1, Action: action, Issued: now, Expires: now + localLinkNavigationLifetime}) |
| + sealed, err := n.sealer.Seal(n.purpose(), payload) |
| + if err != nil { |
| + return "", errNavigationSeal |
| + } |
| encoded := base64.RawURLEncoding.EncodeToString(sealed) |
| if len(encoded) > localLinkNavigationLimit { |
| - n.fail(w, r, http.StatusServiceUnavailable) |
| - return |
| + return "", errNavigationSeal |
| } |
| - localNavigationCookie(w, localLinkNavigationCookie, encoded, int(localLinkNavigationLifetime)) |
| - http.Redirect(w, r, "/signin/local", http.StatusSeeOther) |
| + return encoded, nil |
| } |
| -func (n *localLinkNavigation) marker(r *http.Request, now int64) bool { |
| +// rememberUnknown records, in the same sealed short-lived marker, that an |
| +// Oficina assertion arrived with no link here. It carries no identity: the |
| +// link is still bound to a fresh Home assertion and an explicit confirm, as |
| +// from the menu. Failing to seal costs only the shortcut. |
| +func (n *localLinkNavigation) rememberUnknown(w http.ResponseWriter) { |
| + if encoded, err := n.seal(linkResume); err == nil { |
| + localNavigationCookie(w, localLinkNavigationCookie, encoded, int(localLinkNavigationLifetime)) |
| + } |
| +} |
| + |
| +// marker returns the action of the one valid, unexpired marker, or "". |
| +func (n *localLinkNavigation) marker(r *http.Request, now int64) string { |
| value := "" |
| count := 0 |
| for _, c := range r.Cookies() { |
| @@ -112,32 +154,39 @@ func (n *localLinkNavigation) marker(r *http.Request, now int64) bool { |
| } |
| } |
| if count != 1 || value == "" || len(value) > localLinkNavigationLimit { |
| - return false |
| + return "" |
| } |
| sealed, err := base64.RawURLEncoding.Strict().DecodeString(value) |
| if err != nil || base64.RawURLEncoding.EncodeToString(sealed) != value { |
| - return false |
| + return "" |
| } |
| payload, err := n.sealer.Open(n.purpose(), sealed) |
| if err != nil || len(payload) > localLinkNavigationLimit { |
| - return false |
| + return "" |
| } |
| var marker localLinkMarker |
| if json.Unmarshal(payload, &marker) != nil { |
| - return false |
| + return "" |
| } |
| // Only this helper writes the payload. Exact re-encoding excludes duplicate |
| // and unknown fields, alternate numbers, and any trailing JSON value. |
| canonical, _ := json.Marshal(marker) |
| if !bytes.Equal(payload, canonical) { |
| - return false |
| + return "" |
| + } |
| + if marker.Version == 1 && (marker.Action == linkStart || marker.Action == linkResume) && marker.Issued > 0 && marker.Issued <= now && now < marker.Expires && marker.Expires > marker.Issued && marker.Expires-marker.Issued <= localLinkNavigationLifetime { |
| + return marker.Action |
| } |
| - return marker.Version == 1 && marker.Action == "link-start" && marker.Issued > 0 && marker.Issued <= now && now < marker.Expires && marker.Expires > marker.Issued && marker.Expires-marker.Issued <= localLinkNavigationLifetime |
| + return "" |
| } |
| // Complete reads the newly presented session after local verification. It |
| -// cannot initiate or confirm linking, and never treats a Home mint as local |
| -// proof. A copied marker can at most repeat navigation to the same page. |
| +// never confirms a link, and never treats a Home mint as local proof. With |
| +// a remembered unknown assertion it begins one, exactly as the Connect |
| +// button would, which is bound to this fresh session and still needs a |
| +// fresh Home assertion and an explicit same-origin confirm. A copied marker |
| +// can at most repeat that navigation. An expired marker is ignored: the |
| +// person lands as from any sign-in, with the menu item still on offer. |
| func (n *localLinkNavigation) Complete(w http.ResponseWriter, r *http.Request) { |
| localNavigationCookie(w, localLinkNavigationCookie, "", -1) |
| if !n.guard(w, r, localLinkCompletePath) { |
| @@ -145,7 +194,7 @@ func (n *localLinkNavigation) Complete(w http.ResponseWriter, r *http.Request) { |
| } |
| now := n.now() |
| target := n.landingPath |
| - if n.marker(r, now.Unix()) { |
| + if action := n.marker(r, now.Unix()); action != "" { |
| count := 0 |
| for _, c := range r.Cookies() { |
| if c.Name == n.sessionCookie { |
| @@ -155,6 +204,9 @@ func (n *localLinkNavigation) Complete(w http.ResponseWriter, r *http.Request) { |
| if count == 1 { |
| if session, err := n.readSession(r); err == nil && session != nil { |
| if _, fresh := FreshLocal(*session, now); fresh { |
| + if action == linkResume && n.resume != nil && n.resume(w, r) { |
| + return |
| + } |
| target = "/account/home" |
| } |
| } |
diff --git a/connect/navigation_test.go b/connect/navigation_test.go| index 5f9d42f..f87707d 100644 |
| --- a/connect/navigation_test.go |
| +++ b/connect/navigation_test.go |
| @@ -82,12 +82,12 @@ func TestNavigationPurposeIsolationAndFixedAction(t *testing.T) { |
| r.AddCookie(c) |
| } |
| } |
| - if !n.marker(r, n.now().Unix()) { |
| + if n.marker(r, n.now().Unix()) != linkStart { |
| t.Fatal("valid marker refused") |
| } |
| other := *n |
| other.namespace = "oficina/calls" |
| - if other.marker(r, n.now().Unix()) { |
| + if other.marker(r, n.now().Unix()) != "" { |
| t.Fatal("cross-app marker accepted") |
| } |
| for _, target := range []string{navigationOrigin + "/account/home?return_to=https://bad.test", "https://bad.test/account/home"} { |
diff --git a/connect/routes.go b/connect/routes.go| index 038b21f..a3ef883 100644 |
| --- a/connect/routes.go |
| +++ b/connect/routes.go |
| @@ -44,7 +44,9 @@ func NewRoutes(b *Bridge, c RoutesConfig) (*Routes, error) { |
| return nil, errors.New("home connect: invalid navigation") |
| } |
| n.now = b.now |
| + n.resume = b.resumeLink |
| b.returnPath = n.returnPath |
| + b.rememberUnknown = n.rememberUnknown |
| return &Routes{bridge: b, navigation: n, cfg: c}, nil |
| } |
diff --git a/connect/view.go b/connect/view.go| index c7736a2..d4bcfb8 100644 |
| --- a/connect/view.go |
| +++ b/connect/view.go |
| @@ -1,14 +1,27 @@ |
| package connect |
| import ( |
| - "amadan.net/oficina/estilo.git/homeconnect" |
| "embed" |
| + "net/http" |
| + |
| + "amadan.net/oficina/estilo.git/homeconnect" |
| + "amadan.net/oficina/home/handoff" |
| ) |
| func Templates() embed.FS { return homeconnect.Templates() } |
| type PageData = homeconnect.PageData |
| +// PageFor is Page for the request being answered. On "Accounts connected" |
| +// its way back is the page the link began from, where Page's is "/". |
| +func PageFor(r *http.Request, state, label string, translate ...func(string) string) PageData { |
| + p := Page(state, label, translate...) |
| + if back, ok := r.Context().Value(successReturnKey{}).(string); ok && state == "success" && handoff.SafePath(back) { |
| + p.Action = back |
| + } |
| + return p |
| +} |
| + |
| func Page(state, label string, translate ...func(string) string) PageData { |
| t := func(k string) string { return English[k] } |
| if len(translate) > 0 && translate[0] != nil { |
| @@ -50,10 +63,17 @@ func Page(state, label string, translate ...func(string) string) PageData { |
| // never names the hub: the account is "your Oficina account" (Paul, |
| // 2026-09-23), worded as Docs' approved docs.home.* strings are. The |
| // signed-out state speaks the door's words (estilo chrome.English). |
| +// |
| +// The confirm step must not read as the start page reloaded (Paul, |
| +// 2026-10-24): it has its own question for a title and says the Oficina |
| +// half is already done. The assertion carries an opaque subject and no |
| +// address, so the Oficina account cannot be named, only the local one. |
| +// The unknown state says what signing in will do, because it now does it: |
| +// local sign-in resumes the link (localLinkNavigation.Complete). |
| var English = map[string]string{ |
| "signedout_title": "You’re signed out", "signedout_body": "You can sign in again with your Oficina account.", "signedout_action": "Sign in", |
| "start_title": "Connect your Oficina account", "start_body": "Use your Oficina account to sign in to this account. Your content and sharing settings stay as they are.", "start_action": "Connect", "cancel_action": "Back", |
| - "confirm_title": "Confirm account connection", "confirm_body": "Connect the account below to the Oficina account you just signed in to.", "confirm_action": "Connect accounts", |
| - "unknown_title": "Oficina account not connected", "unknown_body": "Sign in to your existing account, then connect your Oficina account from the account menu.", "local_action": "Sign in to your existing account", |
| + "confirm_title": "Connect these two accounts?", "confirm_body": "Your Oficina account is confirmed. Connect it to the account below, and you can sign in to that account with Oficina from now on.", "confirm_action": "Connect accounts", |
| + "unknown_title": "Oficina account not connected", "unknown_body": "Sign in to your existing account once to connect it to your Oficina account.", "local_action": "Sign in to your existing account", |
| "failed_title": "Could not connect accounts", "failed_body": "Return to the app and start again.", "success_title": "Accounts connected", "success_body": "You can now use your Oficina account to sign in to this account.", "documents_action": "Back to the app", "menu_action": "Connect your Oficina account", |
| } |
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"> |