Move Docs onto rastrillo main fb806a2: confirm-then-spend links, the refusal hook
An emailed link now opens a confirm step drawn as Docs' sign-in door, with one Sign in button; GET spends nothing, and the button's POST to /auth/verify (now mounted) spends the link. A verified address the allowlist refuses gets the door with the refusal inside the 403 through auth.Config.Refused; doorOnRefusal, which matched rastrillo's bare text, is gone. Absorbed from a month of rastrillo: - auth.New needs Proof or ProofOff: ProofOff, as Docs has never had a proof-of-work door (rate limits plus the allowlist-gated mail queue). - The default CSP no longer allows inline styles, which Docs' pages use: Docs now sets its own policy (the old default) via ServeOptions, and a test serves real pages through rastrillo's production middleware. - Sessions.FromContext was only ever on feat-session-context, the branch Docs was pinned to: the team session reader now abandons From's answer when its context ends. - Tests sign in by POSTing the link's token with same-origin evidence; the browser drive presses the confirm button.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
26 files changed,
+593
−117
AGENTS.md+8 −2cmd/docs/main.go+1 −8fixtures/browser-drive.mjs+10 −2go.mod+4 −2go.sum+8 −4internal/docs/app.go+19 −4internal/docs/auth.go+29 −7internal/docs/auth_allowlist_test.go+1 −1internal/docs/auth_navigation.go+46 −39internal/docs/auth_test.go+5 −5internal/docs/errors_test.go+9 −4internal/docs/home_exchange_test.go+1 −1internal/docs/home_local_navigation_test.go+2 −2internal/docs/home_router_integration_test.go+8 −4internal/docs/home_security.go+37 −3internal/docs/home_security_test.go+9 −4internal/docs/identity_test.go+1 −1internal/docs/list_test.go+1 −1internal/docs/served_policy_test.go+105 −0internal/docs/signin_confirm_test.go+203 −0internal/docs/signin_loop_test.go+4 −2internal/docs/team_session_reader.go+28 −4internal/docs/testing.go+32 −4internal/docs/updates_test.go+1 −1internal/docs/views/signin.html+17 −6scripts/browser-drive.sh+4 −6
CI passed — run details
diff --git a/AGENTS.md b/AGENTS.md| index bb74ee4..fba97f0 100644 |
| --- a/AGENTS.md |
| +++ b/AGENTS.md |
| @@ -25,8 +25,14 @@ nothing about either is in your training data. |
| Every document route — `GET /`, `POST /documents`, `GET /d/{sqid}` — sits |
| behind rastrillo/auth's `RequireSession` and is unreachable without a real |
| session (`internal/docs/auth.go`). `POST /signin` uses Keymail OAuth when |
| -detected. Otherwise it emails (or, in development, logs) a single-use link; following it |
| -(`GET /auth/verify`) sets a real session cookie; `POST /signout` (in the shell |
| +detected. Otherwise it emails (or, in development, logs) a single-use link. Opening it |
| +(`GET /auth/verify`) draws a confirm step in the sign-in door and spends |
| +nothing, so mail scanners that fetch every link cannot sign anybody in; its |
| +one Sign in button POSTs the token back to `/auth/verify`, which spends it |
| +and sets a real session cookie (rastrillo `Config.RenderConfirm`). A |
| +verified address that is not admitted gets the door, with the refusal, in a |
| +403 (`Config.Refused`). Tests sign in by POSTing the link's token with |
| +same-origin evidence (`confirmRequest`, testing.go), never by GETting it; `POST /signout` (in the shell |
| bar's account menu on both signed-in screens) really revokes it, |
| not just clearing the cookie client-side. No passkey second factor is |
| wired, on purpose — spec §8.1's ruling: `passkey.Config.Origin` derives |
diff --git a/cmd/docs/main.go b/cmd/docs/main.go| index 0fdd9d5..22d2cb1 100644 |
| --- a/cmd/docs/main.go |
| +++ b/cmd/docs/main.go |
| @@ -334,14 +334,7 @@ func main() { |
| logger.Info("docs: seeded sample documents", "address", seedAddress) |
| } |
| - opts.Mux = app.Handler() |
| - // A panic outside the router's signed-in group (which has its own |
| - // recoverer) still gets the error page rather than plain text. |
| - opts.ErrorPage = app.ErrorPage |
| - opts.DBPath = "" |
| - opts.Locales = docs.Locales |
| - opts.DefaultLocale = docs.DefaultLocale |
| - opts.BaseCatalog = docs.Catalog |
| + opts = docs.ServeOptions(opts, app) |
| if err := rastrillo.Serve(opts); err != nil { |
| logger.Error("docs: serve", "err", err) |
diff --git a/fixtures/browser-drive.mjs b/fixtures/browser-drive.mjs| index b2f1494..424f178 100644 |
| --- a/fixtures/browser-drive.mjs |
| +++ b/fixtures/browser-drive.mjs |
| @@ -30,9 +30,9 @@ |
| // depends on to keep the selection alive while the button is pressed. |
| // A drive that fakes its input tests the fake. |
| -const [, , wsUrl, base] = process.argv |
| +const [, , wsUrl, base, signinLink] = process.argv |
| if (!wsUrl || !base) { |
| - console.error('usage: node browser-drive.mjs <devtools-ws-url> <base-url>') |
| + console.error('usage: node browser-drive.mjs <devtools-ws-url> <base-url> [sign-in-link]') |
| process.exit(2) |
| } |
| @@ -303,6 +303,14 @@ async function run() { |
| await send('Page.enable') |
| await send('Runtime.enable') |
| + // Sign in the way a person does: the emailed link opens the confirm |
| + // door, which spends nothing, and its one Sign in button posts it. |
| + if (signinLink) { |
| + await send('Page.navigate', { url: signinLink }) |
| + await sleep(1500) |
| + await clickSelector('form[action="/auth/verify"] button[type="submit"]') |
| + await sleep(1500) |
| + } |
| await send('Page.navigate', { url: base + '/' }) |
| await sleep(1500) |
| const href = await pickLongestDocument() |
diff --git a/go.mod b/go.mod| index f06c25c..8abdd1f 100644 |
| --- a/go.mod |
| +++ b/go.mod |
| @@ -7,7 +7,7 @@ require ( |
| amadan.net/oficina/home/handoff v0.0.0-20260908102137-481d2d57f489 |
| amadan.net/oficina/home/roster v0.0.0-20260908123429-74dda570e0cf |
| amadan.net/rastrillo/native/server v0.0.0-20260923173546-2a5d07b2c8d3 |
| - amadan.net/rastrillo/rastrillo v0.26.1-0.20260908132728-d9c28d708556 |
| + amadan.net/rastrillo/rastrillo v0.27.1-0.20261006204347-fb806a287060 |
| github.com/carlosframework/rastrillo v0.23.0 |
| github.com/chromedp/cdproto v0.0.0-20250724212937-08a3db8b4327 |
| github.com/chromedp/chromedp v0.14.2 |
| @@ -16,12 +16,13 @@ require ( |
| github.com/google/uuid v1.6.0 |
| github.com/keymaildev/signin v0.1.1 |
| github.com/tetratelabs/wazero v1.12.0 |
| - golang.org/x/text v0.20.0 |
| + golang.org/x/text v0.39.0 |
| gorm.io/gorm v1.31.2 |
| modernc.org/sqlite v1.55.0 |
| ) |
| require ( |
| + amadan.net/rastrillo/rastrillo/money v0.1.0 // indirect |
| github.com/BurntSushi/toml v1.6.0 // indirect |
| github.com/chromedp/sysutil v1.1.0 // indirect |
| github.com/dustin/go-humanize v1.0.1 // indirect |
| @@ -33,6 +34,7 @@ require ( |
| github.com/mattn/go-isatty v0.0.20 // indirect |
| github.com/ncruces/go-strftime v1.0.0 // indirect |
| github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect |
| + golang.org/x/mod v0.37.0 // indirect |
| golang.org/x/sys v0.46.0 // indirect |
| gorm.io/plugin/dbresolver v1.6.2 // indirect |
| modernc.org/libc v1.74.1 // indirect |
diff --git a/go.sum b/go.sum| index f0fc0b1..18f936f 100644 |
| --- a/go.sum |
| +++ b/go.sum |
| @@ -6,8 +6,10 @@ amadan.net/oficina/home/roster v0.0.0-20260908123429-74dda570e0cf h1:SRKjCUgtk42 |
| amadan.net/oficina/home/roster v0.0.0-20260908123429-74dda570e0cf/go.mod h1:gqshuXyDtFZUCYbhuZyV3Epc51pUcsLbpqAqiA5UiXg= |
| amadan.net/rastrillo/native/server v0.0.0-20260923173546-2a5d07b2c8d3 h1:5EFx7BLJj/+G/rt8bTmeyMWVfF5s5Sns7ajTvX4w/I8= |
| amadan.net/rastrillo/native/server v0.0.0-20260923173546-2a5d07b2c8d3/go.mod h1:ZaaxeE278dJltdrLwmwpxUjQ5wuKzqDAVSNRet+WupY= |
| -amadan.net/rastrillo/rastrillo v0.26.1-0.20260908132728-d9c28d708556 h1:/vHMeq9T+PZmUACixGkg32YEjyM8s31+bfAqqrMha0A= |
| -amadan.net/rastrillo/rastrillo v0.26.1-0.20260908132728-d9c28d708556/go.mod h1:RpyHVPD0udcSfHJroY0KZE/FUjgw6Tvfo8SJm2qeZGE= |
| +amadan.net/rastrillo/rastrillo v0.27.1-0.20261006204347-fb806a287060 h1:K2PXcCKfm+AYrqgH1ea6cNsFs4sN7MKLvq+uBY11NZE= |
| +amadan.net/rastrillo/rastrillo v0.27.1-0.20261006204347-fb806a287060/go.mod h1:WmC8TAIfqjAkSwmD+FCTqr7VuqAO5FaX03HlV49K608= |
| +amadan.net/rastrillo/rastrillo/money v0.1.0 h1:MxU4oqNrW8abxRTkgZBv24OYNpFnvonajNqeLIzmmaM= |
| +amadan.net/rastrillo/rastrillo/money v0.1.0/go.mod h1:cmgkjBEIQh1pFSYvQk0UU6oPYS8kSDypdT9+t4Flx0U= |
| github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk= |
| github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho= |
| github.com/carlosframework/rastrillo v0.23.0 h1:tKAAlwPt4Pg/rkqk7o6jvV12bbZ0r34oEVpuOlKfX7w= |
| @@ -56,6 +58,8 @@ github.com/orisano/pixelmatch v0.0.0-20220722002657-fb0b55479cde h1:x0TT0RDC7UhA |
| github.com/orisano/pixelmatch v0.0.0-20220722002657-fb0b55479cde/go.mod h1:nZgzbfBr3hhjoZnS66nKrHmduYNpc34ny7RK4z5/HM0= |
| github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= |
| github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= |
| +github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e h1:MRM5ITcdelLK2j1vwZ3Je0FKVCfqOLp5zO6trqMLYs0= |
| +github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e/go.mod h1:XV66xRDqSt+GTGFMVlhk3ULuV0y9ZmzeVGR4mloJI3M= |
| github.com/tetratelabs/wazero v1.12.0 h1:DuWcpNu/FzgEXgGBDp8J1Spc+CWOvvtvVyjKlaZopYU= |
| github.com/tetratelabs/wazero v1.12.0/go.mod h1:LvKtzl2RqO4gyF27BiXU+nKAjcV8f38U+kP/q2vgxh0= |
| golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ= |
| @@ -65,8 +69,8 @@ golang.org/x/sync v0.21.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= |
| golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= |
| golang.org/x/sys v0.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw= |
| golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= |
| -golang.org/x/text v0.20.0 h1:gK/Kv2otX8gz+wn7Rmb3vT96ZwuoxnQlY+HlJVj7Qug= |
| -golang.org/x/text v0.20.0/go.mod h1:D4IsuqiFMhST5bX19pQ9ikHC2GsaKyk/oF+pn3ducp4= |
| +golang.org/x/text v0.39.0 h1:UbZz4pLOvn600D6Oh6GGEI6VAmndrEBLv8/6BEXzyus= |
| +golang.org/x/text v0.39.0/go.mod h1:3UwRclnC2g0TU9x8PZiyfOajCd1zaUNHF9cvqcQZ+ZM= |
| golang.org/x/tools v0.47.0 h1:7Kn5x/d1svx/PzryTsqeoZN4TZwqeH5pGWjefhLi/1Q= |
| golang.org/x/tools v0.47.0/go.mod h1:dFHnyTvFWY212G+h7ZY4Vsp/K3U4/7W9TyVaAul8uCA= |
| gorm.io/driver/mysql v1.5.7 h1:MndhOPYOfEp2rHKgkZIhJ16eVUIRf2HmzgoPmh7FCWo= |
diff --git a/internal/docs/app.go b/internal/docs/app.go| index 548e0b7..27f33b5 100644 |
| --- a/internal/docs/app.go |
| +++ b/internal/docs/app.go |
| @@ -27,6 +27,7 @@ import ( |
| "amadan.net/oficina/home/handoff" |
| nativeauth "amadan.net/rastrillo/native/server" |
| "amadan.net/rastrillo/rastrillo" |
| + rauth "amadan.net/rastrillo/rastrillo/auth" |
| "amadan.net/rastrillo/rastrillo/db" |
| "amadan.net/rastrillo/rastrillo/mail" |
| "amadan.net/rastrillo/rastrillo/migrate" |
| @@ -472,7 +473,14 @@ func New(cfg Config) (*App, error) { |
| signinMail.close() |
| } |
| }() |
| - authPlugin, err := newAuthPlugin(cfg, d.Writer(), instanceKey, signinMail, list, logger) |
| + // h is built below, after the plugin it wraps; the door rastrillo |
| + // calls back into is bound to it late. |
| + var h *handlers |
| + door := signinDoor{ |
| + refused: func(w http.ResponseWriter, r *http.Request) { h.signinRefused(w, r) }, |
| + confirm: func(w http.ResponseWriter, r *http.Request, d rauth.ConfirmPageData) { h.confirmSignin(w, r, d) }, |
| + } |
| + authPlugin, err := newAuthPlugin(cfg, d.Writer(), instanceKey, signinMail, list, logger, door) |
| if err != nil { |
| rt.Close(context.Background()) |
| d.Close() |
| @@ -485,7 +493,7 @@ func New(cfg Config) (*App, error) { |
| d.Close() |
| return nil, err |
| } |
| - h := &handlers{render: render, logger: logger, store: store, hub: newHub(), previews: newPreviews(), origin: cfg.Origin, isMember: list.configured, oneShots: newOneShots(), directory: directory} |
| + h = &handlers{render: render, logger: logger, store: store, hub: newHub(), previews: newPreviews(), origin: cfg.Origin, isMember: list.configured, oneShots: newOneShots(), directory: directory} |
| render.frame = h.frame |
| // peek: the viewer on routes no session guards (chrome.go). Standalone |
| // reads rastrillo/auth's own cookie; with Home, the Home bridge's. |
| @@ -603,8 +611,15 @@ func New(cfg Config) (*App, error) { |
| // the menu was open cannot turn the click into a sign-in loop. |
| r.Post("/appearance", chrome.HandleAppearance) |
| r.Post("/signin", h.beginSignin(authPlugin.Begin)) |
| - r.Get("/auth/callback", localAuthGuard(home, doorOnRefusal(authPlugin.Callback, h.signin))) |
| - r.Get("/auth/verify", localAuthGuard(home, doorOnRefusal(authPlugin.Verify, h.signin))) |
| + // An emailed link opens GET /auth/verify, which only draws the |
| + // confirm door (h.confirmSignin); its Sign in button POSTs the token |
| + // back, and the POST spends it. Without the POST nobody signs in by |
| + // email. Both sit inside the app-wide CSRF check, which the POST must |
| + // pass like any other form. A refused address gets the door in a 403 |
| + // (h.signinRefused), from either route. |
| + r.Get("/auth/callback", localAuthGuard(home, authPlugin.Callback)) |
| + r.Get("/auth/verify", localAuthGuard(home, authPlugin.Verify)) |
| + r.Post("/auth/verify", localAuthGuard(home, authPlugin.Verify)) |
| // The published document, and the only route here no session guards. |
| // It is authorized by the token in its own path (links.go) rather |
| // than by who is asking — which is what a capability is, and why it |
diff --git a/internal/docs/auth.go b/internal/docs/auth.go| index 9661838..63cae18 100644 |
| --- a/internal/docs/auth.go |
| +++ b/internal/docs/auth.go |
| @@ -404,7 +404,18 @@ func requireAdmissionOf(list allowlist, signinPath string, identity func(*http.R |
| // say "could not tell" and refusing is the safe answer here. |
| // Delivery and callback admission are checked independently. No local passkey |
| // second factor is enrolled; Keymail verifies credentials at its own origin. |
| -func newAuthPlugin(cfg Config, writer *sql.DB, instanceKey string, mailer mail.Sender, list allowlist, logger *slog.Logger) (*rauth.Auth, error) { |
| +// |
| +// door draws the two pages rastrillo hands back to the app: Refused, a |
| +// verified address the allowlist does not hold, and RenderConfirm, the |
| +// page an emailed link opens (GET /auth/verify), whose one Sign in button |
| +// POSTs the token back to spend it. Both are the sign-in door. |
| +// |
| +// ProofOff: Docs has never put a proof-of-work front door on POST |
| +// /signin. Its abuse controls are rastrillo's per-address and per-IP rate |
| +// limits and the allowlist-gated mail queue, which never delivers to an |
| +// address it does not hold. rastrillo now refuses to start without the |
| +// choice being made, and this keeps today's behaviour. |
| +func newAuthPlugin(cfg Config, writer *sql.DB, instanceKey string, mailer mail.Sender, list allowlist, logger *slog.Logger, door signinDoor) (*rauth.Auth, error) { |
| // Both modes land on /auth/local/complete, which sends a person to |
| // the page they came from (signin_return.go), since Verify itself can |
| // only land on one fixed path. |
| @@ -417,6 +428,13 @@ func newAuthPlugin(cfg Config, writer *sql.DB, instanceKey string, mailer mail.S |
| Authorize: list.admits, |
| Logger: logger, |
| Subject: chrome.EmailSubject("Docs"), |
| + ProofOff: true, |
| + Refused: func(w http.ResponseWriter, r *http.Request, _ rauth.Identity) { |
| + door.refused(w, r) |
| + }, |
| + RenderConfirm: func(w http.ResponseWriter, r *http.Request, d rauth.ConfirmPageData) { |
| + door.confirm(w, r, d) |
| + }, |
| }) |
| } |
| @@ -425,17 +443,20 @@ func newAuthPlugin(cfg Config, writer *sql.DB, instanceKey string, mailer mail.S |
| // §5/magic-links.md: "the sign-in page stays yours" — they report |
| // outcomes by redirecting back here with a query this handler reads. |
| // |
| -// Exactly one of Form, Sent and ContinueURL is set: the form (estilo's |
| -// estilo-signin), the check-your-email state that replaces it |
| -// (estilo-signin-sent), or the Keymail continuation (auth_navigation.go). |
| +// Exactly one of Form, Sent, Confirm and ContinueURL is set: the form |
| +// (estilo's estilo-signin), the check-your-email state that replaces it |
| +// (estilo-signin-sent), the emailed link's confirm step |
| +// (auth_navigation.go), or the Keymail continuation (auth_navigation.go). |
| type signinPage struct { |
| Frame Frame |
| Form *chrome.SignIn |
| Sent *chrome.SignInNotice |
| + Confirm *signinConfirm |
| ContinueURL string |
| SubmitLabel string |
| - // Door heads the continuation card (Icon, App, Sky), so the moment |
| - // between the form and Keymail looks like the same door. |
| + // Door heads the continuation and confirm cards (Icon, App, Sky), so |
| + // the moment between the form and Keymail, and the page an emailed |
| + // link opens, look like the same door. |
| Door chrome.SignInNotice |
| } |
| @@ -514,7 +535,8 @@ func (h *handlers) signin(w http.ResponseWriter, r *http.Request) { |
| } |
| if refusedHere(r) { |
| // Keymail or a link verified the address and the allowlist |
| - // does not hold it, in this very response (doorOnRefusal). |
| + // does not hold it, in this very response (Config.Refused, |
| + // auth_navigation.go's refused). |
| // Never from the query. The form is the way on. |
| form.Error = rastrillo.T(r, "docs.signin.error.refused") |
| } |
diff --git a/internal/docs/auth_allowlist_test.go b/internal/docs/auth_allowlist_test.go| index 118a53d..d29f6b3 100644 |
| --- a/internal/docs/auth_allowlist_test.go |
| +++ b/internal/docs/auth_allowlist_test.go |
| @@ -159,7 +159,7 @@ func TestPermittedAddressStillSignsIn(t *testing.T) { |
| t.Fatalf("TestSignIn: %v", err) |
| } |
| - verifyReq := httptest.NewRequest(http.MethodGet, link, nil) |
| + verifyReq := confirmRequest(link) |
| verifyRec := httptest.NewRecorder() |
| app.Handler().ServeHTTP(verifyRec, verifyReq) |
| cookies := verifyRec.Result().Cookies() |
diff --git a/internal/docs/auth_navigation.go b/internal/docs/auth_navigation.go| index 3cb31d6..707069b 100644 |
| --- a/internal/docs/auth_navigation.go |
| +++ b/internal/docs/auth_navigation.go |
| @@ -11,6 +11,7 @@ import ( |
| "strings" |
| "amadan.net/rastrillo/rastrillo" |
| + rauth "amadan.net/rastrillo/rastrillo/auth" |
| ) |
| // End the POST with a document before navigating to an identity provider. |
| @@ -96,55 +97,61 @@ func (w *signinResponse) Write(p []byte) (int, error) { |
| return w.body.Write(p) |
| } |
| -// authRefusal is the bare-text body rastrillo/auth's admit() writes, |
| -// with a 403, when a verified address is not admitted. rastrillo at the |
| -// version pinned here has no hook to render anything else, so |
| -// doorOnRefusal recognises this exact answer; |
| -// TestKeymailOAuthActualIntegration pins it, so a bump that changes the |
| -// sentence fails loudly. |
| -const authRefusal = "This address is verified but not admitted here." |
| +// signinDoor is what rastrillo/auth calls back into for the two pages it |
| +// hands to the app (newAuthPlugin). The plugin is built before the |
| +// handlers, so these are bound late, by New. |
| +type signinDoor struct { |
| + refused func(http.ResponseWriter, *http.Request) |
| + confirm func(http.ResponseWriter, *http.Request, rauth.ConfirmPageData) |
| +} |
| -// doorOnRefusal wraps rastrillo's Callback and Verify, the handlers that |
| -// end in admission, and turns its bare-text refusal into the sign-in |
| -// door, rendered in the refusal's own 403 by door (h.signin) with the |
| -// refusal marked on the request context (refusedHere). Every other |
| -// answer, cookies included, passes through untouched. |
| +// signinRefused is Config.Refused: Keymail or an emailed link verified |
| +// an address the allowlist does not hold. It answers with the door, in a |
| +// 403, with the refusal marked on the request context (refusedHere), so |
| +// the form is the way on. rastrillo has already set any cookies the |
| +// attempt clears. |
| // |
| // Rendered, not redirected to ?err=refused: a query parameter is |
| // something anybody can type, and the sentence means "you proved this |
| // address and it is not admitted". Only someone who has just verified |
| -// the address reaches it, so it is no oracle. Remove it when rastrillo |
| -// has a refusal hook (feat/auth-refused-hook) and the pin is bumped. |
| -func doorOnRefusal(next, door http.HandlerFunc) http.HandlerFunc { |
| - return func(w http.ResponseWriter, r *http.Request) { |
| - rec := &signinResponse{header: make(http.Header)} |
| - next(rec, r) |
| - if rec.status == http.StatusForbidden && strings.TrimSpace(rec.body.String()) == authRefusal { |
| - for _, c := range rec.header.Values("Set-Cookie") { |
| - w.Header().Add("Set-Cookie", c) |
| - } |
| - w.Header().Set("Cache-Control", "no-store") |
| - door(&forcedStatus{ResponseWriter: w, status: http.StatusForbidden}, |
| - r.WithContext(context.WithValue(r.Context(), refusedKey{}, true))) |
| - return |
| - } |
| - for name, values := range rec.header { |
| - for _, v := range values { |
| - w.Header().Add(name, v) |
| - } |
| - } |
| - if rec.status == 0 { |
| - rec.status = http.StatusOK |
| - } |
| - w.WriteHeader(rec.status) |
| - _, _ = w.Write(rec.body.Bytes()) |
| +// the address reaches it, so it is no oracle. |
| +func (h *handlers) signinRefused(w http.ResponseWriter, r *http.Request) { |
| + w.Header().Set("Cache-Control", "no-store") |
| + h.signin(&forcedStatus{ResponseWriter: w, status: http.StatusForbidden}, |
| + r.WithContext(context.WithValue(r.Context(), refusedKey{}, true))) |
| +} |
| + |
| +// signinConfirm is the emailed link's confirm step: the door with one |
| +// Sign in button that POSTs the token back to /auth/verify, where |
| +// rastrillo spends it. The GET spends nothing, so a mail scanner that |
| +// fetches every link cannot sign anybody in. |
| +type signinConfirm struct { |
| + Heading, Submit string |
| + Action, Token string |
| +} |
| + |
| +// confirmSignin is Config.RenderConfirm. rastrillo has already set |
| +// no-store, Referrer-Policy strict-origin (the page's URL is a live |
| +// credential) and the framing refusals; nothing here may loosen them. |
| +// The words are estilo's door copy: the heading and the button are the |
| +// form's own "Sign in", so the step reads as the door, not a new page. |
| +func (h *handlers) confirmSignin(w http.ResponseWriter, r *http.Request, d rauth.ConfirmPageData) { |
| + door := chrome.SignIn{} |
| + data := signinPage{ |
| + Frame: h.frame(r, frameOptions{titleParts: []string{door.Page()}, signinPage: true}), |
| + Confirm: &signinConfirm{Heading: door.Heading(), Submit: door.Submit(), Action: d.Action, Token: d.Token}, |
| + Door: chrome.SignInNotice{Icon: brand.Path("docs"), App: "Docs", Sky: sky.For(r.Host)}, |
| + } |
| + if err := h.render.page(w, r, "signin", data); err != nil { |
| + h.logger.Error("docs: render sign-in confirm", "err", err) |
| + h.fail(w, r, http.StatusInternalServerError, failStatus) |
| } |
| } |
| -// refusedKey marks a request doorOnRefusal is answering with the door. |
| +// refusedKey marks a request signinRefused is answering with the door. |
| type refusedKey struct{} |
| -// refusedHere reports whether r is a refusal doorOnRefusal is rendering. |
| +// refusedHere reports whether r is a refusal signinRefused is rendering. |
| func refusedHere(r *http.Request) bool { |
| v, _ := r.Context().Value(refusedKey{}).(bool) |
| return v |
diff --git a/internal/docs/auth_test.go b/internal/docs/auth_test.go| index f021e8d..e2d404a 100644 |
| --- a/internal/docs/auth_test.go |
| +++ b/internal/docs/auth_test.go |
| @@ -59,7 +59,7 @@ func TestMagicLinkSignsSomebodyIn(t *testing.T) { |
| t.Fatalf("TestSignIn: %v", err) |
| } |
| // Following the link must establish a session. |
| - req := httptest.NewRequest(http.MethodGet, link, nil) |
| + req := app.TestConfirmRequest(link) |
| rec := httptest.NewRecorder() |
| app.Handler().ServeHTTP(rec, req) |
| if len(rec.Result().Cookies()) == 0 { |
| @@ -82,7 +82,7 @@ func TestMagicLinkThenSignedInRouteWorks(t *testing.T) { |
| t.Fatalf("TestSignIn: %v", err) |
| } |
| - verifyReq := httptest.NewRequest(http.MethodGet, link, nil) |
| + verifyReq := app.TestConfirmRequest(link) |
| verifyRec := httptest.NewRecorder() |
| app.Handler().ServeHTTP(verifyRec, verifyReq) |
| cookies := verifyRec.Result().Cookies() |
| @@ -137,7 +137,7 @@ func TestSignOutEndsTheSession(t *testing.T) { |
| if err != nil { |
| t.Fatalf("TestSignIn: %v", err) |
| } |
| - verifyReq := httptest.NewRequest(http.MethodGet, link, nil) |
| + verifyReq := app.TestConfirmRequest(link) |
| verifyRec := httptest.NewRecorder() |
| app.Handler().ServeHTTP(verifyRec, verifyReq) |
| cookies := verifyRec.Result().Cookies() |
| @@ -220,14 +220,14 @@ func TestSecondClickOfTheSameMagicLinkOffersRecovery(t *testing.T) { |
| t.Fatalf("TestSignIn: %v", err) |
| } |
| - firstReq := httptest.NewRequest(http.MethodGet, link, nil) |
| + firstReq := app.TestConfirmRequest(link) |
| firstRec := httptest.NewRecorder() |
| app.Handler().ServeHTTP(firstRec, firstReq) |
| if len(firstRec.Result().Cookies()) == 0 { |
| t.Fatal("first click set no session cookie") |
| } |
| - secondReq := httptest.NewRequest(http.MethodGet, link, nil) |
| + secondReq := app.TestConfirmRequest(link) |
| secondRec := httptest.NewRecorder() |
| app.Handler().ServeHTTP(secondRec, secondReq) |
| loc := secondRec.Header().Get("Location") |
diff --git a/internal/docs/errors_test.go b/internal/docs/errors_test.go| index 26d3b82..5131c2c 100644 |
| --- a/internal/docs/errors_test.go |
| +++ b/internal/docs/errors_test.go |
| @@ -33,7 +33,7 @@ func signedInForTest(t *testing.T, app *App, address string) []*http.Cookie { |
| t.Fatal(err) |
| } |
| rec := httptest.NewRecorder() |
| - app.Handler().ServeHTTP(rec, httptest.NewRequest(http.MethodGet, link, nil)) |
| + app.Handler().ServeHTTP(rec, confirmRequest(link)) |
| return rec.Result().Cookies() |
| } |
| @@ -303,9 +303,13 @@ func TestSigningInReturnsToTheDeepLink(t *testing.T) { |
| deep := created.Header().Get("Location") + "?view=1" |
| jar := map[string]*http.Cookie{} |
| - do := func(method, path string) *httptest.ResponseRecorder { |
| + do := func(method, path string, form ...string) *httptest.ResponseRecorder { |
| // The landing checks the Host, so ask it the way a browser would. |
| - req := httptest.NewRequest(method, DefaultOrigin+path, nil) |
| + req := httptest.NewRequest(method, DefaultOrigin+path, strings.NewReader(strings.Join(form, ""))) |
| + if method == http.MethodPost { |
| + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| + req.Header.Set("Sec-Fetch-Site", "same-origin") |
| + } |
| for _, c := range jar { |
| req.AddCookie(c) |
| } |
| @@ -332,7 +336,8 @@ func TestSigningInReturnsToTheDeepLink(t *testing.T) { |
| if err != nil { |
| t.Fatal(err) |
| } |
| - verified := do("GET", link) |
| + verifyPath, verifyForm := confirmForm(link) |
| + verified := do("POST", verifyPath, verifyForm) |
| if verified.Header().Get("Location") != localLinkCompletePath { |
| t.Fatalf("the link landed on %q, not %s", verified.Header().Get("Location"), localLinkCompletePath) |
| } |
diff --git a/internal/docs/home_exchange_test.go b/internal/docs/home_exchange_test.go| index 68ff9ca..72dd595 100644 |
| --- a/internal/docs/home_exchange_test.go |
| +++ b/internal/docs/home_exchange_test.go |
| @@ -44,7 +44,7 @@ func newBridgeFixture(t *testing.T) *bridgeFixture { |
| t.Fatal(err) |
| } |
| settings := &homeSettings{issuer: bridgeIssuer, consumerID: "blue-docs", keys: map[string][]byte{"key": key.SignPub()}, dek: bytes.Repeat([]byte{41}, 32)} |
| - auth, err := rauth.New(rauth.Config{DB: app.db.Writer(), Origin: bridgeOrigin, InstanceKey: devInstanceKey, Logger: app.logger}) |
| + auth, err := rauth.New(rauth.Config{DB: app.db.Writer(), Origin: bridgeOrigin, InstanceKey: devInstanceKey, Logger: app.logger, ProofOff: true}) |
| if err != nil { |
| t.Fatal(err) |
| } |
diff --git a/internal/docs/home_local_navigation_test.go b/internal/docs/home_local_navigation_test.go| index 5299f88..c9a6d1a 100644 |
| --- a/internal/docs/home_local_navigation_test.go |
| +++ b/internal/docs/home_local_navigation_test.go |
| @@ -182,7 +182,7 @@ func TestLocalNavigationUsesActualFreshSessionMethod(t *testing.T) { |
| func TestLocalNavigationRealEmailRotationAndChangedAccount(t *testing.T) { |
| app, n := navigationFixture(t) |
| // This plugin differs only in its configured successful local landing. |
| - plugin, err := rauth.New(rauth.Config{DB: app.db.Writer(), Origin: navigationOrigin, InstanceKey: devInstanceKey, Mailer: app.mailRecorder, SignedInPath: localLinkCompletePath}) |
| + plugin, err := rauth.New(rauth.Config{DB: app.db.Writer(), Origin: navigationOrigin, InstanceKey: devInstanceKey, Mailer: app.mailRecorder, SignedInPath: localLinkCompletePath, ProofOff: true}) |
| if err != nil { |
| t.Fatal(err) |
| } |
| @@ -198,7 +198,7 @@ func TestLocalNavigationRealEmailRotationAndChangedAccount(t *testing.T) { |
| if err != nil { |
| t.Fatal(err) |
| } |
| - verify := httptest.NewRequest("GET", link, nil) |
| + verify := confirmRequest(link) |
| verify.AddCookie(old) |
| rec := httptest.NewRecorder() |
| plugin.Verify(rec, verify) |
diff --git a/internal/docs/home_router_integration_test.go b/internal/docs/home_router_integration_test.go| index d5e3772..bc649e4 100644 |
| --- a/internal/docs/home_router_integration_test.go |
| +++ b/internal/docs/home_router_integration_test.go |
| @@ -130,7 +130,8 @@ func (b *routerBrowser) localSignin(t *testing.T, address string, landing ...str |
| want = landing[0] |
| } |
| path := b.localLink(t, address) |
| - rec := b.do("GET", path, "") |
| + verifyPath, verifyForm := confirmForm(path) |
| + rec := b.do("POST", verifyPath, verifyForm) |
| routerRedirect(t, rec, localLinkCompletePath) |
| routerRedirect(t, b.do("GET", localLinkCompletePath, ""), want) |
| if _, ok := b.cookies[b.f.sessions.CookieName()]; !ok { |
| @@ -383,7 +384,8 @@ func TestHomeRouterRejectsDuplicateCookiesBeforeActualEmailVerification(t *testi |
| old := b.cookies[f.sessions.CookieName()] |
| path := b.localLink(t, "alice@example.com") |
| for _, name := range []string{f.sessions.CookieName(), "__Host-rastrillo_pending"} { |
| - r := b.request("GET", path, "") |
| + verifyPath, verifyForm := confirmForm(path) |
| + r := b.request("POST", verifyPath, verifyForm) |
| if name == f.sessions.CookieName() { |
| r.AddCookie(old) |
| } else { |
| @@ -402,7 +404,8 @@ func TestHomeRouterRejectsDuplicateCookiesBeforeActualEmailVerification(t *testi |
| } |
| } |
| // Both refusals happened before CompleteMagicLink consumed the token. |
| - routerRedirect(t, b.do("GET", path, ""), localLinkCompletePath) |
| + verifyPath, verifyForm := confirmForm(path) |
| + routerRedirect(t, b.do("POST", verifyPath, verifyForm), localLinkCompletePath) |
| if b.cookies[f.sessions.CookieName()].Value == old.Value { |
| t.Fatal("clean real Verify did not rotate cookie") |
| } |
| @@ -437,7 +440,8 @@ func TestHomeRouterStaleLocalGestureRestartsWithoutResumingProof(t *testing.T) { |
| t.Fatal("signed-in stale visitor could not see local signin") |
| } |
| path := b.localLink(t, "alice@example.com") |
| - routerRedirect(t, b.do("GET", path, ""), localLinkCompletePath) |
| + verifyPath, verifyForm := confirmForm(path) |
| + routerRedirect(t, b.do("POST", verifyPath, verifyForm), localLinkCompletePath) |
| routerRedirect(t, b.do("GET", localLinkCompletePath, ""), "/account/home") |
| if b.cookies[f.sessions.CookieName()].Value == oldSession.Value || b.cookies[homeProofCookie] != nil || b.cookies[homeInitCookie] != nil || routerRows(t, f, "docs_identity_links") != 0 { |
| t.Fatal("navigation minted or resumed link authority") |
diff --git a/internal/docs/home_security.go b/internal/docs/home_security.go| index 5ef7b0d..963f111 100644 |
| --- a/internal/docs/home_security.go |
| +++ b/internal/docs/home_security.go |
| @@ -1,9 +1,43 @@ |
| package docs |
| +import "amadan.net/rastrillo/rastrillo" |
| + |
| +// ContentSecurityPolicy is the policy Docs serves (cmd/docs sets it as |
| +// rastrillo.Options.CSP). It is rastrillo's default as of the |
| +// 2026-09-08 pin, which allowed inline styles. rastrillo's default |
| +// dropped 'unsafe-inline' from style-src on 2026-09-13 (c7e1a09), and |
| +// Docs draws its pages with <style> blocks (list, show, share, the |
| +// jump-to partial) and one style attribute (home_link.html); under the |
| +// new default every one of them is blocked and the app renders |
| +// unstyled, with no error anywhere. Moving them to stylesheets is its |
| +// own piece of work; until then this keeps Docs' behaviour exactly as |
| +// it was. |
| +const ContentSecurityPolicy = "default-src 'self'; style-src 'self' 'unsafe-inline'; " + |
| + "img-src 'self' data:; frame-ancestors 'none'; base-uri 'self'; form-action 'self'" |
| + |
| // Browsers enforce form-action through a form's redirect chain. Linking starts |
| // with a local POST and reaches Home; allow only the validated credential origin. |
| -// The drift test pins every other directive to the framework's actual default. |
| +// The drift test pins every other directive to ContentSecurityPolicy. |
| func homeFormPolicy(issuer string) string { |
| - return "default-src 'self'; style-src 'self' 'unsafe-inline'; " + |
| - "img-src 'self' data:; frame-ancestors 'none'; base-uri 'self'; form-action 'self' " + issuer |
| + return ContentSecurityPolicy + " " + issuer |
| +} |
| + |
| +// ServeOptions fills in what cmd/docs hands rastrillo.Serve for this |
| +// app: the router, the error page, the locales and catalog, and the |
| +// policy above. One function, so the test that serves pages through |
| +// rastrillo's production middleware (TestServedPolicyAllowsThePagesInlineStyles) |
| +// serves them exactly as the binary does. |
| +func ServeOptions(opts rastrillo.Options, app *App) rastrillo.Options { |
| + opts.Mux = app.Handler() |
| + // A panic outside the router's signed-in group (which has its own |
| + // recoverer) still gets the error page rather than plain text. |
| + opts.ErrorPage = app.ErrorPage |
| + opts.DBPath = "" |
| + opts.Locales = Locales |
| + opts.DefaultLocale = DefaultLocale |
| + opts.BaseCatalog = Catalog |
| + // Docs' own policy, not rastrillo's default, which no longer allows |
| + // the inline styles Docs' pages are drawn with (see its comment). |
| + opts.CSP = ContentSecurityPolicy |
| + return opts |
| } |
diff --git a/internal/docs/home_security_test.go b/internal/docs/home_security_test.go| index 8bc59c2..5b154a1 100644 |
| --- a/internal/docs/home_security_test.go |
| +++ b/internal/docs/home_security_test.go |
| @@ -10,9 +10,11 @@ import ( |
| ) |
| func TestHomeFormPolicyPreservesFrameworkAndStandalone(t *testing.T) { |
| + // Served the way cmd/docs serves it: rastrillo's handler with Docs' |
| + // own policy (ContentSecurityPolicy) in place of the default. |
| mux := http.NewServeMux() |
| mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(200) }) |
| - baselineHandler, cleanup, err := rastrillo.Handler(rastrillo.Options{Mux: mux}) |
| + baselineHandler, cleanup, err := rastrillo.Handler(rastrillo.Options{Mux: mux, CSP: ContentSecurityPolicy}) |
| if err != nil { |
| t.Fatal(err) |
| } |
| @@ -22,12 +24,15 @@ func TestHomeFormPolicyPreservesFrameworkAndStandalone(t *testing.T) { |
| rec := httptest.NewRecorder() |
| baselineHandler.ServeHTTP(rec, httptest.NewRequest("GET", bridgeOrigin+"/", nil)) |
| baseline := rec.Header().Get("Content-Security-Policy") |
| + if baseline != ContentSecurityPolicy { |
| + t.Fatalf("rastrillo did not serve Options.CSP as given: %q", baseline) |
| + } |
| want := strings.Replace(baseline, "form-action 'self'", "form-action 'self' "+bridgeIssuer, 1) |
| if want == baseline { |
| - t.Fatal("framework form-action changed; review policy") |
| + t.Fatal("form-action changed; review policy") |
| } |
| f := newRouterHomeFixture(t) |
| - wrapped, done, err := rastrillo.Handler(rastrillo.Options{Mux: f.app.Handler()}) |
| + wrapped, done, err := rastrillo.Handler(rastrillo.Options{Mux: f.app.Handler(), CSP: ContentSecurityPolicy}) |
| if err != nil { |
| t.Fatal(err) |
| } |
| @@ -45,7 +50,7 @@ func TestHomeFormPolicyPreservesFrameworkAndStandalone(t *testing.T) { |
| if err != nil { |
| t.Fatal(err) |
| } |
| - standalone, closeStandalone, err := rastrillo.Handler(rastrillo.Options{Mux: app.Handler()}) |
| + standalone, closeStandalone, err := rastrillo.Handler(rastrillo.Options{Mux: app.Handler(), CSP: ContentSecurityPolicy}) |
| if err != nil { |
| t.Fatal(err) |
| } |
diff --git a/internal/docs/identity_test.go b/internal/docs/identity_test.go| index 48d5447..ea5a9a2 100644 |
| --- a/internal/docs/identity_test.go |
| +++ b/internal/docs/identity_test.go |
| @@ -257,7 +257,7 @@ func TestLocalMagicLinkUsesPersistedVerificationAndRotation(t *testing.T) { |
| if err != nil { |
| t.Fatal(err) |
| } |
| - verify := httptest.NewRequest("GET", link, nil) |
| + verify := confirmRequest(link) |
| verify.AddCookie(oldCookie) |
| rec := httptest.NewRecorder() |
| app.Handler().ServeHTTP(rec, verify) |
diff --git a/internal/docs/list_test.go b/internal/docs/list_test.go| index b99a976..103e40a 100644 |
| --- a/internal/docs/list_test.go |
| +++ b/internal/docs/list_test.go |
| @@ -43,7 +43,7 @@ func signInCookies(t *testing.T, app *docs.App, address string) []*http.Cookie { |
| if err != nil { |
| t.Fatalf("TestSignIn: %v", err) |
| } |
| - req := httptest.NewRequest(http.MethodGet, link, nil) |
| + req := app.TestConfirmRequest(link) |
| rec := httptest.NewRecorder() |
| app.Handler().ServeHTTP(rec, req) |
| cookies := rec.Result().Cookies() |
diff --git a/internal/docs/served_policy_test.go b/internal/docs/served_policy_test.go| new file mode 100644 |
| index 0000000..117f302 |
| --- /dev/null |
| +++ b/internal/docs/served_policy_test.go |
| @@ -0,0 +1,105 @@ |
| +package docs_test |
| + |
| +import ( |
| + "net/http" |
| + "net/http/httptest" |
| + "regexp" |
| + "strings" |
| + "testing" |
| + |
| + "amadan.net/rastrillo/rastrillo" |
| + "github.com/carlosframework/docs/internal/docs" |
| +) |
| + |
| +var inlineStyle = regexp.MustCompile(`<style[\s>]|\sstyle="`) |
| + |
| +// Docs' pages are drawn with <style> blocks and a style attribute. |
| +// rastrillo's default CSP stopped allowing either on 2026-09-13, and a |
| +// blocked style fails silently: the page renders unstyled and nothing |
| +// errors. Unit tests call app.Handler() and never see the policy, so |
| +// this serves real pages through rastrillo's production middleware, |
| +// built by the same ServeOptions cmd/docs uses, and checks that every |
| +// page with an inline style is served a policy that runs it. |
| +func TestServedPolicyAllowsThePagesInlineStyles(t *testing.T) { |
| + app := members(t, "alice@example.com,bob@example.com") |
| + served, done, err := rastrillo.Handler(docs.ServeOptions(rastrillo.Options{}, app)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if done != nil { |
| + defer done() |
| + } |
| + alice := signInCookies(t, app, "alice@example.com") |
| + sqid := createDoc(t, app, alice, "Minutes") |
| + link, err := app.TestSignIn(t, "bob@example.com") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + |
| + pages := []struct { |
| + path string |
| + cookies []*http.Cookie |
| + }{ |
| + {"/signin", nil}, |
| + {link, nil}, // the confirm door |
| + {"/signed-out", nil}, |
| + {"/", alice}, |
| + {"/d/" + sqid, alice}, |
| + {"/d/" + sqid + "/share", alice}, |
| + } |
| + styled := 0 |
| + for _, p := range pages { |
| + req := httptest.NewRequest(http.MethodGet, p.path, nil) |
| + req.Header.Set("Accept", "text/html") |
| + for _, c := range p.cookies { |
| + req.AddCookie(c) |
| + } |
| + rec := httptest.NewRecorder() |
| + served.ServeHTTP(rec, req) |
| + if rec.Code != http.StatusOK { |
| + t.Errorf("GET %s through the served handler: %d, want 200", p.path, rec.Code) |
| + continue |
| + } |
| + if !inlineStyle.MatchString(rec.Body.String()) { |
| + continue |
| + } |
| + styled++ |
| + for _, policy := range rec.Header().Values("Content-Security-Policy") { |
| + if !styleSrcAllowsInline(policy) { |
| + t.Errorf("GET %s has inline styles but is served %q, which blocks them: the page renders unstyled", p.path, policy) |
| + } |
| + } |
| + } |
| + // Without a styled page this test would pass on any policy at all. |
| + if styled == 0 { |
| + t.Fatal("no page had an inline style; this test checks nothing — delete it, and ContentSecurityPolicy's 'unsafe-inline' with it") |
| + } |
| +} |
| + |
| +// styleSrcAllowsInline reports whether policy lets a <style> block and a |
| +// style attribute apply. With no style-src the browser uses default-src. |
| +func styleSrcAllowsInline(policy string) bool { |
| + fallback := "" |
| + for _, d := range strings.Split(policy, ";") { |
| + f := strings.Fields(d) |
| + if len(f) == 0 { |
| + continue |
| + } |
| + switch f[0] { |
| + case "style-src": |
| + return contains(f[1:], "'unsafe-inline'") |
| + case "default-src": |
| + fallback = strings.Join(f[1:], " ") |
| + } |
| + } |
| + return contains(strings.Fields(fallback), "'unsafe-inline'") |
| +} |
| + |
| +func contains(list []string, want string) bool { |
| + for _, s := range list { |
| + if s == want { |
| + return true |
| + } |
| + } |
| + return false |
| +} |
diff --git a/internal/docs/signin_confirm_test.go b/internal/docs/signin_confirm_test.go| new file mode 100644 |
| index 0000000..2f09ec8 |
| --- /dev/null |
| +++ b/internal/docs/signin_confirm_test.go |
| @@ -0,0 +1,203 @@ |
| +package docs_test |
| + |
| +import ( |
| + "html" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/url" |
| + "regexp" |
| + "strings" |
| + "testing" |
| + |
| + "github.com/carlosframework/docs/internal/docs" |
| +) |
| + |
| +// confirmDoor is what a test reads off the page an emailed link opens: |
| +// the form's target and the token it carries, taken from the page itself |
| +// rather than from the link, so the POST is the one the button sends. |
| +type confirmDoor struct { |
| + action, token string |
| +} |
| + |
| +var ( |
| + formTag = regexp.MustCompile(`<form[^>]*>`) |
| + formAction = regexp.MustCompile(`action="([^"]*)"`) |
| + tokenField = regexp.MustCompile(`<input type="hidden" name="token" value="([^"]*)">`) |
| + submitButton = regexp.MustCompile(`<button[^>]*type="submit"[^>]*>([^<]*)</button>`) |
| +) |
| + |
| +// readConfirmDoor checks that rec is the confirm step drawn as Docs' |
| +// own sign-in door, and returns what its one button submits. |
| +func readConfirmDoor(t *testing.T, rec *httptest.ResponseRecorder) confirmDoor { |
| + t.Helper() |
| + body := rec.Body.String() |
| + if rec.Code != http.StatusOK { |
| + t.Fatalf("GET verify: status %d, want 200 and the confirm door:\n%s", rec.Code, body) |
| + } |
| + for _, c := range rec.Result().Cookies() { |
| + if c.MaxAge >= 0 && c.Value != "" { |
| + t.Fatalf("GET verify set cookie %q; the GET must spend nothing and sign nobody in", c.Name) |
| + } |
| + } |
| + // The app's chrome: the door (estilo), Docs' own mark and name, the |
| + // shell's bar. Not rastrillo's plain English fallback page. |
| + // (Tests run without the catalog loaded, so the app's own name in the |
| + // tab title is its key; the door's words are estilo's English.) |
| + for _, want := range []string{"estilo-door", "estilo-signin", "<span>Docs</span>", "estilo-bar", "<title>Sign in · ", "<h1>Sign in</h1>"} { |
| + if !strings.Contains(body, want) { |
| + t.Errorf("confirm page lacks %q: not Docs' sign-in door", want) |
| + } |
| + } |
| + if strings.Contains(body, "Sign in to localhost") || strings.Contains(body, "Sign in to example.com") { |
| + t.Error("confirm page is rastrillo's fallback, not Docs' door") |
| + } |
| + // One form, posting; one button, "Sign in"; no address field. |
| + forms := formTag.FindAllString(body, -1) |
| + var confirm []string |
| + for _, f := range forms { |
| + if strings.Contains(f, `action="/auth/verify"`) { |
| + confirm = append(confirm, f) |
| + } |
| + } |
| + if len(confirm) != 1 || !strings.Contains(confirm[0], `method="post"`) { |
| + t.Fatalf("want exactly one POST form to /auth/verify, got %q", confirm) |
| + } |
| + if strings.Contains(body, `name="address"`) { |
| + t.Error("confirm door shows the address form; it should show one Sign in button") |
| + } |
| + start := strings.Index(body, confirm[0]) |
| + end := strings.Index(body[start:], "</form>") |
| + form := body[start : start+end] |
| + buttons := submitButton.FindAllStringSubmatch(form, -1) |
| + if len(buttons) != 1 || strings.TrimSpace(buttons[0][1]) != "Sign in" { |
| + t.Fatalf("want one Sign in button in the confirm form, got %q", buttons) |
| + } |
| + token := tokenField.FindStringSubmatch(form) |
| + if token == nil || token[1] == "" { |
| + t.Fatal("confirm form carries no token") |
| + } |
| + // The page's address is a live credential: rastrillo's headers must |
| + // survive Docs' rendering. |
| + h := rec.Header() |
| + if h.Get("Cache-Control") != "no-store" || h.Get("Referrer-Policy") != "strict-origin" || h.Get("X-Frame-Options") != "DENY" { |
| + t.Errorf("confirm headers loosened: Cache-Control=%q Referrer-Policy=%q X-Frame-Options=%q", |
| + h.Get("Cache-Control"), h.Get("Referrer-Policy"), h.Get("X-Frame-Options")) |
| + } |
| + if !strings.Contains(strings.Join(h.Values("Content-Security-Policy"), ";"), "frame-ancestors 'none'") { |
| + t.Error("confirm page can be framed") |
| + } |
| + action := formAction.FindStringSubmatch(confirm[0]) |
| + return confirmDoor{action: html.UnescapeString(action[1]), token: html.UnescapeString(token[1])} |
| +} |
| + |
| +// press submits the confirm door's button the way a browser does from |
| +// the page: a same-origin form POST. |
| +func (d confirmDoor) press(t *testing.T, app *docs.App, site string) *httptest.ResponseRecorder { |
| + t.Helper() |
| + req := httptest.NewRequest(http.MethodPost, d.action, strings.NewReader(url.Values{"token": {d.token}}.Encode())) |
| + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| + req.Header.Set("Sec-Fetch-Site", site) |
| + rec := httptest.NewRecorder() |
| + app.Handler().ServeHTTP(rec, req) |
| + return rec |
| +} |
| + |
| +func sessionCookies(rec *httptest.ResponseRecorder) []*http.Cookie { |
| + var live []*http.Cookie |
| + for _, c := range rec.Result().Cookies() { |
| + if c.MaxAge >= 0 && c.Value != "" { |
| + live = append(live, c) |
| + } |
| + } |
| + return live |
| +} |
| + |
| +// The emailed-link sign-in end to end: begin (POST /signin), the mail, |
| +// GET of the link drawing the confirm door and spending nothing, the |
| +// button's POST spending it, and a session that reaches the list. |
| +func TestEmailSignInConfirmsInTheDoorThenSpendsOnPost(t *testing.T) { |
| + app := members(t, "alice@example.com") |
| + |
| + // Begin and mail: TestSignIn POSTs /signin and reads the link out of |
| + // the mail the queue delivered. |
| + link, err := app.TestSignIn(t, "alice@example.com") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + |
| + // A link scanner fetches the link first. Twice, even: it spends |
| + // nothing, so the person's own click still works. |
| + readConfirmDoor(t, get(t, app, nil, link)) |
| + door := readConfirmDoor(t, get(t, app, nil, link)) |
| + |
| + // A post carrying cross-site evidence is refused, and spends nothing. |
| + if rec := door.press(t, app, "cross-site"); rec.Code != http.StatusForbidden || len(sessionCookies(rec)) != 0 { |
| + t.Fatalf("cross-site confirm: %d with cookies %v, want a bare 403", rec.Code, sessionCookies(rec)) |
| + } |
| + |
| + signedIn := door.press(t, app, "same-origin") |
| + if signedIn.Code != http.StatusSeeOther || signedIn.Header().Get("Location") != "/auth/local/complete" { |
| + t.Fatalf("POST verify: %d → %q, want 303 → /auth/local/complete", signedIn.Code, signedIn.Header().Get("Location")) |
| + } |
| + cookies := sessionCookies(signedIn) |
| + if len(cookies) == 0 { |
| + t.Fatal("POST verify set no session cookie") |
| + } |
| + landed := get(t, app, cookies, "/auth/local/complete") |
| + if landed.Code != http.StatusSeeOther || landed.Header().Get("Location") != "/" { |
| + t.Fatalf("landing: %d → %q, want 303 → /", landed.Code, landed.Header().Get("Location")) |
| + } |
| + if rec := get(t, app, cookies, "/"); rec.Code != http.StatusOK { |
| + t.Fatalf("GET / with the new session: %d, want 200", rec.Code) |
| + } |
| + |
| + // Single use: the same button again finds the link spent. |
| + again := door.press(t, app, "same-origin") |
| + if again.Code != http.StatusSeeOther || again.Header().Get("Location") != "/signin?err=expired" || len(sessionCookies(again)) != 0 { |
| + t.Fatalf("second POST: %d → %q, want 303 → /signin?err=expired and no session", again.Code, again.Header().Get("Location")) |
| + } |
| +} |
| + |
| +// A link mailed while the address was admitted, pressed after it no |
| +// longer is: the door, with the refusal, inside the 403 (Config.Refused), |
| +// and no session. |
| +func TestEmailSignInRefusedAfterConfirmGetsTheDoor(t *testing.T) { |
| + app := members(t, "alice@example.com") |
| + alice := signInCookies(t, app, "alice@example.com") |
| + sqid := createDoc(t, app, alice, "Minutes") |
| + post(t, app, alice, "/d/"+sqid+"/share", "address=bob@example.com&role=reader") |
| + link, err := app.TestSignIn(t, "bob@example.com") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + post(t, app, alice, "/d/"+sqid+"/share/revoke", "address=bob@example.com") |
| + |
| + door := readConfirmDoor(t, get(t, app, nil, link)) |
| + refused := door.press(t, app, "same-origin") |
| + body := refused.Body.String() |
| + if refused.Code != http.StatusForbidden { |
| + t.Fatalf("refused POST verify: %d, want 403:\n%s", refused.Code, body) |
| + } |
| + if strings.Contains(body, "verified but not admitted") { |
| + t.Fatal("refusal is rastrillo's bare text, not the door") |
| + } |
| + for _, want := range []string{"estilo-door", `name="address"`, `rst-tone="negative"`} { |
| + if !strings.Contains(body, want) { |
| + t.Errorf("refusal lacks %q: want the sign-in door with the refusal", want) |
| + } |
| + } |
| + // The catalog key in tests, the sentence with the catalog loaded. |
| + if !strings.Contains(body, "docs.signin.error.refused") && !strings.Contains(body, "can’t sign in to Docs") { |
| + t.Error("refusal door does not say the address was refused") |
| + } |
| + if refused.Header().Get("Cache-Control") != "no-store" { |
| + t.Error("refusal is cacheable") |
| + } |
| + if len(sessionCookies(refused)) != 0 { |
| + t.Fatal("a refused address got a session cookie") |
| + } |
| + // And the sentence is not something a query can conjure. |
| + if spoof := get(t, app, nil, "/signin?err=refused").Body.String(); strings.Contains(spoof, "docs.signin.error.refused") || strings.Contains(spoof, "can’t sign in to Docs") { |
| + t.Fatal("anybody can show the refusal by visiting /signin?err=refused") |
| + } |
| +} |
diff --git a/internal/docs/signin_loop_test.go b/internal/docs/signin_loop_test.go| index 58f01ed..cc7d4c1 100644 |
| --- a/internal/docs/signin_loop_test.go |
| +++ b/internal/docs/signin_loop_test.go |
| @@ -47,7 +47,8 @@ func (b *browser) signIn(address string) { |
| if err != nil { |
| b.t.Fatal(err) |
| } |
| - b.do("GET", link, "") |
| + verifyPath, verifyForm := confirmForm(link) |
| + b.do("POST", verifyPath, verifyForm) |
| b.do("GET", localLinkCompletePath, "") |
| } |
| @@ -123,7 +124,8 @@ func TestUseADifferentAddressKeepsTheDeepLink(t *testing.T) { |
| if err != nil { |
| t.Fatal(err) |
| } |
| - b.do("GET", link, "") |
| + verifyPath, verifyForm := confirmForm(link) |
| + b.do("POST", verifyPath, verifyForm) |
| landed := b.do("GET", localLinkCompletePath, "") |
| if landed.Header().Get("Location") != deep { |
| t.Fatalf("after \"Use a different address\" (%s) the sign-in landed on %q, want %q", again, landed.Header().Get("Location"), deep) |
diff --git a/internal/docs/team_session_reader.go b/internal/docs/team_session_reader.go| index c69e117..352795c 100644 |
| --- a/internal/docs/team_session_reader.go |
| +++ b/internal/docs/team_session_reader.go |
| @@ -9,18 +9,42 @@ import ( |
| "amadan.net/rastrillo/rastrillo/sessions" |
| ) |
| -// Keep validation in the shared reader: FromContext bounds the session |
| -// lookup by the caller's context. (Before Docs moved off rastrillo's |
| -// pre-move path, this converted between the two packages' Session types.) |
| +// The caller's context bounds the wait for the session lookup. Docs used |
| +// to pin rastrillo's feat-session-context branch for Sessions.FromContext, |
| +// which bounded the query itself; that branch never reached rastrillo's |
| +// main, so here From runs aside and a canceled or expired context answers |
| +// "no session" without waiting for it. The query is not interrupted (From |
| +// takes no context), but From only reads: it never deletes, refreshes or |
| +// rotates the row, so abandoning its answer changes nothing. |
| func newTeamSessionReader(db *sql.DB, origin, cookieName string, logger *slog.Logger) (func(context.Context, *http.Request) (sessions.Session, bool), error) { |
| reader, e := sessions.New(sessions.Config{DB: db, Origin: origin, Logger: logger}) |
| if e != nil || reader.CookieName() != cookieName { |
| return nil, errTeamConfig |
| } |
| + type answer struct { |
| + session sessions.Session |
| + ok bool |
| + } |
| return func(ctx context.Context, r *http.Request) (sessions.Session, bool) { |
| if _, present, ok := homeCookie(r, cookieName); !ok || !present { |
| return sessions.Session{}, false |
| } |
| - return reader.FromContext(ctx, r) |
| + if ctx.Err() != nil { |
| + return sessions.Session{}, false |
| + } |
| + done := make(chan answer, 1) |
| + go func() { |
| + s, ok := reader.From(r) |
| + done <- answer{s, ok} |
| + }() |
| + select { |
| + case a := <-done: |
| + if ctx.Err() != nil { |
| + return sessions.Session{}, false |
| + } |
| + return a.session, a.ok |
| + case <-ctx.Done(): |
| + return sessions.Session{}, false |
| + } |
| }, nil |
| } |
diff --git a/internal/docs/testing.go b/internal/docs/testing.go| index 704e04c..29a22a7 100644 |
| --- a/internal/docs/testing.go |
| +++ b/internal/docs/testing.go |
| @@ -69,8 +69,8 @@ func NewForTestWith(t *testing.T, cfg Config) (*App, error) { |
| } |
| // TestSignIn mints a magic link for address and returns its path |
| -// (e.g. "/auth/verify?token=..."), suitable for |
| -// httptest.NewRequest(http.MethodGet, link, nil) directly. It never |
| +// (e.g. "/auth/verify?token=..."). GETting it draws the confirm door; |
| +// confirmRequest(link) is the POST that spends it. It never |
| // sends real mail: it POSTs /signin with force=1 — the escape hatch |
| // auth.Begin's own doc comment describes ("skips classification and |
| // goes straight to the magic link") — so no outbound classification |
| @@ -143,6 +143,35 @@ func (a *App) TestSignIn(t *testing.T, address string) (string, error) { |
| return linkPath(link) |
| } |
| +// confirmForm is what the confirm door's Sign in button submits for an |
| +// emailed link: the link's own path, and a form body carrying its token. |
| +// GET /auth/verify only draws that door and spends nothing, so a test |
| +// that signs in must POST this, as a browser does. |
| +func confirmForm(link string) (path, form string) { |
| + u, err := url.Parse(link) |
| + if err != nil { |
| + return link, "" |
| + } |
| + return u.Path, url.Values{"token": {u.Query().Get("token")}}.Encode() |
| +} |
| + |
| +// confirmRequest is that POST, with the same-origin evidence a browser |
| +// sends from the door (Sec-Fetch-Site), which both csrf.Protect and |
| +// rastrillo's own redeem check. |
| +func confirmRequest(link string) *http.Request { |
| + path, form := confirmForm(link) |
| + req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(form)) |
| + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| + req.Header.Set("Sec-Fetch-Site", "same-origin") |
| + return req |
| +} |
| + |
| +// TestConfirmRequest is confirmRequest for tests outside the package: |
| +// the POST that spends a link TestSignIn returned. |
| +func (a *App) TestConfirmRequest(link string) *http.Request { |
| + return confirmRequest(link) |
| +} |
| + |
| // TestPerson creates (or finds) a person by address and returns this |
| // app's own numeric id for them — Store.EnsurePerson, the same |
| // address-to-id mapping a real request goes through via handlers.go's |
| @@ -193,9 +222,8 @@ func (a *App) TestRequest(t *testing.T, address, method, path string, body io.Re |
| if err != nil { |
| t.Fatalf("docs: TestRequest: TestSignIn(%q): %v", address, err) |
| } |
| - verifyReq := httptest.NewRequest(http.MethodGet, link, nil) |
| verifyRec := httptest.NewRecorder() |
| - a.Handler().ServeHTTP(verifyRec, verifyReq) |
| + a.Handler().ServeHTTP(verifyRec, confirmRequest(link)) |
| cookies := verifyRec.Result().Cookies() |
| if len(cookies) == 0 { |
| t.Fatalf("docs: TestRequest: following the magic link for %q set no session cookie", address) |
diff --git a/internal/docs/updates_test.go b/internal/docs/updates_test.go| index c58d31a..13b3b38 100644 |
| --- a/internal/docs/updates_test.go |
| +++ b/internal/docs/updates_test.go |
| @@ -252,7 +252,7 @@ func TestConcurrentUpdatesDoNotCollideOnSeq(t *testing.T) { |
| t.Fatalf("TestSignIn: %v", err) |
| } |
| verifyRec := httptest.NewRecorder() |
| - app.Handler().ServeHTTP(verifyRec, httptest.NewRequest(http.MethodGet, link, nil)) |
| + app.Handler().ServeHTTP(verifyRec, confirmRequest(link)) |
| cookies := verifyRec.Result().Cookies() |
| if len(cookies) == 0 { |
| t.Fatal("sign-in set no session cookie") |
diff --git a/internal/docs/views/signin.html b/internal/docs/views/signin.html| index fc34fbc..678d98a 100644 |
| --- a/internal/docs/views/signin.html |
| +++ b/internal/docs/views/signin.html |
| @@ -1,11 +1,15 @@ |
| {{/* signin — GET /signin (auth.go's signin handler): estilo's sign-in |
| - form, the check-your-email state that replaces it, or the Keymail |
| - continuation (auth_navigation.go), which needs its meta refresh. |
| + form, the check-your-email state that replaces it, the Keymail |
| + continuation (auth_navigation.go), which needs its meta refresh, or |
| + the confirm step an emailed link opens (GET /auth/verify, |
| + auth_navigation.go's confirmSignin): one Sign in button that POSTs |
| + the token back, because a GET must spend nothing. |
| - rastrillo/auth's own handlers never render this page (magic-links.md: |
| - "the sign-in page stays yours"). Begin, Callback and Verify report |
| - every outcome by redirecting back here with ?sent=1 or ?err=…, which |
| - auth.go resolves into the data below. |
| + rastrillo/auth's own handlers never render this page themselves |
| + (magic-links.md: "the sign-in page stays yours"). Begin, Callback and |
| + Verify report outcomes by redirecting back here with ?sent=1 or |
| + ?err=…, which auth.go resolves into the data below; the confirm step |
| + and a refusal call back into it (Config.RenderConfirm, Config.Refused). |
| The bar shows the brand only: no account, no Sign in (chrome.go's |
| signinPage). It used to be hidden outright, because the rastrillo |
| @@ -14,6 +18,13 @@ |
| {{- if .ContinueURL}} |
| <meta http-equiv="refresh" content="0;url={{.ContinueURL}}"> |
| {{template "estilo-door-open" .Door}}<p><a rst-btn="primary" href="{{.ContinueURL}}">{{.SubmitLabel}}</a></p>{{template "estilo-door-close"}} |
| +{{- else if .Confirm}}{{template "estilo-door-open" .Door}} |
| + <h1>{{.Confirm.Heading}}</h1> |
| + <form rst-form method="post" action="{{.Confirm.Action}}"> |
| + <input type="hidden" name="token" value="{{.Confirm.Token}}"> |
| + <div rst-form-foot><button rst-btn="primary" type="submit" autofocus>{{.Confirm.Submit}}</button></div> |
| + </form> |
| +{{template "estilo-door-close"}} |
| {{- else if .Sent}}{{template "estilo-signin-sent" .Sent}} |
| {{- else}}{{template "estilo-signin" .Form}}{{end}} |
| {{end}} |
diff --git a/scripts/browser-drive.sh b/scripts/browser-drive.sh| index 8c5154f..2959a8c 100755 |
| --- a/scripts/browser-drive.sh |
| +++ b/scripts/browser-drive.sh |
| @@ -86,11 +86,9 @@ curl -fsS -X POST -H 'Sec-Fetch-Site: same-origin' \ |
| link="$(grep -o "http://${addr}/auth/verify?token=[A-Za-z0-9_-]*" "${scratch}/server.log" | tail -1)" |
| [ -n "$link" ] || { echo "browser-drive: no sign-in link in the log" >&2; exit 1; } |
| -# Following the link in the browser is what leaves the session cookie |
| -# in the profile the drive then uses. |
| -"$chrome" --headless=new --no-sandbox --disable-gpu --disable-crash-reporter \ |
| - --user-data-dir="${scratch}/profile" --virtual-time-budget=5000 --window-size=1280,900 \ |
| - --screenshot="${scratch}/signin.png" "$link" >/dev/null 2>&1 || true |
| +# The link opens a confirm door that spends nothing; the drive presses |
| +# its Sign in button (browser-drive.mjs), which is what leaves the |
| +# session cookie in the profile it then uses. |
| "$chrome" --headless=new --no-sandbox --disable-gpu --disable-crash-reporter \ |
| --remote-debugging-port="${debug_port}" --user-data-dir="${scratch}/profile" \ |
| @@ -108,4 +106,4 @@ done |
| [ -n "$target" ] || { echo "browser-drive: Chrome did not expose a debugging target" >&2; exit 1; } |
| echo "browser-drive: driving http://${addr}" |
| -node fixtures/browser-drive.mjs "$target" "http://${addr}" |
| +node fixtures/browser-drive.mjs "$target" "http://${addr}" "$link" |