oficina / home Public

Clone
git clone https://amadan.net/oficina/home

Plain git — no account needed to clone.

Download

Download this file

1package home
2
3import (
4 "bytes"
5 "io/fs"
6 "net/http"
7 "net/http/httptest"
8 "net/url"
9 "os"
10 "path"
11 "path/filepath"
12 "regexp"
13 "slices"
14 "sort"
15 "strings"
16 "testing"
17
18 "amadan.net/oficina/estilo.git/busy"
19 "amadan.net/oficina/estilo.git/theme"
20 "amadan.net/oficina/home/internal/home/sealtest"
21 "amadan.net/rastrillo/rastrillo"
22 "amadan.net/rastrillo/rastrillo/lastsignin"
23 "amadan.net/rastrillo/rastrillo/passkey"
24 "amadan.net/rastrillo/rastrillo/ui"
25 "github.com/go-chi/chi/v5"
26)
27
28// homeScripts is every script Home serves, by stable path. Paul,
29// 2026-09-29: no script by default, a script only to enhance a page or
30// provide interaction, and always prefer none. So any page may load one of
31// these — they are all progressive enhancements over a page that works
32// without them — but nothing else, and never inline.
33//
34// Paths, not fingerprints: a template writes {{v "/static/x.js"}} (a
35// content-versioned URL), which the sweep reads back to the bare path.
36var homeScripts = []string{
37 "/static/assertion.js", // the handoff's auto-submit; Continue stays for script-off
38 "/static/passkey.js", // the passkey ceremonies: webauthn cannot be done without script
39 "/static/busy.js", // estilo's busy rule: spinner and double-submit guard
40 "/static/signin.mjs", // the door's passkey (rastrillo's passkey.JS()): its button, and the field's autofill
41}
42
43// templateSrc unwraps {{v "PATH"}} to PATH, so the sweep checks the file,
44// not the helper call that versions it.
45var templateSrc = regexp.MustCompile(`^\{\{\s*v\s+"([^"]+)"\s*\}\}$`)
46
47// scriptTag matches a complete <script ...>...</script>.
48//
49// The closing pattern tolerates whitespace — `</script >` is valid HTML
50// that every browser accepts, and the first version of this regex
51// required the literal `</script>` and so walked straight past a page
52// loading an arbitrary script. The justification for hand-rolling was
53// "the shapes it has to survive are the ones we write", which is exactly
54// the assumption that failed: nobody writes `</script >` on purpose,
55// which is why nobody would notice.
56var scriptTag = regexp.MustCompile(`(?is)<script\b([^>]*)>(.*?)</\s*script\s*>`)
57
58// scriptOpen matches just the opening tag, so a <script> with no
59// matching close can be counted and refused rather than silently
60// skipped.
61var scriptOpen = regexp.MustCompile(`(?is)<script\b`)
62
63// srcAttr accepts double quotes, single quotes and an unquoted value.
64// Only the double-quoted form was matched at first, so a
65// single-quoted src fell through to the "inline" branch — which still
66// FAILED the guard, since fail-safe was the right default, but with a
67// diagnosis naming the wrong problem. A guard that reports the wrong
68// reason gets the wrong fix.
69// It also requires a whitespace boundary before src, not \b: \b matches
70// inside data-src=, so a tag carrying both reported the wrong one.
71var srcAttr = regexp.MustCompile(`(?i)(?:^|\s)src\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))`)
72
73// scriptSrcs returns one entry per <script> in b: its src, or the empty
74// string for an inline one. An inline body counts even when a src is
75// also present, because the empty string is what the guard refuses.
76func scriptSrcs(b []byte) []string {
77 var out []string
78 for _, m := range scriptTag.FindAllSubmatch(b, -1) {
79 attrs, body := m[1], m[2]
80 if len(bytes.TrimSpace(body)) > 0 {
81 out = append(out, "")
82 continue
83 }
84 if m := srcAttr.FindSubmatch(attrs); m != nil {
85 // One of the three alternatives matched; the others are empty.
86 for _, g := range m[1:] {
87 if len(g) > 0 {
88 out = append(out, string(g))
89 break
90 }
91 }
92 continue
93 }
94 out = append(out, "")
95 }
96 return out
97}
98
99// templateNames is every template file this app ships, including the
100// layout — the sweep reads SOURCE, so the layout is a page like any
101// other and can carry a script too.
102func templateNames(t *testing.T) []string {
103 t.Helper()
104 files, err := fs.Glob(templatesFS, "templates/*.html")
105 if err != nil {
106 t.Fatal(err)
107 }
108 names := make([]string, 0, len(files))
109 for _, f := range files {
110 names = append(names, path.Base(f))
111 }
112 sort.Strings(names)
113 if len(names) == 0 {
114 t.Fatal("no templates found: the sweep would pass by not looking")
115 }
116 return names
117}
118
119// templateSource is one template file's raw text.
120func templateSource(t *testing.T, name string) []byte {
121 t.Helper()
122 b, err := templatesFS.ReadFile("templates/" + name)
123 if err != nil {
124 t.Fatal(err)
125 }
126 return b
127}
128
129// sampleData is enough data to render each page for the tests that need
130// a rendered page.
131//
132// It is deliberately NOT what the script sweep uses. A fixed key set
133// cannot reach a branch keyed on something it does not carry — on a map,
134// {{if .Debug}} resolves to nil with no error — so a sweep built on it
135// passes by not looking. The sweep reads template source instead. This
136// stays for the recovery-form test, which needs real output.
137func sampleData(name string) []any {
138 common := map[string]any{
139 "RPID": "id.oficina.works", "LegacyRPID": "",
140 "UserID": "cHJfdGVzdA", "UserName": "pr_test",
141 "Token": "sample-token", "Remaining": 7,
142 }
143 withError := map[string]any{}
144 for k, v := range common {
145 withError[k] = v
146 }
147 withError["Error"] = "something went wrong"
148 withError["RecoveryFailed"] = true
149 withError["Codes"] = []string{"AAAA-BBBB", "CCCC-DDDD"}
150 return []any{common, withError}
151}
152
153// TestNoScriptTagOutsideTheAllowlist is the script rule, made
154// mechanical (it once also named the only screens allowed any script; the
155// rule is now no script by default and prefer none, so it names the
156// files instead). Historically: every
157// screen works with scripts off, and ruling 21 once carved out only the
158// passkey screens.
159//
160// Two stated limits, so nobody reads more into a green run than is
161// there. It does not catch inline event handlers — onclick= and its
162// relatives are script and are not <script>; rastrillo's default CSP
163// (default-src 'self', no unsafe-inline) is what makes them inert, and
164// TestServedCSPAllowsNoInlineScript is what guards that. And it reads
165// only this app's templates/*.html, while roughly thirty rastrillo ui
166// partials are parsed into every page tree. Those are clean at the
167// pinned version — no <script> anywhere in partials/, and ui.Templates()
168// excludes the layouts/ files that do have one — but an upgrade could
169// change that without this sweep noticing.
170//
171// It reads template SOURCE, not rendered output, and that is the
172// correction. The first version rendered each page with a hand-written
173// fixture and scanned the result, with a comment claiming the fixture
174// reached "every branch". It could not: on a map, {{if .Debug}}
175// resolves to nil with no error, so a <script> inside a branch the
176// fixture never satisfies rendered as nothing and the sweep passed by
177// not looking. Any key a future template introduced was invisible to it
178// by construction. Source has no branches to miss.
179func TestNoScriptTagOutsideTheAllowlist(t *testing.T) {
180 for _, name := range templateNames(t) {
181 src := templateSource(t, name)
182
183 // A <script> with no matching close is refused rather than
184 // skipped: an unbalanced tag is either a typo or an evasion, and
185 // neither should pass silently.
186 if opens, full := len(scriptOpen.FindAll(src, -1)), len(scriptTag.FindAll(src, -1)); opens != full {
187 t.Errorf("%s has %d <script opening tags but %d complete elements; "+
188 "an unbalanced tag cannot be swept", name, opens, full)
189 continue
190 }
191
192 srcs := scriptSrcs(src)
193 if len(srcs) == 0 {
194 continue // no script at all: the common case
195 }
196 for _, srcAttr := range srcs {
197 if m := templateSrc.FindStringSubmatch(srcAttr); m != nil {
198 srcAttr = m[1]
199 }
200 switch {
201 case srcAttr == "":
202 t.Errorf("%s has an INLINE <script>; scripts are static same-origin "+
203 "files, and the default CSP forbids inline anyway", name)
204 case !slices.Contains(homeScripts, srcAttr):
205 t.Errorf("%s loads %q, which is not one of Home's scripts (homeScripts)", name, srcAttr)
206 }
207 }
208 }
209}
210
211// scriptSrcs must actually see the shapes it is meant to refuse, or the
212// sweep above is a sweep over nothing.
213func TestScriptSrcsSeesInlineAndSourced(t *testing.T) {
214 got := scriptSrcs([]byte(`
215 <script src="/static/passkey.js"></script>
216 <script>alert(1)</script>
217 <script type="module" src="/static/other.js"></script>
218 <script src="/static/x.js">alert(2)</script>
219 <script src="/static/spaced.js"></script >
220 <SCRIPT SRC="/static/shouty.js"></SCRIPT>
221 <script src='/static/singly.js'></script>
222 <script src=/static/bare.js></script>
223 `))
224 want := []string{"/static/passkey.js", "", "/static/other.js", "",
225 "/static/spaced.js", "/static/shouty.js",
226 "/static/singly.js", "/static/bare.js"}
227 if !slices.Equal(got, want) {
228 t.Errorf("scriptSrcs = %q, want %q", got, want)
229 }
230}
231
232// The carve-out must not widen into unsafe-inline behind our backs.
233//
234// Asserted against the SERVED header rather than against rastrillo's
235// defaultCSP, which is an unexported const: the point is what a browser
236// receives, not what a library declares.
237func TestServedCSPAllowsNoInlineScript(t *testing.T) {
238 app := newTestApp(t)
239 mux := http.NewServeMux()
240 mux.Handle("/", app.Router())
241
242 h, cleanup, err := rastrillo.Handler(rastrillo.Options{Mux: mux, Logger: quietLogger(), CSP: app.SecurityPolicy()})
243 if err != nil {
244 t.Fatalf("rastrillo.Handler: %v", err)
245 }
246 if cleanup != nil {
247 t.Cleanup(func() { cleanup() })
248 }
249
250 // EVERY route, not just one. rastrillo's securityHeaders sets the
251 // default and a handler's own header REPLACES it, so an
252 // unsafe-inline carve-out added to the one page that actually loads
253 // script — the tempting place to put it — would never be seen by a
254 // check that only requests /signin.
255 routes, ok := app.Router().(chi.Routes)
256 if !ok {
257 t.Fatalf("Router() is %T, which does not implement chi.Routes", app.Router())
258 }
259 // Method AND route, AND a session. It took three goes, and the
260 // history is the useful part because each version's comment claimed
261 // more coverage than it had.
262 //
263 // It first issued GET on every path, so all ten POST handlers were
264 // skipped and an unsafe-inline header in handleSigninBegin survived
265 // the whole suite. Using chi.Walk's method fixed that, and the
266 // comment then called it "the whole fix" — wrong again: five
267 // handlers still never ran, all five stopped by RequireFresh
268 // (GET and POST /passkey/codes, GET /passkey/enrol, and both
269 // register endpoints). None was stopped by csrf; the Origin header
270 // below sees to that. So the sweep reached eighteen of
271 // twenty-three, and one of the five it missed renders the enrolment
272 // screen, which is one of the pages that loads a script to enhance it.
273 //
274 // So: a fresh session cookie as well. With it, all twenty-three
275 // targets reach and run their handler — probe-verified rather than
276 // inferred from status codes, which is how an earlier version of
277 // this comment got it wrong in the other direction. The three
278 // ceremony endpoints answer 403, but that 403 is written by
279 // passkey.Handlers.refuse from INSIDE the handler after the pending
280 // half-session lookup misses, so a header set at the top of one
281 // would be caught here.
282 type target struct{ method, path string }
283 var targets []target
284 if err := chi.Walk(routes, func(method string, route string, _ http.Handler, _ ...func(http.Handler) http.Handler) error {
285 targets = append(targets, target{method, strings.ReplaceAll(route, "/*", "")})
286 return nil
287 }); err != nil {
288 t.Fatalf("walk routes: %v", err)
289 }
290 if len(targets) < 5 {
291 t.Fatalf("walked %d routes; the sweep would pass by not looking", len(targets))
292 }
293 var posts int
294 for _, tg := range targets {
295 if tg.method == http.MethodPost {
296 posts++
297 }
298 }
299 if posts == 0 {
300 t.Fatal("walked no POST routes; the sweep would miss every state-changing handler")
301 }
302
303 // A real, fresh session: the passkey routes want one, and the codes
304 // and enrol pages want a recent one. Without it this sweep silently
305 // covered eighteen routes while claiming twenty-three.
306 cookie := signInFully(t, app, "sweeper@example.invalid")
307
308 for _, tg := range targets {
309 p := tg.path
310 req := httptest.NewRequest(tg.method, p, strings.NewReader("address=someone@example.invalid"))
311 req.Host = credentialHost
312 if req.URL.Path == "/" {
313 req.Host = directoryHost
314 }
315 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
316 // The POSTs are behind csrf.Protect, which short-circuits before
317 // the handler runs — and a handler that never runs sets no
318 // header to inspect.
319 req.Header.Set("Origin", Origin)
320 req.AddCookie(cookie)
321 rec := httptest.NewRecorder()
322 h.ServeHTTP(rec, req)
323
324 csp := rec.Header().Get("Content-Security-Policy")
325 if csp == "" {
326 t.Errorf("%s served no Content-Security-Policy header", p)
327 continue
328 }
329 for _, directive := range strings.Split(csp, ";") {
330 d := strings.TrimSpace(directive)
331 name, _, _ := strings.Cut(d, " ")
332 // Inline STYLES are allowed on purpose: ui's partials set
333 // style attributes. Inline SCRIPT is what §11 and the script rule
334 // are about.
335 if name == "style-src" {
336 continue
337 }
338 if strings.Contains(d, "'unsafe-inline'") || strings.Contains(d, "'unsafe-eval'") {
339 t.Errorf("%s: CSP directive %q permits inline or eval'd script", p, d)
340 }
341 }
342 if !strings.Contains(csp, "default-src 'self'") {
343 t.Errorf("%s: CSP %q does not restrict script to same-origin", p, csp)
344 }
345 }
346}
347
348// The binary uses the policy whose only framework change is tested
349// separately: cmd/home hands Serve exactly ServeOptions (serveopts.go),
350// sets no CSP of its own, and ServeOptions sets exactly the reviewed one.
351func TestAppUsesReviewedCSP(t *testing.T) {
352 b, err := os.ReadFile("../../cmd/home/main.go")
353 if err != nil {
354 t.Fatal(err)
355 }
356 call := []byte("opts = app.ServeOptions(opts)")
357 if bytes.Count(b, call) != 1 || bytes.Contains(b, []byte("CSP")) {
358 t.Error("binary must hand Serve exactly app.ServeOptions, and set no CSP itself")
359 }
360 s, err := os.ReadFile("serveopts.go")
361 if err != nil {
362 t.Fatal(err)
363 }
364 assignment := []byte("opts.CSP = a.SecurityPolicy()")
365 if bytes.Count(s, assignment) != 1 || bytes.Contains(bytes.ReplaceAll(s, assignment, nil), []byte("CSP")) {
366 t.Error("ServeOptions must wire exactly the reviewed policy")
367 }
368 app := newTestApp(t)
369 if got := app.ServeOptions(rastrillo.Options{}).CSP; got != app.SecurityPolicy() {
370 t.Errorf("ServeOptions CSP = %q, want the reviewed policy", got)
371 }
372}
373
374// The one screen that carries script must still work without it.
375// passkey.SignInRecovery is a plain form POST, because recovery is
376// exactly the moment WebAuthn is not working — so stripping every
377// <script> must leave the code form intact and pointed at its endpoint.
378func TestConfirmPageRecoveryFormSurvivesScriptStripping(t *testing.T) {
379 app := newTestApp(t)
380 var buf bytes.Buffer
381 if err := app.renderer.pages["passkey_confirm.html"].
382 ExecuteTemplate(&buf, "layout", sampleData("passkey_confirm.html")[0]); err != nil {
383 t.Fatal(err)
384 }
385
386 stripped := scriptTag.ReplaceAll(buf.Bytes(), nil)
387 page := string(stripped)
388
389 if strings.Contains(page, "<script") {
390 t.Fatal("stripping left a script tag behind; the rest of this test would be meaningless")
391 }
392 for _, want := range []string{
393 `action="/passkey/signin/recovery"`,
394 `method="post"`,
395 `name="code"`,
396 `type="submit"`,
397 } {
398 if !strings.Contains(page, want) {
399 t.Errorf("the recovery form lost %s when script was stripped", want)
400 }
401 }
402}
403
404func TestVendoredAssetsMatchTheLibrary(t *testing.T) {
405 tokens, err := os.ReadFile("static/tokens.css")
406 if err != nil {
407 t.Fatal(err)
408 }
409 if !bytes.Equal(tokens, ui.TokensCSS()) {
410 t.Error("static/tokens.css differs from ui.TokensCSS(); run `rastrillo doctor --fix`")
411 }
412
413 // The theme is estilo's own now — Calma, not rastrillo's day (estilo
414 // AGENTS.md, decisions table, row 8) — so the check is that Home serves
415 // exactly what its estilo pin ships, below, and that the theme still
416 // declares every token tokens.css uses.
417 day, ok := ui.ThemeCSS("day")
418 if !ok {
419 t.Fatal("ui has no day theme")
420 }
421 names := regexp.MustCompile(`(?m)^\s*(--rst-[a-z0-9-]+)\s*:`)
422 have := map[string]bool{}
423 for _, m := range names.FindAllSubmatch(theme.CSS(), -1) {
424 have[string(m[1])] = true
425 }
426 for _, m := range names.FindAllSubmatch(day, -1) {
427 if !have[string(m[1])] {
428 t.Errorf("estilo's theme does not declare %s, which tokens.css expects", m[1])
429 }
430 }
431 app := newTestApp(t)
432 for _, host := range []string{directoryHost, credentialHost} {
433 req := httptest.NewRequest(http.MethodGet, "/static/theme.css", nil)
434 req.Host = host
435 rec := httptest.NewRecorder()
436 app.Router().ServeHTTP(rec, req)
437 if rec.Code != http.StatusOK || rec.Header().Get("Content-Type") != "text/css; charset=utf-8" || !bytes.Equal(rec.Body.Bytes(), theme.CSS()) {
438 t.Fatalf("%s: shared theme response mismatch (status %d)", host, rec.Code)
439 }
440 }
441}
442
443// rastrilloScripts are the files `rastrillo doctor --fix` writes into
444// static/ beside tokens.css: at v0.26 four scripts, from v0.34 (when the
445// look moved to Fiesta) every script ui.VendoredAssets names plus
446// shell.css. Home uses none of them. rastrillo.js is the combined shim
447// with rastrillo's old busy rule inside, and Home serves estilo's
448// busy.js; the two rules on one page fight over the same submit (each
449// holds it, then re-submits). So after a doctor run they are deleted,
450// and this fails if one is left on disk or served. The four names stay
451// listed so the check does not depend on the library's list alone.
452func rastrilloScripts(t *testing.T) []string {
453 t.Helper()
454 assets, ok := ui.VendoredAssets("day")
455 if !ok {
456 t.Fatal("ui has no day theme")
457 }
458 names := map[string]bool{"rastrillo.js": true, "select.js": true, "datetime.js": true, "calendar.js": true}
459 for name := range assets {
460 if name != "tokens.css" && name != "theme.css" {
461 names[name] = true
462 }
463 }
464 list := make([]string, 0, len(names))
465 for name := range names {
466 list = append(list, name)
467 }
468 sort.Strings(list)
469 return list
470}
471
472// estiloServed are the doctor-written names Home serves from estilo
473// rather than from static/: the path answers, with estilo's bytes.
474var estiloServed = map[string][]byte{"busy.js": busy.JS()}
475
476func TestNoRastrilloShimBesideBusy(t *testing.T) {
477 scripts := rastrilloScripts(t)
478 for _, name := range scripts {
479 if _, err := os.Stat(filepath.Join("static", name)); err == nil {
480 t.Errorf("static/%s is on disk: `rastrillo doctor --fix` adds it, and Home serves none of rastrillo's (estilo's busy.js instead); delete it", name)
481 }
482 }
483 app := newTestApp(t)
484 for _, host := range []string{directoryHost, credentialHost} {
485 for _, name := range scripts {
486 req := httptest.NewRequest(http.MethodGet, "/static/"+name, nil)
487 req.Host = host
488 rec := httptest.NewRecorder()
489 app.Router().ServeHTTP(rec, req)
490 if want, ok := estiloServed[name]; ok {
491 if rec.Code != http.StatusOK || !bytes.Equal(rec.Body.Bytes(), want) {
492 t.Errorf("%s /static/%s: %d, want estilo's copy", host, name, rec.Code)
493 }
494 continue
495 }
496 if rec.Code != http.StatusNotFound {
497 t.Errorf("%s /static/%s: %d, want 404 (Home serves no rastrillo script)", host, name, rec.Code)
498 }
499 }
500 }
501}
502
503// No handler in this package may set its own Content-Security-Policy.
504//
505// rastrillo's securityHeaders sets the default on every response, and a
506// handler's own header REPLACES it — the one move that turns ruling
507// 21's carve-out into a blanket exemption, and it would show up in no
508// rendered page.
509//
510// What this adds over TestServedCSPAllowsNoInlineScript, which does now
511// reach all twenty-three routes: a route added later and not yet swept,
512// and a code path inside a handler that the sweep's one canned request
513// does not take — a branch behind a form value, an error path.
514//
515// What it does NOT add, contrary to an earlier version of this comment:
516// coverage of the three passkey ceremony endpoints. Those handlers live
517// in rastrillo's passkey package, and this globs *.go in THIS package,
518// so it never reads them. The runtime sweep is what covers those.
519//
520// It is also evadable by anyone trying: a header key built by
521// concatenation does not contain the literal string. That is acceptable
522// — this is the belt and the sweep is the braces, and the braces reach
523// every route.
524func TestNoHandlerSetsItsOwnCSP(t *testing.T) {
525 files, err := filepath.Glob("*.go")
526 if err != nil {
527 t.Fatal(err)
528 }
529 var checked int
530 for _, f := range files {
531 // security.go's setConsumerPolicy is the one exception: it may only
532 // add one registered consumer to form-action, and
533 // TestConsumerPolicyOnlyWidensFormAction holds it to that.
534 if strings.HasSuffix(f, "_test.go") || f == "security.go" {
535 continue
536 }
537 checked++
538 b, err := os.ReadFile(f)
539 if err != nil {
540 t.Fatal(err)
541 }
542 if bytes.Contains(bytes.ToLower(b), []byte("content-security-policy")) {
543 t.Errorf("%s mentions Content-Security-Policy; a handler's own header replaces "+
544 "rastrillo's default, which is how the passkey carve-out would quietly "+
545 "become a blanket one", f)
546 }
547 }
548 if checked == 0 {
549 t.Fatal("scanned no files; the guard would pass by not looking")
550 }
551}
552
553// busyScript is the one script every non-hop page carries: estilo's busy
554// rule, a progressive enhancement over forms that work without it.
555var busyScript = regexp.MustCompile(`<script defer src=["']/static/busy\.js\?v=[0-9a-f]{16}["']></script>`)
556
557// hasOtherScript reports whether a rendered page carries any script
558// beyond the busy rule — what "no script" means for a page since the
559// busy rule arrived.
560func hasOtherScript(body string) bool {
561 return strings.Contains(busyScript.ReplaceAllString(body, ""), "<script")
562}
563
564// The operator endpoint's pages and routes, which the sweep above cannot
565// reach (its fixture has no HOME_OPERATOR_HTTP): both confirm pages on both
566// outcomes and both transport routes, on both origins, under the served
567// policy. No inline or eval'd script, and no script but estilo's busy rule.
568func TestOperatorPagesUnderTheScriptlessSweep(t *testing.T) {
569 f := newOperatorFixture(t)
570 signInFully(t, f.credential, sealtest.CanaryAddress)
571 f.submit(t, "directory", "create-team", []string{"docs"})
572 f.submit(t, "credential", "create-team", []string{"docs"})
573 paul := f.paulCredential(t)
574 directory := f.paulDirectory(t, paul)
575 stranger := signInFully(t, f.credential, "stranger@example.invalid")
576 type probe struct {
577 role, method, path string
578 form url.Values
579 cookie *http.Cookie
580 }
581 probes := []probe{
582 {"credential", "GET", operatorConfirm, nil, paul},
583 {"credential", "GET", operatorConfirm, nil, stranger},
584 {"credential", "GET", operatorConfirm, nil, nil},
585 {"credential", "POST", operatorConfirm, url.Values{"plan": {fixtureToken(90)}, "owner": {"wrong@example.invalid"}}, paul},
586 {"credential", "POST", operatorConfirm, url.Values{"plan": {fixtureToken(90)}, "owner": {sealtest.CanaryAddress}}, paul},
587 {"directory", "GET", operatorConfirm, nil, directory},
588 {"directory", "GET", operatorConfirm, nil, nil},
589 {"directory", "POST", operatorConfirm, url.Values{"plan": {fixtureToken(91)}}, directory},
590 {"directory", "POST", operatorConfirm, url.Values{"plan": {fixtureToken(90)}}, directory},
591 {"credential", "POST", operatorPath, nil, nil},
592 {"directory", "POST", operatorPlanPath, nil, nil},
593 }
594 for i, p := range probes {
595 a := f.app(p.role)
596 mux := http.NewServeMux()
597 mux.Handle("/", a.Router())
598 h, cleanup, err := rastrillo.Handler(rastrillo.Options{Mux: mux, Logger: quietLogger(), CSP: a.SecurityPolicy()})
599 if err != nil {
600 t.Fatal(err)
601 }
602 if cleanup != nil {
603 t.Cleanup(func() { cleanup() })
604 }
605 body := ""
606 if p.form != nil {
607 body = p.form.Encode()
608 }
609 req := httptest.NewRequest(p.method, roleOrigin(p.role)+p.path, strings.NewReader(body))
610 if p.form != nil {
611 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
612 req.Header.Set("Origin", roleOrigin(p.role))
613 }
614 if p.cookie != nil {
615 req.AddCookie(p.cookie)
616 }
617 rec := httptest.NewRecorder()
618 h.ServeHTTP(rec, req)
619 csp := rec.Header().Get("Content-Security-Policy")
620 if !strings.Contains(csp, "default-src 'self'") || strings.Contains(csp, "'unsafe-eval'") || strings.Contains(strings.Replace(csp, "style-src 'self' 'unsafe-inline'", "", 1), "'unsafe-inline'") {
621 t.Errorf("probe %d (%s %s %s): CSP %q", i, p.role, p.method, p.path, csp)
622 }
623 if hasOtherScript(rec.Body.String()) {
624 t.Errorf("probe %d (%s %s %s, %d) carries a script beyond busy.js", i, p.role, p.method, p.path, rec.Code)
625 }
626 }
627 if f.openCount(t, f.directory) != 1 || f.openCount(t, f.credential.App) != 1 {
628 t.Fatal("the sweep did not reach the confirm pages' success paths")
629 }
630}
631
632// The door is rastrillo's partial, whose <script> the source sweep above
633// cannot see (it reads Home's templates), so its every state is swept
634// rendered: each script it loads is one of Home's, never inline, and with
635// every script stripped each state keeps a way in that works without
636// one. The passkey door's button is the one allowed affordance that needs
637// script (ruling 25), and it is drawn visible-but-disabled before
638// enhancement, with a <noscript> line and Other ways right below it.
639func TestDoorStatesUnderTheScriptRule(t *testing.T) {
640 app := newTestApp(t)
641 link := sealedRecord(t, app.App, lastsignin.Record{Method: lastsignin.MethodMagicLink, Address: "kept@example.invalid"})
642 keymail := sealedRecord(t, app.App, lastsignin.Record{Method: lastsignin.MethodKeymail, Address: "kept@example.invalid"})
643 remembered := sealedRecord(t, app.App, lastsignin.Record{Method: lastsignin.MethodPasskey})
644 type state struct {
645 path string
646 cookie *http.Cookie
647 // what survives stripping: a form posting somewhere, or a link on
648 works []string
649 }
650 states := []state{
651 {"/signin", nil, []string{`action="/signin"`, `name="address"`, `type="submit"`, "Other ways to sign in"}},
652 {"/signin?ways=1&way=email", nil, []string{`href="/signin?way=passkey"`, "<span>Back</span>"}},
653 {"/signin", link, []string{`action="/signin"`, `name="address" value="kept@example.invalid"`, `type="submit"`}},
654 {"/signin", keymail, []string{`action="/signin"`, `name="expect" value="keymail"`, `type="submit"`}},
655 {"/signin", remembered, []string{"<noscript><p>To use a passkey, turn on JavaScript.</p></noscript>", `href="/signin?way=passkey&amp;ways=1"`}},
656 {"/signin?ways=1&way=passkey", remembered, []string{`href="/signin?way=email"`, `action="/signin/forget"`}},
657 {"/signin?force=1", keymail, []string{`action="/signin?force=1"`, `name="force" value="1"`}},
658 {"/signin?err=rate", nil, []string{`action="/signin"`, `name="address"`}},
659 {"/signin/sent", link, []string{`action="/signin/forget"`}},
660 }
661 for _, s := range states {
662 var cookies []*http.Cookie
663 if s.cookie != nil {
664 cookies = append(cookies, s.cookie)
665 }
666 body := doorGet(t, app, s.path, cookies...).Body.String()
667 for _, src := range scriptSrcs([]byte(body)) {
668 if i := strings.Index(src, "?v="); i >= 0 {
669 src = src[:i]
670 }
671 if !slices.Contains(homeScripts, src) {
672 t.Errorf("%s: loads %q, not one of Home's scripts", s.path, src)
673 }
674 }
675 stripped := scriptTag.ReplaceAllString(body, "")
676 for _, w := range s.works {
677 if !strings.Contains(stripped, w) {
678 t.Errorf("%s: without script, lost %q", s.path, w)
679 }
680 }
681 if strings.Contains(stripped, "data-rst-passkey") && !strings.Contains(stripped, "<noscript>") && !strings.Contains(stripped, "data-rst-passkey-conditional") {
682 t.Errorf("%s: a passkey control with no script-off way past it", s.path)
683 }
684 }
685 // The module the door loads is rastrillo's, served at its stable path.
686 r := httptest.NewRequest(http.MethodGet, signinModule, nil)
687 r.Host = credentialHost
688 w := httptest.NewRecorder()
689 app.Router().ServeHTTP(w, r)
690 if w.Code != 200 || !bytes.Equal(w.Body.Bytes(), passkey.JS()) || w.Header().Get("Content-Type") != "text/javascript; charset=utf-8" {
691 t.Fatal("the door's module is not rastrillo's passkey.JS()", w.Code)
692 }
693}
694