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 scene work through the drive API (scenes and clips spec §4,
4// §8 calls 4 and 5; internal/slides/scenestills.go): a bundle before the
5// scene exists, new code for one that does, and a still for each state,
6// each refused when it was made from a version of the scene that has
7// since moved on.
8
9import (
10 "bytes"
11 "encoding/binary"
12 "encoding/json"
13 "hash/crc32"
14 "image/png"
15 "net/http"
16 "net/http/httptest"
17 "strings"
18 "testing"
19
20 slides "amadan.net/oficina/slides/internal/slides"
21 "amadan.net/oficina/slides/internal/slides/deck"
22)
23
24// agentCall is one raw API request with a body that is not JSON.
25func agentCall(t *testing.T, a *testApp, method, target, token string, body []byte) *httptest.ResponseRecorder {
26 t.Helper()
27 req := httptest.NewRequest(method, target, bytes.NewReader(body))
28 req.Header.Set("Authorization", "Bearer "+token)
29 return send(t, a, req)
30}
31
32func decode(t *testing.T, rec *httptest.ResponseRecorder) map[string]any {
33 t.Helper()
34 var out map[string]any
35 if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
36 t.Fatalf("body is not a JSON object: %v\n%s", err, rec.Body)
37 }
38 return out
39}
40
41// sceneOf reads one scene out of the deck as an agent sees it.
42func sceneOf(t *testing.T, a *testApp, token, sqid, id string) deck.Scene {
43 t.Helper()
44 rec := agentCall(t, a, http.MethodGet, "/api/v1/decks/"+sqid, token, nil)
45 var view struct {
46 Scenes map[string]deck.Scene `json:"scenes"`
47 }
48 if err := json.Unmarshal(rec.Body.Bytes(), &view); err != nil {
49 t.Fatal(err)
50 }
51 s, ok := view.Scenes[id]
52 if !ok {
53 t.Fatalf("the deck has no scene %s: %s", id, rec.Body)
54 }
55 return s
56}
57
58// stillsCurrent is the twin of the editor's stillsCurrent
59// (fixtures/scenes.mjs): every state has a still, made from the scene's
60// version now.
61func stillsCurrent(s deck.Scene) bool {
62 v := deck.SceneVersion(s)
63 for _, st := range s.States {
64 if got, ok := s.Stills[st.ID]; !ok || got.Made != v {
65 return false
66 }
67 }
68 return true
69}
70
71func stillURL(sqid, id, state, made string) string {
72 return "/api/v1/decks/" + sqid + "/scenes/" + id + "/stills/" + state + "?made=" + made
73}
74
75// agentScene is an app, a signed-in person, their agent's token, a deck
76// and a scene in it whose bundle went up through the API.
77func agentScene(t *testing.T) (a *testApp, token, sqid, id string) {
78 t.Helper()
79 cfg, mailer := newConfig(t)
80 cfg.AllowedAddresses = []string{allowedAddress, otherAddress}
81 cfg.Blobs = dirStore(t)
82 a = newAppWith(t, cfg, mailer)
83 cookies := signedIn(t, a, allowedAddress)
84 token = mintAgent(t, a, cookies, "scenes")
85 sqid = apiDeck(t, a, token, "Stills")
86 rec := agentCall(t, a, http.MethodPost, "/api/v1/decks/"+sqid+"/scene-bundles", token, sceneBundle)
87 if rec.Code != http.StatusOK {
88 t.Fatalf("POST scene-bundles: status %d\n%s", rec.Code, rec.Body)
89 }
90 ref, _ := decode(t, rec)["ref"].(string)
91 if ref != hashOf(sceneBundle) {
92 t.Fatalf("scene-bundles answered ref %q, want the hash of the bytes", ref)
93 }
94 return a, token, sqid, addScene(t, a, token, sqid, ref)
95}
96
97// TestAnAgentUploadsAStillForEveryState: each PUT is checked, stored,
98// registered to the deck as a picture and set on the scene as the agent;
99// after one for each state the scene's stills are current, and the
100// pictures are served by the deck's own picture route.
101func TestAnAgentUploadsAStillForEveryState(t *testing.T) {
102 a, token, sqid, id := agentScene(t)
103 cookies := signedIn(t, a, allowedAddress)
104 if stillsCurrent(sceneOf(t, a, token, sqid, id)) {
105 t.Fatal("a scene with no stills reads as current")
106 }
107 made := deck.SceneVersion(sceneOf(t, a, token, sqid, id))
108 for _, state := range []string{"one", "two"} {
109 rec := agentCall(t, a, http.MethodPut, stillURL(sqid, id, state, made), token, onePixelPNG)
110 if rec.Code != http.StatusOK {
111 t.Fatalf("PUT still %s: status %d, want 200\n%s", state, rec.Code, rec.Body)
112 }
113 out := decode(t, rec)
114 if out["ref"] != hashOf(onePixelPNG) || out["made"] != made {
115 t.Errorf("PUT still %s answered %v, want the picture's hash and the version", state, out)
116 }
117 }
118 s := sceneOf(t, a, token, sqid, id)
119 if !stillsCurrent(s) {
120 t.Errorf("a still for each state, and the scene's stills are not current: %+v", s.Stills)
121 }
122 if got := s.Stills["one"]; got.Ref != hashOf(onePixelPNG) || got.Made != made {
123 t.Errorf("the scene's still for one is %+v", got)
124 }
125 // A picture of the deck: registered, verified, served.
126 rec := mustGet(t, a, "/d/"+sqid+"/assets/"+hashOf(onePixelPNG), http.StatusOK, cookies)
127 if !bytes.Equal(rec.Body.Bytes(), onePixelPNG) {
128 t.Error("the still's bytes differ from what went up")
129 }
130 // The change was the agent's, through the op path.
131 var actor string
132 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 {
133 t.Fatal(err)
134 }
135 if !strings.HasPrefix(actor, "agent:") {
136 t.Errorf("the last update's actor is %q, want an agent's", actor)
137 }
138}
139
140// TestAStillMadeFromOldCodeIsRefused: a stale or malformed made is a
141// 409 stale and the scene is untouched.
142func TestAStillMadeFromOldCodeIsRefused(t *testing.T) {
143 a, token, sqid, id := agentScene(t)
144 made := deck.SceneVersion(sceneOf(t, a, token, sqid, id))
145 for _, bad := range []string{strings.Repeat("0", 64), "", "nonsense"} {
146 rec := agentCall(t, a, http.MethodPut, stillURL(sqid, id, "one", bad), token, onePixelPNG)
147 if rec.Code != http.StatusConflict {
148 t.Errorf("made=%q: status %d, want 409\n%s", bad, rec.Code, rec.Body)
149 continue
150 }
151 if out := decode(t, rec); out["error"] != "stale" {
152 t.Errorf("made=%q: error %v, want stale", bad, out["error"])
153 }
154 }
155 if s := sceneOf(t, a, token, sqid, id); len(s.Stills) != 0 {
156 t.Errorf("a refused still was set anyway: %+v", s.Stills)
157 }
158
159 // A hand edit of the words moves the version: stills made before it
160 // are stale to the editor's note, and a new upload against the old
161 // version is refused.
162 for _, state := range []string{"one", "two"} {
163 agentCall(t, a, http.MethodPut, stillURL(sqid, id, state, made), token, onePixelPNG)
164 }
165 apiJSON(t, a, http.MethodPost, "/api/v1/decks/"+sqid+"/ops", token,
166 `{"ops":[{"op":"set_scene","id":"`+id+`","words":{"one":"Changed"}}]}`, http.StatusOK)
167 if stillsCurrent(sceneOf(t, a, token, sqid, id)) {
168 t.Error("a hand edit of words left the stills current")
169 }
170 if rec := agentCall(t, a, http.MethodPut, stillURL(sqid, id, "one", made), token, onePixelPNG); rec.Code != http.StatusConflict {
171 t.Errorf("a still against the old version: status %d, want 409", rec.Code)
172 }
173}
174
175// TestStillsAreRefusedForWhatIsNotYours: another person's deck, a scene
176// or a state that is not there.
177func TestStillsAreRefusedForWhatIsNotYours(t *testing.T) {
178 a, token, sqid, id := agentScene(t)
179 made := deck.SceneVersion(sceneOf(t, a, token, sqid, id))
180 theirs := mintAgent(t, a, signedIn(t, a, otherAddress), "theirs")
181 for name, call := range map[string]struct{ token, target string }{
182 "another person's deck": {theirs, stillURL(sqid, id, "one", made)},
183 "an unknown scene": {token, stillURL(sqid, "zzzzzzzzzzzz", "one", made)},
184 "an unknown state": {token, stillURL(sqid, id, "three", made)},
185 } {
186 rec := agentCall(t, a, http.MethodPut, call.target, call.token, onePixelPNG)
187 if rec.Code != http.StatusNotFound {
188 t.Errorf("%s: status %d, want 404\n%s", name, rec.Code, rec.Body)
189 }
190 }
191 // Another person's deck, for their code and a bundle, too.
192 if rec := agentCall(t, a, http.MethodPut, "/api/v1/decks/"+sqid+"/scenes/"+id+"/code", theirs, sceneBundle); rec.Code != http.StatusNotFound {
193 t.Errorf("code for another person's deck: status %d, want 404", rec.Code)
194 }
195 if rec := agentCall(t, a, http.MethodPost, "/api/v1/decks/"+sqid+"/scene-bundles", theirs, sceneBundle); rec.Code != http.StatusNotFound {
196 t.Errorf("a bundle for another person's deck: status %d, want 404", rec.Code)
197 }
198 if s := sceneOf(t, a, token, sqid, id); len(s.Stills) != 0 {
199 t.Errorf("a refused still was set anyway: %+v", s.Stills)
200 }
201}
202
203// TestNewCodeChangesTheVersionAndMarksStillsStale: PUT code registers the
204// bundle, sets it as the scene's code with the agent as its author, and
205// answers the new version; stills made before it are stale.
206func TestNewCodeChangesTheVersionAndMarksStillsStale(t *testing.T) {
207 a, token, sqid, id := agentScene(t)
208 cookies := signedIn(t, a, allowedAddress)
209 made := deck.SceneVersion(sceneOf(t, a, token, sqid, id))
210 for _, state := range []string{"one", "two"} {
211 agentCall(t, a, http.MethodPut, stillURL(sqid, id, state, made), token, onePixelPNG)
212 }
213 if !stillsCurrent(sceneOf(t, a, token, sqid, id)) {
214 t.Fatal("the stills were not current to begin with")
215 }
216
217 next := append([]byte("<!DOCTYPE html>\n<title>v2</title>\n"), sceneBundle...)
218 rec := agentCall(t, a, http.MethodPut, "/api/v1/decks/"+sqid+"/scenes/"+id+"/code", token, next)
219 if rec.Code != http.StatusOK {
220 t.Fatalf("PUT code: status %d\n%s", rec.Code, rec.Body)
221 }
222 out := decode(t, rec)
223 s := sceneOf(t, a, token, sqid, id)
224 if out["ref"] != hashOf(next) || s.Code != hashOf(next) {
225 t.Errorf("code ref: answered %v, scene has %s, want %s", out["ref"], s.Code, hashOf(next))
226 }
227 if out["version"] != deck.SceneVersion(s) || out["version"] == made {
228 t.Errorf("version answered %v, scene's is %s (was %s)", out["version"], deck.SceneVersion(s), made)
229 }
230 if !strings.HasPrefix(s.Author, "agent:") {
231 t.Errorf("author = %q, want the agent", s.Author)
232 }
233 if stillsCurrent(s) {
234 t.Error("new code left the old stills current")
235 }
236 // The new bundle is served under the sealed route of the deck.
237 rec = mustGet(t, a, "/d/"+sqid+"/scenes/"+id+"/"+hashOf(next), http.StatusOK, cookies)
238 if !bytes.Equal(rec.Body.Bytes(), next) {
239 t.Error("the new bundle's bytes differ from what went up")
240 }
241 // And a still made against the new version is accepted.
242 if rec := agentCall(t, a, http.MethodPut, stillURL(sqid, id, "one", out["version"].(string)), token, onePixelPNG); rec.Code != http.StatusOK {
243 t.Errorf("a still against the new version: status %d\n%s", rec.Code, rec.Body)
244 }
245}
246
247// TestACodeBodyThatIsNotOneHTMLDocumentIsRefused: for both routes, and
248// over the limit.
249func TestACodeBodyThatIsNotOneHTMLDocumentIsRefused(t *testing.T) {
250 a, token, sqid, id := agentScene(t)
251 big := append([]byte("<!doctype html>"), bytes.Repeat([]byte("x"), 2<<20)...)
252 for name, call := range map[string]struct {
253 method, target string
254 body []byte
255 status int
256 code string
257 }{
258 "code, a picture": {http.MethodPut, "/scenes/" + id + "/code", onePixelPNG, http.StatusUnprocessableEntity, "not_html"},
259 "code, text": {http.MethodPut, "/scenes/" + id + "/code", []byte("hello"), http.StatusUnprocessableEntity, "not_html"},
260 "code, too big": {http.MethodPut, "/scenes/" + id + "/code", big, http.StatusRequestEntityTooLarge, "too_large"},
261 "code, unknown scene": {http.MethodPut, "/scenes/zzzzzzzzzzzz/code", sceneBundle, http.StatusNotFound, "not_found"},
262 "bundle, a picture": {http.MethodPost, "/scene-bundles", onePixelPNG, http.StatusUnprocessableEntity, "not_html"},
263 "bundle, too big": {http.MethodPost, "/scene-bundles", big, http.StatusRequestEntityTooLarge, "too_large"},
264 } {
265 rec := agentCall(t, a, call.method, "/api/v1/decks/"+sqid+call.target, token, call.body)
266 if rec.Code != call.status || decode(t, rec)["error"] != call.code {
267 t.Errorf("%s: status %d %s, want %d %s", name, rec.Code, rec.Body, call.status, call.code)
268 }
269 }
270 if s := sceneOf(t, a, token, sqid, id); s.Code != hashOf(sceneBundle) {
271 t.Errorf("a refused bundle changed the scene's code to %s", s.Code)
272 }
273}
274
275// TestAStillIsAPictureOfTheRightSize: a PNG or WebP, at most 4 MiB, an
276// image that decodes at a size the pictures allow.
277func TestAStillIsAPictureOfTheRightSize(t *testing.T) {
278 a, token, sqid, id := agentScene(t)
279 made := deck.SceneVersion(sceneOf(t, a, token, sqid, id))
280 big := append(append([]byte{}, onePixelPNG...), bytes.Repeat([]byte{0}, 4<<20)...)
281 // A PNG whose header, checksum right, declares 40000 x 1: it decodes
282 // as far as its size, which is over the 30000 the pictures allow.
283 wide := append([]byte{}, onePixelPNG...)
284 wide[16], wide[17], wide[18], wide[19] = 0, 0, 0x9c, 0x40
285 binary.BigEndian.PutUint32(wide[29:33], crc32.ChecksumIEEE(wide[12:29]))
286 if cfg, err := png.DecodeConfig(bytes.NewReader(wide)); err != nil || cfg.Width != 40000 {
287 t.Fatalf("the wide PNG is not a valid header of width 40000: %v %+v", err, cfg)
288 }
289 // 10000 x 10000: each edge allowed, the 100 megapixels together over
290 // the budget every decode is held to (svg.MaxDecodePixels).
291 square := append([]byte{}, onePixelPNG...)
292 binary.BigEndian.PutUint32(square[16:20], 10000)
293 binary.BigEndian.PutUint32(square[20:24], 10000)
294 binary.BigEndian.PutUint32(square[29:33], crc32.ChecksumIEEE(square[12:29]))
295 for name, call := range map[string]struct {
296 body []byte
297 status int
298 code string
299 }{
300 "too many pixels together": {square, http.StatusUnprocessableEntity, "not_an_image"},
301 "a webp header of 30000 x 30000": {hugeWebP(), http.StatusUnprocessableEntity, "not_an_image"},
302 "too big": {big, http.StatusRequestEntityTooLarge, "too_large"},
303 "html": {sceneBundle, http.StatusUnprocessableEntity, "not_an_image"},
304 "svg": {[]byte(`<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1"/>`), http.StatusUnprocessableEntity, "not_an_image"},
305 "jpeg": {[]byte("\xff\xd8\xff\xe0 not really"), http.StatusUnprocessableEntity, "not_an_image"},
306 "a broken png": {onePixelPNG[:20], http.StatusUnprocessableEntity, "not_an_image"},
307 "empty": {nil, http.StatusUnprocessableEntity, "not_an_image"},
308 "too many pixels": {wide, http.StatusUnprocessableEntity, "not_an_image"},
309 } {
310 rec := agentCall(t, a, http.MethodPut, stillURL(sqid, id, "one", made), token, call.body)
311 if rec.Code != call.status || decode(t, rec)["error"] != call.code {
312 t.Errorf("%s: status %d %s, want %d %s", name, rec.Code, rec.Body, call.status, call.code)
313 }
314 }
315 if s := sceneOf(t, a, token, sqid, id); len(s.Stills) != 0 {
316 t.Errorf("a refused still was set anyway: %+v", s.Stills)
317 }
318}
319
320// TestWithoutAStoreThereIsNowhereToPutThem: 503, as the pictures answer.
321func TestWithoutAStoreThereIsNowhereToPutThem(t *testing.T) {
322 a := newApp(t)
323 token := mintAgent(t, a, signedIn(t, a, allowedAddress), "scenes")
324 sqid := apiDeck(t, a, token, "Bare")
325 rec := agentCall(t, a, http.MethodPost, "/api/v1/decks/"+sqid+"/scene-bundles", token, sceneBundle)
326 if rec.Code != http.StatusServiceUnavailable {
327 t.Errorf("a bundle with no store: status %d, want 503", rec.Code)
328 }
329}
330
331// duringWrite lands one hand edit of the scene's words at the moment a
332// scene write has been checked against the document and not yet made.
333func duringWrite(t *testing.T, a *testApp, token, sqid, id string) {
334 t.Helper()
335 fired := 0
336 slides.BeforeSceneWrite = func() {
337 fired++
338 if fired > 1 {
339 return
340 }
341 apiJSON(t, a, http.MethodPost, "/api/v1/decks/"+sqid+"/ops", token,
342 `{"ops":[{"op":"set_scene","id":"`+id+`","words":{"one":"Landed in between"}}]}`, http.StatusOK)
343 }
344 t.Cleanup(func() { slides.BeforeSceneWrite = nil })
345}
346
347// TestAHandEditBetweenTheCheckAndTheWriteStillRefusesTheStill: the
348// version is checked against the document the write lands on, so an edit
349// that arrives after an earlier check cannot be overwritten by a still
350// made before it.
351func TestAHandEditBetweenTheCheckAndTheWriteStillRefusesTheStill(t *testing.T) {
352 a, token, sqid, id := agentScene(t)
353 made := deck.SceneVersion(sceneOf(t, a, token, sqid, id))
354 duringWrite(t, a, token, sqid, id)
355 rec := agentCall(t, a, http.MethodPut, stillURL(sqid, id, "one", made), token, onePixelPNG)
356 if rec.Code != http.StatusConflict || decode(t, rec)["error"] != "stale" {
357 t.Fatalf("status %d %s, want 409 stale", rec.Code, rec.Body)
358 }
359 s := sceneOf(t, a, token, sqid, id)
360 if len(s.Stills) != 0 {
361 t.Errorf("a still made from the old version was written: %+v", s.Stills)
362 }
363 if s.Words["one"] != "Landed in between" {
364 t.Errorf("the hand edit is not in the scene: %v", s.Words)
365 }
366}
367
368// TestACodeUploadAnswersTheVersionTheWriteLeft: an edit of the words that
369// lands while the code is being set is in the scene, and so in the
370// version the answer names.
371func TestACodeUploadAnswersTheVersionTheWriteLeft(t *testing.T) {
372 a, token, sqid, id := agentScene(t)
373 duringWrite(t, a, token, sqid, id)
374 next := append([]byte("<!DOCTYPE html>\n<title>v3</title>\n"), sceneBundle...)
375 rec := agentCall(t, a, http.MethodPut, "/api/v1/decks/"+sqid+"/scenes/"+id+"/code", token, next)
376 if rec.Code != http.StatusOK {
377 t.Fatalf("PUT code: status %d\n%s", rec.Code, rec.Body)
378 }
379 s := sceneOf(t, a, token, sqid, id)
380 if s.Words["one"] != "Landed in between" || s.Code != hashOf(next) {
381 t.Fatalf("the scene is not the write's: %+v", s)
382 }
383 if got := decode(t, rec)["version"]; got != deck.SceneVersion(s) {
384 t.Errorf("answered version %v, the scene's is %s", got, deck.SceneVersion(s))
385 }
386}
387