oficina / slides Public

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

Plain git — no account needed to clone.

Download

Download this file

1package slidestest
2
3// A font from a person's library, put to use in a deck (deckfonts.go):
4// POST /d/{sqid}/fonts records which files the deck may serve, and the
5// three surfaces serve a file only through a deck that both recorded it
6// and lists it in meta.fontFiles. Liberation (SIL OFL) is the font
7// throughout, as in library_test.go.
8
9import (
10 "bytes"
11 "encoding/json"
12 "html"
13 "net/http"
14 "net/http/httptest"
15 "net/url"
16 "strings"
17 "sync"
18 "testing"
19
20 "amadan.net/oficina/slides/internal/slides"
21 "amadan.net/oficina/slides/internal/slides/deck"
22 "amadan.net/oficina/slides/internal/slides/fonts"
23 "amadan.net/rastrillo/rastrillo/blobs"
24)
25
26// newFontsApp is two people on one instance with an object store.
27func newFontsApp(t *testing.T) (*testApp, blobs.Store) {
28 t.Helper()
29 cfg, mailer := newConfig(t)
30 cfg.AllowedAddresses = []string{allowedAddress, otherAddress}
31 cfg.Blobs = dirStore(t)
32 return newAppWith(t, cfg, mailer), cfg.Blobs
33}
34
35// pickFont is the editor's POST /d/{sqid}/fonts for one family.
36func pickFont(t *testing.T, a *testApp, sqid, family string, cookies []*http.Cookie) *httptest.ResponseRecorder {
37 t.Helper()
38 return postJSON(t, a, "/d/"+sqid+"/fonts", `{"family":`+quote(family)+`}`, cookies)
39}
40
41// pickedFamily is pickFont insisting on a 200, decoded.
42func pickedFamily(t *testing.T, a *testApp, sqid, family string, cookies []*http.Cookie) deck.FontFamily {
43 t.Helper()
44 rec := pickFont(t, a, sqid, family, cookies)
45 if rec.Code != http.StatusOK {
46 t.Fatalf("POST /d/%s/fonts %q: status %d, want 200\n%s", sqid, family, rec.Code, rec.Body)
47 }
48 var fam deck.FontFamily
49 if err := json.Unmarshal(rec.Body.Bytes(), &fam); err != nil {
50 t.Fatalf("POST /d/%s/fonts: not a font family: %v\n%s", sqid, err, rec.Body)
51 }
52 return fam
53}
54
55// useFamily is the batch the editor commits after a pick, over the API:
56// the family in meta.fontFiles and the heading set in it.
57func useFamily(t *testing.T, a *testApp, token, sqid string, fam deck.FontFamily) {
58 t.Helper()
59 files, _ := json.Marshal([]deck.FontFamily{fam})
60 stack := "'" + fam.CSS + "', Liberation Sans, sans-serif"
61 apiJSON(t, a, http.MethodPost, "/api/v1/decks/"+sqid+"/ops", token,
62 `{"ops":[{"op":"set_meta","fontFiles":`+string(files)+`,"fonts":{"heading":`+quote(stack)+`,"body":""}}]}`, http.StatusOK)
63}
64
65func deckFontRows(t *testing.T, a *testApp, sqid string) int64 {
66 t.Helper()
67 var n int64
68 if err := a.db.G.Model(&slides.DeckFont{}).
69 Where("deck_id = (SELECT id FROM decks WHERE sqid = ?)", sqid).Count(&n).Error; err != nil {
70 t.Fatal(err)
71 }
72 return n
73}
74
75// fontGet is a GET of a font route, with or without a session.
76func fontGet(t *testing.T, a *testApp, target string, cookies []*http.Cookie) *httptest.ResponseRecorder {
77 t.Helper()
78 return get(t, a, target, cookies...)
79}
80
81// served insists target answers the face's bytes with the font headers.
82func served(t *testing.T, a *testApp, target string, cookies []*http.Cookie, want []byte) {
83 t.Helper()
84 rec := fontGet(t, a, target, cookies)
85 if rec.Code != http.StatusOK {
86 t.Errorf("GET %s: status %d, want 200", target, rec.Code)
87 return
88 }
89 if ct := rec.Header().Get("Content-Type"); ct != "font/ttf" {
90 t.Errorf("GET %s: Content-Type %q, want font/ttf", target, ct)
91 }
92 if rec.Header().Get("X-Content-Type-Options") != "nosniff" {
93 t.Errorf("GET %s: no nosniff", target)
94 }
95 if !strings.HasPrefix(rec.Header().Get("Cache-Control"), "private") {
96 t.Errorf("GET %s: Cache-Control %q, want private", target, rec.Header().Get("Cache-Control"))
97 }
98 if rec.Header().Get("Content-Security-Policy") != "default-src 'none'" {
99 t.Errorf("GET %s: CSP %q", target, rec.Header().Get("Content-Security-Policy"))
100 }
101 if !bytes.Equal(rec.Body.Bytes(), want) {
102 t.Errorf("GET %s: %d bytes, not the face", target, rec.Body.Len())
103 }
104}
105
106func refused(t *testing.T, a *testApp, target string, cookies []*http.Cookie) {
107 t.Helper()
108 if rec := fontGet(t, a, target, cookies); rec.Code != http.StatusNotFound {
109 t.Errorf("GET %s: status %d, want 404", target, rec.Code)
110 }
111}
112
113func TestPickingAFontRecordsItForTheDeck(t *testing.T) {
114 a, _ := newFontsApp(t)
115 cookies := signedIn(t, a, allowedAddress)
116 token := mintAgent(t, a, cookies, "claude")
117 sqid := apiDeck(t, a, token, "Picked")
118
119 reg, bold := libFont(t, "LiberationSans-Regular.ttf"), libFont(t, "LiberationSans-Bold.ttf")
120 if rec := uploadFonts(t, a, cookies, upFile{"a.ttf", reg}, upFile{"b.ttf", bold}); rec.Code != http.StatusOK {
121 t.Fatalf("upload: %d", rec.Code)
122 }
123 sans := cssOf(t, a, sha(reg))
124
125 fam := pickedFamily(t, a, sqid, sans, cookies)
126 want := deck.FontFamily{Family: "Liberation Sans", CSS: sans, Faces: []deck.FontFace{
127 {Ref: sha(reg), Format: "ttf", Weight: [2]int{400, 400}, Pictures: true},
128 {Ref: sha(bold), Format: "ttf", Weight: [2]int{700, 700}, Pictures: true},
129 }}
130 got, _ := json.Marshal(fam)
131 wantJSON, _ := json.Marshal(want)
132 if string(got) != string(wantJSON) {
133 t.Errorf("the pick answered %s, want %s", got, wantJSON)
134 }
135 if n := deckFontRows(t, a, sqid); n != 2 {
136 t.Errorf("%d DeckFont rows, want one per face (2)", n)
137 }
138 // The answer is what set_meta takes, as it is.
139 useFamily(t, a, token, sqid, fam)
140
141 // Again: the same two rows, not four.
142 pickedFamily(t, a, sqid, sans, cookies)
143 if n := deckFontRows(t, a, sqid); n != 2 {
144 t.Errorf("%d DeckFont rows after a second pick, want 2", n)
145 }
146
147 // A family the person does not have, and a body that is not one.
148 if rec := pickFont(t, a, sqid, "Liberation Serif", cookies); rec.Code != http.StatusNotFound {
149 t.Errorf("a family not in the library: status %d, want 404", rec.Code)
150 }
151 if rec := postJSON(t, a, "/d/"+sqid+"/fonts", `{"family":`, cookies); rec.Code != http.StatusBadRequest {
152 t.Errorf("a broken body: status %d, want 400", rec.Code)
153 }
154 if n := deckFontRows(t, a, sqid); n != 2 {
155 t.Errorf("%d DeckFont rows after refusals, want 2", n)
156 }
157}
158
159func TestAFontIsServedOnlyThroughADeckThatUsesIt(t *testing.T) {
160 a, _ := newFontsApp(t)
161 mine := signedIn(t, a, allowedAddress)
162 theirs := signedIn(t, a, otherAddress)
163 token := mintAgent(t, a, mine, "claude")
164 theirToken := mintAgent(t, a, theirs, "theirs")
165
166 reg := libFont(t, "LiberationSans-Regular.ttf")
167 uploadFonts(t, a, mine, upFile{"a.ttf", reg})
168 ref := sha(reg)
169 sans := cssOf(t, a, ref)
170
171 using := apiDeck(t, a, token, "Uses it")
172 fam := pickedFamily(t, a, using, sans, mine)
173 useFamily(t, a, token, using, fam)
174
175 // Another deck of mine that never picked it, but lists it.
176 other := apiDeck(t, a, token, "Lists it")
177 useFamily(t, a, token, other, fam)
178 // A deck that picked it, then stopped listing it.
179 dropped := apiDeck(t, a, token, "Dropped it")
180 pickedFamily(t, a, dropped, sans, mine)
181 // Another person's deck, listing the ref through their own agent.
182 stranger := apiDeck(t, a, theirToken, "Theirs")
183 useFamily(t, a, theirToken, stranger, fam)
184
185 refused(t, a, "/d/"+other+"/fonts/"+ref, mine)
186 // A deck that recorded it and no longer lists it serves it only to
187 // the person whose library holds it (deckFont: a pick the editor is
188 // still waiting on looks the same), never over a share link.
189 served(t, a, "/d/"+dropped+"/fonts/"+ref, mine, reg)
190 refused(t, a, "/s/"+mintShareLink(t, a, "/d/"+dropped, mine)+"/fonts/"+ref, nil)
191 refused(t, a, "/d/"+stranger+"/fonts/"+ref, theirs)
192 refused(t, a, "/d/"+using+"/fonts/"+ref, theirs) // a deck they cannot see
193 // Signed out, the session route sends a person to sign in.
194 if rec := fontGet(t, a, "/d/"+using+"/fonts/"+ref, nil); rec.Code != http.StatusSeeOther {
195 t.Errorf("signed out: status %d, want 303 to sign in", rec.Code)
196 }
197 refused(t, a, "/d/"+using+"/fonts/"+strings.Repeat("0", 64), mine)
198 refused(t, a, "/d/"+using+"/fonts/"+strings.ToUpper(ref), mine)
199 otherLink := mintShareLink(t, a, "/d/"+other, mine)
200 refused(t, a, "/s/"+otherLink+"/fonts/"+ref, nil)
201
202 served(t, a, "/d/"+using+"/fonts/"+ref, mine, reg)
203 link := mintShareLink(t, a, "/d/"+using, mine)
204 served(t, a, "/s/"+link+"/fonts/"+ref, nil, reg)
205 out := apiJSON(t, a, http.MethodPost, "/api/v1/decks/"+using+"/present", token, "", http.StatusOK)
206 session, _ := out["session"].(string)
207 served(t, a, "/p/"+session+"/fonts/"+ref, nil, reg)
208 refused(t, a, "/p/nosuchsess/fonts/"+ref, nil)
209}
210
211func TestOnlyTheLibraryOwnerCanAddTheirFont(t *testing.T) {
212 a, _ := newFontsApp(t)
213 mine := signedIn(t, a, allowedAddress)
214 theirs := signedIn(t, a, otherAddress)
215
216 uploadFonts(t, a, mine, upFile{"sans.ttf", libFont(t, "LiberationSans-Regular.ttf")})
217 uploadFonts(t, a, theirs, upFile{"serif.ttf", libFont(t, "LiberationSerif-Regular.ttf")})
218 sans := cssOf(t, a, sha(libFont(t, "LiberationSans-Regular.ttf")))
219 serif := cssOf(t, a, sha(libFont(t, "LiberationSerif-Regular.ttf")))
220
221 shared := createDeck(t, a, mine, "All hands")
222 if rec := post(t, a, shared+"/settings", url.Values{
223 "title": {"All hands"}, "theme": {"ink"}, "rung": {"team"},
224 }, mine...); rec.Code != http.StatusSeeOther {
225 t.Fatalf("raise the deck to the team: %d", rec.Code)
226 }
227 private := createDeck(t, a, mine, "Mine alone")
228
229 // Sam can edit the team deck, but my family is not Sam's to add.
230 if rec := pickFont(t, a, sqidOf(shared), sans, theirs); rec.Code != http.StatusNotFound {
231 t.Errorf("someone else's family: status %d, want 404", rec.Code)
232 }
233 if n := deckFontRows(t, a, sqidOf(shared)); n != 0 {
234 t.Errorf("%d DeckFont rows after a refused pick", n)
235 }
236 // Sam's own family goes into the team deck.
237 if fam := pickedFamily(t, a, sqidOf(shared), serif, theirs); fam.CSS != serif {
238 t.Errorf("Sam's pick answered %+v", fam)
239 }
240 // And not into a deck Sam cannot see.
241 if rec := pickFont(t, a, sqidOf(private), serif, theirs); rec.Code != http.StatusNotFound {
242 t.Errorf("a deck Sam cannot see: status %d, want 404", rec.Code)
243 }
244 // Nor is Sam's family mine to add.
245 if rec := pickFont(t, a, sqidOf(private), serif, mine); rec.Code != http.StatusNotFound {
246 t.Errorf("Sam's family into my deck: status %d, want 404", rec.Code)
247 }
248
249 // Each person's Deck settings offers their own families only.
250 mySettings := html.UnescapeString(mustGet(t, a, shared+"/edit", http.StatusOK, mine).Body.String())
251 theirSettings := html.UnescapeString(mustGet(t, a, shared+"/edit", http.StatusOK, theirs).Body.String())
252 if !strings.Contains(mySettings, `<option value="`+sans+`">Liberation Sans</option>`) ||
253 strings.Contains(mySettings, `<option value="`+serif+`">`) {
254 t.Errorf("my Deck settings do not offer exactly my family")
255 }
256 if !strings.Contains(theirSettings, `<option value="`+serif+`">Liberation Serif</option>`) ||
257 strings.Contains(theirSettings, `<option value="`+sans+`">`) {
258 t.Errorf("Sam's Deck settings do not offer exactly Sam's family")
259 }
260}
261
262func TestDeletingAFontKeepsDecksThatUseIt(t *testing.T) {
263 a, store := newFontsApp(t)
264 cookies := signedIn(t, a, allowedAddress)
265 token := mintAgent(t, a, cookies, "claude")
266
267 reg := libFont(t, "LiberationSans-Regular.ttf")
268 serif := libFont(t, "LiberationSerif-Regular.ttf")
269 uploadFonts(t, a, cookies, upFile{"a.ttf", reg}, upFile{"s.ttf", serif})
270 sqid := apiDeck(t, a, token, "Keeps it")
271 sans := cssOf(t, a, sha(reg))
272 useFamily(t, a, token, sqid, pickedFamily(t, a, sqid, sans, cookies))
273
274 for _, family := range []string{sans, cssOf(t, a, sha(serif))} {
275 if rec := post(t, a, "/fonts/delete", url.Values{"family": {family}}, cookies...); rec.Code != http.StatusSeeOther {
276 t.Fatalf("delete %s: status %d, want 303\n%s", family, rec.Code, rec.Body)
277 }
278 }
279 if n := countRows(t, a, "1 = 1"); n != 0 {
280 t.Errorf("%d library rows after deleting both families", n)
281 }
282 if !hasObject(store, sha(reg)) {
283 t.Fatal("the deck's font was deleted with the library's family")
284 }
285 if hasObject(store, sha(serif)) {
286 t.Error("a family no deck uses kept its object")
287 }
288 served(t, a, "/d/"+sqid+"/fonts/"+sha(reg), cookies, reg)
289 // It cannot be picked again, though: it is not in the library.
290 if rec := pickFont(t, a, sqid, sans, cookies); rec.Code != http.StatusNotFound {
291 t.Errorf("a deleted family picked: status %d, want 404", rec.Code)
292 }
293
294 // The deck going takes its rows, and with them the last hold on
295 // the object.
296 if rec := post(t, a, "/d/"+sqid+"/delete", nil, cookies...); rec.Code != http.StatusSeeOther {
297 t.Fatalf("delete the deck: %d", rec.Code)
298 }
299 if got := scalar(t, a, "SELECT count(*) FROM deck_fonts WHERE deck_id NOT IN (SELECT id FROM decks)"); got != "0" {
300 t.Errorf("deck_fonts holds %s rows for a deck that no longer exists", got)
301 }
302 if hasObject(store, sha(reg)) {
303 t.Error("the font outlived the last deck and library row that named it")
304 }
305}
306
307// A pick that found the deck, then lost it to a deletion before taking
308// the library's lock, records nothing: a row for a deck that is gone
309// would keep the font's object for ever.
310func TestAPickRacingTheDecksDeletionRecordsNothing(t *testing.T) {
311 a, store := newFontsApp(t)
312 cookies := signedIn(t, a, allowedAddress)
313 reg := libFont(t, "LiberationSans-Regular.ttf")
314 uploadFonts(t, a, cookies, upFile{"a.ttf", reg})
315 path := createDeck(t, a, cookies, "Going")
316 sans := cssOf(t, a, sha(reg))
317
318 var once sync.Once
319 a.app.SetFontTrace(func(stage string) {
320 if stage != "pick" {
321 return
322 }
323 once.Do(func() {
324 if rec := post(t, a, path+"/delete", nil, cookies...); rec.Code != http.StatusSeeOther {
325 t.Errorf("delete the deck mid-pick: %d", rec.Code)
326 }
327 })
328 })
329 t.Cleanup(func() { a.app.SetFontTrace(nil) })
330
331 if rec := pickFont(t, a, sqidOf(path), sans, cookies); rec.Code != http.StatusNotFound {
332 t.Errorf("a pick for a deck deleted under it: status %d, want 404", rec.Code)
333 }
334 if got := scalar(t, a, "SELECT count(*) FROM deck_fonts"); got != "0" {
335 t.Errorf("deck_fonts holds %s rows after the deck went", got)
336 }
337 // The library still holds it, so the object stays; deleting the
338 // family then takes it, with no orphan row in the way.
339 post(t, a, "/fonts/delete", url.Values{"family": {sans}}, cookies...)
340 if hasObject(store, sha(reg)) {
341 t.Error("an orphan deck row kept the font's object")
342 }
343}
344
345func TestAnOddFamilyNameStillLoads(t *testing.T) {
346 a, _ := newFontsApp(t)
347 cookies := signedIn(t, a, allowedAddress)
348 token := mintAgent(t, a, cookies, "claude")
349
350 f, err := fonts.Parse(libFont(t, "LiberationSans-Regular.ttf"))
351 if err != nil {
352 t.Fatal(err)
353 }
354 const name = "Oddity Sans™ 2"
355 odd, err := f.Renamed(name, 400, false)
356 if err != nil {
357 t.Fatal(err)
358 }
359
360 // With nothing in the library, Deck settings has the link alone.
361 bare := html.UnescapeString(mustGet(t, a, "/d/"+apiDeck(t, a, token, "Bare")+"/edit", http.StatusOK, cookies).Body.String())
362 if strings.Contains(bare, "<optgroup") || !strings.Contains(bare, `<a href="/fonts" target="_blank" rel="noopener"`) ||
363 !strings.Contains(bare, "Upload a font…</a>") {
364 t.Errorf("an empty library's Deck settings are not the link alone")
365 }
366
367 if rec := uploadFonts(t, a, cookies, upFile{"odd.ttf", odd}); rec.Code != http.StatusOK {
368 t.Fatalf("upload: %d\n%s", rec.Code, rec.Body)
369 }
370 sqid := apiDeck(t, a, token, "Odd")
371 edit := html.UnescapeString(mustGet(t, a, "/d/"+sqid+"/edit", http.StatusOK, cookies).Body.String())
372 if !strings.Contains(edit, `<option value="Oddity Sans 2">`+name+`</option>`) {
373 t.Errorf("Deck settings do not offer the family under its cleaned name")
374 }
375
376 fam := pickedFamily(t, a, sqid, "Oddity Sans 2", cookies)
377 if fam.Family != name || fam.CSS != "Oddity Sans 2" || len(fam.Faces) != 1 || fam.Faces[0].Ref != sha(odd) {
378 t.Fatalf("the pick answered %+v", fam)
379 }
380 useFamily(t, a, token, sqid, fam)
381
382 view := apiJSON(t, a, http.MethodGet, "/api/v1/decks/"+sqid, token, "", http.StatusOK)
383 meta, _ := view["meta"].(map[string]any)
384 files, _ := meta["fontFiles"].([]any)
385 if len(files) != 1 || files[0].(map[string]any)["css"] != "Oddity Sans 2" || files[0].(map[string]any)["family"] != name {
386 t.Errorf("the deck lists %v, want the family under its cleaned name", meta["fontFiles"])
387 }
388 served(t, a, "/d/"+sqid+"/fonts/"+sha(odd), cookies, odd)
389}
390
391// The editor waits for a picked family's faces before it commits the
392// set_meta that lists it (editor-fonts.mjs), so between the pick and
393// that change the deck serves the file to the person whose library
394// holds it, and to nobody else: not a co-editor, not a share link.
395func TestAPickIsServedToItsOwnerBeforeTheDeckListsIt(t *testing.T) {
396 a, _ := newFontsApp(t)
397 mine := signedIn(t, a, allowedAddress)
398 theirs := signedIn(t, a, otherAddress)
399 reg := libFont(t, "LiberationSans-Regular.ttf")
400 uploadFonts(t, a, mine, upFile{"a.ttf", reg})
401 shared := createDeck(t, a, mine, "All hands")
402 if rec := post(t, a, shared+"/settings", url.Values{
403 "title": {"All hands"}, "theme": {"ink"}, "rung": {"team"},
404 }, mine...); rec.Code != http.StatusSeeOther {
405 t.Fatalf("raise the deck to the team: %d", rec.Code)
406 }
407 sqid := sqidOf(shared)
408 ref := sha(reg)
409 refused(t, a, "/d/"+sqid+"/fonts/"+ref, mine) // not picked yet
410 pickedFamily(t, a, sqid, cssOf(t, a, ref), mine)
411 served(t, a, "/d/"+sqid+"/fonts/"+ref, mine, reg)
412 refused(t, a, "/d/"+sqid+"/fonts/"+ref, theirs)
413 refused(t, a, "/s/"+mintShareLink(t, a, shared, mine)+"/fonts/"+ref, nil)
414}
415