oficina / slides Public

Fonts: renaming for the PDF is bounded by the file it came from

A face whose tables share bytes, or whose name records share one
string, grew past anything its size allows when renamed for the PDF:
every table and every PostScript-name record was copied in full, in
Go, before the PDF module's limits (final review, C1). buildSfnt now
sizes the file first and refuses (errTooLarge) past twice the input;
Renamed returns that error and the export fails with it. Every name
record counts against the name table's bounds; the family and one
PostScript name go in first, repeats are dropped.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 08185bd3a6402f8c3864d255bea953e597f21eaf parent 025fbfa
8 files changed, +209 −47
  • internal/slides/export.go +5 −1
  • internal/slides/fonts/rename_budget_test.go +104 −0
  • internal/slides/fonts/truetype.go +17 −5
  • internal/slides/fonts/uploaded.go +66 −37
  • internal/slides/fonts/uploaded_test.go +5 −1
  • internal/slidestest/deckfonts_test.go +4 −1
  • internal/slidestest/fonts_browser_test.go +4 −1
  • internal/slidestest/library_test.go +4 −1
diff --git a/internal/slides/export.go b/internal/slides/export.go
index 3b36b4c..3998f6f 100644
--- a/internal/slides/export.go
+++ b/internal/slides/export.go
@@ -188,7 +188,11 @@ func Export(ctx context.Context, d *deck.Deck, o ExportOptions) ([]byte, []layou
// family the pages' SVG names it by: the module matches a
// font-family against the name inside the font (fonts.Renamed).
for _, u := range lay.Uploaded() {
- faces = append(faces, u.Font.Renamed(u.CSS, u.Weight, u.Italic))
+ b, err := u.Font.Renamed(u.CSS, u.Weight, u.Italic)
+ if err != nil {
+ return nil, x.warnings, fmt.Errorf("slides: export: %s: %w", u.CSS, err)
+ }
+ faces = append(faces, b)
}
pdf, err := o.Runtime.Render(ctx, pages, faces)
if err != nil {
diff --git a/internal/slides/fonts/rename_budget_test.go b/internal/slides/fonts/rename_budget_test.go
new file mode 100644
index 0000000..aa5a681
--- /dev/null
+++ b/internal/slides/fonts/rename_budget_test.go
@@ -0,0 +1,104 @@
+package fonts
+
+import (
+ "encoding/binary"
+ "errors"
+ "fmt"
+ "runtime"
+ "testing"
+
+ "amadan.net/oficina/slides/internal/slides/fonts/fontstest"
+)
+
+// Renaming copies every table into a new file for the PDF, so a file
+// whose tables share bytes, or whose name records share one string,
+// grew past anything its size allows: a 10 MiB upload became 4.8 GB to
+// copy, in Go, before the PDF module's own limits (final review, C1).
+// The copy is never more than twice the file.
+
+// sharedTables is the serif face plus n tables over its glyf.
+func sharedTables(t *testing.T, n int) []byte {
+ t.Helper()
+ data := serifBytes()
+ for i := 0; i < n; i++ {
+ data = fontstest.WithTable(t, data, fmt.Sprintf("z%03d", i), []byte{0, 0, 0, 0})
+ }
+ count := int(binary.BigEndian.Uint16(data[4:]))
+ var off, length uint32
+ for i := 0; i < count; i++ {
+ rec := data[12+16*i:]
+ if string(rec[:4]) == "glyf" {
+ off, length = binary.BigEndian.Uint32(rec[8:]), binary.BigEndian.Uint32(rec[12:])
+ }
+ }
+ for i := 0; i < count; i++ {
+ rec := data[12+16*i:]
+ if rec[0] == 'z' {
+ binary.BigEndian.PutUint32(rec[8:], off)
+ binary.BigEndian.PutUint32(rec[12:], length)
+ }
+ }
+ return data
+}
+
+// sharedNames is a name table of n PostScript-name records, each in its
+// own language, all pointing at one string of size bytes.
+func sharedNames(n, size int) []byte {
+ b := make([]byte, 6+12*n)
+ binary.BigEndian.PutUint16(b[2:], uint16(n))
+ binary.BigEndian.PutUint16(b[4:], uint16(len(b)))
+ for i := 0; i < n; i++ {
+ at := 6 + 12*i
+ for j, v := range []uint16{3, 1, uint16(i + 1), 6, uint16(size), 0} {
+ binary.BigEndian.PutUint16(b[at+2*j:], v)
+ }
+ }
+ return append(b, make([]byte, size)...)
+}
+
+func TestRenamingIsBoundedByTheFile(t *testing.T) {
+ for _, c := range []struct {
+ name string
+ data []byte
+ refused bool // too large even once the names are bounded
+ }{
+ {"a hundred tables over glyf", sharedTables(t, 100), true},
+ {"a thousand PostScript names over one string", fontstest.WithTable(t, serifBytes(), "name", sharedNames(1000, 30000)), false},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ f, err := Parse(c.data)
+ if err != nil {
+ t.Fatalf("Parse: %v", err)
+ }
+ var before, after runtime.MemStats
+ runtime.ReadMemStats(&before)
+ out, err := f.Renamed("Upload", 400, false)
+ runtime.ReadMemStats(&after)
+ if alloc := after.TotalAlloc - before.TotalAlloc; alloc > uint64(3*len(c.data)) {
+ t.Errorf("renaming %d bytes allocated %d", len(c.data), alloc)
+ }
+ if c.refused {
+ if !errors.Is(err, errTooLarge) {
+ t.Fatalf("Renamed = %d bytes, %v; want errTooLarge", len(out), err)
+ }
+ return
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(out) > 2*len(c.data) {
+ t.Fatalf("renaming %d bytes made %d", len(c.data), len(out))
+ }
+ renamed, err := Parse(out)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if n := len(renamed.tables["name"]); n > 6+12*maxNameRecords+maxNameStorage {
+ t.Errorf("the renamed name table is %d bytes", n)
+ }
+ if names := nameStrings(t, renamed); len(names[6]) == 0 || len(names[1]) != 1 || names[1][0] != "Upload" {
+ t.Errorf("PostScript names %d, families %q; want a PostScript name and Upload", len(names[6]), names[1])
+ }
+ })
+ }
+}
diff --git a/internal/slides/fonts/truetype.go b/internal/slides/fonts/truetype.go
index 42d48bd..795d6d4 100644
--- a/internal/slides/fonts/truetype.go
+++ b/internal/slides/fonts/truetype.go
@@ -630,11 +630,17 @@ func (f *Font) Subset(keep map[uint16]bool) ([]byte, error) {
return nil, fmt.Errorf("%w: %s", errNoTable, tag)
}
}
- return buildSfnt(out), nil
+ return buildSfnt(out, 2*len(f.data))
}
-// buildSfnt assembles a TrueType file from a tag→bytes map.
-func buildSfnt(tables map[string][]byte) []byte {
+// errTooLarge is a font built from another's tables that would be more
+// than budget bytes.
+var errTooLarge = errors.New("fonts: the font built would be too large for the file it came from")
+
+// buildSfnt assembles a TrueType file from a tag→bytes map, refusing
+// (errTooLarge) before it copies anything when the file would be more
+// than budget bytes.
+func buildSfnt(tables map[string][]byte, budget int) ([]byte, error) {
tags := make([]string, 0, len(tables))
for t := range tables {
tags = append(tags, t)
@@ -642,6 +648,12 @@ func buildSfnt(tables map[string][]byte) []byte {
sort.Strings(tags) // the table directory must be in tag order
n := len(tags)
+ total := 12 + 16*n
+ for _, tag := range tags {
+ if total += (len(tables[tag]) + 3) &^ 3; total > budget {
+ return nil, errTooLarge
+ }
+ }
// searchRange/entrySelector/rangeShift are a binary-search hint a
// modern reader ignores but a strict validator checks.
entrySelector := 0
@@ -658,7 +670,7 @@ func buildSfnt(tables map[string][]byte) []byte {
binary.BigEndian.PutUint16(header[8:], uint16(entrySelector))
binary.BigEndian.PutUint16(header[10:], uint16(rangeShift))
- body := []byte{}
+ body := make([]byte, 0, total-len(header))
offset := len(header)
for i, tag := range tags {
b := tables[tag]
@@ -687,7 +699,7 @@ func buildSfnt(tables map[string][]byte) []byte {
binary.BigEndian.PutUint32(file[headOff+8:], adj)
}
}
- return file
+ return file, nil
}
func tableChecksum(b []byte) uint32 {
diff --git a/internal/slides/fonts/uploaded.go b/internal/slides/fonts/uploaded.go
index 84ae2b1..2e007d6 100644
--- a/internal/slides/fonts/uploaded.go
+++ b/internal/slides/fonts/uploaded.go
@@ -2,6 +2,7 @@ package fonts
import (
"encoding/binary"
+ "fmt"
"sort"
"strings"
"unicode/utf16"
@@ -162,12 +163,20 @@ func (f *Font) Embeddable() bool {
// and keeps an upload from shadowing a built-in face. Every other name
// stays, the PostScript name among them, which is what the PDF writes
// as the face's /BaseFont.
-func (f *Font) Renamed(family string, weight int, italic bool) []byte {
+//
+// The copy is never more than twice the file (errTooLarge otherwise),
+// checked before anything is copied: a file whose tables share bytes
+// would otherwise be copied once per table that names them.
+func (f *Font) Renamed(family string, weight int, italic bool) ([]byte, error) {
tables := make(map[string][]byte, len(f.tables))
for tag, b := range f.tables {
tables[tag] = b
}
- tables["name"] = renameTable(f.tables["name"], family)
+ name, err := renameTable(f.tables["name"], family)
+ if err != nil {
+ return nil, err
+ }
+ tables["name"] = name
if os2, ok := f.tables["OS/2"]; ok && len(os2) >= 64 {
os2 = append([]byte(nil), os2...)
binary.BigEndian.PutUint16(os2[4:], uint16(weight))
@@ -182,7 +191,7 @@ func (f *Font) Renamed(family string, weight int, italic bool) []byte {
head := append([]byte(nil), tables["head"]...)
binary.BigEndian.PutUint32(head[8:], 0) // checkSumAdjustment, set by buildSfnt
tables["head"] = head
- return buildSfnt(tables)
+ return buildSfnt(tables, 2*len(f.data))
}
// nameRecord is one string of a name table.
@@ -191,14 +200,28 @@ type nameRecord struct {
value []byte
}
+// Bounds on a renamed name table: string offsets are 16 bits, and a
+// real table has a few dozen records.
+const (
+ maxNameStorage = 0xffff
+ maxNameRecords = 4096
+)
+
// renameTable is a format 0 name table holding old's records except
-// its family names (1, 16 and 21) and any language-tagged record, plus
-// family as the Windows Unicode English family name — and a PostScript
-// name made from family should old carry none, because a font without
-// one is a font the PDF module will not load.
-func renameTable(old []byte, family string) []byte {
+// its family names (1, 16 and 21), any language-tagged record and any
+// repeat of a record already kept, plus family as the Windows Unicode
+// English family name, and one PostScript name: old's (Windows English
+// first), or one made from family should old carry none, because a font
+// without one is a font the PDF module will not load.
+//
+// Every record counts against the bounds, the PostScript names among
+// them: old's records may share one string, and each is copied here, so
+// a table of a thousand records over one long string would otherwise
+// grow a thousandfold. The family and the one PostScript name go in
+// first; what does not fit after them is dropped.
+func renameTable(old []byte, family string) ([]byte, error) {
var recs []nameRecord
- hasPS := false
+ seen := map[[4]uint16]bool{}
if len(old) >= 6 {
count := int(binary.BigEndian.Uint16(old[2:]))
base := int(binary.BigEndian.Uint16(old[4:]))
@@ -215,25 +238,20 @@ func renameTable(old []byte, family string) []byte {
}
length := int(binary.BigEndian.Uint16(old[at+8:]))
off := base + int(binary.BigEndian.Uint16(old[at+10:]))
- if off+length > len(old) || r.language >= 0x8000 {
+ key := [4]uint16{r.platform, r.encoding, r.language, r.id}
+ if off+length > len(old) || r.language >= 0x8000 || seen[key] {
continue
}
switch r.id {
case 1, 16, 21:
continue
- case 6:
- hasPS = true
}
+ seen[key] = true
r.value = old[off : off+length]
recs = append(recs, r)
}
}
- recs = append(recs, nameRecord{3, 1, 0x409, 1, utf16BE(family)})
- if !hasPS {
- recs = append(recs, nameRecord{3, 1, 0x409, 6, utf16BE(postScriptFrom(family))})
- }
- sort.SliceStable(recs, func(i, j int) bool {
- a, b := recs[i], recs[j]
+ less := func(a, b nameRecord) bool {
if a.platform != b.platform {
return a.platform < b.platform
}
@@ -244,37 +262,48 @@ func renameTable(old []byte, family string) []byte {
return a.language < b.language
}
return a.id < b.id
- })
+ }
+ sort.SliceStable(recs, func(i, j int) bool { return less(recs[i], recs[j]) })
- // String offsets are 16 bits. Strings old shared are copied once
- // each here, so a table already near the limit could pass it: drop
- // what does not fit (and any record past the 4,096th, which keeps
- // the header's own size in range), keeping room for the family and
- // PostScript names this table exists to carry.
- reserve := 0
- for _, r := range recs {
- if r.id == 1 || r.id == 6 {
- reserve += len(r.value)
+ fam := nameRecord{3, 1, 0x409, 1, utf16BE(family)}
+ if len(fam.value) > maxNameStorage/2 {
+ return nil, fmt.Errorf("fonts: family name of %d bytes", len(fam.value))
+ }
+ // The PostScript name kept: Windows English, else the first.
+ ps := -1
+ for i, r := range recs {
+ if r.id == 6 && (ps < 0 || (r.platform == 3 && r.language == 0x409 && recs[ps].language != 0x409)) {
+ ps = i
}
}
- kept, size := recs[:0], 0
- for _, r := range recs {
- essential := r.id == 1 || r.id == 6
- if !essential && (size+len(r.value)+reserve > 0xffff || len(kept) >= 4096) {
+ kept := []nameRecord{fam}
+ size := len(fam.value)
+ if ps >= 0 && size+len(recs[ps].value) <= maxNameStorage {
+ kept = append(kept, recs[ps])
+ size += len(recs[ps].value)
+ } else {
+ r := nameRecord{3, 1, 0x409, 6, utf16BE(postScriptFrom(family))}
+ kept = append(kept, r)
+ size += len(r.value)
+ ps = -1
+ }
+ for i, r := range recs {
+ if i == ps {
continue
}
- if essential {
- reserve -= len(r.value)
+ if len(kept) >= maxNameRecords || size+len(r.value) > maxNameStorage {
+ continue
}
- size += len(r.value)
kept = append(kept, r)
+ size += len(r.value)
}
recs = kept
+ sort.SliceStable(recs, func(i, j int) bool { return less(recs[i], recs[j]) })
head := make([]byte, 6+12*len(recs))
binary.BigEndian.PutUint16(head[2:], uint16(len(recs)))
binary.BigEndian.PutUint16(head[4:], uint16(len(head)))
- var store []byte
+ store := make([]byte, 0, size)
for i, r := range recs {
at := 6 + i*12
binary.BigEndian.PutUint16(head[at:], r.platform)
@@ -285,7 +314,7 @@ func renameTable(old []byte, family string) []byte {
binary.BigEndian.PutUint16(head[at+10:], uint16(len(store)))
store = append(store, r.value...)
}
- return append(head, store...)
+ return append(head, store...), nil
}
func utf16BE(s string) []byte {
diff --git a/internal/slides/fonts/uploaded_test.go b/internal/slides/fonts/uploaded_test.go
index 3b6c29d..2b7e719 100644
--- a/internal/slides/fonts/uploaded_test.go
+++ b/internal/slides/fonts/uploaded_test.go
@@ -74,7 +74,11 @@ func nameStrings(t *testing.T, f *Font) map[uint16][]string {
// its PostScript name, and is the same font otherwise.
func TestRenamedCallsTheFontByTheDecksName(t *testing.T) {
orig := serifRegular(t)
- renamed, err := Parse(orig.Renamed("Test Upload", 700, true))
+ b, err := orig.Renamed("Test Upload", 700, true)
+ if err != nil {
+ t.Fatal(err)
+ }
+ renamed, err := Parse(b)
if err != nil {
t.Fatalf("the renamed font does not parse: %v", err)
}
diff --git a/internal/slidestest/deckfonts_test.go b/internal/slidestest/deckfonts_test.go
index 89a78cd..5226678 100644
--- a/internal/slidestest/deckfonts_test.go
+++ b/internal/slidestest/deckfonts_test.go
@@ -352,7 +352,10 @@ func TestAnOddFamilyNameStillLoads(t *testing.T) {
t.Fatal(err)
}
const name = "Oddity Sans™ 2"
- odd := f.Renamed(name, 400, false)
+ odd, err := f.Renamed(name, 400, false)
+ if err != nil {
+ t.Fatal(err)
+ }
// With nothing in the library, Deck settings has the link alone.
bare := html.UnescapeString(mustGet(t, a, "/d/"+apiDeck(t, a, token, "Bare")+"/edit", http.StatusOK, cookies).Body.String())
diff --git a/internal/slidestest/fonts_browser_test.go b/internal/slidestest/fonts_browser_test.go
index eb4bb06..7e127bb 100644
--- a/internal/slidestest/fonts_browser_test.go
+++ b/internal/slidestest/fonts_browser_test.go
@@ -1811,7 +1811,10 @@ func uploadFamily(t *testing.T, fr *fontRig, file, name string) (css, ref string
if err != nil {
t.Fatal(err)
}
- data := f.Renamed(name, 400, false)
+ data, err := f.Renamed(name, 400, false)
+ if err != nil {
+ t.Fatal(err)
+ }
if rec := uploadFonts(t, fr.app, fr.cookies, upFile{"f.ttf", data}); rec.Code != http.StatusOK {
t.Fatalf("upload: %d\n%s", rec.Code, rec.Body)
}
diff --git a/internal/slidestest/library_test.go b/internal/slidestest/library_test.go
index 0df1cb9..c832140 100644
--- a/internal/slidestest/library_test.go
+++ b/internal/slidestest/library_test.go
@@ -553,7 +553,10 @@ func TestAnUploadedFamilyNeverTakesAReservedName(t *testing.T) {
t.Fatal(err)
}
for _, name := range []string{"Liberation Serif", "SANS-SERIF", "System-UI", "liberation mono"} {
- data := f.Renamed(name, 400, false)
+ 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)
}