| 1 | //go:build browser |
| 2 | |
| 3 | package memoriatest |
| 4 | |
| 5 | import ( |
| 6 | "bytes" |
| 7 | "context" |
| 8 | "crypto/sha256" |
| 9 | "encoding/base64" |
| 10 | "encoding/json" |
| 11 | "io" |
| 12 | "log/slog" |
| 13 | "mime/multipart" |
| 14 | "net/http" |
| 15 | "path/filepath" |
| 16 | "regexp" |
| 17 | "strings" |
| 18 | "testing" |
| 19 | "time" |
| 20 | |
| 21 | "amadan.net/rastrillo/rastrillo" |
| 22 | "amadan.net/rastrillo/rastrillo/db" |
| 23 | "amadan.net/rastrillo/rastrillo/harness" |
| 24 | "github.com/chromedp/cdproto/page" |
| 25 | "github.com/chromedp/chromedp" |
| 26 | |
| 27 | memoria "amadan.net/oficina/memoria/internal/memoria" |
| 28 | ) |
| 29 | |
| 30 | // cspWatch records every securitypolicyviolation a page raises, from |
| 31 | // before its first byte is parsed, into window.__csp. |
| 32 | const cspWatch = `window.__csp = []; |
| 33 | document.addEventListener("securitypolicyviolation", e => |
| 34 | window.__csp.push(e.violatedDirective + " " + (e.blockedURI || "inline") + " " + (e.sample || "")));` |
| 35 | |
| 36 | // cspProbe is the presence half. It writes one inline style attribute the |
| 37 | // way a page or script would, and reports whether the browser refused it. |
| 38 | // A refusal proves the listener is live and the page really runs under a |
| 39 | // policy that blocks inline styles. Without it, "no violations" would pass |
| 40 | // against a policy that allows inline styles, or a listener that never |
| 41 | // attached. |
| 42 | const cspProbe = `new Promise(done => { |
| 43 | const before = window.__csp.length; |
| 44 | const probe = document.createElement("i"); |
| 45 | probe.setAttribute("style", "outline: 1px solid"); |
| 46 | document.body.appendChild(probe); |
| 47 | setTimeout(() => { |
| 48 | const refused = window.__csp.length > before; |
| 49 | window.__csp.length = before; |
| 50 | probe.remove(); |
| 51 | done(refused); |
| 52 | }, 200); |
| 53 | })` |
| 54 | |
| 55 | // TestPagesRenderUnderTheProductionCSP: every page Memoria serves |
| 56 | // standalone, in Chromium, through rastrillo's production stack |
| 57 | // (memoria.ServeOptions under rastrillo.Handler, so the real CSP), raises |
| 58 | // no Content-Security-Policy violation. That includes the sign-in door, |
| 59 | // the confirm door an emailed link opens on, the signed-in pages, and |
| 60 | // search.js's live results swapped in by script. rastrillo fb806a2 refuses |
| 61 | // inline style attributes by default, and this is the check that nothing |
| 62 | // Memoria draws or scripts relies on one. |
| 63 | // |
| 64 | // The plain-Go TestNoPageCarriesAStyleAttribute reads the served markup in |
| 65 | // CI; this one also sees what scripts do after load. The other browser |
| 66 | // checks serve the bare router and get no CSP at all, so they could not |
| 67 | // catch this. |
| 68 | // |
| 69 | // MUTATIONS (author-chosen, 2026-10-06; an independent pass is owed per |
| 70 | // AGENTS.md): style="color:red" on the confirm form in signin.html fails |
| 71 | // here; ServeOptions setting the pre-fb806a2 policy (style-src 'self' |
| 72 | // 'unsafe-inline') fails the probe; the native approval route without its |
| 73 | // hash (651f370) fails on style-src-elem; search.js assigning |
| 74 | // main.style.outline fails the [style] check. Reverted. |
| 75 | func TestPagesRenderUnderTheProductionCSP(t *testing.T) { |
| 76 | logger := slog.New(slog.NewTextHandler(io.Discard, nil)) |
| 77 | served := func(t *testing.T, test bool) func(origin string) http.Handler { |
| 78 | return func(origin string) http.Handler { |
| 79 | d, err := db.Open(filepath.Join(t.TempDir(), "app.db"), logger) |
| 80 | if err != nil { |
| 81 | t.Fatalf("db.Open: %v", err) |
| 82 | } |
| 83 | t.Cleanup(func() { d.Close() }) |
| 84 | build := memoria.App |
| 85 | if test { |
| 86 | build = memoria.AppForTest |
| 87 | } |
| 88 | mux, a, err := build(d, origin, testDEK(t), logger) |
| 89 | if err != nil { |
| 90 | t.Fatalf("App: %v", err) |
| 91 | } |
| 92 | if !test { |
| 93 | a.SetOwners([]string{chromeOwner}) |
| 94 | au, err := memoria.NewAuth(d.Writer(), memoria.AuthEnv{ |
| 95 | Origin: origin, InstanceKey: "csp-browser-instance-key", |
| 96 | Owners: []string{chromeOwner}, Mailer: &capturingMailer{}, |
| 97 | }, logger, a) |
| 98 | if err != nil { |
| 99 | t.Fatalf("NewAuth: %v", err) |
| 100 | } |
| 101 | a.UseAuth(au) |
| 102 | a.MountAuth(mux, origin) |
| 103 | } |
| 104 | h, done, err := rastrillo.Handler(a.ServeOptions(rastrillo.Options{Logger: logger}, mux)) |
| 105 | if err != nil { |
| 106 | t.Fatalf("rastrillo.Handler: %v", err) |
| 107 | } |
| 108 | if done != nil { |
| 109 | t.Cleanup(func() { _ = done() }) |
| 110 | } |
| 111 | return h |
| 112 | } |
| 113 | } |
| 114 | |
| 115 | visit := func(t *testing.T, rig *harness.Rig, path, ready string, then ...chromedp.Action[chromedp.Void]) { |
| 116 | t.Helper() |
| 117 | ctx, cancel := context.WithTimeout(rig.Context(), 20*time.Second) |
| 118 | defer cancel() |
| 119 | var violations, styled []string |
| 120 | var refused bool |
| 121 | actions := []chromedp.Action[chromedp.Void]{ |
| 122 | chromedp.Navigate(rig.Origin + path), |
| 123 | chromedp.WaitVisible(chromedp.CSS(ready)), |
| 124 | } |
| 125 | actions = append(actions, then...) |
| 126 | actions = append(actions, |
| 127 | chromedp.Sleep(150*time.Millisecond), |
| 128 | evalInto(&violations, `window.__csp`), |
| 129 | // A script assigning element.style.x raises no violation (the |
| 130 | // CSSOM is not policed), so look at the DOM itself too (Astra |
| 131 | // on #27): no element may carry a style attribute. |
| 132 | evalInto(&styled, `[...document.querySelectorAll("[style]")].map(e => e.tagName.toLowerCase() + '[style="' + e.getAttribute("style") + '"]')`), |
| 133 | evalInto(&refused, cspProbe, chromedp.EvalAwaitPromise), |
| 134 | ) |
| 135 | if err := chromedp.Do(ctx, actions...); err != nil { |
| 136 | t.Fatalf("%s: %v", path, err) |
| 137 | } |
| 138 | if len(violations) > 0 { |
| 139 | t.Errorf("%s: the production CSP refused: %s", path, strings.Join(violations, "; ")) |
| 140 | } |
| 141 | if len(styled) > 0 { |
| 142 | t.Errorf("%s: elements carry inline styles after load: %s", path, strings.Join(styled, "; ")) |
| 143 | } |
| 144 | if !refused { |
| 145 | t.Errorf("%s: an inline style attribute was NOT refused: this page is not under rastrillo's strict policy, or the watch never attached", path) |
| 146 | } |
| 147 | } |
| 148 | watch := func(t *testing.T, rig *harness.Rig) { |
| 149 | t.Helper() |
| 150 | if err := chromedp.Do(rig.Context(), |
| 151 | cdpStep(page.AddScriptToEvaluateOnNewDocument, page.AddScriptToEvaluateOnNewDocumentParams{Source: cspWatch})); err != nil { |
| 152 | t.Fatal(err) |
| 153 | } |
| 154 | } |
| 155 | |
| 156 | t.Run("signed out", func(t *testing.T) { |
| 157 | rig := harness.New(t, served(t, false)) |
| 158 | watch(t, rig) |
| 159 | visit(t, rig, "/signin", `input[name="address"]`) |
| 160 | visit(t, rig, "/signin?err=expired", `[rst-callout]`) |
| 161 | visit(t, rig, "/signin?sent=1", `[estilo-door]`) |
| 162 | visit(t, rig, "/signed-out", `[estilo-door]`) |
| 163 | visit(t, rig, "/auth/verify?token=not-a-real-token", `[rst-signin-form] button[type="submit"]`) |
| 164 | visit(t, rig, "/help/open-source", `main`) |
| 165 | }) |
| 166 | |
| 167 | t.Run("signed in", func(t *testing.T) { |
| 168 | rig := harness.New(t, served(t, true)) |
| 169 | watch(t, rig) |
| 170 | var buf bytes.Buffer |
| 171 | mw := multipart.NewWriter(&buf) |
| 172 | _ = mw.WriteField("title", "Office handbook") |
| 173 | _ = mw.WriteField("body", "The Lisbon office is at Rua Augusta 100.") |
| 174 | mw.Close() |
| 175 | req, _ := http.NewRequest(http.MethodPost, rig.Origin+"/documents", &buf) |
| 176 | req.Header.Set("Content-Type", mw.FormDataContentType()) |
| 177 | req.Header.Set("Origin", rig.Origin) |
| 178 | req.Header.Set("Sec-Fetch-Site", "same-origin") |
| 179 | res, err := http.DefaultClient.Do(req) |
| 180 | if err != nil { |
| 181 | t.Fatalf("store a document: %v", err) |
| 182 | } |
| 183 | res.Body.Close() |
| 184 | |
| 185 | var at string |
| 186 | visit(t, rig, "/documents", `a[href^="/documents/"]`, |
| 187 | attributeInto(chromedp.CSS(`a[href^="/documents/"]`), "href", &at, nil)) |
| 188 | doc := regexp.MustCompile(`^/documents/\d+$`).FindString(at) |
| 189 | if doc == "" { |
| 190 | t.Fatalf("the document list links no document (got %q)", at) |
| 191 | } |
| 192 | // search.js: typing fills the typeahead by script. |
| 193 | visit(t, rig, "/", `form[rst-search] input[type="search"]`, |
| 194 | chromedp.SendKeys(chromedp.CSS(`form[rst-search] input[type="search"]`), "Lisbon"), |
| 195 | chromedp.WaitVisible(chromedp.CSS(`[rst-suggest-box] [rst-suggest-item]`))) |
| 196 | visit(t, rig, "/?q=Lisbon", `main`) |
| 197 | visit(t, rig, "/add", `textarea[name="body"]`) |
| 198 | visit(t, rig, doc, `main`) |
| 199 | visit(t, rig, doc+"/delete", `main`) |
| 200 | visit(t, rig, "/connectors", `main`) |
| 201 | visit(t, rig, "/connectors/notion", `input[name="token"]`) |
| 202 | |
| 203 | // The native kit's approval page (Astra on #27, P2): its whole |
| 204 | // stylesheet is one inline <style>, admitted by hash on that route |
| 205 | // alone (memoria native.go). On 651f370 this was refused |
| 206 | // (style-src-elem), and the card and button went unstyled — so |
| 207 | // also check the stylesheet applied: the button is the kit's |
| 208 | // purple, not the browser's grey. |
| 209 | sum := sha256.Sum256([]byte(strings.Repeat("v", 43))) |
| 210 | nreq, _ := http.NewRequest(http.MethodPost, rig.Origin+"/native/request", |
| 211 | strings.NewReader(`{"challenge":"`+base64.RawURLEncoding.EncodeToString(sum[:])+`"}`)) |
| 212 | nreq.Header.Set("Content-Type", "application/json") |
| 213 | nreq.Header.Set("Origin", rig.Origin) |
| 214 | nres, err := http.DefaultClient.Do(nreq) |
| 215 | if err != nil { |
| 216 | t.Fatalf("POST /native/request: %v", err) |
| 217 | } |
| 218 | var native struct{ ID string } |
| 219 | _ = json.NewDecoder(nres.Body).Decode(&native) |
| 220 | nres.Body.Close() |
| 221 | if native.ID == "" { |
| 222 | t.Fatalf("POST /native/request = %d with no id", nres.StatusCode) |
| 223 | } |
| 224 | var bg string |
| 225 | visit(t, rig, "/native/authorize?id="+native.ID, `main form button`, |
| 226 | evalInto(&bg, `getComputedStyle(document.querySelector("main form button")).backgroundColor`)) |
| 227 | if bg != "rgb(112, 82, 162)" { |
| 228 | t.Errorf("/native/authorize: the approval button's background is %q, want the kit's #7052a2 — its stylesheet did not apply", bg) |
| 229 | } |
| 230 | }) |
| 231 | } |
| 232 | |