oficina / estilo Public

typeface: check TrueType and CFF outline structure before keeping

Outline-table presence alone passed as validation, so an empty glyf,
a loca that ran backwards or past glyf, or a CFF stub was kept and
served (final review, I1). Inspect now checks what is cheap: loca
climbs inside glyf, each glyph holds its header, maxp's count agrees
with loca and hmtx; CFF and CFF2 headers and top-level INDEXes parse
inside the table with one CharStrings per glyph. WOFF2's transformed
glyf, loca and hmtx are not rebuilt and so not checked here. The CFF
test fixture is now a genuine CFF, not a four-byte stub.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 1b49fcfbe3f634de492520d047a9015f68fd570e parent 0b81861
5 files changed, +610 −24
  • typeface/outlines.go +313 −0
  • typeface/outlines_test.go +267 −0
  • typeface/typeface.go +16 −10
  • typeface/typeface_test.go +3 −6
  • typeface/woff.go +11 −8

CI passed — run details

CI log
=== modcache ===
all modules verified
=== vet ===
CGO_ENABLED=0 go vet ./...
go: downloading github.com/andybalholm/brotli v1.2.7
CGO_ENABLED=0 go vet -tags browser ./...
=== fmt ===
=== build ===
CGO_ENABLED=0 go build -buildvcs=false ./...
=== go-test ===
CGO_ENABLED=0 go test -count=1 ./...
ok  	amadan.net/oficina/estilo.git/base	0.006s
ok  	amadan.net/oficina/estilo.git/brand	0.003s
ok  	amadan.net/oficina/estilo.git/busy	0.009s
ok  	amadan.net/oficina/estilo.git/callui	0.004s
ok  	amadan.net/oficina/estilo.git/chrome	1.061s
?   	amadan.net/oficina/estilo.git/cmd/oficina-notices	[no test files]
ok  	amadan.net/oficina/estilo.git/colophon	0.024s
ok  	amadan.net/oficina/estilo.git/credits	0.005s
ok  	amadan.net/oficina/estilo.git/credits/catalog	0.005s
ok  	amadan.net/oficina/estilo.git/desk	0.004s
ok  	amadan.net/oficina/estilo.git/googleimport	0.169s
ok  	amadan.net/oficina/estilo.git/homeconnect	0.005s
ok  	amadan.net/oficina/estilo.git/internal/lint	0.006s
?   	amadan.net/oficina/estilo.git/internal/tokencheck	[no test files]
ok  	amadan.net/oficina/estilo.git/menu	0.010s
ok  	amadan.net/oficina/estilo.git/savestatus	0.105s
ok  	amadan.net/oficina/estilo.git/side	0.130s
ok  	amadan.net/oficina/estilo.git/sky	0.038s
ok  	amadan.net/oficina/estilo.git/theme	0.013s
ok  	amadan.net/oficina/estilo.git/typeface	0.319s
=== spacing ===
go run amadan.net/rastrillo/fiesta/cmd/fiesta@v1.7.0 spacing .
diff --git a/typeface/outlines.go b/typeface/outlines.go
new file mode 100644
index 0000000..6668e3d
--- /dev/null
+++ b/typeface/outlines.go
@@ -0,0 +1,313 @@
+package typeface
+
+import "encoding/binary"
+
+// Outline checks: what Inspect can check about a face's glyphs cheaply,
+// before the file is kept. They read structure only, never a glyph's
+// instructions or charstrings: a TrueType face's loca must climb inside
+// glyf, each glyph must hold at least its header, and maxp's glyph count
+// must agree with loca and hmtx; a CFF or CFF2 table's header and
+// top-level INDEXes must parse inside the table, with as many
+// CharStrings as maxp has glyphs. Anything deeper is left to the
+// browser's own font sanitiser and to the app's parser when it draws.
+//
+// A WOFF2's transformed glyf, loca and hmtx are not rebuilt, so they are
+// not checked here.
+
+// checkOutlines runs the checks for the face's outline kind.
+func checkOutlines(ft fontTables, outline Outline) error {
+ maxp := ft.data["maxp"]
+ if len(maxp) < 6 {
+ return malformed("no maxp table")
+ }
+ n := int(binary.BigEndian.Uint16(maxp[4:]))
+ if n == 0 {
+ return malformed("maxp counts no glyphs")
+ }
+ if outline == CFF {
+ if b, ok := ft.data["CFF2"]; ok {
+ return checkCFF2(b, n)
+ }
+ return checkCFF(ft.data["CFF "], n)
+ }
+ if err := checkMetrics(ft, n); err != nil {
+ return err
+ }
+ return checkGlyf(ft, n)
+}
+
+// checkMetrics checks hhea's numberOfHMetrics against maxp and hmtx.
+func checkMetrics(ft fontTables, n int) error {
+ hhea := ft.data["hhea"]
+ if len(hhea) < 36 {
+ return malformed("no hhea table")
+ }
+ m := int(binary.BigEndian.Uint16(hhea[34:]))
+ if m == 0 || m > n {
+ return malformed("%d horizontal metrics for %d glyphs", m, n)
+ }
+ if ft.transformed["hmtx"] {
+ return nil
+ }
+ if need := 4*m + 2*(n-m); len(ft.data["hmtx"]) < need {
+ return malformed("hmtx holds %d bytes, its metrics need %d", len(ft.data["hmtx"]), need)
+ }
+ return nil
+}
+
+// checkGlyf checks loca against glyf and maxp.
+func checkGlyf(ft fontTables, n int) error {
+ if ft.transformed["glyf"] {
+ return nil
+ }
+ head := ft.data["head"] // describe has checked its length
+ size := 0
+ switch int16(binary.BigEndian.Uint16(head[50:])) {
+ case 0:
+ size = 2
+ case 1:
+ size = 4
+ default:
+ return malformed("indexToLocFormat is neither short nor long")
+ }
+ loca, glyf := ft.data["loca"], ft.data["glyf"]
+ if len(loca) < size*(n+1) {
+ return malformed("loca holds %d bytes, %d glyphs need %d", len(loca), n, size*(n+1))
+ }
+ at := func(i int) uint64 {
+ if size == 2 {
+ return 2 * uint64(binary.BigEndian.Uint16(loca[2*i:]))
+ }
+ return uint64(binary.BigEndian.Uint32(loca[4*i:]))
+ }
+ prev := at(0)
+ for i := 1; i <= n; i++ {
+ next := at(i)
+ if next < prev {
+ return malformed("loca goes backwards at glyph %d", i-1)
+ }
+ if next > uint64(len(glyf)) {
+ return malformed("glyph %d runs past glyf", i-1)
+ }
+ // A glyph with any bytes has at least its 10-byte header.
+ if l := next - prev; l != 0 && l < 10 {
+ return malformed("glyph %d is %d bytes, shorter than its header", i-1, l)
+ }
+ prev = next
+ }
+ return nil
+}
+
+// cffIndex is a CFF INDEX that readIndex has checked.
+type cffIndex struct {
+ b []byte
+ count, offSize int
+ offsets, data int // where the offset array and the data begin
+ end int // the first byte after the INDEX
+}
+
+// off is the INDEX's offset i (1-based, as stored).
+func (x cffIndex) off(i int) int {
+ v := 0
+ for _, c := range x.b[x.offsets+i*x.offSize : x.offsets+(i+1)*x.offSize] {
+ v = v<<8 | int(c)
+ }
+ return v
+}
+
+// item is the INDEX's item i.
+func (x cffIndex) item(i int) []byte {
+ return x.b[x.data+x.off(i)-1 : x.data+x.off(i+1)-1]
+}
+
+// readIndex reads the INDEX at b[at:]. countSize is 2 in CFF and 4 in
+// CFF2. Offsets must start at 1 and never go back, and the data must lie
+// inside b.
+func readIndex(b []byte, at, countSize int) (cffIndex, error) {
+ x := cffIndex{b: b}
+ if at < 0 || at+countSize > len(b) {
+ return x, malformed("CFF INDEX past the table")
+ }
+ if countSize == 4 {
+ c := binary.BigEndian.Uint32(b[at:])
+ if c > uint32(len(b)) {
+ return x, malformed("CFF INDEX of %d items in a %d-byte table", c, len(b))
+ }
+ x.count = int(c)
+ } else {
+ x.count = int(binary.BigEndian.Uint16(b[at:]))
+ }
+ at += countSize
+ if x.count == 0 {
+ x.end = at
+ return x, nil
+ }
+ if at >= len(b) {
+ return x, malformed("CFF INDEX cut short")
+ }
+ x.offSize, x.offsets = int(b[at]), at+1
+ if x.offSize < 1 || x.offSize > 4 {
+ return x, malformed("CFF INDEX offSize %d", x.offSize)
+ }
+ if (x.count+1)*x.offSize > len(b)-x.offsets {
+ return x, malformed("CFF INDEX offsets past the table")
+ }
+ if x.off(0) != 1 {
+ return x, malformed("CFF INDEX's first offset is not 1")
+ }
+ prev := 1
+ for i := 1; i <= x.count; i++ {
+ o := x.off(i)
+ if o < prev {
+ return x, malformed("CFF INDEX offsets go back")
+ }
+ prev = o
+ }
+ x.data = x.offsets + (x.count+1)*x.offSize
+ if prev-1 > len(b)-x.data {
+ return x, malformed("CFF INDEX data past the table")
+ }
+ x.end = x.data + prev - 1
+ return x, nil
+}
+
+// charStringsAt reads a Top DICT and returns its CharStrings offset (the
+// operand before operator 17), or -1 when it names none.
+func charStringsAt(dict []byte) (int, error) {
+ var last int64
+ have, at := false, -1
+ for i := 0; i < len(dict); {
+ b := dict[i]
+ switch {
+ case b == 28:
+ if i+3 > len(dict) {
+ return 0, malformed("CFF DICT cut short")
+ }
+ last, have = int64(int16(binary.BigEndian.Uint16(dict[i+1:]))), true
+ i += 3
+ case b == 29:
+ if i+5 > len(dict) {
+ return 0, malformed("CFF DICT cut short")
+ }
+ last, have = int64(int32(binary.BigEndian.Uint32(dict[i+1:]))), true
+ i += 5
+ case b == 30: // a real: nibbles to an 0xf
+ i++
+ for {
+ if i >= len(dict) {
+ return 0, malformed("CFF DICT real cut short")
+ }
+ c := dict[i]
+ i++
+ if c&0x0f == 0x0f || c>>4 == 0x0f {
+ break
+ }
+ }
+ have = false
+ case b >= 32 && b <= 246:
+ last, have = int64(b)-139, true
+ i++
+ case b >= 247 && b <= 254:
+ if i+2 > len(dict) {
+ return 0, malformed("CFF DICT cut short")
+ }
+ w := int64(b)
+ if b <= 250 {
+ last = (w-247)*256 + int64(dict[i+1]) + 108
+ } else {
+ last = -(w-251)*256 - int64(dict[i+1]) - 108
+ }
+ have = true
+ i += 2
+ case b == 12: // two-byte operator
+ i += 2
+ have = false
+ case b <= 27:
+ if b == 17 {
+ if !have || last < 0 {
+ return 0, malformed("CFF CharStrings with no offset")
+ }
+ at = int(last)
+ }
+ i++
+ have = false
+ default:
+ return 0, malformed("CFF DICT byte %d is reserved", b)
+ }
+ }
+ return at, nil
+}
+
+// checkCharStrings checks the CharStrings INDEX at b[at:] holds n glyphs.
+func checkCharStrings(b []byte, at, countSize, n int) error {
+ if at < 0 {
+ return malformed("CFF names no CharStrings")
+ }
+ x, err := readIndex(b, at, countSize)
+ if err != nil {
+ return err
+ }
+ if x.count != n {
+ return malformed("%d CharStrings for %d glyphs", x.count, n)
+ }
+ return nil
+}
+
+// checkCFF checks a CFF table: header, Name, Top DICT, String and Global
+// Subr INDEXes, and the CharStrings INDEX the one Top DICT names.
+func checkCFF(b []byte, n int) error {
+ if len(b) < 4 || b[0] != 1 {
+ return malformed("CFF header is not one")
+ }
+ hdrSize := int(b[2])
+ if hdrSize < 4 || hdrSize > len(b) || b[3] < 1 || b[3] > 4 {
+ return malformed("CFF header is not one")
+ }
+ names, err := readIndex(b, hdrSize, 2)
+ if err != nil {
+ return err
+ }
+ if names.count != 1 {
+ return malformed("CFF with %d fonts", names.count)
+ }
+ top, err := readIndex(b, names.end, 2)
+ if err != nil {
+ return err
+ }
+ if top.count != 1 {
+ return malformed("CFF with %d Top DICTs", top.count)
+ }
+ strs, err := readIndex(b, top.end, 2)
+ if err != nil {
+ return err
+ }
+ if _, err := readIndex(b, strs.end, 2); err != nil { // Global Subrs
+ return err
+ }
+ cs, err := charStringsAt(top.item(0))
+ if err != nil {
+ return err
+ }
+ return checkCharStrings(b, cs, 2, n)
+}
+
+// checkCFF2 checks a CFF2 table: header, Top DICT, Global Subr INDEX,
+// and the CharStrings INDEX the Top DICT names.
+func checkCFF2(b []byte, n int) error {
+ if len(b) < 5 || b[0] != 2 {
+ return malformed("CFF2 header is not one")
+ }
+ hdrSize := int(b[2])
+ topLen := int(binary.BigEndian.Uint16(b[3:]))
+ if hdrSize < 5 || hdrSize+topLen > len(b) {
+ return malformed("CFF2 header is not one")
+ }
+ if _, err := readIndex(b, hdrSize+topLen, 4); err != nil { // Global Subrs
+ return err
+ }
+ cs, err := charStringsAt(b[hdrSize : hdrSize+topLen])
+ if err != nil {
+ return err
+ }
+ return checkCharStrings(b, cs, 4, n)
+}
diff --git a/typeface/outlines_test.go b/typeface/outlines_test.go
new file mode 100644
index 0000000..8afd9e4
--- /dev/null
+++ b/typeface/outlines_test.go
@@ -0,0 +1,267 @@
+package typeface
+
+import (
+ "bytes"
+ "encoding/binary"
+ "errors"
+ "testing"
+)
+
+// Outlines are checked before a file is kept, as far as it is cheap to:
+// for TrueType, that loca's offsets climb and stay inside glyf, that each
+// glyph holds at least its header, and that maxp's glyph count agrees
+// with loca and hmtx; for CFF and CFF2, that the header and the top-level
+// INDEXes parse inside the table and the CharStrings count is maxp's.
+// Outline-table presence alone was taken as validation before (final
+// review, I1). A WOFF2's transformed glyf and loca are not rebuilt, so
+// they are not checked here; the browser's own sanitiser still is.
+
+// buildIndex is a CFF INDEX of items: a count of countSize bytes (2 in
+// CFF, 4 in CFF2), then 4-byte offsets and the data.
+func buildIndex(countSize int, items ...[]byte) []byte {
+ var b []byte
+ if countSize == 4 {
+ b = binary.BigEndian.AppendUint32(b, uint32(len(items)))
+ } else {
+ b = binary.BigEndian.AppendUint16(b, uint16(len(items)))
+ }
+ if len(items) == 0 {
+ return b
+ }
+ b = append(b, 4)
+ off := uint32(1)
+ b = binary.BigEndian.AppendUint32(b, off)
+ for _, it := range items {
+ off += uint32(len(it))
+ b = binary.BigEndian.AppendUint32(b, off)
+ }
+ for _, it := range items {
+ b = append(b, it...)
+ }
+ return b
+}
+
+// charStrings is n glyphs, each a lone endchar.
+func charStrings(n int) [][]byte {
+ out := make([][]byte, n)
+ for i := range out {
+ out[i] = []byte{14}
+ }
+ return out
+}
+
+// dictInt is a DICT operand in its five-byte form, so a DICT's length
+// does not depend on the numbers in it.
+func dictInt(v int32) []byte {
+ return binary.BigEndian.AppendUint32([]byte{29}, uint32(v))
+}
+
+// cffTable is a CFF table with one font of n glyphs: header, Name INDEX,
+// Top DICT INDEX (CharStrings only), empty String and Global Subr
+// INDEXes, then the CharStrings INDEX.
+func cffTable(n int) []byte {
+ header := []byte{1, 0, 4, 4}
+ name := buildIndex(2, []byte("Test"))
+ empty := buildIndex(2)
+ // The Top DICT INDEX's size is fixed (one item of 6 bytes), so the
+ // CharStrings offset can be worked out before it is written.
+ topLen := len(buildIndex(2, make([]byte, 6)))
+ at := len(header) + len(name) + topLen + 2*len(empty)
+ top := buildIndex(2, append(dictInt(int32(at)), 17))
+ b := append(append(append(header, name...), top...), empty...)
+ b = append(b, empty...)
+ return append(b, buildIndex(2, charStrings(n)...)...)
+}
+
+// cff2Table is a CFF2 table of n glyphs: header, Top DICT (CharStrings
+// only), an empty Global Subr INDEX, then the CharStrings INDEX.
+func cff2Table(n int) []byte {
+ const headerSize, topLen = 5, 6
+ at := headerSize + topLen + 4
+ top := append(dictInt(int32(at)), 17)
+ b := []byte{2, 0, headerSize}
+ b = binary.BigEndian.AppendUint16(b, topLen)
+ b = append(b, top...)
+ b = append(b, buildIndex(4)...)
+ return append(b, buildIndex(4, charStrings(n)...)...)
+}
+
+// numGlyphs is maxp's glyph count in tables ts.
+func numGlyphs(ts []table) int {
+ return int(binary.BigEndian.Uint16(tableData(ts, "maxp")[4:]))
+}
+
+// otto is Liberation's other tables in an OTTO, with outlines cffTag
+// built by make for Liberation's glyph count, where glyf and loca were.
+func otto(t *testing.T, cffTag string, make func(n int) []byte) []byte {
+ t.Helper()
+ _, ts := tablesOf(t, liberation(t))
+ ts = withoutTable(ts, "glyf", "loca")
+ return buildSFNT(sigOTTO, append(ts, table{cffTag, make(numGlyphs(ts))}))
+}
+
+// liberationWith is Liberation with table tag changed by edit.
+func liberationWith(t *testing.T, tag string, edit func(b []byte) []byte) []byte {
+ t.Helper()
+ v, ts := tablesOf(t, liberation(t))
+ return buildSFNT(v, withTable(ts, tag, edit(bytes.Clone(tableData(ts, tag)))))
+}
+
+// locaAt and setLoca read and write Liberation's long-format loca.
+func locaAt(b []byte, i int) uint32 { return binary.BigEndian.Uint32(b[4*i:]) }
+func setLoca(b []byte, i int, v uint32) { binary.BigEndian.PutUint32(b[4*i:], v) }
+
+// someGlyph is the first glyph after .notdef longer than n bytes.
+func someGlyph(t *testing.T, loca []byte, n uint32) int {
+ t.Helper()
+ for i := 1; 4*(i+2) <= len(loca); i++ {
+ if locaAt(loca, i+1)-locaAt(loca, i) > n {
+ return i
+ }
+ }
+ t.Fatal("no glyph long enough")
+ return 0
+}
+
+func TestInspectReadsGenuineCFFAndCFF2(t *testing.T) {
+ for _, c := range []struct {
+ name string
+ data []byte
+ }{
+ {"cff", otto(t, "CFF ", cffTable)},
+ {"cff2", otto(t, "CFF2", cff2Table)},
+ {"woff of a cff", buildWOFF(t, otto(t, "CFF ", cffTable))},
+ {"woff2 of a cff2", buildWOFF2(t, otto(t, "CFF2", cff2Table))},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ if f := mustInspect(t, c.data); f.Outline != CFF {
+ t.Errorf("Outline = %q", f.Outline)
+ }
+ })
+ }
+}
+
+// A WOFF2's transformed glyf and loca are not rebuilt, so their bytes are
+// not checked: the file is taken on its other tables.
+func TestInspectTakesATransformedWOFF2Glyf(t *testing.T) {
+ flavor, es, _ := woff2Parts(t, liberation(t))
+ var stream []byte
+ _, ts := tablesOf(t, liberation(t))
+ for i := range es {
+ switch es[i].tag {
+ case "glyf":
+ es[i].version, es[i].transform = 0, 64
+ stream = append(stream, make([]byte, 64)...)
+ case "loca":
+ es[i].version, es[i].transform = 0, 0
+ default:
+ stream = append(stream, tableData(ts, es[i].tag)...)
+ }
+ }
+ mustInspect(t, assembleWOFF2(flavor, es, brotliOf(stream)))
+}
+
+func TestInspectRefusesBrokenOutlines(t *testing.T) {
+ _, ts := tablesOf(t, liberation(t))
+ loca := tableData(ts, "loca")
+ glyfLen := uint32(len(tableData(ts, "glyf")))
+ g := someGlyph(t, loca, 16)
+
+ backwards := liberationWith(t, "loca", func(b []byte) []byte {
+ setLoca(b, g+1, locaAt(b, g)-2)
+ return b
+ })
+ pastGlyf := liberationWith(t, "loca", func(b []byte) []byte {
+ setLoca(b, len(b)/4-1, glyfLen+4)
+ return b
+ })
+ shortGlyph := liberationWith(t, "loca", func(b []byte) []byte {
+ setLoca(b, g+1, locaAt(b, g)+4)
+ return b
+ })
+ moreGlyphs := liberationWith(t, "maxp", func(b []byte) []byte {
+ binary.BigEndian.PutUint16(b[4:], uint16(numGlyphs(ts)+10))
+ return b
+ })
+ badLocFormat := liberationWith(t, "head", func(b []byte) []byte {
+ binary.BigEndian.PutUint16(b[50:], 2)
+ return b
+ })
+ shortHmtx := liberationWith(t, "hmtx", func(b []byte) []byte { return b[:100] })
+ noMetrics := liberationWith(t, "hhea", func(b []byte) []byte {
+ binary.BigEndian.PutUint16(b[34:], 0)
+ return b
+ })
+ tooManyMetrics := liberationWith(t, "hhea", func(b []byte) []byte {
+ binary.BigEndian.PutUint16(b[34:], uint16(numGlyphs(ts)+1))
+ return b
+ })
+ v, _ := tablesOf(t, liberation(t))
+ empty := buildSFNT(v, withTable(withTable(ts, "glyf", nil), "loca", nil))
+ noMaxp := buildSFNT(v, withoutTable(ts, "maxp"))
+
+ cffWith := func(edit func(b []byte) []byte) []byte {
+ return otto(t, "CFF ", func(n int) []byte { return edit(cffTable(n)) })
+ }
+ stub := cffWith(func([]byte) []byte { return []byte{1, 0, 4, 1} })
+ fewerCharStrings := otto(t, "CFF ", func(n int) []byte { return cffTable(n - 1) })
+ cffCutShort := cffWith(func(b []byte) []byte { return b[:len(b)-1] })
+ cffBadVersion := cffWith(func(b []byte) []byte { b[0] = 3; return b })
+ cffTwoNames := cffWith(func(b []byte) []byte {
+ binary.BigEndian.PutUint16(b[4:], 2) // the Name INDEX's count
+ return b
+ })
+ cffOffsetsBack := cffWith(func(b []byte) []byte {
+ // The Name INDEX's second offset, before its first.
+ binary.BigEndian.PutUint32(b[4+2+1+4:], 0)
+ return b
+ })
+ cffNoCharStrings := cffWith(func(b []byte) []byte {
+ // The Top DICT's operator, 17, made a different one (15,
+ // charset), so the DICT names no CharStrings.
+ i := bytes.Index(b, []byte{17, 0, 0})
+ if i < 0 {
+ t.Fatal("no CharStrings operator")
+ }
+ b[i] = 15
+ return b
+ })
+ cff2CutShort := otto(t, "CFF2", func(n int) []byte { return cff2Table(n)[:12] })
+ cff2Fewer := otto(t, "CFF2", func(n int) []byte { return cff2Table(n - 1) })
+
+ for _, c := range []struct {
+ name string
+ data []byte
+ }{
+ {"loca going backwards", backwards},
+ {"loca past the end of glyf", pastGlyf},
+ {"a glyph shorter than its header", shortGlyph},
+ {"maxp counting more glyphs than loca holds", moreGlyphs},
+ {"an indexToLocFormat that is neither", badLocFormat},
+ {"hmtx shorter than its metrics", shortHmtx},
+ {"no horizontal metrics", noMetrics},
+ {"more metrics than glyphs", tooManyMetrics},
+ {"an empty glyf and loca", empty},
+ {"no maxp", noMaxp},
+ {"a WOFF of a backwards loca", buildWOFF(t, backwards)},
+ {"a WOFF2 of a loca past glyf", buildWOFF2(t, pastGlyf)},
+ {"a stub CFF", stub},
+ {"a CFF with fewer CharStrings than glyphs", fewerCharStrings},
+ {"a CFF cut short", cffCutShort},
+ {"a CFF of an unknown version", cffBadVersion},
+ {"a CFF with two fonts", cffTwoNames},
+ {"a CFF INDEX whose offsets go back", cffOffsetsBack},
+ {"a CFF with no CharStrings", cffNoCharStrings},
+ {"a CFF2 cut short", cff2CutShort},
+ {"a CFF2 with fewer CharStrings than glyphs", cff2Fewer},
+ {"a WOFF2 of a stub CFF", buildWOFF2(t, stub)},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ f, err := Inspect(c.data)
+ if !errors.Is(err, ErrMalformed) {
+ t.Fatalf("Inspect = %+v, %v; want ErrMalformed", f, err)
+ }
+ t.Log(err)
+ })
+ }
+}
diff --git a/typeface/typeface.go b/typeface/typeface.go
index 34df26c..2b82dde 100644
--- a/typeface/typeface.go
+++ b/typeface/typeface.go
@@ -4,9 +4,10 @@
// SHA-256 ref. It also says whether the app's own layout and PDF engines
// may use the face (Pictures) and sets the headers for serving it.
//
-// It takes TTF, OTF, WOFF and WOFF2 and nothing else. It reads only the
-// table directory and the head, name, OS/2 and fvar tables, bounds-checks
-// every offset against the bytes it has, and believes no length it has not
+// It takes TTF, OTF, WOFF and WOFF2 and nothing else. It reads the table
+// directory, the head, name, OS/2 and fvar tables, and the outline
+// structure (outlines.go); bounds-checks every offset against the bytes
+// it has; refuses tables that overlap; and believes no length it has not
// checked. It has no storage and no routes: the app gives it bytes.
package typeface
@@ -100,15 +101,18 @@ const (
// fontTables is an sfnt after unwrapping: its version, the tags it has,
// and the bytes of the tables Inspect reads.
type fontTables struct {
- version uint32
- has map[string]bool
- data map[string][]byte
+ version uint32
+ has map[string]bool
+ data map[string][]byte
+ transformed map[string]bool // a WOFF2's transformed glyf, loca or hmtx
}
-// wanted are the only tables whose bytes Inspect reads.
+// wanted are the only tables whose bytes Inspect reads: the ones it
+// describes the face from, and the ones checkOutlines reads.
func wanted(tag string) bool {
switch tag {
- case "head", "name", "OS/2", "fvar":
+ case "head", "name", "OS/2", "fvar",
+ "maxp", "hhea", "hmtx", "glyf", "loca", "CFF ", "CFF2":
return true
}
return false
@@ -251,8 +255,7 @@ func disjoint(spans []span, header, size uint64) error {
// describe turns the tables into a Face (all but Ref and Format).
func describe(ft fontTables) (Face, error) {
var f Face
- // Outlines must be there; checking them deeper is left to the
- // browser's sanitiser and to the app's own parser when it uses them.
+ // Outlines must be there, and pass checkOutlines once head is read.
if ft.version == sigOTTO {
if !ft.has["CFF "] && !ft.has["CFF2"] {
return Face{}, malformed("OTTO with no CFF or CFF2 table")
@@ -273,6 +276,9 @@ func describe(ft fontTables) (Face, error) {
return Face{}, malformed("head table is not one")
}
macStyle := binary.BigEndian.Uint16(head[44:])
+ if err := checkOutlines(ft, f.Outline); err != nil {
+ return Face{}, err
+ }
os2, ok := ft.data["OS/2"]
if !ok {
diff --git a/typeface/typeface_test.go b/typeface/typeface_test.go
index 8d338c5..6597deb 100644
--- a/typeface/typeface_test.go
+++ b/typeface/typeface_test.go
@@ -112,14 +112,11 @@ func patched(t *testing.T, fsType, fsSelection uint16) []byte {
return buildSFNT(v, withTable(ts, "OS/2", os2))
}
-// cff is Liberation's metadata tables in an OTTO with a stub CFF table
-// where its glyf and loca were.
+// cff is Liberation's other tables in an OTTO with a CFF table of as
+// many glyphs where its glyf and loca were (outlines_test.go).
func cff(t *testing.T) []byte {
t.Helper()
- _, ts := tablesOf(t, liberation(t))
- ts = withoutTable(ts, "glyf", "loca")
- ts = append(ts, table{"CFF ", []byte{1, 0, 4, 1}})
- return buildSFNT(0x4F54544F, ts)
+ return otto(t, "CFF ", cffTable)
}
type axis struct {
diff --git a/typeface/woff.go b/typeface/woff.go
index 8e5c37f..d141bce 100644
--- a/typeface/woff.go
+++ b/typeface/woff.go
@@ -142,10 +142,10 @@ var woff2Tags = [63]string{
// readWOFF2 reads a WOFF2 file: the table directory, then the one brotli
// stream holding every table end to end. The stream must unpack to
// exactly the tables' total length, and that total may not pass
-// maxUnpacked. The tables Inspect reads are never transformed by a valid
-// encoder; one that says it is transformed is refused, since its bytes
-// are not the table. glyf, loca and hmtx may be transformed: their bytes
-// are only skipped.
+// maxUnpacked. Only glyf, loca and hmtx may be transformed; their
+// transformed bytes are not rebuilt, so the outline checks skip them. Any
+// other table Inspect reads that says it is transformed is refused,
+// since its bytes are not the table.
func readWOFF2(data []byte) (fontTables, error) {
const headerLen = 48
if len(data) < headerLen {
@@ -169,7 +169,7 @@ func readWOFF2(data []byte) (fontTables, error) {
off, size uint64 // in the unpacked stream
}
entries := make([]entry, 0, n)
- has := map[string]bool{}
+ has, transforms := map[string]bool{}, map[string]bool{}
p := data[headerLen:]
var total uint64
for i := 0; i < n; i++ {
@@ -204,7 +204,10 @@ func readWOFF2(data []byte) (fontTables, error) {
return fontTables{}, err
}
p, size = rest, uint64(transformLen)
- if wanted(tag) {
+ switch {
+ case tag == "glyf" || tag == "loca" || tag == "hmtx":
+ transforms[tag] = true // not rebuilt, so not checked
+ case wanted(tag):
return fontTables{}, malformed("table %q is transformed", tag)
}
}
@@ -228,9 +231,9 @@ func readWOFF2(data []byte) (fontTables, error) {
if err != nil {
return fontTables{}, malformed("WOFF2 stream: %v", err)
}
- ft := fontTables{version: flavor, has: has, data: map[string][]byte{}}
+ ft := fontTables{version: flavor, has: has, data: map[string][]byte{}, transformed: transforms}
for _, e := range entries {
- if wanted(e.tag) {
+ if wanted(e.tag) && !transforms[e.tag] {
ft.data[e.tag] = stream[e.off : e.off+e.size]
}
}