| 1 | // Package slidestest tests the app from the outside: real HTTP |
| 2 | // requests against the real router, wired exactly as |
| 3 | // cmd/slides/main.go wires it. |
| 4 | // |
| 5 | // The TDD loop: write a failing test here, make it pass in |
| 6 | // internal/slides, repeat. |
| 7 | package slidestest |
| 8 | |
| 9 | import ( |
| 10 | "context" |
| 11 | "fmt" |
| 12 | "html" |
| 13 | "io" |
| 14 | "log/slog" |
| 15 | "net/http" |
| 16 | "net/http/httptest" |
| 17 | "net/url" |
| 18 | "path/filepath" |
| 19 | "regexp" |
| 20 | "strings" |
| 21 | "sync" |
| 22 | "testing" |
| 23 | |
| 24 | "amadan.net/rastrillo/rastrillo" |
| 25 | "amadan.net/rastrillo/rastrillo/db" |
| 26 | |
| 27 | slides "amadan.net/oficina/slides/internal/slides" |
| 28 | ) |
| 29 | |
| 30 | // testOrigin is the origin newApp wires and post presents as its |
| 31 | // same-origin evidence — the pair a browser form submission would be. |
| 32 | const testOrigin = "http://app.test" |
| 33 | |
| 34 | // allowedAddress is on newConfig's allowlist; deniedAddress is not. |
| 35 | // Named constants rather than literals per test, so a test that means |
| 36 | // "the allowlist let this through" cannot silently become a test about |
| 37 | // a typo. |
| 38 | const ( |
| 39 | allowedAddress = "paul@example.test" |
| 40 | deniedAddress = "someone@else.test" |
| 41 | ) |
| 42 | |
| 43 | // testInstanceKey seals rastrillo/auth's pending blob for a test app. |
| 44 | // Explicit, so the suite exercises the same fully-configured path a |
| 45 | // real deployment takes rather than the development fallbacks — those |
| 46 | // get tests of their own (config_test's refusals). |
| 47 | const testInstanceKey = "slidestest-instance-key-not-a-secret" |
| 48 | |
| 49 | // sentMail is one message the fake mailer captured. |
| 50 | type sentMail struct{ To, Subject, Body string } |
| 51 | |
| 52 | // fakeMailer is the test suite's mail.Sender: it delivers nothing and |
| 53 | // remembers everything, so a test can assert both that a link was sent |
| 54 | // and — the case the allowlist exists for — that one was not. The app |
| 55 | // itself carries no recorder of its own; this is wired in through |
| 56 | // slides.Config.Mailer like any other sender. |
| 57 | type fakeMailer struct { |
| 58 | mu sync.Mutex |
| 59 | sent []sentMail |
| 60 | // flush waits for the app's mail queue: links are sent after the |
| 61 | // response (mailqueue.go), so messages reads only after it. |
| 62 | flush func() |
| 63 | } |
| 64 | |
| 65 | func (m *fakeMailer) Send(_ context.Context, to, subject, body string) error { |
| 66 | m.mu.Lock() |
| 67 | defer m.mu.Unlock() |
| 68 | m.sent = append(m.sent, sentMail{To: to, Subject: subject, Body: body}) |
| 69 | return nil |
| 70 | } |
| 71 | |
| 72 | // messages returns a copy of everything sent so far. |
| 73 | func (m *fakeMailer) messages() []sentMail { |
| 74 | if m.flush != nil { |
| 75 | m.flush() |
| 76 | } |
| 77 | m.mu.Lock() |
| 78 | defer m.mu.Unlock() |
| 79 | return append([]sentMail(nil), m.sent...) |
| 80 | } |
| 81 | |
| 82 | // magicLinkPattern finds the emailed link inside the mail body |
| 83 | // rastrillo/auth writes. Anchored to the app's own verify path so it |
| 84 | // cannot mistake some other URL the body might someday carry for the |
| 85 | // sign-in link itself. |
| 86 | var magicLinkPattern = regexp.MustCompile(`https?://\S+/auth/verify\?token=\S+`) |
| 87 | |
| 88 | // testApp is the wired app plus the two seams a test needs to look |
| 89 | // behind it: the mail the app tried to send, and the database it wrote. |
| 90 | type testApp struct { |
| 91 | http.Handler |
| 92 | mailer *fakeMailer |
| 93 | db *db.DB |
| 94 | // mux is slides.New's own mux, before the locale middleware |
| 95 | // localised puts around it: what production hands rastrillo.Serve, |
| 96 | // and what productionHandler builds the real serving stack over. |
| 97 | mux *http.ServeMux |
| 98 | // app is the built app itself, reachable only through its exported |
| 99 | // methods — slides.New returns an unexported type on purpose, so |
| 100 | // this names the shape rather than the type. Today: Close; the |
| 101 | // export caps, which a test moves so it can prove the refusal |
| 102 | // without first making a 50 MiB PDF; and an empty job registry, so |
| 103 | // a test can reach the fifty minutes in which the file outlives the |
| 104 | // job record without waiting ten. |
| 105 | app interface { |
| 106 | Close() error |
| 107 | SetExportCaps(perDeck, perInstance int64) |
| 108 | ForgetExportJobs() error |
| 109 | FlushMail() |
| 110 | ServeOptions(rastrillo.Options, *http.ServeMux) rastrillo.Options |
| 111 | Drain() |
| 112 | SetFontTrace(func(stage string)) |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | // newConfig is the fully-configured Config every test starts from: |
| 117 | // nothing left to a development fallback, so a test that means to |
| 118 | // exercise one has to ask for it. Tweak the returned value and hand it |
| 119 | // to newAppWith. |
| 120 | func newConfig(t *testing.T) (slides.Config, *fakeMailer) { |
| 121 | t.Helper() |
| 122 | mailer := &fakeMailer{} |
| 123 | return slides.Config{ |
| 124 | KeymailServers: testKeymailServers, |
| 125 | Origin: testOrigin, |
| 126 | InstanceKey: testInstanceKey, |
| 127 | Mailer: mailer, |
| 128 | AllowedAddresses: []string{allowedAddress}, |
| 129 | Logger: slog.New(slog.NewTextHandler(io.Discard, nil)), |
| 130 | }, mailer |
| 131 | } |
| 132 | |
| 133 | // newApp builds the whole app per test over a fresh temp database, |
| 134 | // exactly as main.go does. |
| 135 | func newApp(t *testing.T) *testApp { |
| 136 | t.Helper() |
| 137 | cfg, mailer := newConfig(t) |
| 138 | return newAppWith(t, cfg, mailer) |
| 139 | } |
| 140 | |
| 141 | // newAppWith is newApp with the config spelled out — for the tests |
| 142 | // whose subject is a config decision rather than a screen. |
| 143 | func newAppWith(t *testing.T, cfg slides.Config, mailer *fakeMailer) *testApp { |
| 144 | t.Helper() |
| 145 | d := openTestDB(t, cfg) |
| 146 | mux, a, err := slides.New(d, cfg) |
| 147 | if err != nil { |
| 148 | t.Fatalf("slides.New: %v", err) |
| 149 | } |
| 150 | // Releases the compiled deck core's wazero runtime; every test app |
| 151 | // built over slides.New leaks one without this (task 3 fix round 1). |
| 152 | t.Cleanup(func() { a.Close() }) |
| 153 | if mailer != nil { |
| 154 | mailer.flush = a.FlushMail |
| 155 | } |
| 156 | return &testApp{Handler: localised(t, mux), mailer: mailer, db: d, mux: mux, app: a} |
| 157 | } |
| 158 | |
| 159 | // openTestDB opens a fresh SQLite file for one test, closed on |
| 160 | // cleanup. Separate from newAppWith so a test whose subject is |
| 161 | // slides.New's own refusals can open a database without also expecting |
| 162 | // New to succeed over it. |
| 163 | func openTestDB(t *testing.T, cfg slides.Config) *db.DB { |
| 164 | t.Helper() |
| 165 | logger := cfg.Logger |
| 166 | if logger == nil { |
| 167 | logger = slog.New(slog.NewTextHandler(io.Discard, nil)) |
| 168 | } |
| 169 | d, err := db.Open(filepath.Join(t.TempDir(), "app.db"), logger) |
| 170 | if err != nil { |
| 171 | t.Fatalf("db.Open: %v", err) |
| 172 | } |
| 173 | t.Cleanup(func() { d.Close() }) |
| 174 | return d |
| 175 | } |
| 176 | |
| 177 | // localised wraps the app's mux in the same locale middleware |
| 178 | // rastrillo.Serve mounts around it in production (cmd/slides/main.go |
| 179 | // wires Options.Locales/LocaleFS; Serve builds the middleware from |
| 180 | // them). Without it rastrillo.T returns the key verbatim, so every |
| 181 | // assertion about a rendered string would be an assertion about a key. |
| 182 | func localised(t *testing.T, mux http.Handler) http.Handler { |
| 183 | t.Helper() |
| 184 | loc, err := rastrillo.NewLocales(slides.Locales, slides.DefaultLocale, rastrillo.BaseCatalog(), slides.LocaleFS) |
| 185 | if err != nil { |
| 186 | t.Fatalf("rastrillo.NewLocales: %v", err) |
| 187 | } |
| 188 | return loc.Middleware(mux) |
| 189 | } |
| 190 | |
| 191 | func get(t *testing.T, h http.Handler, target string, cookies ...*http.Cookie) *httptest.ResponseRecorder { |
| 192 | t.Helper() |
| 193 | req := httptest.NewRequest(http.MethodGet, target, nil) |
| 194 | for _, c := range cookies { |
| 195 | req.AddCookie(c) |
| 196 | } |
| 197 | rec := httptest.NewRecorder() |
| 198 | h.ServeHTTP(rec, req) |
| 199 | return rec |
| 200 | } |
| 201 | |
| 202 | // getHTML is a browser navigation. Error pages deliberately distinguish this |
| 203 | // from a client fetch without Accept: text/html. |
| 204 | func getHTML(t *testing.T, h http.Handler, target string, cookies ...*http.Cookie) *httptest.ResponseRecorder { |
| 205 | t.Helper() |
| 206 | req := httptest.NewRequest(http.MethodGet, target, nil) |
| 207 | req.Header.Set("Accept", "text/html") |
| 208 | for _, c := range cookies { |
| 209 | req.AddCookie(c) |
| 210 | } |
| 211 | rec := httptest.NewRecorder() |
| 212 | h.ServeHTTP(rec, req) |
| 213 | return rec |
| 214 | } |
| 215 | |
| 216 | func post(t *testing.T, h http.Handler, target string, form url.Values, cookies ...*http.Cookie) *httptest.ResponseRecorder { |
| 217 | t.Helper() |
| 218 | req := httptest.NewRequest(http.MethodPost, target, strings.NewReader(form.Encode())) |
| 219 | req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| 220 | // The same-origin evidence csrf.Protect requires — every current |
| 221 | // browser sends it on a form POST; a test client must too. |
| 222 | req.Header.Set("Origin", testOrigin) |
| 223 | req.Header.Set("Sec-Fetch-Site", "same-origin") |
| 224 | for _, c := range cookies { |
| 225 | req.AddCookie(c) |
| 226 | } |
| 227 | rec := httptest.NewRecorder() |
| 228 | h.ServeHTTP(rec, req) |
| 229 | return rec |
| 230 | } |
| 231 | |
| 232 | // postLegacy is post without the Sec-Fetch-Site header, with origin as |
| 233 | // the only same-origin evidence. |
| 234 | // |
| 235 | // It exists because post sends both, and csrf.Protect checks |
| 236 | // Sec-Fetch-Site FIRST and never consults Origin at all when it is |
| 237 | // present — so every ordinary test here leaves the app's configured |
| 238 | // Origin entirely unexercised, and would pass with a wrong one. This is |
| 239 | // the shape a non-browser client (or an old browser) sends, and the |
| 240 | // only shape that puts the app's own resolved origin under test. |
| 241 | func postLegacy(t *testing.T, h http.Handler, target, origin string, form url.Values) *httptest.ResponseRecorder { |
| 242 | t.Helper() |
| 243 | req := httptest.NewRequest(http.MethodPost, target, strings.NewReader(form.Encode())) |
| 244 | req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| 245 | req.Header.Set("Origin", origin) |
| 246 | rec := httptest.NewRecorder() |
| 247 | h.ServeHTTP(rec, req) |
| 248 | return rec |
| 249 | } |
| 250 | |
| 251 | // confirmForm is the confirm door's one form, as a browser would read it |
| 252 | // (signin.html's Confirm branch, auth.go's renderConfirm). |
| 253 | var confirmForm = regexp.MustCompile(`<form[^>]*method="post" action="([^"]+)">\s*<input type="hidden" name="token" value="([^"]+)">`) |
| 254 | |
| 255 | // openLink is opening an emailed link: a GET that must spend nothing and |
| 256 | // answer with the confirm door. It returns the door's form action and the |
| 257 | // token it carries, read off the page rather than the link, so a door |
| 258 | // that dropped or mangled the token fails here. |
| 259 | func openLink(t *testing.T, h http.Handler, link string, cookies ...*http.Cookie) (action, token string) { |
| 260 | t.Helper() |
| 261 | u, err := url.Parse(link) |
| 262 | if err != nil { |
| 263 | t.Fatalf("parse emailed link %q: %v", link, err) |
| 264 | } |
| 265 | rec := get(t, h, u.RequestURI(), cookies...) |
| 266 | if rec.Code != http.StatusOK || len(rec.Result().Cookies()) != 0 { |
| 267 | t.Fatalf("GET %s = %d with %d cookies, want 200 and the confirm door, minting nothing", u.Path, rec.Code, len(rec.Result().Cookies())) |
| 268 | } |
| 269 | m := confirmForm.FindStringSubmatch(rec.Body.String()) |
| 270 | if m == nil { |
| 271 | t.Fatalf("GET %s: no confirm form on the page:\n%s", u.Path, rec.Body.String()) |
| 272 | } |
| 273 | return html.UnescapeString(m[1]), html.UnescapeString(m[2]) |
| 274 | } |
| 275 | |
| 276 | // postLink is pressing the confirm door's Sign in button: the token, |
| 277 | // POSTed back to the door's action with a browser's same-origin |
| 278 | // evidence (post sends Origin and Sec-Fetch-Site: same-origin). This is |
| 279 | // the request that spends the link. |
| 280 | func postLink(t *testing.T, h http.Handler, action, token string, cookies ...*http.Cookie) *httptest.ResponseRecorder { |
| 281 | t.Helper() |
| 282 | return post(t, h, action, url.Values{"token": {token}}, cookies...) |
| 283 | } |
| 284 | |
| 285 | // followLink is both: open the emailed link, then press Sign in. |
| 286 | func followLink(t *testing.T, h http.Handler, link string, cookies ...*http.Cookie) *httptest.ResponseRecorder { |
| 287 | t.Helper() |
| 288 | action, token := openLink(t, h, link, cookies...) |
| 289 | return postLink(t, h, action, token, cookies...) |
| 290 | } |
| 291 | |
| 292 | // attemptID is the attempt rastrillo's door puts on a Sent answer |
| 293 | // (/signin?sent=1&attempt=<id>, with SigninScreen on): random per post, |
| 294 | // so two answers are compared with it masked. |
| 295 | var attemptID = regexp.MustCompile(`([?&]attempt=)[^&]*`) |
| 296 | |
| 297 | // masked is loc with its attempt id hidden. |
| 298 | func masked(loc string) string { return attemptID.ReplaceAllString(loc, "${1}…") } |
| 299 | |
| 300 | // isSent reports whether loc is the door's Sent answer: /signin?sent=1, |
| 301 | // with or without the attempt id, and nothing else. |
| 302 | func isSent(loc string) bool { |
| 303 | u, err := url.Parse(loc) |
| 304 | if err != nil || u.Path != "/signin" || u.Query().Get("sent") != "1" { |
| 305 | return false |
| 306 | } |
| 307 | for key := range u.Query() { |
| 308 | if key != "sent" && key != "attempt" { |
| 309 | return false |
| 310 | } |
| 311 | } |
| 312 | return true |
| 313 | } |
| 314 | |
| 315 | // signedIn runs the whole magic-link flow for address against the fake |
| 316 | // mailer — POST /signin, read the link out of the captured message, |
| 317 | // open it and press the confirm door's Sign in — and returns the |
| 318 | // cookies the verify step set. Every later |
| 319 | // test that needs a signed-in request builds on this rather than |
| 320 | // minting a session by hand, so the suite always signs in the way a |
| 321 | // person does. |
| 322 | func signedIn(t *testing.T, a *testApp, address string) []*http.Cookie { |
| 323 | t.Helper() |
| 324 | |
| 325 | before := len(a.mailer.messages()) |
| 326 | rec := post(t, a, "/signin", url.Values{"address": {address}}) |
| 327 | if rec.Code != http.StatusSeeOther { |
| 328 | t.Fatalf("POST /signin as %q: status %d, want %d", address, rec.Code, http.StatusSeeOther) |
| 329 | } |
| 330 | msgs := a.mailer.messages() |
| 331 | if len(msgs) != before+1 { |
| 332 | t.Fatalf("POST /signin as %q: mailer captured %d messages, want %d", address, len(msgs), before+1) |
| 333 | } |
| 334 | link := magicLinkPattern.FindString(msgs[len(msgs)-1].Body) |
| 335 | if link == "" { |
| 336 | t.Fatalf("no magic link in the mailed body for %q:\n%s", address, msgs[len(msgs)-1].Body) |
| 337 | } |
| 338 | verify := followLink(t, a, link) |
| 339 | cookies := verify.Result().Cookies() |
| 340 | if len(cookies) == 0 { |
| 341 | t.Fatalf("following the magic link for %q set no session cookie (status %d)", address, verify.Code) |
| 342 | } |
| 343 | return cookies |
| 344 | } |
| 345 | |
| 346 | // deckWithSlides makes a deck of n slides over the API, as an agent of |
| 347 | // the person whose cookies these are, and returns its editor path |
| 348 | // (/d/{sqid}/edit). The first slide carries 400 words of notes: the |
| 349 | // long deck and the long notes the editor's layout is held against |
| 350 | // (the editor tidied, spec §8). |
| 351 | func deckWithSlides(t *testing.T, a *testApp, cookies []*http.Cookie, n int) string { |
| 352 | t.Helper() |
| 353 | token := mintAgent(t, a, cookies, "deck-with-slides") |
| 354 | sqid := apiDeck(t, a, token, fmt.Sprintf("%d slides", n)) |
| 355 | view := apiJSON(t, a, http.MethodGet, "/api/v1/decks/"+sqid, token, "", http.StatusOK) |
| 356 | slides, _ := view["slides"].([]any) |
| 357 | if len(slides) == 0 || len(slides) > n { |
| 358 | t.Fatalf("a new deck has %d slides; deckWithSlides(%d) cannot make that %d", len(slides), n, n) |
| 359 | } |
| 360 | first, _ := slides[0].(map[string]any)["id"].(string) |
| 361 | |
| 362 | words := make([]string, 0, 400) |
| 363 | for i := range 400 { |
| 364 | words = append(words, notesWords[i%len(notesWords)]) |
| 365 | } |
| 366 | var paras []string |
| 367 | for i := 0; i < len(words); i += 50 { |
| 368 | paras = append(paras, strings.Join(words[i:i+50], " ")+".") |
| 369 | } |
| 370 | ops := []string{`{"op":"set_notes","id":` + quote(first) + `,"markdown":` + quote(strings.Join(paras, "\n\n")) + `}`} |
| 371 | for range n - len(slides) { |
| 372 | ops = append(ops, `{"op":"add_slide","layout":"flow","template":"title-body"}`) |
| 373 | } |
| 374 | apiJSON(t, a, http.MethodPost, "/api/v1/decks/"+sqid+"/ops", token, `{"ops":[`+strings.Join(ops, ",")+`]}`, http.StatusOK) |
| 375 | return "/d/" + sqid + "/edit" |
| 376 | } |
| 377 | |
| 378 | // notesWords is what deckWithSlides' notes say, over and over. |
| 379 | var notesWords = strings.Fields("pause here and look at the room before the next slide because the numbers need a moment to land") |
| 380 | |
| 381 | // deckWithEveryKind is deckWithSlides(2) with a canvas slide added |
| 382 | // after them that carries one box of each of the twelve kinds the add |
| 383 | // menu lists, laid out four to a row so that none is under another. |
| 384 | // It returns the editor path and the canvas slide's id (the editor |
| 385 | // tidied, spec §4.2: each kind's options). |
| 386 | func deckWithEveryKind(t *testing.T, a *testApp, cookies []*http.Cookie) (path, slide string) { |
| 387 | t.Helper() |
| 388 | path = deckWithSlides(t, a, cookies, 2) |
| 389 | sqid := strings.TrimSuffix(strings.TrimPrefix(path, "/d/"), "/edit") |
| 390 | token := mintAgent(t, a, cookies, "deck-with-every-kind") |
| 391 | apiJSON(t, a, http.MethodPost, "/api/v1/decks/"+sqid+"/ops", token, |
| 392 | `{"ops":[{"op":"add_slide","layout":"canvas","template":"blank"}]}`, http.StatusOK) |
| 393 | view := apiJSON(t, a, http.MethodGet, "/api/v1/decks/"+sqid, token, "", http.StatusOK) |
| 394 | slides, _ := view["slides"].([]any) |
| 395 | slide, _ = slides[len(slides)-1].(map[string]any)["id"].(string) |
| 396 | |
| 397 | props := map[string]string{"heading": `{"level":1}`, "table": `{"rows":2,"cols":2}`, "columns": `{"count":2}`} |
| 398 | words := map[string]string{"heading": "Heading", "text": "Text", "list": "- List", "quote": "Quote", "code": "code", "shape": "Shape"} |
| 399 | var ops []string |
| 400 | for i, kind := range everyKind { |
| 401 | p := props[kind] |
| 402 | if p == "" { |
| 403 | p = "{}" |
| 404 | } |
| 405 | op := fmt.Sprintf(`{"op":"add_block","slide":%s,"type":%q,"props":%s,"box":{"x":%.3f,"y":%.3f,"w":0.22,"h":0.28},"z":%d`, |
| 406 | quote(slide), kind, p, 0.03+float64(i%4)*0.245, 0.04+float64(i/4)*0.32, i) |
| 407 | if w, ok := words[kind]; ok { |
| 408 | op += `,"markdown":` + quote(w) |
| 409 | } |
| 410 | ops = append(ops, op+"}") |
| 411 | } |
| 412 | apiJSON(t, a, http.MethodPost, "/api/v1/decks/"+sqid+"/ops", token, `{"ops":[`+strings.Join(ops, ",")+`]}`, http.StatusOK) |
| 413 | return path, slide |
| 414 | } |
| 415 | |
| 416 | // everyKind is the Insert menu's list (editor.go's blockTypes), in its order. |
| 417 | var everyKind = []string{"heading", "text", "list", "quote", "image", "columns", "code", "shape", "table", "divider", "spacer", "qr"} |
| 418 | |
| 419 | // emptyDeck makes a deck and takes its one slide away over the API, |
| 420 | // the only way a deck ends up with none, and returns its editor path. |
| 421 | func emptyDeck(t *testing.T, a *testApp, cookies []*http.Cookie) string { |
| 422 | t.Helper() |
| 423 | token := mintAgent(t, a, cookies, "empty-deck") |
| 424 | sqid := apiDeck(t, a, token, "Empty") |
| 425 | view := apiJSON(t, a, http.MethodGet, "/api/v1/decks/"+sqid, token, "", http.StatusOK) |
| 426 | slides, _ := view["slides"].([]any) |
| 427 | var ops []string |
| 428 | for _, s := range slides { |
| 429 | id, _ := s.(map[string]any)["id"].(string) |
| 430 | ops = append(ops, `{"op":"remove_slide","id":`+quote(id)+`}`) |
| 431 | } |
| 432 | apiJSON(t, a, http.MethodPost, "/api/v1/decks/"+sqid+"/ops", token, `{"ops":[`+strings.Join(ops, ",")+`]}`, http.StatusOK) |
| 433 | return "/d/" + sqid + "/edit" |
| 434 | } |
| 435 | |