oficina / docs Public

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

Plain git — no account needed to clone.

Download

Download this file

1package docs
2
3import (
4 "context"
5 "database/sql"
6 "fmt"
7 "io"
8 "io/fs"
9 "net/http"
10 "net/http/httptest"
11 "net/url"
12 "os"
13 "path/filepath"
14 "strings"
15 "testing"
16)
17
18// NewForTest builds an App against a temporary SQLite database. It is
19// the constructor every later task's tests use — deliberately not in a
20// _test.go file, so packages other than this one's own tests can reach
21// it too.
22//
23// Env is fixed at "development": that is what lets InstanceKey and
24// Mailer (auth.go) default rather than refuse to start, and what
25// installs the *recordingMailer TestSignIn (below) reads a minted
26// link back from. It used to also enable a development-only stand-in
27// identity (devauth.go); that identity had zero readers once real
28// sign-in landed and was deleted in fix round 1 on Task 1 — every
29// test built on NewForTest signs in for real via TestSignIn now.
30func NewForTest(t *testing.T) (*App, error) {
31 return NewForTestWith(t, Config{})
32}
33
34// NewForTestWith is NewForTest with the caller's own Config, for the tests
35// that need a real allowlist.
36//
37// It exists because NewForTest fixes an empty AllowedAddresses, which in
38// development means "admit everyone" (resolveAllowlist) — so the whole
39// grant-admission path, and the guest/member distinction built on it, were
40// unreachable from any test in the suite. The branch review found exactly
41// that hole: allows() and HasGrant were each tested in isolation, and the
42// wiring that makes them one thing was not, so moving one line in app.go
43// would have silently recreated the unredeemable invitation its comment
44// warns about, green. (Branch review, finding 7e.)
45//
46// DBPath and Env are filled in when the caller leaves them empty, so a test
47// that only wants an allowlist writes only an allowlist.
48func NewForTestWith(t *testing.T, cfg Config) (*App, error) {
49 t.Helper()
50
51 if cfg.DBPath == "" {
52 cfg.DBPath = filepath.Join(t.TempDir(), "docs.db")
53 }
54 if cfg.Env == "" {
55 cfg.Env = "development"
56 }
57
58 app, err := New(cfg)
59 if err != nil {
60 return nil, err
61 }
62 t.Cleanup(func() {
63 if cerr := app.Close(); cerr != nil {
64 t.Errorf("docs.App.Close: %v", cerr)
65 }
66 })
67 return app, nil
68}
69
70// TestSignIn mints a magic link for address and returns its path
71// (e.g. "/auth/verify?token=..."). GETting it draws the confirm door;
72// confirmRequest(link) is the POST that spends it. It never
73// sends real mail: it POSTs /signin with force=1 — the escape hatch
74// auth.Begin's own doc comment describes ("skips classification and
75// goes straight to the magic link") — so no outbound classification
76// call ever happens, and it reads the link back out of the app's
77// *recordingMailer (auth.go), installed only in development
78// (NewForTest's Env), rather than through any real transport. It is
79// test scaffolding, not a shortcut available in production: an App
80// built with a non-development Env has no recordingMailer and this
81// returns an error.
82//
83// Every later task's tests that need a signed-in request build on
84// this — get its shape right (a path, ready for httptest.NewRequest)
85// and address (a plain email string) is all that changes.
86func (a *App) TestSignIn(t *testing.T, address string) (string, error) {
87 t.Helper()
88
89 if a.mailRecorder == nil {
90 return "", fmt.Errorf("docs: TestSignIn requires Env %q; app was built with Env %q", "development", a.cfg.Env)
91 }
92
93 // Snapshot the send count before the POST: the check below has to see
94 // a NEW mail, not merely a recorder whose last occupant matches.
95 a.mailRecorder.mu.Lock()
96 before := a.mailRecorder.sends
97 a.mailRecorder.mu.Unlock()
98
99 form := url.Values{"address": {address}, "force": {"1"}}
100 req := httptest.NewRequest(http.MethodPost, "/signin", strings.NewReader(form.Encode()))
101 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
102 // auth.Begin CSRF-checks this itself (its own doc comment: an
103 // unauthenticated endpoint that sends mail and makes outbound
104 // calls decided by the submitted address must never accept a
105 // cross-site form) and csrf.Protect guards it again app-wide;
106 // Sec-Fetch-Site: same-origin is exactly what a real same-origin
107 // browser POST sends and satisfies both the same way
108 // list_test.go's TestCreateThenRead does for POST /documents.
109 req.Header.Set("Sec-Fetch-Site", "same-origin")
110
111 rec := httptest.NewRecorder()
112 a.Handler().ServeHTTP(rec, req)
113 if rec.Code != http.StatusSeeOther {
114 return "", fmt.Errorf("docs: TestSignIn: POST /signin: status %d, want %d", rec.Code, http.StatusSeeOther)
115 }
116 if loc := rec.Header().Get("Location"); !strings.Contains(loc, "sent=1") {
117 return "", fmt.Errorf("docs: TestSignIn: POST /signin redirected to %q, want a %q outcome", loc, "?sent=1")
118 }
119
120 a.signinMail.wait() // the link is sent after the response (mailqueue.go)
121 a.mailRecorder.mu.Lock()
122 to, body, after := a.mailRecorder.lastTo, a.mailRecorder.lastBody, a.mailRecorder.sends
123 a.mailRecorder.mu.Unlock()
124
125 // A refused address gets the same 303 ?sent=1 a real one gets
126 // (gateBegin, deliberately, so the endpoint is not a membership
127 // oracle). So the only evidence that this address was admitted is that
128 // a new mail went out, to it. Both halves are needed: the count alone
129 // would accept somebody else's mail, and the recipient alone stays
130 // true for every later refusal of an address that once succeeded.
131 if after == before {
132 return "", fmt.Errorf("docs: TestSignIn: no mail was sent for %q — the address was refused", address)
133 }
134 if normalizeAddress(to) != normalizeAddress(address) {
135 return "", fmt.Errorf("docs: TestSignIn: the mail went to %q, not %q", to, address)
136 }
137
138 link := magicLinkPattern.FindString(body)
139 if link == "" {
140 return "", fmt.Errorf("docs: TestSignIn: no magic link found in the mailed body for %q", address)
141 }
142 return linkPath(link)
143}
144
145// confirmForm is what the confirm door's Sign in button submits for an
146// emailed link: the link's own path, and a form body carrying its token.
147// GET /auth/verify only draws that door and spends nothing, so a test
148// that signs in must POST this, as a browser does.
149func confirmForm(link string) (path, form string) {
150 u, err := url.Parse(link)
151 if err != nil {
152 return link, ""
153 }
154 return u.Path, url.Values{"token": {u.Query().Get("token")}}.Encode()
155}
156
157// confirmRequest is that POST, with the same-origin evidence a browser
158// sends from the door (Sec-Fetch-Site), which both csrf.Protect and
159// rastrillo's own redeem check.
160func confirmRequest(link string) *http.Request {
161 path, form := confirmForm(link)
162 req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(form))
163 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
164 req.Header.Set("Sec-Fetch-Site", "same-origin")
165 return req
166}
167
168// TestConfirmRequest is confirmRequest for tests outside the package:
169// the POST that spends a link TestSignIn returned.
170func (a *App) TestConfirmRequest(link string) *http.Request {
171 return confirmRequest(link)
172}
173
174// TestPerson creates (or finds) a person by address and returns this
175// app's own numeric id for them — Store.EnsurePerson, the same
176// address-to-id mapping a real request goes through via handlers.go's
177// owner helper (auth.From(r).Address, never sessions.UserID — see
178// Document.OwnerID's doc comment). It is what Store.Create/List/Get's
179// owner parameter expects, and what Task 2's own tests use directly
180// against the store without any HTTP round trip at all:
181//
182// alice := app.TestPerson(t, "alice@example.com")
183// doc, err := app.Store().Create(ctx, alice, "Alice's private notes")
184//
185// TestPerson does not sign anyone in — no cookie, no session. For a
186// request that carries one, use TestRequest, which calls TestPerson
187// itself so the two always agree on who an address maps to.
188func (a *App) TestPerson(t *testing.T, address string) int64 {
189 t.Helper()
190 id, err := a.store.EnsurePerson(context.Background(), address)
191 if err != nil {
192 t.Fatalf("docs: TestPerson(%q): %v", address, err)
193 }
194 return id
195}
196
197// TestRequest builds an httptest request for method and path, signed
198// in as address: a real magic-link round trip (TestSignIn) mints the
199// session cookies, and TestPerson ensures address's Person row exists
200// first — the same row Store.Create/List/Get's owner id needs to
201// already be there for handlers.go's owner helper to find on the
202// request this returns.
203//
204// For a state-changing method (anything but GET/HEAD) it also sets
205// Sec-Fetch-Site: same-origin, exactly what a real same-origin
206// browser sends and csrf.Protect (app.go) checks first (TestSignIn's
207// own doc comment) — so a later task's signed-in POST does not have
208// to re-derive this to get past CSRF.
209//
210// req := app.TestRequest(t, "bob@example.com", http.MethodGet, "/d/"+doc.Sqid, nil)
211func (a *App) TestRequest(t *testing.T, address, method, path string, body io.Reader) *http.Request {
212 t.Helper()
213
214 // Ensure address's Person row exists before any handler on this
215 // request reads it — EnsurePerson is get-or-create, so this is a
216 // no-op if TestSignIn's own callback already created it via the
217 // exact same call.
218 a.TestPerson(t, address)
219
220 link, err := a.TestSignIn(t, address)
221 if err != nil {
222 t.Fatalf("docs: TestRequest: TestSignIn(%q): %v", address, err)
223 }
224 verifyRec := httptest.NewRecorder()
225 a.Handler().ServeHTTP(verifyRec, confirmRequest(link))
226 cookies := verifyRec.Result().Cookies()
227 if len(cookies) == 0 {
228 t.Fatalf("docs: TestRequest: following the magic link for %q set no session cookie", address)
229 }
230
231 req := httptest.NewRequest(method, path, body)
232 for _, c := range cookies {
233 req.AddCookie(c)
234 }
235 if method != http.MethodGet && method != http.MethodHead {
236 req.Header.Set("Sec-Fetch-Site", "same-origin")
237 }
238 return req
239}
240
241// testHandlers exposes the app's handler struct so a test can reach
242// the two seams that only exist for testing: the stream's heartbeat
243// and TTL overrides (stream_test.go, whose subject is behaviour over
244// time), and the hub, whose subscriber count is the only observable
245// consequence of a stream handler having returned.
246//
247// Unexported, and in this file rather than a _test.go one for the
248// same reason NewForTest is: it is scaffolding this package's own
249// tests share, not an interface the app has.
250func (a *App) testHandlers() *handlers { return a.handlers }
251
252// ReadFixture loads fixtures/data/<name>.update.bin — a real Yjs
253// update produced by browser yjs (fixtures/generate.mjs), never
254// hand-edited. Not in a _test.go file for the same reason as
255// NewForTest: other packages' tests may need it too.
256func ReadFixture(t *testing.T, name string) []byte {
257 t.Helper()
258 b, err := os.ReadFile(filepath.Join("..", "..", "fixtures", "data", name+".update.bin"))
259 if err != nil {
260 t.Fatalf("docs.ReadFixture(%q): %v", name, err)
261 }
262 return b
263}
264
265// ReadFragmentFixture loads fixtures/vectors/fragment/<name>.update.bin
266// — a real Yjs update, produced by real yjs
267// (fixtures/generate-fragment.mjs), that builds a Y.XmlFragment on
268// root "prosemirror" rather than a bare Y.Text on root "content".
269//
270// Distinct from ReadFixture, not a parameter on it: since Store.Text
271// and Store.HTML were repointed to read the "prosemirror" root
272// (core/src/abi.rs's text_string doc comment — fix round 1 on the
273// fragment-migration task), a test that wants to see real content
274// come back through either of them needs an update built on that
275// root. ReadFixture's own fixtures/data updates still apply cleanly
276// (ApplyUpdate/apply_slice decode and merge regardless of which root
277// an update targets) but read back as "" through Text/HTML now — a
278// test reaching for ReadFixture("hello") expecting "hello world" back
279// through Store.Text would be reaching for the wrong fixture set.
280func ReadFragmentFixture(t *testing.T, name string) []byte {
281 t.Helper()
282 b, err := os.ReadFile(filepath.Join("..", "..", "fixtures", "vectors", "fragment", name+".update.bin"))
283 if err != nil {
284 t.Fatalf("docs.ReadFragmentFixture(%q): %v", name, err)
285 }
286 return b
287}
288
289// TestActorFor returns the Actor for a document's own owner.
290//
291// It exists because ApplyUpdate now authorizes the acting person rather than
292// the document, so a test that writes to a document has to say who is
293// writing. Almost every existing one is the owner editing their own document,
294// and this resolves that owner for real — through the people row the document
295// points at — rather than fabricating an Actor that would satisfy the check
296// without exercising it. A test wanting a grantee builds the Actor itself, as
297// grants_write_test.go does.
298func (a *App) TestActorFor(t *testing.T, doc *Document) Actor {
299 t.Helper()
300 return a.TestActorForPerson(t, doc.OwnerID)
301}
302
303// TestActorForPerson is the same lookup keyed on the person directly, for a
304// test that has an id in hand rather than a document.
305func (a *App) TestActorForPerson(t *testing.T, person int64) Actor {
306 t.Helper()
307 var p Person
308 if err := a.Store().db.Where("id = ?", person).First(&p).Error; err != nil {
309 t.Fatalf("TestActorForPerson: resolving person %d: %v", person, err)
310 }
311 return localActor(p.ID, p.Email)
312}
313
314// TestEditorScriptPath is the served path of the editor bundle, exported so
315// an external test can assert a page does or does not ship it.
316//
317// It exists because the branch review found a test banning the string
318// "editor-entry" from the public page — a string that appears on no page in
319// this app, so the ban could never fail. A test that names the real path
320// cannot drift from what staticHandler actually serves, because it is the
321// same function that builds the <script src>.
322func TestEditorScriptPath() string { return editorScriptPath() }
323
324// TestSoftDelete marks a document deleted the way a delete verb would, for
325// tests that need a live link pointing at a document that is no longer
326// there. There is no delete route yet; this is the state the schema
327// already models (documents.deleted_at) and that ByToken filters on. It
328// goes through Store.deleteDocument, so the suite feed announces it gone
329// exactly as a real deletion will.
330func (a *App) TestSoftDelete(t *testing.T, sqid string) {
331 t.Helper()
332 var doc Document
333 if err := a.store.db.Where("sqid = ?", sqid).First(&doc).Error; err != nil {
334 t.Fatalf("docs: TestSoftDelete(%q): %v", sqid, err)
335 }
336 if err := a.store.deleteDocument(context.Background(), doc.ID); err != nil {
337 t.Fatalf("docs: TestSoftDelete(%q): %v", sqid, err)
338 }
339}
340
341// TestCreatePrivate makes a document on the private rung, for a test outside
342// the package whose subject is who reaches a private document. Store.Create
343// puts a new document on the team rung (spec §8.2.1), and in development every
344// signed-in address is a member, so a test of grants or of a stranger's 404
345// needs the private rung said out loud.
346func (a *App) TestCreatePrivate(t *testing.T, owner int64, title string) *Document {
347 t.Helper()
348 doc, err := a.store.createDocument(context.Background(), owner, title, "", VisibilityPrivate)
349 if err != nil {
350 t.Fatalf("docs: TestCreatePrivate(%q): %v", title, err)
351 }
352 return doc
353}
354
355// TestWrite applies one update to a document as the signed-in owner,
356// through the same store path a real edit takes, so a test can publish a
357// document that actually has text in it.
358func (a *App) TestWrite(t *testing.T, cookies []*http.Cookie, sqid, fixture string) {
359 t.Helper()
360 var doc Document
361 if err := a.store.db.Where("sqid = ?", sqid).First(&doc).Error; err != nil {
362 t.Fatalf("docs: TestWrite: find %q: %v", sqid, err)
363 }
364 actor := a.TestActorFor(t, &doc)
365 if _, err := a.store.ApplyUpdate(context.Background(), &doc, actor, ReadFragmentFixture(t, fixture)); err != nil {
366 t.Fatalf("docs: TestWrite(%q): %v", fixture, err)
367 }
368}
369
370// TestRowContains reports whether any column of any row in table holds
371// needle as a substring.
372//
373// It exists for the one assertion that cannot be made against behaviour:
374// ruling 16 says the plaintext token is not in the database, and the only
375// honest way to check that is to look in the database. A test that asked
376// the store instead would be asking the code that is supposed to be wrong.
377func (a *App) TestRowContains(t *testing.T, table, needle string) bool {
378 t.Helper()
379 rows, err := a.store.db.Raw("SELECT * FROM " + table).Rows()
380 if err != nil {
381 t.Fatalf("docs: TestRowContains: %v", err)
382 }
383 defer rows.Close()
384
385 cols, err := rows.Columns()
386 if err != nil {
387 t.Fatalf("docs: TestRowContains: columns: %v", err)
388 }
389 for rows.Next() {
390 cells := make([]any, len(cols))
391 for i := range cells {
392 cells[i] = new(sql.RawBytes)
393 }
394 if err := rows.Scan(cells...); err != nil {
395 t.Fatalf("docs: TestRowContains: scan: %v", err)
396 }
397 for _, c := range cells {
398 if strings.Contains(string(*(c.(*sql.RawBytes))), needle) {
399 return true
400 }
401 }
402 }
403 return false
404}
405
406// TestViewSources returns every template this app authors, by path, for
407// the tests that hold its markup to a vocabulary.
408func TestViewSources(t *testing.T) map[string]string {
409 t.Helper()
410 out := map[string]string{}
411 err := fs.WalkDir(viewsFS, ".", func(path string, d fs.DirEntry, err error) error {
412 if err != nil || d.IsDir() {
413 return err
414 }
415 b, err := fs.ReadFile(viewsFS, path)
416 out[path] = string(b)
417 return err
418 })
419 if err != nil {
420 t.Fatal(err)
421 }
422 return out
423}
424
425// TestSetLateLimit raises (or lowers) the per-session late-answer limit
426// (push.go, the live-push spec's §5). For the live-push probe, whose
427// simulated clients all share one session where real ones each have their
428// own: without it, five probe typists in one document pace each other.
429func (a *App) TestSetLateLimit(n int) { a.handlers.late.limit = n }
430