| 1 | package scratchpad_test |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/tls" |
| 6 | "encoding/json" |
| 7 | "html" |
| 8 | "io" |
| 9 | "log/slog" |
| 10 | "net" |
| 11 | "net/http" |
| 12 | "net/http/cookiejar" |
| 13 | "net/http/httptest" |
| 14 | "net/url" |
| 15 | "os" |
| 16 | "regexp" |
| 17 | "strings" |
| 18 | "testing" |
| 19 | "time" |
| 20 | |
| 21 | "amadan.net/rastrillo/rastrillo/assertion" |
| 22 | "amadan.net/rastrillo/rastrillo/budget" |
| 23 | "amadan.net/rastrillo/rastrillo/crypto" |
| 24 | "amadan.net/rastrillo/rastrillo/db" |
| 25 | "amadan.net/rastrillo/rastrillo/dbtest" |
| 26 | |
| 27 | "amadan.net/oficina/base/internal/config" |
| 28 | "amadan.net/oficina/base/internal/consumer" |
| 29 | "amadan.net/oficina/base/internal/install" |
| 30 | "amadan.net/oficina/base/internal/scratchpad" |
| 31 | ) |
| 32 | |
| 33 | const ( |
| 34 | issuerOrigin = "https://base.test" |
| 35 | appOrigin = "https://acme-scratchpad.test" |
| 36 | ) |
| 37 | |
| 38 | var schema = dbtest.FromSet(scratchpad.BootSchema) |
| 39 | |
| 40 | func TestMain(m *testing.M) { |
| 41 | code := budget.Main(m) |
| 42 | schema.Remove() |
| 43 | os.Exit(code) |
| 44 | } |
| 45 | |
| 46 | type pad struct { |
| 47 | t *testing.T |
| 48 | key *crypto.Keypair |
| 49 | addr string |
| 50 | } |
| 51 | |
| 52 | // newPad serves Scratchpad over TLS, configured as Base would install it. |
| 53 | func newPad(t *testing.T) *pad { |
| 54 | t.Helper() |
| 55 | key, err := crypto.Generate() |
| 56 | if err != nil { |
| 57 | t.Fatal(err) |
| 58 | } |
| 59 | vars := install.AppVars(config.Config{Origin: issuerOrigin, AssertionKey: key}, "scratchpad", appOrigin) |
| 60 | cfg, err := consumer.Load(func(k string) string { return vars[k] }) |
| 61 | if err != nil { |
| 62 | t.Fatal(err) |
| 63 | } |
| 64 | logger := slog.New(slog.NewTextHandler(io.Discard, nil)) |
| 65 | d, err := db.Open(schema.Path(t), logger) |
| 66 | if err != nil { |
| 67 | t.Fatal(err) |
| 68 | } |
| 69 | t.Cleanup(func() { d.Close() }) |
| 70 | h, err := scratchpad.App(d, cfg, logger) |
| 71 | if err != nil { |
| 72 | t.Fatalf("App: %v", err) |
| 73 | } |
| 74 | srv := httptest.NewTLSServer(h) // 127.0.0.1 only |
| 75 | t.Cleanup(srv.Close) |
| 76 | return &pad{t: t, key: key, addr: srv.Listener.Addr().String()} |
| 77 | } |
| 78 | |
| 79 | type resp struct { |
| 80 | Code int |
| 81 | Header http.Header |
| 82 | Body string |
| 83 | } |
| 84 | |
| 85 | type browser struct { |
| 86 | p *pad |
| 87 | client *http.Client |
| 88 | } |
| 89 | |
| 90 | func (p *pad) browser() *browser { |
| 91 | jar, _ := cookiejar.New(nil) |
| 92 | tr := &http.Transport{ |
| 93 | DialContext: func(ctx context.Context, network, _ string) (net.Conn, error) { |
| 94 | return (&net.Dialer{}).DialContext(ctx, network, p.addr) |
| 95 | }, |
| 96 | TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // the test server's own certificate |
| 97 | } |
| 98 | p.t.Cleanup(tr.CloseIdleConnections) |
| 99 | return &browser{p: p, client: &http.Client{Jar: jar, Transport: tr, |
| 100 | CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}} |
| 101 | } |
| 102 | |
| 103 | func (b *browser) do(method, path string, form url.Values, origin string) resp { |
| 104 | b.p.t.Helper() |
| 105 | var body io.Reader |
| 106 | if form != nil { |
| 107 | body = strings.NewReader(form.Encode()) |
| 108 | } |
| 109 | req, _ := http.NewRequest(method, appOrigin+path, body) |
| 110 | if form != nil { |
| 111 | req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| 112 | } |
| 113 | if origin != "" { |
| 114 | req.Header.Set("Origin", origin) |
| 115 | } |
| 116 | res, err := b.client.Do(req) |
| 117 | if err != nil { |
| 118 | b.p.t.Fatal(err) |
| 119 | } |
| 120 | defer res.Body.Close() |
| 121 | raw, _ := io.ReadAll(res.Body) |
| 122 | return resp{res.StatusCode, res.Header, string(raw)} |
| 123 | } |
| 124 | |
| 125 | func (b *browser) get(path string) resp { b.p.t.Helper(); return b.do(http.MethodGet, path, nil, "") } |
| 126 | |
| 127 | var revisionRE = regexp.MustCompile(`<input type="hidden" name="revision" value="([0-9]+)">`) |
| 128 | |
| 129 | // revision is the revision the notepad form on body carries, or "". |
| 130 | func revision(body string) string { |
| 131 | if m := revisionRE.FindStringSubmatch(body); m != nil { |
| 132 | return m[1] |
| 133 | } |
| 134 | return "" |
| 135 | } |
| 136 | |
| 137 | // save loads the page and posts its notepad form with note, as a person |
| 138 | // editing it would. |
| 139 | func (b *browser) save(note string) resp { |
| 140 | b.p.t.Helper() |
| 141 | return b.saveAt(revision(b.get("/").Body), note) |
| 142 | } |
| 143 | |
| 144 | // saveAt posts the notepad form as a page loaded at rev would. |
| 145 | func (b *browser) saveAt(rev, note string) resp { |
| 146 | b.p.t.Helper() |
| 147 | return b.do(http.MethodPost, "/", url.Values{"note": {note}, "revision": {rev}}, appOrigin) |
| 148 | } |
| 149 | |
| 150 | // signIn runs the handoff with an assertion signed as Base would sign it. |
| 151 | func (b *browser) signIn(sub, name, base string) { |
| 152 | b.p.t.Helper() |
| 153 | r := b.get("/") |
| 154 | if r.Code != http.StatusSeeOther { |
| 155 | b.p.t.Fatalf("signed-out page: %d", r.Code) |
| 156 | } |
| 157 | r = b.get(r.Header.Get("Location")) |
| 158 | u, _ := url.Parse(r.Header.Get("Location")) |
| 159 | if r.Code != http.StatusSeeOther || u.Host != "base.test" { |
| 160 | b.p.t.Fatalf("start: %d %q", r.Code, r.Header.Get("Location")) |
| 161 | } |
| 162 | kid, _ := install.KeySet(b.p.key) |
| 163 | jti, _ := assertion.RandomID() |
| 164 | ext, _ := json.Marshal(map[string]string{"name": name, "email": sub + "@acme.test", "base": base}) |
| 165 | now := time.Now().Unix() |
| 166 | token, err := assertion.Sign(b.p.key, assertion.Claims{Version: 1, Issuer: issuerOrigin, Audience: appOrigin, |
| 167 | Subject: sub, KeyID: kid, ID: jti, Nonce: u.Query().Get("nonce"), IssuedAt: now, ExpiresAt: now + 120, AuthTime: now, Ext: ext}) |
| 168 | if err != nil { |
| 169 | b.p.t.Fatal(err) |
| 170 | } |
| 171 | if r := b.do(http.MethodPost, consumer.AssertionPath, url.Values{"assertion": {token}}, issuerOrigin); r.Code != http.StatusSeeOther { |
| 172 | b.p.t.Fatalf("assertion: %d %s", r.Code, r.Body) |
| 173 | } |
| 174 | if r := b.get(consumer.FinishPath); r.Code != http.StatusSeeOther || r.Header.Get("Location") != "/" { |
| 175 | b.p.t.Fatalf("finish: %d %q", r.Code, r.Header.Get("Location")) |
| 176 | } |
| 177 | } |
| 178 | |
| 179 | func TestNotesSharedAcrossMembers(t *testing.T) { |
| 180 | p := newPad(t) |
| 181 | paul, ana := p.browser(), p.browser() |
| 182 | paul.signIn("member-paul", "Paul", "Acme Ltd") |
| 183 | ana.signIn("member-ana", "Ana", "Acme Ltd") |
| 184 | |
| 185 | page := paul.get("/") |
| 186 | if page.Code != 200 || !strings.Contains(page.Body, "Signed in as Paul, Acme Ltd") { |
| 187 | t.Fatalf("Paul's page: %d\n%s", page.Code, page.Body) |
| 188 | } |
| 189 | if !strings.Contains(page.Body, `<textarea`) || !strings.Contains(page.Body, `name="note"`) || !strings.Contains(page.Body, `method="post"`) { |
| 190 | t.Fatalf("no notepad form:\n%s", page.Body) |
| 191 | } |
| 192 | |
| 193 | note := "Order more coffee <b>today</b> & tomorrow" |
| 194 | if r := paul.save(note); r.Code != http.StatusSeeOther || r.Header.Get("Location") != "/" { |
| 195 | t.Fatalf("save: %d %q %s", r.Code, r.Header.Get("Location"), r.Body) |
| 196 | } |
| 197 | page = ana.get("/") |
| 198 | if page.Code != 200 || !strings.Contains(page.Body, "Signed in as Ana, Acme Ltd") { |
| 199 | t.Fatalf("Ana's page: %d\n%s", page.Code, page.Body) |
| 200 | } |
| 201 | if !strings.Contains(page.Body, html.EscapeString(note)) { |
| 202 | t.Fatalf("Ana does not see Paul's note:\n%s", page.Body) |
| 203 | } |
| 204 | if strings.Contains(page.Body, "<b>today</b>") { |
| 205 | t.Errorf("the note is not escaped") |
| 206 | } |
| 207 | |
| 208 | // Ana's edit replaces it for Paul too. |
| 209 | if r := ana.save("Coffee ordered"); r.Code != http.StatusSeeOther { |
| 210 | t.Fatalf("Ana's save: %d", r.Code) |
| 211 | } |
| 212 | if page := paul.get("/"); !strings.Contains(page.Body, "Coffee ordered") || strings.Contains(page.Body, "tomorrow") { |
| 213 | t.Errorf("Paul's page after Ana's edit:\n%s", page.Body) |
| 214 | } |
| 215 | } |
| 216 | |
| 217 | func TestNotesNeedSignIn(t *testing.T) { |
| 218 | p := newPad(t) |
| 219 | b := p.browser() |
| 220 | if r := b.get("/"); r.Code != http.StatusSeeOther || r.Header.Get("Location") != consumer.StartPath+"?return_to=%2F" { |
| 221 | t.Fatalf("signed-out page: %d %q", r.Code, r.Header.Get("Location")) |
| 222 | } |
| 223 | if r := b.save("hello"); r.Code != http.StatusForbidden { |
| 224 | t.Fatalf("signed-out save: %d", r.Code) |
| 225 | } |
| 226 | } |
| 227 | |
| 228 | func TestNotesRefuseCrossOriginSave(t *testing.T) { |
| 229 | p := newPad(t) |
| 230 | b := p.browser() |
| 231 | b.signIn("member-paul", "Paul", "Acme Ltd") |
| 232 | b.save("kept") |
| 233 | for _, origin := range []string{"https://evil.test", issuerOrigin} { |
| 234 | if r := b.do(http.MethodPost, "/", url.Values{"note": {"defaced"}}, origin); r.Code != http.StatusForbidden { |
| 235 | t.Errorf("save from %s: %d, want 403", origin, r.Code) |
| 236 | } |
| 237 | } |
| 238 | if page := b.get("/"); !strings.Contains(page.Body, "kept") || strings.Contains(page.Body, "defaced") { |
| 239 | t.Errorf("note changed by a cross-origin post:\n%s", page.Body) |
| 240 | } |
| 241 | } |
| 242 | |
| 243 | func TestNotesRefuseOversizedNote(t *testing.T) { |
| 244 | p := newPad(t) |
| 245 | b := p.browser() |
| 246 | b.signIn("member-paul", "Paul", "Acme Ltd") |
| 247 | if r := b.save(strings.Repeat("x", 70*1024)); r.Code == http.StatusSeeOther { |
| 248 | t.Fatalf("a 70 KiB note was saved") |
| 249 | } |
| 250 | } |
| 251 | |
| 252 | func TestScratchpadServesTheLook(t *testing.T) { |
| 253 | p := newPad(t) |
| 254 | b := p.browser() |
| 255 | b.signIn("member-paul", "Paul", "Acme Ltd") |
| 256 | page := b.get("/") |
| 257 | i := strings.Index(page.Body, `href="/static/app.`) |
| 258 | if i < 0 { |
| 259 | t.Fatalf("no stylesheet link:\n%s", page.Body) |
| 260 | } |
| 261 | href := page.Body[i+len(`href="`):] |
| 262 | href = href[:strings.Index(href, `"`)] |
| 263 | if r := b.get(href); r.Code != 200 || !strings.Contains(r.Header.Get("Content-Type"), "css") { |
| 264 | t.Errorf("stylesheet %s: %d %q", href, r.Code, r.Header.Get("Content-Type")) |
| 265 | } |
| 266 | } |
| 267 | |
| 268 | // Finding 6 (R29): two people edit the same note; the second save is refused |
| 269 | // and keeps what they typed, and saving again from there replaces the note. |
| 270 | func TestStaleSaveIsRefused(t *testing.T) { |
| 271 | p := newPad(t) |
| 272 | paul, ana := p.browser(), p.browser() |
| 273 | paul.signIn("member-paul", "Paul", "Acme Ltd") |
| 274 | ana.signIn("member-ana", "Ana", "Acme Ltd") |
| 275 | paul.save("first draft") |
| 276 | |
| 277 | paulRev, anaRev := revision(paul.get("/").Body), revision(ana.get("/").Body) |
| 278 | if paulRev == "" || paulRev != anaRev { |
| 279 | t.Fatalf("revisions %q and %q", paulRev, anaRev) |
| 280 | } |
| 281 | if r := paul.saveAt(paulRev, "Paul's <edit>"); r.Code != http.StatusSeeOther { |
| 282 | t.Fatalf("Paul's save: %d", r.Code) |
| 283 | } |
| 284 | r := ana.saveAt(anaRev, "Ana's edit") |
| 285 | if r.Code != http.StatusConflict { |
| 286 | t.Fatalf("stale save: %d, want 409\n%s", r.Code, r.Body) |
| 287 | } |
| 288 | if !strings.Contains(r.Body, "Someone else saved this note while you were editing it.") { |
| 289 | t.Errorf("no explanation:\n%s", r.Body) |
| 290 | } |
| 291 | if !strings.Contains(r.Body, "\nAna's edit</textarea>") { |
| 292 | t.Errorf("Ana's text is not in the form:\n%s", r.Body) |
| 293 | } |
| 294 | if !strings.Contains(r.Body, html.EscapeString("Paul's <edit>")) { |
| 295 | t.Errorf("the saved note is not shown:\n%s", r.Body) |
| 296 | } |
| 297 | if page := paul.get("/"); !strings.Contains(page.Body, html.EscapeString("Paul's <edit>")) || strings.Contains(page.Body, "Ana") { |
| 298 | t.Fatalf("the stale save changed the note:\n%s", page.Body) |
| 299 | } |
| 300 | // Saving the refused page again is a deliberate replace. |
| 301 | if r := ana.saveAt(revision(r.Body), "Ana's edit"); r.Code != http.StatusSeeOther { |
| 302 | t.Fatalf("second save: %d\n%s", r.Code, r.Body) |
| 303 | } |
| 304 | if page := paul.get("/"); !strings.Contains(page.Body, "Ana's edit") { |
| 305 | t.Errorf("Ana's second save did not land:\n%s", page.Body) |
| 306 | } |
| 307 | // A form with no revision is not a save of anything in particular. |
| 308 | if r := ana.saveAt("", "no revision"); r.Code != http.StatusConflict { |
| 309 | t.Errorf("save without a revision: %d", r.Code) |
| 310 | } |
| 311 | } |
| 312 | |
| 313 | // Findings 7 and 8: Scratchpad links back to Base's Home, and signs out of |
| 314 | // itself onto the shared signed-out page. |
| 315 | func TestScratchpadLinksHomeAndSignsOut(t *testing.T) { |
| 316 | p := newPad(t) |
| 317 | b := p.browser() |
| 318 | b.signIn("member-paul", "Paul", "Acme Ltd") |
| 319 | page := b.get("/").Body |
| 320 | if !strings.Contains(page, `<div class="crumb"><a class="wordmark" href="`+issuerOrigin+`/">base</a>`) { |
| 321 | t.Errorf("no link to Base's Home:\n%s", page) |
| 322 | } |
| 323 | if !strings.Contains(page, `<form method="post" action="/auth/signout"><button class="btn ghost" type="submit">Sign out of Scratchpad</button></form>`) { |
| 324 | t.Errorf("no sign-out control:\n%s", page) |
| 325 | } |
| 326 | if r := b.do(http.MethodPost, consumer.SignOutPath, url.Values{}, appOrigin); r.Code != http.StatusSeeOther || r.Header.Get("Location") != consumer.SignedOutPath { |
| 327 | t.Fatalf("sign out: %d %q", r.Code, r.Header.Get("Location")) |
| 328 | } |
| 329 | if r := b.get("/"); r.Code != http.StatusSeeOther || !strings.HasPrefix(r.Header.Get("Location"), consumer.StartPath) { |
| 330 | t.Fatalf("still signed in after signing out: %d", r.Code) |
| 331 | } |
| 332 | } |
| 333 | |