Fonts: serialise library uploads and deletes; surface bad multipart
An upload's quota check, CSS-name choice, object write and row insert, and a delete's row removal, reference count and object delete, now run under one mutex, so two uploads cannot both take the last place and a delete cannot remove an object an upload has stored but not yet recorded. A multipart stream that fails to parse is no longer taken for the end: files already added stay and the page says it did not work; with nothing added the answer is 400. Reference-count failures are logged.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
5 files changed,
+218
−4
internal/slides/errors.go+1 −1internal/slides/handlers.go+6 −1internal/slides/library.go+50 −2internal/slidestest/harness_test.go+1 −0internal/slidestest/library_test.go+160 −0
diff --git a/internal/slides/errors.go b/internal/slides/errors.go| index e87cd64..1e0355a 100644 |
| --- a/internal/slides/errors.go |
| +++ b/internal/slides/errors.go |
| @@ -59,7 +59,7 @@ func errorCopy(r *http.Request, status int, kind errorKind) errorWords { |
| // A talk that finished (presentation.go's gone): its own words, |
| // because it is a different fact from a mistyped address. |
| key = "slides.present.over" |
| - case status == http.StatusUnprocessableEntity: |
| + case status == http.StatusUnprocessableEntity, status == http.StatusBadRequest: |
| key = "slides.error.422" |
| case status == http.StatusServiceUnavailable: |
| key = "slides.error.503" |
diff --git a/internal/slides/handlers.go b/internal/slides/handlers.go| index a648754..d827636 100644 |
| --- a/internal/slides/handlers.go |
| +++ b/internal/slides/handlers.go |
| @@ -4,6 +4,7 @@ import ( |
| "context" |
| "log/slog" |
| "net/http" |
| + "sync" |
| "time" |
| "amadan.net/oficina/home/connect" |
| @@ -28,7 +29,11 @@ import ( |
| // The handlers themselves live beside what they serve: sign-in in |
| // auth.go, the deck screens in decks.go. |
| type app struct { |
| - agent http.Handler |
| + agent http.Handler |
| + // fontMu serialises the library's uploads and deletions (library.go); |
| + // fontTrace is a test seam, nil in production. |
| + fontMu sync.Mutex |
| + fontTrace func(stage string) |
| agentAccess *slideAgent |
| // draining is closed by Drain, as the process stops (drain.go). |
| draining drain |
diff --git a/internal/slides/library.go b/internal/slides/library.go| index 14b6dc9..39ea93a 100644 |
| --- a/internal/slides/library.go |
| +++ b/internal/slides/library.go |
| @@ -195,11 +195,24 @@ func (a *app) uploadFonts(w http.ResponseWriter, r *http.Request) { |
| var refused []string |
| for { |
| part, err := mr.NextPart() |
| + if errors.Is(err, io.EOF) { |
| + break |
| + } |
| if err != nil { |
| var tooBig *http.MaxBytesError |
| if errors.As(err, &tooBig) { |
| refused = append(refused, rastrillo.Tf(r, "slides.fonts.refused.big", "name", "…")) |
| + break |
| } |
| + // A stream that cannot be parsed: what was added stays, and |
| + // the page says the generic "that didn't work"; with nothing |
| + // added it is a 400. |
| + a.logger.Info("slides: a font upload would not parse", "err", err) |
| + if added == 0 && len(refused) == 0 { |
| + a.errorPage(w, r, http.StatusBadRequest, kindStatus, "") |
| + return |
| + } |
| + refused = append(refused, rastrillo.T(r, "slides.error.422.heading")) |
| break |
| } |
| if part.FormName() != "file" || part.FileName() == "" { |
| @@ -250,6 +263,16 @@ func (a *app) addFont(r *http.Request, u User, name string, raw []byte) (string, |
| } |
| owner := actorFor(u) |
| + // One upload or delete at a time: the quota check, the CSS-name |
| + // choice, the object write and the row insert are one step, and a |
| + // deletion's reference count and object delete are one step, so |
| + // neither can slip between the other's halves. The app is one |
| + // process with one writer; a mutex says that without holding the |
| + // database's only write connection across a store that may itself |
| + // write there. |
| + a.fontMu.Lock() |
| + defer a.fontMu.Unlock() |
| + |
| var mine []LibraryFont |
| if err := a.db.G.WithContext(ctx).Where("owner = ?", owner).Find(&mine).Error; err != nil { |
| return "", err |
| @@ -283,6 +306,7 @@ func (a *app) addFont(r *http.Request, u User, name string, raw []byte) (string, |
| } |
| } |
| + a.traceFont("checked") |
| stored, err := a.cfg.Blobs.Put(ctx, strings.NewReader(string(raw)), face.ContentType()) |
| if err != nil { |
| return "", fmt.Errorf("put font: %w", err) |
| @@ -290,6 +314,7 @@ func (a *app) addFont(r *http.Request, u User, name string, raw []byte) (string, |
| if stored.Hash != face.Ref { |
| return "", fmt.Errorf("the store keyed a font %s, typeface says %s", stored.Hash, face.Ref) |
| } |
| + a.traceFont("stored") |
| row := LibraryFont{ |
| Owner: owner, Family: face.Family, CSSName: css, Ref: face.Ref, |
| Format: string(face.Format), Outline: string(face.Outline), Style: face.Style, |
| @@ -312,13 +337,19 @@ func (a *app) addFont(r *http.Request, u User, name string, raw []byte) (string, |
| } |
| // dropFontObject deletes a font's object unless some library row (any |
| -// owner) still names it. |
| +// owner) still names it. The caller holds fontMu. |
| func (a *app) dropFontObject(ctx context.Context, ref string) { |
| if a.cfg.Blobs == nil { |
| return |
| } |
| var n int64 |
| - if err := a.db.G.WithContext(ctx).Model(&LibraryFont{}).Where("ref = ?", ref).Count(&n).Error; err != nil || n > 0 { |
| + if err := a.db.G.WithContext(ctx).Model(&LibraryFont{}).Where("ref = ?", ref).Count(&n).Error; err != nil { |
| + // Unknown is not zero: keep the object. A later upload of the |
| + // same font finds it already there. |
| + a.logger.Error("slides: count a font's references", "ref", ref, "err", err) |
| + return |
| + } |
| + if n > 0 { |
| return |
| } |
| if err := a.cfg.Blobs.Delete(ctx, fontObjectKey(ref)); err != nil { |
| @@ -390,6 +421,9 @@ func (a *app) deleteFont(w http.ResponseWriter, r *http.Request) { |
| if !ok { |
| return |
| } |
| + a.traceFont("delete") |
| + a.fontMu.Lock() |
| + defer a.fontMu.Unlock() |
| rows, err := a.ownFontFamily(r.Context(), u, r.FormValue("family")) |
| if err != nil { |
| a.fail(w, r, "read a font family", err) |
| @@ -414,3 +448,17 @@ func (a *app) deleteFont(w http.ResponseWriter, r *http.Request) { |
| } |
| http.Redirect(w, r, "/fonts", http.StatusSeeOther) |
| } |
| + |
| +// traceFont tells a test which step an upload or delete has reached; nil |
| +// in production. |
| +func (a *app) traceFont(stage string) { |
| + if a.fontTrace != nil { |
| + a.fontTrace(stage) |
| + } |
| +} |
| + |
| +// SetFontTrace is the test seam for ordering two font requests against |
| +// each other without a clock: f is called at "checked" and "stored" |
| +// (inside an upload's critical section) and "delete" (before a |
| +// deletion takes it). |
| +func (a *app) SetFontTrace(f func(stage string)) { a.fontTrace = f } |
diff --git a/internal/slidestest/harness_test.go b/internal/slidestest/harness_test.go| index 866b15d..af76d78 100644 |
| --- a/internal/slidestest/harness_test.go |
| +++ b/internal/slidestest/harness_test.go |
| @@ -109,6 +109,7 @@ type testApp struct { |
| FlushMail() |
| ServeOptions(rastrillo.Options, *http.ServeMux) rastrillo.Options |
| Drain() |
| + SetFontTrace(func(stage string)) |
| } |
| } |
diff --git a/internal/slidestest/library_test.go b/internal/slidestest/library_test.go| index 3eb1ab3..e7fc751 100644 |
| --- a/internal/slidestest/library_test.go |
| +++ b/internal/slidestest/library_test.go |
| @@ -14,7 +14,9 @@ import ( |
| "os" |
| "path/filepath" |
| "strings" |
| + "sync" |
| "testing" |
| + "time" |
| "amadan.net/oficina/slides/internal/slides" |
| "amadan.net/rastrillo/rastrillo/blobs" |
| @@ -312,3 +314,161 @@ func TestTheAccountMenuListsFonts(t *testing.T) { |
| 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. |
| +type gate struct { |
| + stage string |
| + reached chan struct{} |
| + hold chan struct{} |
| + once sync.Once |
| +} |
| + |
| +func newGate(stage string) *gate { |
| + return &gate{stage: stage, reached: make(chan struct{}), hold: make(chan struct{})} |
| +} |
| + |
| +func (g *gate) trace(stage string) { |
| + 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") |
| + 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 |
| + }() |
| + time.Sleep(100 * time.Millisecond) // the second is waiting its turn |
| + 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) |
| + } |
| + |
| + g := newGate("stored") |
| + 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": {"Liberation Sans"}}, two...).Code |
| + }() |
| + time.Sleep(100 * time.Millisecond) |
| + 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) |
| + } |
| +} |