package slidestest // A scene's bundle, end to end (scenes and clips spec §3, §8.4, §8.6; // internal/slides/scenes.go): uploaded and registered as an asset of // kind scene, served only through the sealed routes of the deck whose // scene names it, under the sealed policy and nothing else, and the // editor's preview of unsaved code under the same policy. import ( "bytes" "fmt" "io" "mime/multipart" "net/http" "net/http/httptest" "net/url" "strings" "testing" slides "amadan.net/oficina/slides/internal/slides" ) // sealedPolicy is the plan's Global Constraints header, spelled out // here rather than read from slides.SealedPolicy, so a change to the // constant is a failing test rather than a quiet one. const sealedPolicy = "sandbox allow-scripts; default-src 'none'; script-src 'unsafe-inline'; " + "style-src 'unsafe-inline'; img-src data: blob:; font-src data:; media-src data: blob:; frame-ancestors 'self'" // sceneBundle is the smallest bundle there is: one HTML document that // answers ready. var sceneBundle = []byte("\n
\n") // uploadScene runs the upload flow for a bundle (sign as text/html, // PUT, register) and returns the ref registration answered with. func uploadScene(t *testing.T, a *testApp, deck string, cookies []*http.Cookie, body []byte) string { t.Helper() key := stageUpload(t, a, deck, cookies, "scene.html", "text/html", body) reg := postJSON(t, a, deck+"/assets", fmt.Sprintf(`{"ref":%q,"name":"scene.html"}`, key), cookies) if reg.Code != http.StatusOK { t.Fatalf("POST %s/assets (a scene): status %d, want 200\n%s", deck, reg.Code, reg.Body) } out := jsonBody(t, reg) if out["kind"] != "scene" { t.Errorf("registering a bundle answered kind %v, want scene", out["kind"]) } ref, _ := out["ref"].(string) if ref != hashOf(body) { t.Fatalf("registering a bundle answered ref %q, want the hash of its bytes", ref) } return ref } // addScene puts a two-state scene whose code is ref into the deck over // the API and returns its id. func addScene(t *testing.T, a *testApp, token, sqid, ref string) string { t.Helper() out := apiJSON(t, a, http.MethodPost, "/api/v1/decks/"+sqid+"/ops", token, `{"ops":[{"op":"add_scene","name":"Boxes","code":"`+ref+`","states":[`+ `{"id":"one","name":"One","description":"One box"},{"id":"two","name":"Two","description":"Two boxes"}],`+ `"words":{"one":"First","two":"Second"}}]}`, http.StatusOK) id, _ := out["ids"].(map[string]any)["0"].(string) if id == "" { t.Fatalf("add_scene minted no id: %v", out) } return id } // TestTheSceneRouteSealsItsDocument: through the production stack, the // bundle comes back byte for byte with the sealed policy as its only // policy (the app-wide one would only narrow it, and break the // sandbox's scripts), framing allowed to this app alone, no sniffing, // no referrer, and a year's private cache for a content address. func TestTheSceneRouteSealsItsDocument(t *testing.T) { if slides.SealedPolicy != sealedPolicy { t.Fatalf("slides.SealedPolicy = %q, want the plan's %q", slides.SealedPolicy, sealedPolicy) } a := newAppWithStore(t, dirStore(t)) cookies := signedIn(t, a, allowedAddress) token := mintAgent(t, a, cookies, "scenes") sqid := apiDeck(t, a, token, "Sealed") ref := uploadScene(t, a, "/d/"+sqid, cookies, sceneBundle) id := addScene(t, a, token, sqid, ref) h := productionHandler(t, a) rec := get(t, h, "/d/"+sqid+"/scenes/"+id+"/"+ref, cookies...) if rec.Code != http.StatusOK { t.Fatalf("GET the scene: status %d, want 200\n%s", rec.Code, rec.Body) } if !bytes.Equal(rec.Body.Bytes(), sceneBundle) { t.Errorf("the scene came back as %q, want the bytes that went up", rec.Body) } assertSealed(t, "the scene route", rec) if got := rec.Header().Get("Cache-Control"); got != "private, max-age=31536000, immutable" { t.Errorf("Cache-Control = %q, want a year, private and immutable", got) } if got := rec.Header().Get("ETag"); got != `"`+ref+`"` { t.Errorf("ETag = %q, want the ref", got) } } // assertSealed checks the headers every sealed answer carries. func assertSealed(t *testing.T, what string, rec *httptest.ResponseRecorder) { t.Helper() if got := rec.Header().Values("Content-Security-Policy"); len(got) != 1 || got[0] != sealedPolicy { t.Errorf("%s: CSP = %q, want exactly the sealed policy", what, got) } for header, want := range map[string]string{ "Content-Type": "text/html; charset=utf-8", "X-Content-Type-Options": "nosniff", "Referrer-Policy": "no-referrer", // rastrillo's DENY would contradict frame-ancestors 'self' in a // browser that reads only the older header. "X-Frame-Options": "SAMEORIGIN", } { if got := rec.Header().Get(header); got != want { t.Errorf("%s: %s = %q, want %q", what, header, got, want) } } } // TestASceneIsServedOnlyThroughItsDeck: the bundle is served on the // three surfaces only when the deck's scene names it as its code and // the bundle was registered for that deck; never by the picture // routes, never for another deck, a picture, an unverified upload or a // scene that names other code; and always from this app, never a // redirect to the bucket, which would lose the sealed policy. func TestASceneIsServedOnlyThroughItsDeck(t *testing.T) { a := newAppWithStore(t, dirStore(t)) cookies := signedIn(t, a, allowedAddress) token := mintAgent(t, a, cookies, "scenes") sqid := apiDeck(t, a, token, "Mine") deck := "/d/" + sqid ref := uploadScene(t, a, deck, cookies, sceneBundle) id := addScene(t, a, token, sqid, ref) scene := "/scenes/" + id + "/" + ref // The three surfaces, each with its own capability. if rec := mustGet(t, a, deck+scene, http.StatusOK, cookies); !bytes.Equal(rec.Body.Bytes(), sceneBundle) { t.Errorf("GET %s%s: the bytes differ", deck, scene) } share := mintShareLink(t, a, deck, cookies) mustGet(t, a, "/s/"+share+scene, http.StatusOK, nil) out := apiJSON(t, a, http.MethodPost, "/api/v1/decks/"+sqid+"/present", token, "", http.StatusOK) session, _ := out["session"].(string) mustGet(t, a, "/p/"+session+scene, http.StatusOK, nil) notFound := func(what, target string, cookies ...*http.Cookie) { t.Helper() if rec := get(t, a, target, cookies...); rec.Code != http.StatusNotFound { t.Errorf("%s: GET %s = %d, want 404", what, target, rec.Code) } } // Not by the picture routes, even once the deck's assets map names // the ref. apiJSON(t, a, http.MethodPost, "/api/v1/decks/"+sqid+"/ops", token, `{"ops":[{"op":"register_asset","id":"sceneasasset","ref":"`+ref+`","name":"x.svg","width":1,"height":1,"alt":"x"}]}`, http.StatusOK) notFound("a scene as a picture", deck+"/assets/"+ref, cookies...) notFound("a scene as a shared picture", "/s/"+share+"/assets/"+ref) notFound("a scene as a presented picture", "/p/"+session+"/assets/"+ref) // Not under another scene id, nor a ref the scene does not name. notFound("an unknown scene", deck+"/scenes/abcdefghijkm/"+ref, cookies...) notFound("a malformed scene id", deck+"/scenes/ABC/"+ref, cookies...) other := uploadScene(t, a, deck, cookies, []byte("other
")) notFound("a registered bundle the scene does not name", deck+"/scenes/"+id+"/"+other, cookies...) // Not for another deck, even one whose scene names the same code: // the bundle was registered for this deck, not that one. theirs := apiDeck(t, a, token, "Other") theirID := addScene(t, a, token, theirs, ref) notFound("another deck naming the same code", "/d/"+theirs+"/scenes/"+theirID+"/"+ref, cookies...) otherShare := mintShareLink(t, a, "/d/"+theirs, cookies) notFound("another deck's share link", "/s/"+otherShare+"/scenes/"+theirID+"/"+ref) notFound("another deck's share link, this deck's scene", "/s/"+otherShare+scene) notFound("an unknown share link", "/s/nosuchtoken"+scene) notFound("an unknown presentation", "/p/nosuchsess"+scene) // Not a picture named as a scene's code. picture := upload(t, a, deck, cookies, "dot.png", "image/png", onePixelPNG, "A dot") pictureRef := picture["ref"].(string) pictureScene := addScene(t, a, token, sqid, pictureRef) notFound("a picture as a scene", deck+"/scenes/"+pictureScene+"/"+pictureRef, cookies...) // Not a bundle staged and never registered, however firmly the deck // names it: blobs.Dir holds the staged bytes under their own hash. unverified := []byte("") stageUpload(t, a, deck, cookies, "u.html", "text/html", unverified) unverifiedScene := addScene(t, a, token, sqid, hashOf(unverified)) notFound("an unverified bundle", deck+"/scenes/"+unverifiedScene+"/"+hashOf(unverified), cookies...) // Not to somebody signed out. if rec := get(t, a, deck+scene); rec.Code == http.StatusOK { t.Errorf("GET %s%s signed out = 200", deck, scene) } // On a store that presigns, the bytes still come from this app. store := &presigningStore{Store: dirStore(t)} b := newAppWithStore(t, store) bCookies := signedIn(t, b, allowedAddress) bToken := mintAgent(t, b, bCookies, "scenes") bSqid := apiDeck(t, b, bToken, "Bucket") signed := jsonBody(t, postJSON(t, b, "/d/"+bSqid+"/uploads", fmt.Sprintf(`{"name":"s.html","size":%d,"type":"text/html","hash":%q}`, len(sceneBundle), hashOf(sceneBundle)), bCookies)) staged, _ := signed["ref"].(string) store.putDirect(staged, sceneBundle) reg := postJSON(t, b, "/d/"+bSqid+"/assets", fmt.Sprintf(`{"ref":%q}`, staged), bCookies) if reg.Code != http.StatusOK { t.Fatalf("registering on a presigning store: status %d\n%s", reg.Code, reg.Body) } bID := addScene(t, b, bToken, bSqid, hashOf(sceneBundle)) rec := get(t, b, "/d/"+bSqid+"/scenes/"+bID+"/"+hashOf(sceneBundle), bCookies...) if rec.Code != http.StatusOK || !bytes.Equal(rec.Body.Bytes(), sceneBundle) { t.Errorf("a scene on a presigning store: status %d (Location %q), want 200 and the bytes", rec.Code, rec.Header().Get("Location")) } } // TestTheBundleMustBeHTML: a bundle is one HTML document of at most // 2 MiB, judged by its bytes; anything else is refused at sign or at // registration, and a refusal records nothing. func TestTheBundleMustBeHTML(t *testing.T) { a := newAppWithStore(t, dirStore(t)) cookies := signedIn(t, a, allowedAddress) deck := createDeck(t, a, cookies, "Bundles") // Signing refuses a size over the limit before any bytes move. rec := postJSON(t, a, deck+"/uploads", fmt.Sprintf(`{"name":"big.html","size":%d,"type":"text/html","hash":%q}`, 2<<20+1, hashOf(sceneBundle)), cookies) assertRefusal(t, "signing a 2 MiB + 1 bundle", rec, http.StatusRequestEntityTooLarge, "too_large") refused := func(name string, body []byte) { t.Helper() key := stageUpload(t, a, deck, cookies, "x.html", "text/html", body) reg := postJSON(t, a, deck+"/assets", fmt.Sprintf(`{"ref":%q}`, key), cookies) assertRefusal(t, name, reg, http.StatusUnprocessableEntity, "not_html") } refused("a PNG", onePixelPNG) refused("plain text", []byte("hello, world")) refused("an HTML fragment", []byte("no document
")) refused("an SVG", []byte(``)) refused("not UTF-8", []byte("\xff\xfe
")) refused("a doctype that is not html", []byte("x
")) refused("empty after the mark", []byte("\xef\xbb\xbf ")) if n := scalar(t, a, "SELECT count(*) FROM scene_bundles"); n != "0" { t.Errorf("refused bundles left %s scene_bundles rows, want 0", n) } // The shapes a document may open with: a byte-order mark, white // space, either opening in any case. for _, body := range []string{ "\xef\xbb\xbf\n\t \na
", "b", " \nc", "", } { uploadScene(t, a, deck, cookies, []byte(body)) } // Over the limit once it has landed: refused at the PUT on the // development path... big := append([]byte(""), bytes.Repeat([]byte(" "), 2<<20)...) signed := jsonBody(t, postJSON(t, a, deck+"/uploads", fmt.Sprintf(`{"name":"big.html","size":%d,"type":"text/html","hash":%q}`, 100, hashOf(big)), cookies)) assertRefusal(t, "PUT a bundle over 2 MiB", putBytes(t, a, signed["url"].(string), "text/html", big, cookies), http.StatusRequestEntityTooLarge, "too_large") // ...and at registration on a bucket, where the PUT never came here. store := &presigningStore{Store: dirStore(t)} b := newAppWithStore(t, store) bCookies := signedIn(t, b, allowedAddress) bDeck := createDeck(t, b, bCookies, "Bucket") staged := jsonBody(t, postJSON(t, b, bDeck+"/uploads", fmt.Sprintf(`{"name":"big.html","size":%d,"type":"text/html","hash":%q}`, 100, hashOf(big)), bCookies))["ref"].(string) store.putDirect(staged, big) assertRefusal(t, "registering a landed bundle over 2 MiB", postJSON(t, b, bDeck+"/assets", fmt.Sprintf(`{"ref":%q}`, staged), bCookies), http.StatusRequestEntityTooLarge, "too_large") // And the other way round: an HTML document uploaded as a picture // is not a picture, even with an