package slidestest import ( "bytes" "context" "crypto/sha256" "encoding/hex" "fmt" "html" "mime/multipart" "net/http" "net/http/httptest" "net/url" "os" "path/filepath" "strings" "sync" "testing" "amadan.net/oficina/slides/internal/slides" "amadan.net/oficina/slides/internal/slides/fonts" "amadan.net/rastrillo/rastrillo/blobs" ) // The library tests upload Liberation (SIL OFL), which the app already // ships, so no font file is added for them. type upFile struct { name string data []byte } func libFont(t *testing.T, name string) []byte { t.Helper() b, err := os.ReadFile(filepath.Join("..", "slides", "static", "fonts", name)) if err != nil { t.Fatalf("read %s: %v", name, err) } return b } func uploadFonts(t *testing.T, a *testApp, cookies []*http.Cookie, files ...upFile) *httptest.ResponseRecorder { t.Helper() var body bytes.Buffer mw := multipart.NewWriter(&body) for _, f := range files { w, err := mw.CreateFormFile("file", f.name) if err != nil { t.Fatal(err) } w.Write(f.data) } mw.Close() req := httptest.NewRequest(http.MethodPost, "/fonts", &body) req.Header.Set("Content-Type", mw.FormDataContentType()) req.Header.Set("Origin", testOrigin) req.Header.Set("Sec-Fetch-Site", "same-origin") for _, c := range cookies { req.AddCookie(c) } rec := httptest.NewRecorder() a.ServeHTTP(rec, req) // The page escapes an apostrophe; the messages are read as text. rec.Body = bytes.NewBufferString(html.UnescapeString(rec.Body.String())) return rec } func countRows(t *testing.T, a *testApp, where string, args ...any) int64 { t.Helper() var n int64 if err := a.db.G.Model(&slides.LibraryFont{}).Where(where, args...).Count(&n).Error; err != nil { t.Fatal(err) } return n } func hasObject(store blobs.Store, ref string) bool { rc, err := store.Get(context.Background(), ref) if err != nil { return false } rc.Close() return true } // cssOf is the css name the library gave the face with this ref. A // catalog family's own name is reserved (library.go's // reservedFontName), so an upload of a Liberation file is suffixed. func cssOf(t *testing.T, a *testApp, ref string) string { t.Helper() var row slides.LibraryFont if err := a.db.G.Where("ref = ?", ref).First(&row).Error; err != nil { t.Fatal(err) } return row.CSSName } func sha(b []byte) string { s := sha256.Sum256(b) return hex.EncodeToString(s[:]) } func TestUploadAFontAndSeeItListed(t *testing.T) { store := dirStore(t) a := newAppWithStore(t, store) cookies := signedIn(t, a, allowedAddress) empty := mustGet(t, a, "/fonts", http.StatusOK, cookies).Body.String() if !strings.Contains(empty, "No fonts yet.") { t.Errorf("an empty library is not said to be empty:\n%s", empty) } reg, bold := libFont(t, "LiberationSans-Regular.ttf"), libFont(t, "LiberationSans-Bold.ttf") rec := uploadFonts(t, a, cookies, upFile{"a.ttf", reg}, upFile{"b.ttf", bold}) if rec.Code != http.StatusOK { t.Fatalf("POST /fonts: %d\n%s", rec.Code, rec.Body) } if !strings.Contains(rec.Body.String(), "2 files added.") { t.Errorf("the count of files added is not shown:\n%s", rec.Body) } var rows []slides.LibraryFont if err := a.db.G.Order("weight").Find(&rows).Error; err != nil { t.Fatal(err) } if len(rows) != 2 { t.Fatalf("%d rows, want 2", len(rows)) } if rows[0].Ref != sha(reg) || rows[0].Family != "Liberation Sans" || rows[0].CSSName != "Liberation Sans 2" || rows[0].Weight != 400 || rows[0].Size != int64(len(reg)) || rows[0].Owner == "" || rows[0].Format != "ttf" { t.Errorf("row %+v does not describe the uploaded face", rows[0]) } if !hasObject(store, rows[0].Ref) || !hasObject(store, rows[1].Ref) { t.Errorf("the bytes are not in the store under their refs") } page := html.UnescapeString(mustGet(t, a, "/fonts", http.StatusOK, cookies).Body.String()) if !strings.Contains(page, "Liberation Sans") || !strings.Contains(page, "2 styles") { t.Errorf("the family and its styles are not listed:\n%s", page) } if !strings.Contains(page, "/fonts/delete?family=Liberation+Sans+2") && !strings.Contains(page, "/fonts/delete?family=Liberation%20Sans%202") { t.Errorf("no delete link for the family:\n%s", page) } // The same file again is refused, and adds nothing. again := uploadFonts(t, a, cookies, upFile{"a.ttf", reg}) if again.Code != http.StatusUnprocessableEntity || !strings.Contains(again.Body.String(), "a.ttf is already in your fonts.") { t.Errorf("a repeat upload: %d\n%s", again.Code, again.Body) } if n := countRows(t, a, "1 = 1"); n != 2 { t.Errorf("%d rows after a repeat, want 2", n) } } func TestUploadRefusesWhatIsNotAFont(t *testing.T) { store := dirStore(t) a := newAppWithStore(t, store) cookies := signedIn(t, a, allowedAddress) png := append([]byte("\x89PNG\r\n\x1a\n"), bytes.Repeat([]byte{1}, 200)...) good := libFont(t, "LiberationSans-Regular.ttf") cases := []struct { name string file upFile want string }{ {"png", upFile{"pic.ttf", png}, "pic.ttf isn't a font file."}, {"big", upFile{"huge.ttf", append(append([]byte{}, good...), make([]byte, 11<<20)...)}, "huge.ttf is over 10 MB."}, {"truncated", upFile{"cut.ttf", good[:len(good)/3]}, "cut.ttf looks damaged and can't be used."}, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { rec := uploadFonts(t, a, cookies, c.file) if rec.Code != http.StatusUnprocessableEntity { t.Fatalf("status %d, want 422\n%s", rec.Code, rec.Body) } if !strings.Contains(rec.Body.String(), c.want) { t.Errorf("missing %q:\n%s", c.want, rec.Body) } if n := countRows(t, a, "1 = 1"); n != 0 { t.Errorf("%d rows after a refusal", n) } if hasObject(store, sha(c.file.data)) { t.Errorf("a refused file was stored") } }) } // One refusal does not stop the good file beside it. rec := uploadFonts(t, a, cookies, upFile{"pic.ttf", png}, upFile{"ok.ttf", good}) body := rec.Body.String() if rec.Code != http.StatusOK || !strings.Contains(body, "pic.ttf isn't a font file.") || !strings.Contains(body, "1 file added.") { t.Errorf("mixed upload: %d\n%s", rec.Code, body) } } func TestTheLibraryLimits(t *testing.T) { a := newAppWithStore(t, dirStore(t)) cookies := signedIn(t, a, allowedAddress) mustGet(t, a, "/fonts", http.StatusOK, cookies) // the person's row exists once they have been seen var u slides.User if err := a.db.G.Where("email = ?", allowedAddress).Take(&u).Error; err != nil { t.Fatal(err) } owner := fmt.Sprintf("person:%d", u.ID) seed := func(family, css string, i int) { row := slides.LibraryFont{Owner: owner, Family: family, CSSName: css, Ref: sha([]byte(fmt.Sprintf("%s-%d", family, i))), Format: "ttf", Outline: "truetype", Weight: 400} if err := a.db.G.Create(&row).Error; err != nil { t.Fatal(err) } } for i := 0; i < 16; i++ { seed("Liberation Sans", "Liberation Sans", i) } rec := uploadFonts(t, a, cookies, upFile{"x.ttf", libFont(t, "LiberationSans-Regular.ttf")}) if rec.Code != http.StatusUnprocessableEntity || !strings.Contains(rec.Body.String(), "Liberation Sans already has 16 styles.") { t.Errorf("17th face: %d\n%s", rec.Code, rec.Body) } if err := a.db.G.Where("1 = 1").Delete(&slides.LibraryFont{}).Error; err != nil { t.Fatal(err) } for i := 0; i < 32; i++ { seed(fmt.Sprintf("Family %d", i), fmt.Sprintf("Family %d", i), 0) } rec = uploadFonts(t, a, cookies, upFile{"x.ttf", libFont(t, "LiberationSans-Regular.ttf")}) if rec.Code != http.StatusUnprocessableEntity || !strings.Contains(rec.Body.String(), "You can keep up to 32 font families.") { t.Errorf("33rd family: %d\n%s", rec.Code, rec.Body) } if n := countRows(t, a, "ref = ?", sha(libFont(t, "LiberationSans-Regular.ttf"))); n != 0 { t.Errorf("the refused face was recorded") } } func TestALibraryIsOnlyItsOwners(t *testing.T) { a := newAppWithStore(t, dirStore(t)) one := signedIn(t, a, allowedAddress) if rec := uploadFonts(t, a, one, upFile{"a.ttf", libFont(t, "LiberationSans-Regular.ttf")}); rec.Code != http.StatusOK { t.Fatalf("upload: %d", rec.Code) } // Another person's library, seeded: the first person sees none of it. other := slides.LibraryFont{Owner: "person:999", Family: "Secret Face", CSSName: "Secret Face", Ref: sha([]byte("x")), Format: "ttf", Outline: "truetype", Weight: 400} if err := a.db.G.Create(&other).Error; err != nil { t.Fatal(err) } page := mustGet(t, a, "/fonts", http.StatusOK, one).Body.String() if strings.Contains(page, "Secret Face") { t.Errorf("another person's family is listed") } if rec := get(t, a, "/fonts/delete?family=Secret+Face", one...); rec.Code != http.StatusNotFound { t.Errorf("confirm page for another person's family: %d, want 404", rec.Code) } post(t, a, "/fonts/delete", url.Values{"family": {"Secret Face"}}, one...) if n := countRows(t, a, "owner = ?", "person:999"); n != 1 { t.Errorf("another person's family was deleted") } } func TestDeletingAFamilyRemovesItsRows(t *testing.T) { store := dirStore(t) a := newAppWithStore(t, store) cookies := signedIn(t, a, allowedAddress) reg, mono := libFont(t, "LiberationSans-Regular.ttf"), libFont(t, "LiberationMono-Regular.ttf") uploadFonts(t, a, cookies, upFile{"a.ttf", reg}, upFile{"m.ttf", mono}) sans, monoCSS := cssOf(t, a, sha(reg)), cssOf(t, a, sha(mono)) confirm := mustGet(t, a, "/fonts/delete?family="+url.QueryEscape(sans), http.StatusOK, cookies).Body.String() if !strings.Contains(confirm, "Delete Liberation Sans?") || !strings.Contains(confirm, "Delete font") { t.Errorf("confirm page:\n%s", confirm) } if n := countRows(t, a, "1 = 1"); n != 2 { t.Fatalf("the GET deleted something: %d rows", n) } // A second owner holds the same bytes as the mono face: that object // must stay when the first person's family goes. if err := a.db.G.Create(&slides.LibraryFont{Owner: "person:999", Family: "Liberation Mono", CSSName: "Liberation Mono", Ref: sha(mono), Format: "ttf", Outline: "truetype", Weight: 400}).Error; err != nil { t.Fatal(err) } rec := post(t, a, "/fonts/delete", url.Values{"family": {sans}}, cookies...) if rec.Code != http.StatusSeeOther { t.Fatalf("delete: %d\n%s", rec.Code, rec.Body) } if hasObject(store, sha(reg)) { t.Errorf("an unreferenced object was kept") } if n := countRows(t, a, "ref = ?", sha(reg)); n != 0 { t.Errorf("rows remain") } post(t, a, "/fonts/delete", url.Values{"family": {monoCSS}}, cookies...) if !hasObject(store, sha(mono)) { t.Errorf("an object another library still holds was deleted") } if n := countRows(t, a, "owner = ?", "person:999"); n != 1 { t.Errorf("the other library lost its row") } } func TestTheFontsPageWorksWithoutScripts(t *testing.T) { a := newAppWithStore(t, dirStore(t)) cookies := signedIn(t, a, allowedAddress) body := mustGet(t, a, "/fonts", http.StatusOK, cookies).Body.String() for _, want := range []string{`method="post"`, `action="/fonts"`, `enctype="multipart/form-data"`, `type="file"`, `name="file"`, "multiple", "Upload", "Upload only fonts your licence lets you use on the web."} { if !strings.Contains(body, want) { t.Errorf("the form lacks %q:\n%s", want, body) } } // No store: the page says so, and the POST answers 503. b := newApp(t) c := signedIn(t, b, allowedAddress) page := mustGet(t, b, "/fonts", http.StatusOK, c).Body.String() if !strings.Contains(page, "Fonts aren't available here yet.") && !strings.Contains(page, "Fonts aren't available here yet.") { t.Errorf("no-store page lacks the unavailable line:\n%s", page) } if strings.Contains(page, `type="file"`) { t.Errorf("no-store page still offers the form") } if rec := uploadFonts(t, b, c, upFile{"a.ttf", libFont(t, "LiberationSans-Regular.ttf")}); rec.Code != http.StatusServiceUnavailable { t.Errorf("POST without a store: %d, want 503", rec.Code) } } func TestTheAccountMenuListsFonts(t *testing.T) { a := newApp(t) cookies := signedIn(t, a, allowedAddress) body := mustGet(t, a, "/", http.StatusOK, cookies).Body.String() if !strings.Contains(body, `href="/fonts"`) || !strings.Contains(body, ">Fonts<") { t.Errorf("the account menu has no Fonts link:\n%s", body) } } // gate is a SetFontTrace hook that parks the first request to reach // stage until release is called; reached is closed when it has. // // waiter, if set, is a second stage whose Nth arrival (nth, counting // from 1) closes arrived: the competing request, confirmed to be at its // point rather than guessed at with a sleep. type gate struct { stage string reached chan struct{} hold chan struct{} once sync.Once waiter string nth int seen int arrived chan struct{} mu sync.Mutex } func newGate(stage string) *gate { return &gate{stage: stage, reached: make(chan struct{}), hold: make(chan struct{}), arrived: make(chan struct{})} } func (g *gate) waitFor(stage string, nth int) *gate { g.waiter, g.nth = stage, nth return g } func (g *gate) trace(stage string) { if stage == g.waiter { g.mu.Lock() g.seen++ if g.seen == g.nth { close(g.arrived) } g.mu.Unlock() } if stage != g.stage { return } g.once.Do(func() { close(g.reached) <-g.hold }) } func (g *gate) release() { close(g.hold) } // Two uploads race for the last place in a family: the second must see // the first's row. func TestConcurrentUploadsRespectTheFamilyLimit(t *testing.T) { a := newAppWithStore(t, dirStore(t)) cookies := signedIn(t, a, allowedAddress) mustGet(t, a, "/fonts", http.StatusOK, cookies) var u slides.User if err := a.db.G.Where("email = ?", allowedAddress).Take(&u).Error; err != nil { t.Fatal(err) } for i := 0; i < 15; i++ { row := slides.LibraryFont{Owner: fmt.Sprintf("person:%d", u.ID), Family: "Liberation Sans", CSSName: "Liberation Sans", Ref: sha([]byte{byte(i)}), Format: "ttf", Outline: "truetype", Weight: 400} if err := a.db.G.Create(&row).Error; err != nil { t.Fatal(err) } } g := newGate("checked").waitFor("queued", 2) a.app.SetFontTrace(g.trace) t.Cleanup(func() { a.app.SetFontTrace(nil) }) codes := make(chan int, 2) go func() { codes <- uploadFonts(t, a, cookies, upFile{"a.ttf", libFont(t, "LiberationSans-Regular.ttf")}).Code }() <-g.reached go func() { codes <- uploadFonts(t, a, cookies, upFile{"b.ttf", libFont(t, "LiberationSans-Bold.ttf")}).Code }() <-g.arrived // the second upload is at the lock g.release() c1, c2 := <-codes, <-codes if n := countRows(t, a, "1 = 1"); n != 16 { t.Errorf("%d rows, want 16 (codes %d, %d)", n, c1, c2) } if !((c1 == 200 && c2 == 422) || (c1 == 422 && c2 == 200)) { t.Errorf("codes %d and %d: one upload fits, one is refused", c1, c2) } } // A family whose name cleans to another's CSS name gets a name of its own. func TestCollidingCSSNamesAreKeptApart(t *testing.T) { a := newAppWithStore(t, dirStore(t)) cookies := signedIn(t, a, allowedAddress) mustGet(t, a, "/fonts", http.StatusOK, cookies) var u slides.User a.db.G.Where("email = ?", allowedAddress).Take(&u) if err := a.db.G.Create(&slides.LibraryFont{Owner: fmt.Sprintf("person:%d", u.ID), Family: "Liberation Sans!", CSSName: "Liberation Sans", Ref: sha([]byte("z")), Format: "ttf", Outline: "truetype", Weight: 400}).Error; err != nil { t.Fatal(err) } if rec := uploadFonts(t, a, cookies, upFile{"a.ttf", libFont(t, "LiberationSans-Regular.ttf")}); rec.Code != http.StatusOK { t.Fatalf("upload: %d", rec.Code) } var css []string a.db.G.Model(&slides.LibraryFont{}).Distinct().Pluck("css_name", &css) if len(css) != 2 { t.Errorf("css names %v, want two distinct", css) } } // An upload that has stored its bytes but not yet its row must not lose // them to another person's deletion of the same file. func TestADeleteCannotTakeAnUploadsObject(t *testing.T) { store := dirStore(t) cfg, mailer := newConfig(t) cfg.Blobs = store const second = "second@example.test" cfg.AllowedAddresses = append(cfg.AllowedAddresses, second) a := newAppWith(t, cfg, mailer) one := signedIn(t, a, allowedAddress) two := signedIn(t, a, second) face := libFont(t, "LiberationSans-Regular.ttf") if rec := uploadFonts(t, a, two, upFile{"a.ttf", face}); rec.Code != http.StatusOK { t.Fatalf("second person's upload: %d", rec.Code) } css := cssOf(t, a, sha(face)) g := newGate("stored").waitFor("delete", 1) a.app.SetFontTrace(g.trace) t.Cleanup(func() { a.app.SetFontTrace(nil) }) done := make(chan int, 1) go func() { done <- uploadFonts(t, a, one, upFile{"a.ttf", face}).Code }() <-g.reached deleted := make(chan int, 1) go func() { deleted <- post(t, a, "/fonts/delete", url.Values{"family": {css}}, two...).Code }() <-g.arrived // the delete is at the lock g.release() if c := <-done; c != http.StatusOK { t.Fatalf("upload: %d", c) } <-deleted if n := countRows(t, a, "1 = 1"); n != 1 { t.Errorf("%d rows, want the first person's one", n) } if !hasObject(store, sha(face)) { t.Errorf("a row points at bytes that are gone") } } func TestAMalformedMultipartStreamIsNotSilentlyDone(t *testing.T) { a := newAppWithStore(t, dirStore(t)) cookies := signedIn(t, a, allowedAddress) good := libFont(t, "LiberationSans-Regular.ttf") raw := func(parts ...string) *httptest.ResponseRecorder { body := strings.Join(parts, "") req := httptest.NewRequest(http.MethodPost, "/fonts", strings.NewReader(body)) req.Header.Set("Content-Type", "multipart/form-data; boundary=XX") req.Header.Set("Origin", testOrigin) req.Header.Set("Sec-Fetch-Site", "same-origin") req.Header.Set("Accept", "text/html") for _, c := range cookies { req.AddCookie(c) } rec := httptest.NewRecorder() a.ServeHTTP(rec, req) return rec } file := "--XX\r\nContent-Disposition: form-data; name=\"file\"; filename=\"a.ttf\"\r\n\r\n" + string(good) + "\r\n" bad := "--XX\r\nContent-Disposition form-data; name=\"file\"\r\n\r\nx\r\n" if rec := raw(bad); rec.Code != http.StatusBadRequest { t.Errorf("only a malformed part: %d, want 400", rec.Code) } rec := raw(file, bad) if n := countRows(t, a, "1 = 1"); n != 1 { t.Errorf("the good file was not kept: %d rows", n) } if !strings.Contains(html.UnescapeString(rec.Body.String()), "That didn’t work") { t.Errorf("a malformed part after a file says nothing:\n%s", rec.Body) } } // A valid file followed by a part cut off mid-body: Go's reader wraps // io.EOF for that, and it is not the end of the stream. func TestATruncatedMultipartStreamIsNotSilentlyDone(t *testing.T) { a := newAppWithStore(t, dirStore(t)) cookies := signedIn(t, a, allowedAddress) good := libFont(t, "LiberationSans-Regular.ttf") body := "--XX\r\nContent-Disposition: form-data; name=\"file\"; filename=\"a.ttf\"\r\n\r\n" + string(good) + "\r\n" + "--XX\r\nContent-Disposition: form-data; name=\"file\"; filename=\"b.ttf\"\r\n\r\nabc" req := httptest.NewRequest(http.MethodPost, "/fonts", strings.NewReader(body)) req.Header.Set("Content-Type", "multipart/form-data; boundary=XX") req.Header.Set("Origin", testOrigin) req.Header.Set("Sec-Fetch-Site", "same-origin") for _, c := range cookies { req.AddCookie(c) } rec := httptest.NewRecorder() a.ServeHTTP(rec, req) if n := countRows(t, a, "1 = 1"); n != 1 { t.Errorf("the complete file was not kept: %d rows", n) } if !strings.Contains(html.UnescapeString(rec.Body.String()), "That didn’t work") { t.Errorf("a truncated part after a file says nothing:\n%s", rec.Body) } } // A family is never given a css name a stylesheet already means // something by: a catalog family's (an upload called "Liberation Serif" // would join the built-in Serif in the browser) or a generic keyword. // Such a name is treated as taken, and gets the same numeric suffix as // two families that clean to one name. func TestAnUploadedFamilyNeverTakesAReservedName(t *testing.T) { a := newAppWithStore(t, dirStore(t)) cookies := signedIn(t, a, allowedAddress) reserved := map[string]bool{} for _, n := range []string{"Liberation Sans", "Liberation Serif", "Liberation Mono", "serif", "sans-serif", "monospace", "cursive", "fantasy", "system-ui", "ui-serif", "ui-sans-serif", "ui-monospace", "ui-rounded", "math", "emoji", "fangsong"} { reserved[strings.ToLower(n)] = true } f, err := fonts.Parse(libFont(t, "LiberationSans-Regular.ttf")) if err != nil { t.Fatal(err) } for _, name := range []string{"Liberation Serif", "SANS-SERIF", "System-UI", "liberation mono"} { data, err := f.Renamed(name, 400, false) if err != nil { t.Fatal(err) } if rec := uploadFonts(t, a, cookies, upFile{"f.ttf", data}); rec.Code != http.StatusOK { t.Fatalf("upload %q: %d\n%s", name, rec.Code, rec.Body) } var row slides.LibraryFont if err := a.db.G.Where("ref = ?", sha(data)).First(&row).Error; err != nil { t.Fatal(err) } if reserved[strings.ToLower(row.CSSName)] || !strings.HasPrefix(row.CSSName, name+" ") { t.Errorf("%q was given the css name %q, want it with a numeric suffix", name, row.CSSName) } } }