oficina / slides Public

Fonts: a truncated upload is an error; read the delete form before locking

NextPart wraps io.EOF for a part cut off mid-body, so errors.Is let a
truncated stream pass as finished; compare with io.EOF directly. Delete
now reads its form before taking the library lock, and an upload has read
and inspected every byte of a file before it does. The interleaving tests
wait on the trace hook for the competing request instead of sleeping.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev ea57daae92c0c234d44038b48e6f9ffc86fdc8bd parent 367910a
2 files changed, +64 −12
  • internal/slides/library.go +11 −6
  • internal/slidestest/library_test.go +53 −6
diff --git a/internal/slides/library.go b/internal/slides/library.go
index 39ea93a..c579fbe 100644
--- a/internal/slides/library.go
+++ b/internal/slides/library.go
@@ -195,7 +195,7 @@ func (a *app) uploadFonts(w http.ResponseWriter, r *http.Request) {
var refused []string
for {
part, err := mr.NextPart()
- if errors.Is(err, io.EOF) {
+ if err == io.EOF { // exactly: a truncated stream wraps EOF and is not the end
break
}
if err != nil {
@@ -269,7 +269,9 @@ func (a *app) addFont(r *http.Request, u User, name string, raw []byte) (string,
// 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.
+ // write there. Every byte of the file was read and inspected above:
+ // only the checks, the allocation, Put and the insert run locked.
+ a.traceFont("queued")
a.fontMu.Lock()
defer a.fontMu.Unlock()
@@ -421,10 +423,13 @@ func (a *app) deleteFont(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
+ // The body is read before the lock is taken: a stalled request must
+ // not hold up every other person's fonts.
+ family := r.FormValue("family")
a.traceFont("delete")
a.fontMu.Lock()
defer a.fontMu.Unlock()
- rows, err := a.ownFontFamily(r.Context(), u, r.FormValue("family"))
+ rows, err := a.ownFontFamily(r.Context(), u, family)
if err != nil {
a.fail(w, r, "read a font family", err)
return
@@ -458,7 +463,7 @@ func (a *app) traceFont(stage string) {
}
// 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).
+// each other without a clock: f is called at "queued" (an upload, just
+// before it takes the lock), "checked" and "stored" (inside its critical
+// section) and "delete" (a deletion, just before it takes the lock).
func (a *app) SetFontTrace(f func(stage string)) { a.fontTrace = f }
diff --git a/internal/slidestest/library_test.go b/internal/slidestest/library_test.go
index e7fc751..a99aae7 100644
--- a/internal/slidestest/library_test.go
+++ b/internal/slidestest/library_test.go
@@ -16,7 +16,6 @@ import (
"strings"
"sync"
"testing"
- "time"
"amadan.net/oficina/slides/internal/slides"
"amadan.net/rastrillo/rastrillo/blobs"
@@ -317,18 +316,41 @@ func TestTheAccountMenuListsFonts(t *testing.T) {
// 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{})}
+ 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
}
@@ -356,7 +378,7 @@ func TestConcurrentUploadsRespectTheFamilyLimit(t *testing.T) {
t.Fatal(err)
}
}
- g := newGate("checked")
+ g := newGate("checked").waitFor("queued", 2)
a.app.SetFontTrace(g.trace)
t.Cleanup(func() { a.app.SetFontTrace(nil) })
@@ -368,7 +390,7 @@ func TestConcurrentUploadsRespectTheFamilyLimit(t *testing.T) {
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.arrived // the second upload is at the lock
g.release()
c1, c2 := <-codes, <-codes
if n := countRows(t, a, "1 = 1"); n != 16 {
@@ -415,7 +437,7 @@ func TestADeleteCannotTakeAnUploadsObject(t *testing.T) {
t.Fatalf("second person's upload: %d", rec.Code)
}
- g := newGate("stored")
+ g := newGate("stored").waitFor("delete", 1)
a.app.SetFontTrace(g.trace)
t.Cleanup(func() { a.app.SetFontTrace(nil) })
done := make(chan int, 1)
@@ -425,7 +447,7 @@ func TestADeleteCannotTakeAnUploadsObject(t *testing.T) {
go func() {
deleted <- post(t, a, "/fonts/delete", url.Values{"family": {"Liberation Sans"}}, two...).Code
}()
- time.Sleep(100 * time.Millisecond)
+ <-g.arrived // the delete is at the lock
g.release()
if c := <-done; c != http.StatusOK {
t.Fatalf("upload: %d", c)
@@ -472,3 +494,28 @@ func TestAMalformedMultipartStreamIsNotSilentlyDone(t *testing.T) {
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)
+ }
+}