oficina / slides Public

Clone
git clone https://amadan.net/oficina/slides

Plain git — no account needed to clone.

Download

Download this file

1package slidestest
2
3// An agent's pictures through the drive API (internal/slides/agent_assets.go):
4// POST /api/v1/decks/{sqid}/assets takes the image bytes as the body,
5// judges them, keeps them under their own hash, verifies them for the
6// deck and registers them as an asset of it, as the agent.
7
8import (
9 "bytes"
10 "encoding/binary"
11 "encoding/hex"
12 "encoding/json"
13 "fmt"
14 "hash/crc32"
15 "image"
16 "image/color"
17 "image/jpeg"
18 "image/png"
19 "net/http"
20 "net/http/httptest"
21 "net/url"
22 "strings"
23 "testing"
24
25 "golang.org/x/image/webp"
26)
27
28// webpPicture is a 4 by 3 lossless WebP of one flat colour (the export
29// test's fixture): Go has no WebP encoder, so the bytes are written out.
30func webpPicture(t *testing.T) []byte {
31 t.Helper()
32 raw, err := hex.DecodeString("524946461e000000574542505650384c110000002f0380000007508f2217a5ff8188e87f0000")
33 if err != nil {
34 t.Fatal(err)
35 }
36 return raw
37}
38
39// jpegPicture is a w by h JPEG of one colour.
40func jpegPicture(t *testing.T, w, h int) []byte {
41 t.Helper()
42 img := image.NewRGBA(image.Rect(0, 0, w, h))
43 for i := range img.Pix {
44 img.Pix[i] = 0x80
45 }
46 img.Set(0, 0, color.Black)
47 var buf bytes.Buffer
48 if err := jpeg.Encode(&buf, img, nil); err != nil {
49 t.Fatal(err)
50 }
51 return buf.Bytes()
52}
53
54// hugeWebP is forty bytes whose header says 30000 by 30000 with alpha
55// (the svg package's HugeWebP): a decode would allocate 900 MB.
56func hugeWebP() []byte {
57 edge := 30000
58 b := []byte("RIFF\x20\x00\x00\x00WEBPVP8X\x0a\x00\x00\x00\x10\x00\x00\x00" +
59 "\x00\x00\x00\x00\x00\x00ALPH\x02\x00\x00\x00\x00\x00")
60 for _, at := range []int{24, 27} {
61 b[at], b[at+1], b[at+2] = byte(edge-1), byte((edge-1)>>8), byte((edge-1)>>16)
62 }
63 return b
64}
65
66// postPicture is one upload: the bytes as the body, under the token.
67func postPicture(t *testing.T, a *testApp, sqid, token, query string, body []byte) *httptest.ResponseRecorder {
68 t.Helper()
69 req := httptest.NewRequest(http.MethodPost, "/api/v1/decks/"+sqid+"/assets"+query, bytes.NewReader(body))
70 req.Header.Set("Authorization", "Bearer "+token)
71 req.Header.Set("Content-Type", "application/octet-stream")
72 return send(t, a, req)
73}
74
75func jsonObject(t *testing.T, rec *httptest.ResponseRecorder) map[string]any {
76 t.Helper()
77 if ct := rec.Header().Get("Content-Type"); !strings.HasPrefix(ct, "application/json") {
78 t.Fatalf("Content-Type = %q, want JSON\n%s", ct, rec.Body)
79 }
80 var out map[string]any
81 if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
82 t.Fatalf("body is not a JSON object: %v\n%s", err, rec.Body)
83 }
84 return out
85}
86
87type agentAsset struct {
88 Ref string `json:"ref"`
89 Name string `json:"name"`
90 Width int `json:"width"`
91 Height int `json:"height"`
92 Alt string `json:"alt"`
93}
94
95// deckAssets is the deck's assets as an agent reads them.
96func deckAssets(t *testing.T, a *testApp, token, sqid string) map[string]agentAsset {
97 t.Helper()
98 rec := send(t, a, bearerRequest(t, http.MethodGet, "/api/v1/decks/"+sqid, token, ""))
99 if rec.Code != http.StatusOK {
100 t.Fatalf("GET deck: status %d\n%s", rec.Code, rec.Body)
101 }
102 var view struct {
103 Assets map[string]agentAsset `json:"assets"`
104 }
105 if err := json.Unmarshal(rec.Body.Bytes(), &view); err != nil {
106 t.Fatal(err)
107 }
108 return view.Assets
109}
110
111// agentPictures is an app with a store, a signed-in person, their
112// agent's token and a deck.
113func agentPictures(t *testing.T) (a *testApp, cookies []*http.Cookie, token, sqid string) {
114 t.Helper()
115 cfg, mailer := newConfig(t)
116 cfg.AllowedAddresses = []string{allowedAddress, otherAddress}
117 cfg.Blobs = dirStore(t)
118 a = newAppWith(t, cfg, mailer)
119 cookies = signedIn(t, a, allowedAddress)
120 token = mintAgent(t, a, cookies, "pictures")
121 return a, cookies, token, apiDeck(t, a, token, "Pictures")
122}
123
124// TestAnAgentUploadsAPictureAndASlideDrawsIt: a PNG, a WebP and a JPEG go up,
125// come back 201 with their hash and size, are registered as the
126// agent's change, are served by the deck's picture route, and are drawn
127// by the slide's HTML and its thumbnail once an image block names them.
128func TestAnAgentUploadsAPictureAndASlideDrawsIt(t *testing.T) {
129 a, cookies, token, sqid := agentPictures(t)
130 for _, pic := range []struct {
131 name string
132 body []byte
133 width, height int
134 }{
135 {"png", onePixelPNG, 1, 1},
136 {"webp", webpPicture(t), 4, 3},
137 {"jpeg", jpegPicture(t, 5, 2), 5, 2},
138 } {
139 alt := "A " + pic.name + " picture"
140 rec := postPicture(t, a, sqid, token, "?alt="+url.QueryEscape(alt), pic.body)
141 if rec.Code != http.StatusCreated {
142 t.Fatalf("%s: status %d, want 201\n%s", pic.name, rec.Code, rec.Body)
143 }
144 out := jsonObject(t, rec)
145 ref := hashOf(pic.body)
146 if out["ref"] != ref || out["width"] != float64(pic.width) || out["height"] != float64(pic.height) {
147 t.Fatalf("%s: answered %v, want ref %s and %dx%d", pic.name, out, ref, pic.width, pic.height)
148 }
149 id, _ := out["id"].(string)
150 if id == "" {
151 t.Fatalf("%s: no asset id in %v", pic.name, out)
152 }
153
154 got, ok := deckAssets(t, a, token, sqid)[id]
155 if !ok || got != (agentAsset{Ref: ref, Name: got.Name, Width: pic.width, Height: pic.height, Alt: alt}) {
156 t.Fatalf("%s: the deck's asset %s is %+v (present %v)", pic.name, id, got, ok)
157 }
158
159 var actor string
160 if err := a.db.G.Raw("SELECT actor FROM deck_updates WHERE deck_id = (SELECT id FROM decks WHERE sqid = ?) ORDER BY seq DESC LIMIT 1", sqid).Scan(&actor).Error; err != nil {
161 t.Fatal(err)
162 }
163 if !strings.HasPrefix(actor, "agent:") {
164 t.Errorf("%s: the registration's actor is %q, want the agent", pic.name, actor)
165 }
166
167 served := mustGet(t, a, "/d/"+sqid+"/assets/"+ref, http.StatusOK, cookies)
168 if !bytes.Equal(served.Body.Bytes(), pic.body) {
169 t.Errorf("%s: the served bytes differ from what went up", pic.name)
170 }
171
172 slide := apiJSON(t, a, http.MethodPost, "/api/v1/decks/"+sqid+"/ops", token,
173 `{"ops":[{"op":"add_slide","layout":"flow","template":"image-full"}]}`, http.StatusOK)
174 slideID := slide["ids"].(map[string]any)["0"].(string)
175 apiJSON(t, a, http.MethodPost, "/api/v1/decks/"+sqid+"/ops", token,
176 fmt.Sprintf(`{"ops":[{"op":"add_block","slide":%q,"type":"image","region":"media","props":{"asset":%q}}]}`,
177 slideID, id), http.StatusOK)
178 page := mustGet(t, a, "/d/"+sqid+"/slides/"+slideID+".html", http.StatusOK, cookies).Body.String()
179 if !strings.Contains(page, `src="/d/`+sqid+`/assets/`+ref+`"`) {
180 t.Errorf("%s: the slide's HTML does not draw the picture:\n%s", pic.name, page)
181 }
182 thumb := mustGet(t, a, "/d/"+sqid+"/slides/"+slideID+".svg", http.StatusOK, cookies).Body.String()
183 // Inlined, since an SVG in an <img> fetches nothing: a WebP as
184 // a PNG, the others as they are.
185 inline := "data:image/png;base64,"
186 if pic.name == "jpeg" {
187 inline = "data:image/jpeg;base64,"
188 }
189 if !strings.Contains(thumb, inline) {
190 t.Errorf("%s: the slide's SVG does not draw the picture:\n%s", pic.name, thumb)
191 }
192 }
193}
194
195// TestTheSamePictureTwiceIsOneAsset: the second upload answers 200 with
196// the first one's ref and id, and the deck still has one asset.
197func TestTheSamePictureTwiceIsOneAsset(t *testing.T) {
198 a, _, token, sqid := agentPictures(t)
199 first := postPicture(t, a, sqid, token, "", onePixelPNG)
200 if first.Code != http.StatusCreated {
201 t.Fatalf("first: status %d\n%s", first.Code, first.Body)
202 }
203 var seq int64
204 readSeq := func() int64 {
205 var s int64
206 if err := a.db.G.Raw("SELECT seq FROM decks WHERE sqid = ?", sqid).Scan(&s).Error; err != nil {
207 t.Fatal(err)
208 }
209 return s
210 }
211 seq = readSeq()
212 second := postPicture(t, a, sqid, token, "?alt=Again", onePixelPNG)
213 if second.Code != http.StatusOK {
214 t.Fatalf("second: status %d, want 200\n%s", second.Code, second.Body)
215 }
216 a1, a2 := jsonObject(t, first), jsonObject(t, second)
217 if a1["ref"] != a2["ref"] || a1["id"] != a2["id"] || a2["width"] != float64(1) {
218 t.Errorf("the duplicate answered %v, the first %v", a2, a1)
219 }
220 if assets := deckAssets(t, a, token, sqid); len(assets) != 1 {
221 t.Errorf("the deck has %d assets after the same picture twice: %+v", len(assets), assets)
222 }
223 if readSeq() != seq {
224 t.Error("the duplicate wrote to the document")
225 }
226}
227
228// TestWhatIsNotAPictureIsRefused: over 20 MiB is 413; anything that is
229// not a PNG, JPEG or WebP that decodes at a size pictures allow is 422.
230// Nothing is registered.
231func TestWhatIsNotAPictureIsRefused(t *testing.T) {
232 a, _, token, sqid := agentPictures(t)
233 big := append(append([]byte{}, onePixelPNG...), bytes.Repeat([]byte{0}, 20<<20)...)
234 // A PNG whose header, checksum right, declares 40000 x 1: it decodes
235 // as far as its size, which is over the 30000 a picture may be.
236 wide := append([]byte{}, onePixelPNG...)
237 wide[16], wide[17], wide[18], wide[19] = 0, 0, 0x9c, 0x40
238 binary.BigEndian.PutUint32(wide[29:33], crc32.ChecksumIEEE(wide[12:29]))
239 if cfg, err := png.DecodeConfig(bytes.NewReader(wide)); err != nil || cfg.Width != 40000 {
240 t.Fatalf("the wide PNG is not a valid header of width 40000: %v %+v", err, cfg)
241 }
242 // 10000 x 10000: each edge allowed, the 100 megapixels together not.
243 square := append([]byte{}, onePixelPNG...)
244 binary.BigEndian.PutUint32(square[16:20], 10000)
245 binary.BigEndian.PutUint32(square[20:24], 10000)
246 binary.BigEndian.PutUint32(square[29:33], crc32.ChecksumIEEE(square[12:29]))
247 if cfg, err := png.DecodeConfig(bytes.NewReader(square)); err != nil || cfg.Width != 10000 {
248 t.Fatalf("the square PNG is not a valid header of 10000 x 10000: %v %+v", err, cfg)
249 }
250 if cfg, err := webp.DecodeConfig(bytes.NewReader(hugeWebP())); err != nil || cfg.Width != 30000 || cfg.Height != 30000 {
251 t.Fatalf("the huge WebP is not a valid header of 30000 x 30000: %v %+v", err, cfg)
252 }
253 for name, c := range map[string]struct {
254 body []byte
255 status int
256 code string
257 }{
258 "too big": {big, http.StatusRequestEntityTooLarge, "too_large"},
259 "too many pixels together": {square, http.StatusUnprocessableEntity, "not_an_image"},
260 "a webp header of 30000 x 30000": {hugeWebP(), http.StatusUnprocessableEntity, "not_an_image"},
261 "text": {[]byte("hello, this is not a picture"), http.StatusUnprocessableEntity, "not_an_image"},
262 "html": {[]byte("<!doctype html><title>x</title>"), http.StatusUnprocessableEntity, "not_an_image"},
263 "svg": {[]byte(`<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1"/>`), http.StatusUnprocessableEntity, "not_an_image"},
264 "fake png": {[]byte("\x89PNG\r\n\x1a\nnot really a png at all"), http.StatusUnprocessableEntity, "not_an_image"},
265 "fake jpeg": {[]byte("\xff\xd8\xff\xe0 not really"), http.StatusUnprocessableEntity, "not_an_image"},
266 "fake webp": {[]byte("RIFF\x00\x00\x00\x00WEBPnot really"), http.StatusUnprocessableEntity, "not_an_image"},
267 "a broken png": {onePixelPNG[:20], http.StatusUnprocessableEntity, "not_an_image"},
268 "empty": {nil, http.StatusUnprocessableEntity, "not_an_image"},
269 "too many pixels": {wide, http.StatusUnprocessableEntity, "not_an_image"},
270 } {
271 rec := postPicture(t, a, sqid, token, "", c.body)
272 if rec.Code != c.status {
273 t.Errorf("%s: status %d, want %d\n%s", name, rec.Code, c.status, rec.Body)
274 continue
275 }
276 out := jsonObject(t, rec)
277 if out["error"] != c.code || out["message"] == nil || out["message"] == "" {
278 t.Errorf("%s: answered %v, want error %s with a message", name, out, c.code)
279 }
280 }
281 if assets := deckAssets(t, a, token, sqid); len(assets) != 0 {
282 t.Errorf("a refused picture was registered: %+v", assets)
283 }
284}
285
286// TestPicturesAreRefusedForDecksThatAreNotYours: another person's deck
287// and a deck that does not exist are 404, a bad token 401, as the rest
288// of the API answers them.
289func TestPicturesAreRefusedForDecksThatAreNotYours(t *testing.T) {
290 a, _, token, sqid := agentPictures(t)
291 theirs := mintAgent(t, a, signedIn(t, a, otherAddress), "theirs")
292 for name, c := range map[string]struct {
293 token, sqid string
294 status int
295 }{
296 "another person's deck": {theirs, sqid, http.StatusNotFound},
297 "no such deck": {token, "zzzzzzzzzz", http.StatusNotFound},
298 "a bad token": {"sl_not-a-real-token", sqid, http.StatusUnauthorized},
299 } {
300 rec := postPicture(t, a, c.sqid, c.token, "", onePixelPNG)
301 if rec.Code != c.status {
302 t.Errorf("%s: status %d, want %d\n%s", name, rec.Code, c.status, rec.Body)
303 }
304 jsonObject(t, rec)
305 }
306 if assets := deckAssets(t, a, token, sqid); len(assets) != 0 {
307 t.Errorf("a refused picture was registered: %+v", assets)
308 }
309}
310
311// TestWithoutAStoreAPictureHasNowhereToGo: 503 no_store.
312func TestWithoutAStoreAPictureHasNowhereToGo(t *testing.T) {
313 a := newApp(t)
314 token := mintAgent(t, a, signedIn(t, a, allowedAddress), "pictures")
315 sqid := apiDeck(t, a, token, "Bare")
316 rec := postPicture(t, a, sqid, token, "", onePixelPNG)
317 if rec.Code != http.StatusServiceUnavailable {
318 t.Fatalf("status %d, want 503\n%s", rec.Code, rec.Body)
319 }
320 if out := jsonObject(t, rec); out["error"] != "no_store" {
321 t.Errorf("answered %v, want no_store", out)
322 }
323}
324