package typeface import ( "bytes" "compress/zlib" "crypto/sha256" "encoding/binary" "encoding/hex" "errors" "net/http/httptest" "os" "sort" "testing" "github.com/andybalholm/brotli" ) // The test font is Liberation Sans Regular (SIL OFL 1.1; the licence is // beside it in testdata). Every other file these tests read is built from // it here: WOFF and WOFF2 copies, and synthetic sfnts with one table // swapped or patched. type table struct { tag string data []byte } func liberation(t *testing.T) []byte { t.Helper() b, err := os.ReadFile("testdata/LiberationSans-Regular.ttf") if err != nil { t.Fatal(err) } return b } // tablesOf reads an sfnt's version and tables, in directory order. func tablesOf(t *testing.T, sfnt []byte) (uint32, []table) { t.Helper() n := int(binary.BigEndian.Uint16(sfnt[4:])) var ts []table for i := 0; i < n; i++ { rec := sfnt[12+16*i:] off := binary.BigEndian.Uint32(rec[8:]) length := binary.BigEndian.Uint32(rec[12:]) ts = append(ts, table{string(rec[:4]), bytes.Clone(sfnt[off : off+length])}) } return binary.BigEndian.Uint32(sfnt), ts } // buildSFNT writes an sfnt with the tables sorted by tag, each padded to // four bytes. Checksums are left zero: Inspect does not read them. func buildSFNT(version uint32, ts []table) []byte { ts = append([]table(nil), ts...) sort.Slice(ts, func(i, j int) bool { return ts[i].tag < ts[j].tag }) var b []byte b = binary.BigEndian.AppendUint32(b, version) b = binary.BigEndian.AppendUint16(b, uint16(len(ts))) b = append(b, 0, 0, 0, 0, 0, 0) // searchRange and friends: unread off := 12 + 16*len(ts) for _, tb := range ts { b = append(b, tb.tag...) b = binary.BigEndian.AppendUint32(b, 0) b = binary.BigEndian.AppendUint32(b, uint32(off)) b = binary.BigEndian.AppendUint32(b, uint32(len(tb.data))) off += (len(tb.data) + 3) &^ 3 } for _, tb := range ts { b = append(b, tb.data...) for len(b)%4 != 0 { b = append(b, 0) } } return b } func withTable(ts []table, tag string, data []byte) []table { out := withoutTable(ts, tag) return append(out, table{tag, data}) } func withoutTable(ts []table, tags ...string) []table { var out []table for _, tb := range ts { drop := false for _, tag := range tags { drop = drop || tb.tag == tag } if !drop { out = append(out, tb) } } return out } func tableData(ts []table, tag string) []byte { for _, tb := range ts { if tb.tag == tag { return tb.data } } return nil } // patched is Liberation with its OS/2 fsType and fsSelection set. func patched(t *testing.T, fsType, fsSelection uint16) []byte { t.Helper() v, ts := tablesOf(t, liberation(t)) os2 := bytes.Clone(tableData(ts, "OS/2")) binary.BigEndian.PutUint16(os2[8:], fsType) binary.BigEndian.PutUint16(os2[62:], fsSelection) return buildSFNT(v, withTable(ts, "OS/2", os2)) } // 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() return otto(t, "CFF ", cffTable) } type axis struct { tag string min, def, max float64 } func fvar(axes ...axis) []byte { var b []byte b = binary.BigEndian.AppendUint16(b, 1) // majorVersion b = binary.BigEndian.AppendUint16(b, 0) // minorVersion b = binary.BigEndian.AppendUint16(b, 16) // axesArrayOffset b = binary.BigEndian.AppendUint16(b, 2) // reserved b = binary.BigEndian.AppendUint16(b, uint16(len(axes))) b = binary.BigEndian.AppendUint16(b, 20) // axisSize b = binary.BigEndian.AppendUint16(b, 0) // instanceCount b = binary.BigEndian.AppendUint16(b, uint16(4+4*len(axes))) for _, a := range axes { b = append(b, a.tag...) for _, v := range []float64{a.min, a.def, a.max} { b = binary.BigEndian.AppendUint32(b, uint32(int32(v*65536))) } b = binary.BigEndian.AppendUint16(b, 0) // flags b = binary.BigEndian.AppendUint16(b, 256) // axisNameID } return b } func variable(t *testing.T, axes ...axis) []byte { t.Helper() v, ts := tablesOf(t, liberation(t)) return buildSFNT(v, withTable(ts, "fvar", fvar(axes...))) } type nameRec struct { platform, encoding, language, id uint16 value string } // nameTable builds a format 0 name table: platform 1 strings in Mac // Roman (ASCII here, plus é as 0x8E), everything else UTF-16BE. func nameTable(recs ...nameRec) []byte { var storage []byte var b []byte b = binary.BigEndian.AppendUint16(b, 0) b = binary.BigEndian.AppendUint16(b, uint16(len(recs))) b = binary.BigEndian.AppendUint16(b, uint16(6+12*len(recs))) for _, r := range recs { var s []byte if r.platform == 1 { for _, c := range r.value { if c == 'é' { s = append(s, 0x8E) } else { s = append(s, byte(c)) } } } else { for _, c := range r.value { s = binary.BigEndian.AppendUint16(s, uint16(c)) } } for _, v := range []uint16{r.platform, r.encoding, r.language, r.id, uint16(len(s)), uint16(len(storage))} { b = binary.BigEndian.AppendUint16(b, v) } storage = append(storage, s...) } return append(b, storage...) } func named(t *testing.T, recs ...nameRec) []byte { t.Helper() v, ts := tablesOf(t, liberation(t)) return buildSFNT(v, withTable(ts, "name", nameTable(recs...))) } // buildWOFF wraps an sfnt in WOFF 1.0, each table zlib-compressed (or // stored when that is no smaller, as the format requires). func buildWOFF(t *testing.T, sfnt []byte) []byte { t.Helper() flavor, ts := tablesOf(t, sfnt) sort.Slice(ts, func(i, j int) bool { return ts[i].tag < ts[j].tag }) type entry struct { tag string comp []byte origLength int offset int storedLength int } var es []entry off := 44 + 20*len(ts) for _, tb := range ts { var z bytes.Buffer w := zlib.NewWriter(&z) w.Write(tb.data) w.Close() comp := z.Bytes() if len(comp) >= len(tb.data) { comp = tb.data } es = append(es, entry{tb.tag, comp, len(tb.data), off, len(comp)}) off += (len(comp) + 3) &^ 3 } var b []byte b = append(b, "wOFF"...) b = binary.BigEndian.AppendUint32(b, flavor) b = binary.BigEndian.AppendUint32(b, uint32(off)) // length b = binary.BigEndian.AppendUint16(b, uint16(len(ts))) b = binary.BigEndian.AppendUint16(b, 0) b = binary.BigEndian.AppendUint32(b, uint32(len(sfnt))) b = append(b, make([]byte, 4+20)...) // version, metadata, private for _, e := range es { b = append(b, e.tag...) b = binary.BigEndian.AppendUint32(b, uint32(e.offset)) b = binary.BigEndian.AppendUint32(b, uint32(e.storedLength)) b = binary.BigEndian.AppendUint32(b, uint32(e.origLength)) b = binary.BigEndian.AppendUint32(b, 0) } for _, e := range es { b = append(b, e.comp...) for len(b)%4 != 0 { b = append(b, 0) } } return b } var testWOFF2Tags = []string{"cmap", "head", "hhea", "hmtx", "maxp", "name", "OS/2", "post", "cvt ", "fpgm", "glyf", "loca", "prep", "CFF ", "VORG", "EBDT", "EBLC", "gasp", "hdmx", "kern", "LTSH", "PCLT", "VDMX", "vhea", "vmtx", "BASE", "GDEF", "GPOS", "GSUB", "EBSC", "JSTF", "MATH", "CBDT", "CBLC", "COLR", "CPAL", "SVG ", "sbix", "acnt", "avar", "bdat", "bloc", "bsln", "cvar", "fdsc", "feat", "fmtx", "fvar", "gvar", "hsty", "just", "lcar", "mort", "morx", "opbd", "prop", "trak", "Zapf", "Silf", "Glat", "Gloc", "Feat", "Sill"} func encodeBase128(n uint32) []byte { var out []byte for { out = append([]byte{byte(n & 0x7F)}, out...) n >>= 7 if n == 0 { break } } for i := 0; i < len(out)-1; i++ { out[i] |= 0x80 } return out } // woff2Entry is a WOFF2 directory entry as written: lengths may lie, // which is the point of some refusals. type woff2Entry struct { tag string version byte // transform version, the flags' top two bits origLength uint32 transform uint32 // written only when the entry is transformed } func woff2Transformed(e woff2Entry) bool { switch e.tag { case "glyf", "loca": return e.version != 3 default: return e.version != 0 } } func assembleWOFF2(flavor uint32, es []woff2Entry, compressed []byte) []byte { var dir []byte for _, e := range es { idx := 63 for i, tag := range testWOFF2Tags { if tag == e.tag { idx = i } } dir = append(dir, e.version<<6|byte(idx)) if idx == 63 { dir = append(dir, e.tag...) } dir = append(dir, encodeBase128(e.origLength)...) if woff2Transformed(e) { dir = append(dir, encodeBase128(e.transform)...) } } total := 48 + len(dir) + len(compressed) padded := (total + 3) &^ 3 var b []byte b = append(b, "wOF2"...) b = binary.BigEndian.AppendUint32(b, flavor) b = binary.BigEndian.AppendUint32(b, uint32(padded)) b = binary.BigEndian.AppendUint16(b, uint16(len(es))) b = binary.BigEndian.AppendUint16(b, 0) b = binary.BigEndian.AppendUint32(b, 0) // totalSfntSize: unread b = binary.BigEndian.AppendUint32(b, uint32(len(compressed))) b = append(b, make([]byte, 4+20)...) // version, metadata, private b = append(b, dir...) b = append(b, compressed...) return append(b, make([]byte, padded-total)...) } func brotliOf(data []byte) []byte { var z bytes.Buffer w := brotli.NewWriterLevel(&z, 5) w.Write(data) w.Close() return z.Bytes() } // woff2Parts is an sfnt's tables as WOFF2 entries, glyf and loca with // the null transform, and their concatenation (the uncompressed stream). func woff2Parts(t *testing.T, sfnt []byte) (uint32, []woff2Entry, []byte) { t.Helper() flavor, ts := tablesOf(t, sfnt) var es []woff2Entry var stream []byte for _, tb := range ts { e := woff2Entry{tag: tb.tag, origLength: uint32(len(tb.data))} if tb.tag == "glyf" || tb.tag == "loca" { e.version = 3 } es = append(es, e) stream = append(stream, tb.data...) } return flavor, es, stream } func buildWOFF2(t *testing.T, sfnt []byte) []byte { t.Helper() flavor, es, stream := woff2Parts(t, sfnt) return assembleWOFF2(flavor, es, brotliOf(stream)) } func mustInspect(t *testing.T, data []byte) Face { t.Helper() f, err := Inspect(data) if err != nil { t.Fatalf("Inspect: %v", err) } return f } func TestInspectReadsTheNamesAndStyle(t *testing.T) { data := liberation(t) f := mustInspect(t, data) sum := sha256.Sum256(data) want := Face{ Ref: hex.EncodeToString(sum[:]), Format: "ttf", Outline: "truetype", Family: "Liberation Sans", Style: "Regular", Weight: 400, WeightMin: 400, WeightMax: 400, } if f != want { t.Fatalf("Inspect(Liberation Sans)\n got %+v\nwant %+v", f, want) } if f.ContentType() != "font/ttf" { t.Errorf("ContentType = %q", f.ContentType()) } t.Run("italic from fsSelection", func(t *testing.T) { if f := mustInspect(t, patched(t, 0, 0x0001)); !f.Italic { t.Errorf("fsSelection bit 0 set, Italic = false") } }) t.Run("italic from macStyle", func(t *testing.T) { v, ts := tablesOf(t, liberation(t)) head := bytes.Clone(tableData(ts, "head")) binary.BigEndian.PutUint16(head[44:], 0x0002) if f := mustInspect(t, buildSFNT(v, withTable(ts, "head", head))); !f.Italic { t.Errorf("macStyle bit 1 set, Italic = false") } }) t.Run("typographic names win, Windows before Mac", func(t *testing.T) { f := mustInspect(t, named(t, nameRec{1, 0, 0, 1, "Mac Family"}, nameRec{1, 0, 0, 2, "Mac Style"}, nameRec{1, 0, 0, 16, "Mac Typo"}, nameRec{3, 1, 0x0409, 1, "Win Family"}, nameRec{3, 1, 0x0409, 2, "Bold"}, nameRec{3, 1, 0x0409, 16, "Café Sans"}, nameRec{3, 1, 0x0409, 17, "Semibold"}, )) if f.Family != "Café Sans" || f.Style != "Semibold" { t.Errorf("Family, Style = %q, %q; want Café Sans, Semibold", f.Family, f.Style) } }) t.Run("legacy names, Mac Roman when there is nothing else", func(t *testing.T) { f := mustInspect(t, named(t, nameRec{1, 0, 0, 1, "Café Mac"}, nameRec{1, 0, 0, 2, "Italic"}, )) if f.Family != "Café Mac" || f.Style != "Italic" { t.Errorf("Family, Style = %q, %q; want Café Mac, Italic", f.Family, f.Style) } }) } func TestInspectReadsWOFFAndWOFF2(t *testing.T) { ttf := mustInspect(t, liberation(t)) for _, c := range []struct { format Format data []byte ctype string }{ {"woff", buildWOFF(t, liberation(t)), "font/woff"}, {"woff2", buildWOFF2(t, liberation(t)), "font/woff2"}, } { t.Run(string(c.format), func(t *testing.T) { f := mustInspect(t, c.data) sum := sha256.Sum256(c.data) want := ttf want.Ref = hex.EncodeToString(sum[:]) want.Format = c.format if f != want { t.Fatalf("\n got %+v\nwant %+v", f, want) } if f.ContentType() != c.ctype { t.Errorf("ContentType = %q, want %q", f.ContentType(), c.ctype) } }) } t.Run("woff2 of a cff", func(t *testing.T) { f := mustInspect(t, buildWOFF2(t, cff(t))) if f.Format != "woff2" || f.Outline != "cff" { t.Errorf("Format, Outline = %q, %q", f.Format, f.Outline) } }) } func TestInspectReadsCFFAndVariable(t *testing.T) { f := mustInspect(t, cff(t)) if f.Format != "otf" || f.Outline != "cff" || f.Family != "Liberation Sans" || f.ContentType() != "font/otf" { t.Errorf("CFF: %+v (content type %q)", f, f.ContentType()) } v := mustInspect(t, variable(t, axis{"wdth", 75, 100, 100}, axis{"wght", 100, 400, 900})) if !v.Variable || v.Weight != 400 || v.WeightMin != 100 || v.WeightMax != 900 { t.Errorf("variable: Variable %v, Weight %d, range %d..%d; want true, 400, 100..900", v.Variable, v.Weight, v.WeightMin, v.WeightMax) } w := mustInspect(t, buildWOFF2(t, variable(t, axis{"wght", 100, 400, 900}))) if !w.Variable || w.WeightMin != 100 || w.WeightMax != 900 { t.Errorf("variable woff2: %+v", w) } s := mustInspect(t, variable(t, axis{"wdth", 75, 100, 100})) if !s.Variable || s.WeightMin != 400 || s.WeightMax != 400 { t.Errorf("fvar with no wght axis: %+v; want variable, weight range 400..400", s) } } func TestPicturesOnlyForStaticTrueTypeThatMayEmbed(t *testing.T) { for _, c := range []struct { name string data []byte want bool }{ {"ttf, installable", liberation(t), true}, {"preview and print", patched(t, 0x0004, 0), true}, {"editable", patched(t, 0x0008, 0), true}, {"editable, no subsetting", patched(t, 0x0108, 0), false}, {"installable, no subsetting", patched(t, 0x0100, 0), false}, {"restricted licence", patched(t, 0x0002, 0), false}, {"restricted with preview and print", patched(t, 0x0006, 0), false}, {"bitmap embedding only", patched(t, 0x0200, 0), false}, {"cff", cff(t), false}, {"variable", variable(t, axis{"wght", 100, 400, 900}), false}, {"variable in width only", variable(t, axis{"wdth", 75, 100, 100}), false}, {"woff", buildWOFF(t, liberation(t)), false}, {"woff2", buildWOFF2(t, liberation(t)), false}, } { f := mustInspect(t, c.data) if got := f.Pictures(); got != c.want { t.Errorf("%s: Pictures() = %v, want %v (%+v)", c.name, got, c.want, f) } } if f := mustInspect(t, patched(t, 0x0002, 0)); f.FSType != 0x0002 { t.Errorf("FSType = %#x, want 0x2", f.FSType) } } func TestHeaders(t *testing.T) { for format, ctype := range map[Format]string{"ttf": "font/ttf", "otf": "font/otf", "woff": "font/woff", "woff2": "font/woff2"} { w := httptest.NewRecorder() Headers(w, format) h := w.Header() for k, v := range map[string]string{ "Content-Type": ctype, "X-Content-Type-Options": "nosniff", "Cache-Control": "private, max-age=31536000, immutable", "Content-Security-Policy": "default-src 'none'", } { if h.Get(k) != v { t.Errorf("Headers(%s): %s = %q, want %q", format, k, h.Get(k), v) } } } } func TestInspectRefuses(t *testing.T) { ttf := liberation(t) truncatedDir := ttf[:12+16*3] pastEnd := bytes.Clone(ttf) binary.BigEndian.PutUint32(pastEnd[12+16*4+12:], uint32(len(ttf))) // the fifth table's length tooBig := make([]byte, MaxBytes+1) copy(tooBig, ttf) flavor, es, stream := woff2Parts(t, ttf) good := brotliOf(stream) badStream := bytes.Clone(good) for i := 8; i < len(badStream) && i < 64; i++ { badStream[i] ^= 0xA5 } shortStream := assembleWOFF2(flavor, es, good[:len(good)/2]) longer := append([]woff2Entry(nil), es...) longer[0].origLength += 4096 // claims more than the stream holds extra := append([]woff2Entry(nil), es...) extra[0].origLength -= 4 // the stream holds more than the tables claim bomb := append([]woff2Entry(nil), es...) bomb[0].origLength = 4*MaxBytes + 1 transformedName := append([]woff2Entry(nil), es...) for i := range transformedName { if transformedName[i].tag == "name" { transformedName[i].version = 1 transformedName[i].transform = transformedName[i].origLength } } woff := buildWOFF(t, ttf) badZlib := bytes.Clone(woff) { // Corrupt the name table's compressed bytes. n := int(binary.BigEndian.Uint16(woff[12:])) for i := 0; i < n; i++ { rec := woff[44+20*i:] if string(rec[:4]) == "name" { off := binary.BigEndian.Uint32(rec[4:]) for j := off + 2; j < off+40; j++ { badZlib[j] ^= 0xA5 } } } } badGlyf := bytes.Clone(woff) { // Corrupt the glyf table's compressed bytes: a table Inspect // does not otherwise read. n := int(binary.BigEndian.Uint16(woff[12:])) for i := 0; i < n; i++ { rec := woff[44+20*i:] if string(rec[:4]) == "glyf" { off := binary.BigEndian.Uint32(rec[4:]) for j := off + 2; j < off+40; j++ { badGlyf[j] ^= 0xA5 } } } } v, ts := tablesOf(t, ttf) shortFvar := fvar(axis{"wght", 100, 400, 900}) binary.BigEndian.PutUint16(shortFvar[8:], 40) // 40 axes, room for one pngHeader := []byte("\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x06\x00\x00\x00") for _, c := range []struct { name string data []byte want error }{ {"empty", nil, ErrNotAFont}, {"a PNG", pngHeader, ErrNotAFont}, {"a font collection", append([]byte("ttcf"), ttf[4:]...), ErrNotAFont}, {"a truncated table directory", truncatedDir, ErrMalformed}, {"a table past the end", pastEnd, ErrMalformed}, {"no tables", append(bytes.Clone(ttf[:4]), make([]byte, 8)...), ErrMalformed}, {"over MaxBytes", tooBig, ErrTooBig}, {"no OS/2", buildSFNT(v, withoutTable(ts, "OS/2")), ErrMalformed}, {"no name", buildSFNT(v, withoutTable(ts, "name")), ErrMalformed}, {"no family name", named(t, nameRec{3, 1, 0x409, 2, "Regular"}), ErrMalformed}, {"no outlines", buildSFNT(v, withoutTable(ts, "glyf", "loca")), ErrMalformed}, {"a TrueType without glyf", buildSFNT(v, withoutTable(ts, "glyf")), ErrMalformed}, {"a TrueType without loca", buildSFNT(v, withoutTable(ts, "loca")), ErrMalformed}, {"an OTTO without CFF", buildSFNT(0x4F54544F, withoutTable(ts, "glyf", "loca")), ErrMalformed}, {"an OTTO with glyf but no CFF", buildSFNT(0x4F54544F, ts), ErrMalformed}, {"an fvar shorter than its axes", buildSFNT(v, withTable(ts, "fvar", shortFvar)), ErrMalformed}, {"a truncated WOFF", woff[:len(woff)/2], ErrMalformed}, {"a WOFF whose zlib is bad", badZlib, ErrMalformed}, {"a WOFF whose glyf stream is corrupt", badGlyf, ErrMalformed}, {"a WOFF2 whose brotli stream is bad", assembleWOFF2(flavor, es, badStream), ErrMalformed}, {"a WOFF2 whose brotli stream is cut short", shortStream, ErrMalformed}, {"a WOFF2 table past the stream", assembleWOFF2(flavor, longer, good), ErrMalformed}, {"a WOFF2 stream longer than its tables", assembleWOFF2(flavor, extra, good), ErrMalformed}, {"a WOFF2 that unpacks too big", assembleWOFF2(flavor, bomb, good), ErrTooBig}, {"a WOFF2 with a transformed name table", assembleWOFF2(flavor, transformedName, good), ErrMalformed}, } { t.Run(c.name, func(t *testing.T) { f, err := Inspect(c.data) if !errors.Is(err, c.want) { t.Fatalf("Inspect = %+v, %v; want %v", f, err, c.want) } t.Log(err) }) } }