| 1 | package slides |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "crypto/sha256" |
| 7 | "encoding/hex" |
| 8 | "errors" |
| 9 | "io" |
| 10 | "os" |
| 11 | "path/filepath" |
| 12 | "regexp" |
| 13 | "sort" |
| 14 | "strings" |
| 15 | "testing" |
| 16 | "time" |
| 17 | |
| 18 | "amadan.net/oficina/slides/internal/slides/deck" |
| 19 | "amadan.net/oficina/slides/internal/slides/fonts/fontstest" |
| 20 | "amadan.net/oficina/slides/internal/slides/layout" |
| 21 | "amadan.net/oficina/slides/internal/slides/svg" |
| 22 | |
| 23 | "amadan.net/rastrillo/rastrillo/blobs" |
| 24 | ) |
| 25 | |
| 26 | // The "uploaded" font here is Liberation Serif (SIL OFL) under another |
| 27 | // CSS name, in a theme set entirely in Liberation Sans: a PDF that |
| 28 | // carries a Liberation Serif subset got it from the upload. |
| 29 | const ( |
| 30 | uploadedCSS = "Test Upload" |
| 31 | uploadedRef = "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc" |
| 32 | ) |
| 33 | |
| 34 | func embeddedFont(t *testing.T, name string) []byte { |
| 35 | t.Helper() |
| 36 | b, err := os.ReadFile(filepath.Join("fonts", "files", name)) |
| 37 | if err != nil { |
| 38 | t.Fatal(err) |
| 39 | } |
| 40 | return b |
| 41 | } |
| 42 | |
| 43 | func uploadedDeck(face deck.FontFace) *deck.Deck { |
| 44 | stack := "'" + uploadedCSS + "', Liberation Sans, sans-serif" |
| 45 | return &deck.Deck{ |
| 46 | Meta: deck.Meta{ |
| 47 | Title: "Uploads", Theme: "ink", Aspect: "16:9", |
| 48 | Fonts: &deck.Fonts{Heading: "Liberation Sans", Body: stack}, |
| 49 | FontFiles: []deck.FontFamily{{Family: "Test Upload family", CSS: uploadedCSS, Faces: []deck.FontFace{face}}}, |
| 50 | }, |
| 51 | Slides: []deck.Slide{{ |
| 52 | ID: "s1", Layout: "flow", Template: "title-body", |
| 53 | Blocks: []deck.Block{ |
| 54 | {ID: "h1", Type: "heading", Region: "heading", |
| 55 | Props: map[string]any{"level": float64(1)}, Text: deck.Text{{{T: "Heading"}}}}, |
| 56 | {ID: "t1", Type: "text", Region: "body", |
| 57 | Text: deck.Text{{{T: "Quietly drawn in the upload"}}}}, |
| 58 | }, |
| 59 | }}, |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | func fontsFrom(files map[string][]byte) func(string) ([]byte, error) { |
| 64 | return func(ref string) ([]byte, error) { |
| 65 | if b, ok := files[ref]; ok { |
| 66 | return b, nil |
| 67 | } |
| 68 | return nil, errors.New("no such font") |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | var serifSubset = regexp.MustCompile(`/BaseFont ?/[A-Z]{6}\+LiberationSerif\b`) |
| 73 | |
| 74 | func exportWith(t *testing.T, d *deck.Deck, load func(string) ([]byte, error)) ([]byte, []layout.Warning) { |
| 75 | t.Helper() |
| 76 | ctx, cancel := context.WithTimeout(context.Background(), time.Minute) |
| 77 | defer cancel() |
| 78 | pdf, warnings, err := Export(ctx, d, exportOpts(t, ExportOptions{Fonts: load})) |
| 79 | if err != nil { |
| 80 | t.Fatalf("Export: %v", err) |
| 81 | } |
| 82 | return pdf, warnings |
| 83 | } |
| 84 | |
| 85 | func TestTheExportEmbedsAnUploadedFace(t *testing.T) { |
| 86 | face := deck.FontFace{Ref: uploadedRef, Format: "ttf", Weight: [2]int{400, 400}, Pictures: true} |
| 87 | d := uploadedDeck(face) |
| 88 | |
| 89 | // Without the bytes the body falls back to Liberation Sans, and |
| 90 | // there is no serif in the PDF: the control for what follows. |
| 91 | pdf, _ := exportWith(t, d, nil) |
| 92 | if serifSubset.Match(pdf) { |
| 93 | t.Fatal("a Liberation Serif subset in a deck that never draws in it") |
| 94 | } |
| 95 | |
| 96 | pdf, warnings := exportWith(t, d, fontsFrom(map[string][]byte{uploadedRef: embeddedFont(t, "LiberationSerif-Regular.ttf")})) |
| 97 | for _, w := range warnings { |
| 98 | if w.Kind == layout.WarnFont { |
| 99 | t.Errorf("a font warning for an uploaded family: %s", w.Detail) |
| 100 | } |
| 101 | } |
| 102 | if !bytes.Contains(pdf, []byte("/FontFile2")) { |
| 103 | t.Error("no embedded TrueType program (/FontFile2)") |
| 104 | } |
| 105 | if !serifSubset.Match(pdf) { |
| 106 | t.Error("the upload's PostScript name (LiberationSerif) is not a /BaseFont: the PDF drew the body in something else") |
| 107 | } |
| 108 | if text := strings.ReplaceAll(pdfText(t, pdf), " ", ""); !strings.Contains(text, "Quietlydrawnintheupload") { |
| 109 | t.Errorf("the body's words are not in the PDF's text: %q", text) |
| 110 | } |
| 111 | } |
| 112 | |
| 113 | func TestAVariableFontFallsBackInPicturesAndPDF(t *testing.T) { |
| 114 | serif := embeddedFont(t, "LiberationSerif-Regular.ttf") |
| 115 | for name, c := range map[string]struct { |
| 116 | face deck.FontFace |
| 117 | data []byte |
| 118 | }{ |
| 119 | "marked": {deck.FontFace{Ref: uploadedRef, Format: "ttf", Weight: [2]int{100, 900}}, serif}, |
| 120 | "marked for pictures by hand": {deck.FontFace{Ref: uploadedRef, Format: "ttf", Weight: [2]int{400, 400}, Pictures: true}, fontstest.WithTable(t, serif, "fvar", make([]byte, 16))}, |
| 121 | } { |
| 122 | t.Run(name, func(t *testing.T) { |
| 123 | d := uploadedDeck(c.face) |
| 124 | load := fontsFrom(map[string][]byte{uploadedRef: c.data}) |
| 125 | |
| 126 | // The picture. |
| 127 | p, warnings, err := layout.New(d, layout.Options{Fonts: load}).Layout(0) |
| 128 | if err != nil { |
| 129 | t.Fatal(err) |
| 130 | } |
| 131 | for _, w := range warnings { |
| 132 | if w.Kind == layout.WarnFont { |
| 133 | t.Errorf("a font warning for an uploaded family: %s", w.Detail) |
| 134 | } |
| 135 | } |
| 136 | if pic := svg.Encode(p, svg.Options{}); bytes.Contains(pic, []byte(uploadedCSS)) { |
| 137 | t.Error("the picture names the variable upload") |
| 138 | } |
| 139 | |
| 140 | // The PDF. |
| 141 | pdf, _ := exportWith(t, d, load) |
| 142 | if serifSubset.Match(pdf) { |
| 143 | t.Error("the PDF embeds the variable upload") |
| 144 | } |
| 145 | if !regexp.MustCompile(`/BaseFont ?/[A-Z]{6}\+LiberationSans\b`).Match(pdf) { |
| 146 | t.Error("the PDF does not draw the body in the fallback") |
| 147 | } |
| 148 | }) |
| 149 | } |
| 150 | } |
| 151 | |
| 152 | // fakeFontStore is a blobs.Store that answers Get for the keys it holds |
| 153 | // and remembers what it was asked for. |
| 154 | type fakeFontStore struct { |
| 155 | held map[string][]byte |
| 156 | asked []string |
| 157 | } |
| 158 | |
| 159 | func (s *fakeFontStore) Put(context.Context, io.Reader, string) (blobs.Ref, error) { |
| 160 | return blobs.Ref{}, errors.New("read only") |
| 161 | } |
| 162 | |
| 163 | func (s *fakeFontStore) Get(_ context.Context, key string) (io.ReadCloser, error) { |
| 164 | s.asked = append(s.asked, key) |
| 165 | b, ok := s.held[key] |
| 166 | if !ok { |
| 167 | return nil, blobs.ErrNotFound |
| 168 | } |
| 169 | return io.NopCloser(bytes.NewReader(b)), nil |
| 170 | } |
| 171 | |
| 172 | func (s *fakeFontStore) Delete(context.Context, string) error { return nil } |
| 173 | |
| 174 | // fontLoaderApp is an app over store with one deck that recorded refs |
| 175 | // (DeckFont rows, as POST /d/{sqid}/fonts writes them); it answers the |
| 176 | // app and the deck's id. |
| 177 | func fontLoaderApp(t *testing.T, store blobs.Store, refs ...string) (*app, int64) { |
| 178 | t.Helper() |
| 179 | a, _, err := newApp(testDB(t), Config{KeymailServers: testKeymailServers, Env: EnvDevelopment, Logger: quietLogger(), Blobs: store}) |
| 180 | if err != nil { |
| 181 | t.Fatalf("newApp: %v", err) |
| 182 | } |
| 183 | t.Cleanup(func() { a.Close() }) |
| 184 | d := Deck{Sqid: "fontloadr2", Title: "Fonts", OwnerID: 1, Rung: "private"} |
| 185 | if err := a.db.G.Create(&d).Error; err != nil { |
| 186 | t.Fatalf("create a deck: %v", err) |
| 187 | } |
| 188 | for _, ref := range refs { |
| 189 | if err := a.db.G.Create(&DeckFont{DeckID: d.ID, Ref: ref}).Error; err != nil { |
| 190 | t.Fatalf("record a deck font: %v", err) |
| 191 | } |
| 192 | } |
| 193 | return a, d.ID |
| 194 | } |
| 195 | |
| 196 | // The loader reads only the faces the deck recorded: a well-formed ref |
| 197 | // another deck recorded, or that only meta.fontFiles names (any member |
| 198 | // can write that over the API), is never asked of the store. |
| 199 | func TestTheFontLoaderReadsOnlyTheDecksOwnFonts(t *testing.T) { |
| 200 | ctx := context.Background() |
| 201 | serif := embeddedFont(t, "LiberationSerif-Regular.ttf") |
| 202 | theirs := strings.Repeat("e", 64) |
| 203 | store := &fakeFontStore{held: map[string][]byte{ |
| 204 | fontObjectKey(uploadedRef): serif, |
| 205 | fontObjectKey(theirs): serif, |
| 206 | }} |
| 207 | a, deckID := fontLoaderApp(t, store, uploadedRef) |
| 208 | other := Deck{Sqid: "fontloadr3", Title: "Other", OwnerID: 2, Rung: "private"} |
| 209 | if err := a.db.G.Create(&other).Error; err != nil { |
| 210 | t.Fatal(err) |
| 211 | } |
| 212 | if err := a.db.G.Create(&DeckFont{DeckID: other.ID, Ref: theirs}).Error; err != nil { |
| 213 | t.Fatal(err) |
| 214 | } |
| 215 | |
| 216 | load := a.fontLoader(ctx, deckID) |
| 217 | if b, err := load(uploadedRef); err != nil || !bytes.Equal(b, serif) { |
| 218 | t.Errorf("the deck's own face: %d bytes, %v", len(b), err) |
| 219 | } |
| 220 | if _, err := load(theirs); err == nil { |
| 221 | t.Error("a face only another deck recorded loaded") |
| 222 | } |
| 223 | if b, err := a.fontLoader(ctx, other.ID)(theirs); err != nil || !bytes.Equal(b, serif) { |
| 224 | t.Errorf("the other deck's own face: %d bytes, %v", len(b), err) |
| 225 | } |
| 226 | |
| 227 | // And an export of a deck listing a face it never recorded draws in |
| 228 | // the fallback. |
| 229 | pdf, _ := exportWith(t, uploadedDeck(deck.FontFace{Ref: theirs, Format: "ttf", Weight: [2]int{400, 400}, Pictures: true}), load) |
| 230 | if serifSubset.Match(pdf) { |
| 231 | t.Error("the export drew with a face the deck never recorded") |
| 232 | } |
| 233 | // The other deck's face was read once, through the other deck. |
| 234 | sort.Strings(store.asked) |
| 235 | want := []string{fontObjectKey(uploadedRef), fontObjectKey(theirs)} |
| 236 | sort.Strings(want) |
| 237 | if strings.Join(store.asked, " ") != strings.Join(want, " ") { |
| 238 | t.Errorf("the store was asked for %q, want only %q", store.asked, want) |
| 239 | } |
| 240 | } |
| 241 | |
| 242 | func TestTheFontLoaderReadsTheObjectStore(t *testing.T) { |
| 243 | ctx := context.Background() |
| 244 | // The store is content-addressed: a face is kept under its own |
| 245 | // SHA-256, which is its ref. |
| 246 | if got := fontObjectKey(uploadedRef); got != uploadedRef { |
| 247 | t.Errorf("fontObjectKey = %q, want the ref itself", got) |
| 248 | } |
| 249 | |
| 250 | // No store: every read is an error, and so everything falls back. |
| 251 | if _, err := (&app{}).fontLoader(ctx, 1)(uploadedRef); err == nil { |
| 252 | t.Error("a read with no object store succeeded") |
| 253 | } |
| 254 | |
| 255 | serif := embeddedFont(t, "LiberationSerif-Regular.ttf") |
| 256 | store := &fakeFontStore{held: map[string][]byte{ |
| 257 | fontObjectKey(uploadedRef): serif, |
| 258 | fontObjectKey(strings.Repeat("d", 64)): make([]byte, maxFontFileBytes+1), |
| 259 | }} |
| 260 | a, deckID := fontLoaderApp(t, store, uploadedRef, strings.Repeat("d", 64)) |
| 261 | load := a.fontLoader(ctx, deckID) |
| 262 | if b, err := load(uploadedRef); err != nil || !bytes.Equal(b, serif) { |
| 263 | t.Errorf("load = %d bytes, %v; want the stored face", len(b), err) |
| 264 | } |
| 265 | if _, err := load(strings.Repeat("d", 64)); err == nil { |
| 266 | t.Error("a face over the size limit loaded") |
| 267 | } |
| 268 | for _, bad := range []string{"", "../x", "fonts/" + uploadedRef, strings.ToUpper(uploadedRef), uploadedRef[:63]} { |
| 269 | if _, err := load(bad); err == nil { |
| 270 | t.Errorf("ref %q loaded", bad) |
| 271 | } |
| 272 | } |
| 273 | sort.Strings(store.asked) |
| 274 | want := []string{fontObjectKey(uploadedRef), fontObjectKey(strings.Repeat("d", 64))} |
| 275 | sort.Strings(want) |
| 276 | if strings.Join(store.asked, " ") != strings.Join(want, " ") { |
| 277 | t.Errorf("the store was asked for %q, want only %q", store.asked, want) |
| 278 | } |
| 279 | } |
| 280 | |
| 281 | // A face stored the way uploads store one — Put into the object store, |
| 282 | // which keys it by its SHA-256 — is what the loader reads back by ref, |
| 283 | // through a real store rather than a fake that takes any key. |
| 284 | func TestAFontStoredWithPutIsLoaded(t *testing.T) { |
| 285 | ctx := context.Background() |
| 286 | store, err := blobs.Dir(t.TempDir()) |
| 287 | if err != nil { |
| 288 | t.Fatal(err) |
| 289 | } |
| 290 | serif := embeddedFont(t, "LiberationSerif-Regular.ttf") |
| 291 | ref, err := store.Put(ctx, bytes.NewReader(serif), "font/ttf") |
| 292 | if err != nil { |
| 293 | t.Fatal(err) |
| 294 | } |
| 295 | sum := sha256.Sum256(serif) |
| 296 | if ref.Hash != hex.EncodeToString(sum[:]) { |
| 297 | t.Fatalf("Put keyed the face %q, not its SHA-256", ref.Hash) |
| 298 | } |
| 299 | a, deckID := fontLoaderApp(t, store, ref.Hash) |
| 300 | got, err := a.fontLoader(ctx, deckID)(ref.Hash) |
| 301 | if err != nil || !bytes.Equal(got, serif) { |
| 302 | t.Fatalf("load = %d bytes, %v; want the face Put stored", len(got), err) |
| 303 | } |
| 304 | |
| 305 | // And an export through that store draws with it. |
| 306 | pdf, _ := exportWith(t, uploadedDeck(deck.FontFace{Ref: ref.Hash, Format: "ttf", Weight: [2]int{400, 400}, Pictures: true}), a.fontLoader(ctx, deckID)) |
| 307 | if !serifSubset.Match(pdf) { |
| 308 | t.Error("the export did not draw with the stored face") |
| 309 | } |
| 310 | } |
| 311 | |