package slidestest // An agent's scene work through the drive API (scenes and clips spec §4, // §8 calls 4 and 5; internal/slides/scenestills.go): a bundle before the // scene exists, new code for one that does, and a still for each state, // each refused when it was made from a version of the scene that has // since moved on. import ( "bytes" "encoding/binary" "encoding/json" "hash/crc32" "image/png" "net/http" "net/http/httptest" "strings" "testing" slides "amadan.net/oficina/slides/internal/slides" "amadan.net/oficina/slides/internal/slides/deck" ) // agentCall is one raw API request with a body that is not JSON. func agentCall(t *testing.T, a *testApp, method, target, token string, body []byte) *httptest.ResponseRecorder { t.Helper() req := httptest.NewRequest(method, target, bytes.NewReader(body)) req.Header.Set("Authorization", "Bearer "+token) return send(t, a, req) } func decode(t *testing.T, rec *httptest.ResponseRecorder) map[string]any { t.Helper() var out map[string]any if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil { t.Fatalf("body is not a JSON object: %v\n%s", err, rec.Body) } return out } // sceneOf reads one scene out of the deck as an agent sees it. func sceneOf(t *testing.T, a *testApp, token, sqid, id string) deck.Scene { t.Helper() rec := agentCall(t, a, http.MethodGet, "/api/v1/decks/"+sqid, token, nil) var view struct { Scenes map[string]deck.Scene `json:"scenes"` } if err := json.Unmarshal(rec.Body.Bytes(), &view); err != nil { t.Fatal(err) } s, ok := view.Scenes[id] if !ok { t.Fatalf("the deck has no scene %s: %s", id, rec.Body) } return s } // stillsCurrent is the twin of the editor's stillsCurrent // (fixtures/scenes.mjs): every state has a still, made from the scene's // version now. func stillsCurrent(s deck.Scene) bool { v := deck.SceneVersion(s) for _, st := range s.States { if got, ok := s.Stills[st.ID]; !ok || got.Made != v { return false } } return true } func stillURL(sqid, id, state, made string) string { return "/api/v1/decks/" + sqid + "/scenes/" + id + "/stills/" + state + "?made=" + made } // agentScene is an app, a signed-in person, their agent's token, a deck // and a scene in it whose bundle went up through the API. func agentScene(t *testing.T) (a *testApp, token, sqid, id string) { t.Helper() cfg, mailer := newConfig(t) cfg.AllowedAddresses = []string{allowedAddress, otherAddress} cfg.Blobs = dirStore(t) a = newAppWith(t, cfg, mailer) cookies := signedIn(t, a, allowedAddress) token = mintAgent(t, a, cookies, "scenes") sqid = apiDeck(t, a, token, "Stills") rec := agentCall(t, a, http.MethodPost, "/api/v1/decks/"+sqid+"/scene-bundles", token, sceneBundle) if rec.Code != http.StatusOK { t.Fatalf("POST scene-bundles: status %d\n%s", rec.Code, rec.Body) } ref, _ := decode(t, rec)["ref"].(string) if ref != hashOf(sceneBundle) { t.Fatalf("scene-bundles answered ref %q, want the hash of the bytes", ref) } return a, token, sqid, addScene(t, a, token, sqid, ref) } // TestAnAgentUploadsAStillForEveryState: each PUT is checked, stored, // registered to the deck as a picture and set on the scene as the agent; // after one for each state the scene's stills are current, and the // pictures are served by the deck's own picture route. func TestAnAgentUploadsAStillForEveryState(t *testing.T) { a, token, sqid, id := agentScene(t) cookies := signedIn(t, a, allowedAddress) if stillsCurrent(sceneOf(t, a, token, sqid, id)) { t.Fatal("a scene with no stills reads as current") } made := deck.SceneVersion(sceneOf(t, a, token, sqid, id)) for _, state := range []string{"one", "two"} { rec := agentCall(t, a, http.MethodPut, stillURL(sqid, id, state, made), token, onePixelPNG) if rec.Code != http.StatusOK { t.Fatalf("PUT still %s: status %d, want 200\n%s", state, rec.Code, rec.Body) } out := decode(t, rec) if out["ref"] != hashOf(onePixelPNG) || out["made"] != made { t.Errorf("PUT still %s answered %v, want the picture's hash and the version", state, out) } } s := sceneOf(t, a, token, sqid, id) if !stillsCurrent(s) { t.Errorf("a still for each state, and the scene's stills are not current: %+v", s.Stills) } if got := s.Stills["one"]; got.Ref != hashOf(onePixelPNG) || got.Made != made { t.Errorf("the scene's still for one is %+v", got) } // A picture of the deck: registered, verified, served. rec := mustGet(t, a, "/d/"+sqid+"/assets/"+hashOf(onePixelPNG), http.StatusOK, cookies) if !bytes.Equal(rec.Body.Bytes(), onePixelPNG) { t.Error("the still's bytes differ from what went up") } // The change was the agent's, through the op path. var actor string 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 { t.Fatal(err) } if !strings.HasPrefix(actor, "agent:") { t.Errorf("the last update's actor is %q, want an agent's", actor) } } // TestAStillMadeFromOldCodeIsRefused: a stale or malformed made is a // 409 stale and the scene is untouched. func TestAStillMadeFromOldCodeIsRefused(t *testing.T) { a, token, sqid, id := agentScene(t) made := deck.SceneVersion(sceneOf(t, a, token, sqid, id)) for _, bad := range []string{strings.Repeat("0", 64), "", "nonsense"} { rec := agentCall(t, a, http.MethodPut, stillURL(sqid, id, "one", bad), token, onePixelPNG) if rec.Code != http.StatusConflict { t.Errorf("made=%q: status %d, want 409\n%s", bad, rec.Code, rec.Body) continue } if out := decode(t, rec); out["error"] != "stale" { t.Errorf("made=%q: error %v, want stale", bad, out["error"]) } } if s := sceneOf(t, a, token, sqid, id); len(s.Stills) != 0 { t.Errorf("a refused still was set anyway: %+v", s.Stills) } // A hand edit of the words moves the version: stills made before it // are stale to the editor's note, and a new upload against the old // version is refused. for _, state := range []string{"one", "two"} { agentCall(t, a, http.MethodPut, stillURL(sqid, id, state, made), token, onePixelPNG) } apiJSON(t, a, http.MethodPost, "/api/v1/decks/"+sqid+"/ops", token, `{"ops":[{"op":"set_scene","id":"`+id+`","words":{"one":"Changed"}}]}`, http.StatusOK) if stillsCurrent(sceneOf(t, a, token, sqid, id)) { t.Error("a hand edit of words left the stills current") } if rec := agentCall(t, a, http.MethodPut, stillURL(sqid, id, "one", made), token, onePixelPNG); rec.Code != http.StatusConflict { t.Errorf("a still against the old version: status %d, want 409", rec.Code) } } // TestStillsAreRefusedForWhatIsNotYours: another person's deck, a scene // or a state that is not there. func TestStillsAreRefusedForWhatIsNotYours(t *testing.T) { a, token, sqid, id := agentScene(t) made := deck.SceneVersion(sceneOf(t, a, token, sqid, id)) theirs := mintAgent(t, a, signedIn(t, a, otherAddress), "theirs") for name, call := range map[string]struct{ token, target string }{ "another person's deck": {theirs, stillURL(sqid, id, "one", made)}, "an unknown scene": {token, stillURL(sqid, "zzzzzzzzzzzz", "one", made)}, "an unknown state": {token, stillURL(sqid, id, "three", made)}, } { rec := agentCall(t, a, http.MethodPut, call.target, call.token, onePixelPNG) if rec.Code != http.StatusNotFound { t.Errorf("%s: status %d, want 404\n%s", name, rec.Code, rec.Body) } } // Another person's deck, for their code and a bundle, too. if rec := agentCall(t, a, http.MethodPut, "/api/v1/decks/"+sqid+"/scenes/"+id+"/code", theirs, sceneBundle); rec.Code != http.StatusNotFound { t.Errorf("code for another person's deck: status %d, want 404", rec.Code) } if rec := agentCall(t, a, http.MethodPost, "/api/v1/decks/"+sqid+"/scene-bundles", theirs, sceneBundle); rec.Code != http.StatusNotFound { t.Errorf("a bundle for another person's deck: status %d, want 404", rec.Code) } if s := sceneOf(t, a, token, sqid, id); len(s.Stills) != 0 { t.Errorf("a refused still was set anyway: %+v", s.Stills) } } // TestNewCodeChangesTheVersionAndMarksStillsStale: PUT code registers the // bundle, sets it as the scene's code with the agent as its author, and // answers the new version; stills made before it are stale. func TestNewCodeChangesTheVersionAndMarksStillsStale(t *testing.T) { a, token, sqid, id := agentScene(t) cookies := signedIn(t, a, allowedAddress) made := deck.SceneVersion(sceneOf(t, a, token, sqid, id)) for _, state := range []string{"one", "two"} { agentCall(t, a, http.MethodPut, stillURL(sqid, id, state, made), token, onePixelPNG) } if !stillsCurrent(sceneOf(t, a, token, sqid, id)) { t.Fatal("the stills were not current to begin with") } next := append([]byte("\nv2\n"), sceneBundle...) rec := agentCall(t, a, http.MethodPut, "/api/v1/decks/"+sqid+"/scenes/"+id+"/code", token, next) if rec.Code != http.StatusOK { t.Fatalf("PUT code: status %d\n%s", rec.Code, rec.Body) } out := decode(t, rec) s := sceneOf(t, a, token, sqid, id) if out["ref"] != hashOf(next) || s.Code != hashOf(next) { t.Errorf("code ref: answered %v, scene has %s, want %s", out["ref"], s.Code, hashOf(next)) } if out["version"] != deck.SceneVersion(s) || out["version"] == made { t.Errorf("version answered %v, scene's is %s (was %s)", out["version"], deck.SceneVersion(s), made) } if !strings.HasPrefix(s.Author, "agent:") { t.Errorf("author = %q, want the agent", s.Author) } if stillsCurrent(s) { t.Error("new code left the old stills current") } // The new bundle is served under the sealed route of the deck. rec = mustGet(t, a, "/d/"+sqid+"/scenes/"+id+"/"+hashOf(next), http.StatusOK, cookies) if !bytes.Equal(rec.Body.Bytes(), next) { t.Error("the new bundle's bytes differ from what went up") } // And a still made against the new version is accepted. if rec := agentCall(t, a, http.MethodPut, stillURL(sqid, id, "one", out["version"].(string)), token, onePixelPNG); rec.Code != http.StatusOK { t.Errorf("a still against the new version: status %d\n%s", rec.Code, rec.Body) } } // TestACodeBodyThatIsNotOneHTMLDocumentIsRefused: for both routes, and // over the limit. func TestACodeBodyThatIsNotOneHTMLDocumentIsRefused(t *testing.T) { a, token, sqid, id := agentScene(t) big := append([]byte(""), bytes.Repeat([]byte("x"), 2<<20)...) for name, call := range map[string]struct { method, target string body []byte status int code string }{ "code, a picture": {http.MethodPut, "/scenes/" + id + "/code", onePixelPNG, http.StatusUnprocessableEntity, "not_html"}, "code, text": {http.MethodPut, "/scenes/" + id + "/code", []byte("hello"), http.StatusUnprocessableEntity, "not_html"}, "code, too big": {http.MethodPut, "/scenes/" + id + "/code", big, http.StatusRequestEntityTooLarge, "too_large"}, "code, unknown scene": {http.MethodPut, "/scenes/zzzzzzzzzzzz/code", sceneBundle, http.StatusNotFound, "not_found"}, "bundle, a picture": {http.MethodPost, "/scene-bundles", onePixelPNG, http.StatusUnprocessableEntity, "not_html"}, "bundle, too big": {http.MethodPost, "/scene-bundles", big, http.StatusRequestEntityTooLarge, "too_large"}, } { rec := agentCall(t, a, call.method, "/api/v1/decks/"+sqid+call.target, token, call.body) if rec.Code != call.status || decode(t, rec)["error"] != call.code { t.Errorf("%s: status %d %s, want %d %s", name, rec.Code, rec.Body, call.status, call.code) } } if s := sceneOf(t, a, token, sqid, id); s.Code != hashOf(sceneBundle) { t.Errorf("a refused bundle changed the scene's code to %s", s.Code) } } // TestAStillIsAPictureOfTheRightSize: a PNG or WebP, at most 4 MiB, an // image that decodes at a size the pictures allow. func TestAStillIsAPictureOfTheRightSize(t *testing.T) { a, token, sqid, id := agentScene(t) made := deck.SceneVersion(sceneOf(t, a, token, sqid, id)) big := append(append([]byte{}, onePixelPNG...), bytes.Repeat([]byte{0}, 4<<20)...) // A PNG whose header, checksum right, declares 40000 x 1: it decodes // as far as its size, which is over the 30000 the pictures allow. wide := append([]byte{}, onePixelPNG...) wide[16], wide[17], wide[18], wide[19] = 0, 0, 0x9c, 0x40 binary.BigEndian.PutUint32(wide[29:33], crc32.ChecksumIEEE(wide[12:29])) if cfg, err := png.DecodeConfig(bytes.NewReader(wide)); err != nil || cfg.Width != 40000 { t.Fatalf("the wide PNG is not a valid header of width 40000: %v %+v", err, cfg) } // 10000 x 10000: each edge allowed, the 100 megapixels together over // the budget every decode is held to (svg.MaxDecodePixels). square := append([]byte{}, onePixelPNG...) binary.BigEndian.PutUint32(square[16:20], 10000) binary.BigEndian.PutUint32(square[20:24], 10000) binary.BigEndian.PutUint32(square[29:33], crc32.ChecksumIEEE(square[12:29])) for name, call := range map[string]struct { body []byte status int code string }{ "too many pixels together": {square, http.StatusUnprocessableEntity, "not_an_image"}, "a webp header of 30000 x 30000": {hugeWebP(), http.StatusUnprocessableEntity, "not_an_image"}, "too big": {big, http.StatusRequestEntityTooLarge, "too_large"}, "html": {sceneBundle, http.StatusUnprocessableEntity, "not_an_image"}, "svg": {[]byte(``), http.StatusUnprocessableEntity, "not_an_image"}, "jpeg": {[]byte("\xff\xd8\xff\xe0 not really"), http.StatusUnprocessableEntity, "not_an_image"}, "a broken png": {onePixelPNG[:20], http.StatusUnprocessableEntity, "not_an_image"}, "empty": {nil, http.StatusUnprocessableEntity, "not_an_image"}, "too many pixels": {wide, http.StatusUnprocessableEntity, "not_an_image"}, } { rec := agentCall(t, a, http.MethodPut, stillURL(sqid, id, "one", made), token, call.body) if rec.Code != call.status || decode(t, rec)["error"] != call.code { t.Errorf("%s: status %d %s, want %d %s", name, rec.Code, rec.Body, call.status, call.code) } } if s := sceneOf(t, a, token, sqid, id); len(s.Stills) != 0 { t.Errorf("a refused still was set anyway: %+v", s.Stills) } } // TestWithoutAStoreThereIsNowhereToPutThem: 503, as the pictures answer. func TestWithoutAStoreThereIsNowhereToPutThem(t *testing.T) { a := newApp(t) token := mintAgent(t, a, signedIn(t, a, allowedAddress), "scenes") sqid := apiDeck(t, a, token, "Bare") rec := agentCall(t, a, http.MethodPost, "/api/v1/decks/"+sqid+"/scene-bundles", token, sceneBundle) if rec.Code != http.StatusServiceUnavailable { t.Errorf("a bundle with no store: status %d, want 503", rec.Code) } } // duringWrite lands one hand edit of the scene's words at the moment a // scene write has been checked against the document and not yet made. func duringWrite(t *testing.T, a *testApp, token, sqid, id string) { t.Helper() fired := 0 slides.BeforeSceneWrite = func() { fired++ if fired > 1 { return } apiJSON(t, a, http.MethodPost, "/api/v1/decks/"+sqid+"/ops", token, `{"ops":[{"op":"set_scene","id":"`+id+`","words":{"one":"Landed in between"}}]}`, http.StatusOK) } t.Cleanup(func() { slides.BeforeSceneWrite = nil }) } // TestAHandEditBetweenTheCheckAndTheWriteStillRefusesTheStill: the // version is checked against the document the write lands on, so an edit // that arrives after an earlier check cannot be overwritten by a still // made before it. func TestAHandEditBetweenTheCheckAndTheWriteStillRefusesTheStill(t *testing.T) { a, token, sqid, id := agentScene(t) made := deck.SceneVersion(sceneOf(t, a, token, sqid, id)) duringWrite(t, a, token, sqid, id) rec := agentCall(t, a, http.MethodPut, stillURL(sqid, id, "one", made), token, onePixelPNG) if rec.Code != http.StatusConflict || decode(t, rec)["error"] != "stale" { t.Fatalf("status %d %s, want 409 stale", rec.Code, rec.Body) } s := sceneOf(t, a, token, sqid, id) if len(s.Stills) != 0 { t.Errorf("a still made from the old version was written: %+v", s.Stills) } if s.Words["one"] != "Landed in between" { t.Errorf("the hand edit is not in the scene: %v", s.Words) } } // TestACodeUploadAnswersTheVersionTheWriteLeft: an edit of the words that // lands while the code is being set is in the scene, and so in the // version the answer names. func TestACodeUploadAnswersTheVersionTheWriteLeft(t *testing.T) { a, token, sqid, id := agentScene(t) duringWrite(t, a, token, sqid, id) next := append([]byte("\nv3\n"), sceneBundle...) rec := agentCall(t, a, http.MethodPut, "/api/v1/decks/"+sqid+"/scenes/"+id+"/code", token, next) if rec.Code != http.StatusOK { t.Fatalf("PUT code: status %d\n%s", rec.Code, rec.Body) } s := sceneOf(t, a, token, sqid, id) if s.Words["one"] != "Landed in between" || s.Code != hashOf(next) { t.Fatalf("the scene is not the write's: %+v", s) } if got := decode(t, rec)["version"]; got != deck.SceneVersion(s) { t.Errorf("answered version %v, the scene's is %s", got, deck.SceneVersion(s)) } }