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 \n

a

", "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 in its head. page := []byte(``) key := stageUpload(t, a, deck, cookies, "x.svg", "image/svg+xml", page) reg := postJSON(t, a, deck+"/assets", fmt.Sprintf(`{"ref":%q,"alt":"x"}`, key), cookies) if reg.Code != http.StatusUnprocessableEntity || jsonBody(t, reg)["error"] != "not_an_image" { t.Errorf("an HTML document as a picture: status %d %s, want 422 not_an_image", reg.Code, reg.Body) } } // assertRefusal checks a refusal of a bundle or a preview: the status, // a fixed code for a program, and a message for a developer. The // editor's words for one come later, from the catalog (Task 6). func assertRefusal(t *testing.T, what string, rec *httptest.ResponseRecorder, status int, code string) { t.Helper() if rec.Code != status { t.Errorf("%s: status %d, want %d\n%s", what, rec.Code, status, rec.Body) return } out := jsonBody(t, rec) if out["error"] != code { t.Errorf("%s: error = %v, want %s", what, out["error"], code) } if msg, _ := out["message"].(string); msg == "" || strings.HasPrefix(msg, "slides.") { t.Errorf("%s: message = %q, want a sentence for a developer", what, msg) } } // multipartForm is a form posted as multipart/form-data, as a browser // sends one with that enctype: its fields in order, and the // Content-Type with the boundary. func multipartForm(t *testing.T, fields ...[2]string) (string, []byte) { t.Helper() var buf bytes.Buffer w := multipart.NewWriter(&buf) for _, f := range fields { if err := w.WriteField(f[0], f[1]); err != nil { t.Fatal(err) } } if err := w.Close(); err != nil { t.Fatal(err) } return w.FormDataContentType(), buf.Bytes() } // TestThePreviewAnswersUnderTheSealedPolicy: the code panel's preview // posts unsaved text, as text/html or as a form's one html field (the // editor submits a form into a named frame), and gets it back under // the sealed policy, never cached. Signed-in people of the deck only, // same-origin only, the text at most 2 MiB and the whole request at // most 2 MiB + 64 KiB. func TestThePreviewAnswersUnderTheSealedPolicy(t *testing.T) { a := newSharedApp(t) cookies := signedIn(t, a, allowedAddress) deck := createDeck(t, a, cookies, "Preview") h := productionHandler(t, a) draft := "

draft

" // unknownLength posts with no Content-Length, as a chunked request // arrives: the body is a plain reader and ContentLength is -1. unknownLength := false post := func(contentType string, body []byte, cookies []*http.Cookie, origin string) *httptest.ResponseRecorder { req := httptest.NewRequest(http.MethodPost, deck+"/scenes/preview", bytes.NewReader(body)) if unknownLength { req.Body = io.NopCloser(struct{ io.Reader }{bytes.NewReader(body)}) req.ContentLength = -1 } req.Header.Set("Content-Type", contentType) req.Header.Set("Origin", origin) if origin == testOrigin { req.Header.Set("Sec-Fetch-Site", "same-origin") } else { req.Header.Set("Sec-Fetch-Site", "cross-site") } for _, c := range cookies { req.AddCookie(c) } rec := httptest.NewRecorder() h.ServeHTTP(rec, req) return rec } multiType, multiBody := multipartForm(t, [2]string{"html", draft}) for _, c := range []struct { name, contentType string body []byte }{ {"text/html", "text/html; charset=utf-8", []byte(draft)}, {"a form", "application/x-www-form-urlencoded", []byte(url.Values{"html": {draft}}.Encode())}, {"a multipart form", multiType, multiBody}, } { rec := post(c.contentType, c.body, cookies, testOrigin) if rec.Code != http.StatusOK { t.Errorf("preview as %s: status %d, want 200\n%s", c.name, rec.Code, rec.Body) continue } if rec.Body.String() != draft { t.Errorf("preview as %s answered %q, want the draft", c.name, rec.Body) } assertSealed(t, "the preview as "+c.name, rec) if got := rec.Header().Get("Cache-Control"); got != "no-store" { t.Errorf("preview as %s: Cache-Control = %q, want no-store", c.name, got) } } if rec := post("text/html", []byte(draft), cookies, "https://elsewhere.test"); rec.Code == http.StatusOK { t.Error("a cross-site preview was answered") } if rec := post("text/html", []byte(draft), nil, testOrigin); rec.Code == http.StatusOK { t.Error("a signed-out preview was answered") } theirs := signedIn(t, a, otherAddress) if rec := post("text/html", []byte(draft), theirs, testOrigin); rec.Code != http.StatusNotFound { t.Errorf("a preview on somebody else's deck: status %d, want 404", rec.Code) } big := append([]byte(""), bytes.Repeat([]byte(" "), 2<<20)...) assertRefusal(t, "a preview over 2 MiB", post("text/html", big, cookies, testOrigin), http.StatusRequestEntityTooLarge, "too_large") assertRefusal(t, "a form preview over 2 MiB", post("application/x-www-form-urlencoded", []byte(url.Values{"html": {string(big)}}.Encode()), cookies, testOrigin), http.StatusRequestEntityTooLarge, "too_large") bigType, bigBody := multipartForm(t, [2]string{"html", string(big)}) assertRefusal(t, "a multipart preview over 2 MiB", post(bigType, bigBody, cookies, testOrigin), http.StatusRequestEntityTooLarge, "too_large") // The whole request is held to 2 MiB + 64 KiB, whatever it decodes // to: a form of 1 MiB of text, percent-encoded to three times that, // is refused before it is read. wide := strings.Repeat("<", 1<<20) assertRefusal(t, "a form whose encoding is over the request limit", post("application/x-www-form-urlencoded", []byte(url.Values{"html": {wide}}.Encode()), cookies, testOrigin), http.StatusRequestEntityTooLarge, "too_large") // A form carries the html field and nothing else. assertRefusal(t, "a form with another field", post("application/x-www-form-urlencoded", []byte(url.Values{"html": {draft}, "other": {"x"}}.Encode()), cookies, testOrigin), http.StatusBadRequest, "invalid") otherType, otherBody := multipartForm(t, [2]string{"html", draft}, [2]string{"other", "x"}) assertRefusal(t, "a multipart form with another field", post(otherType, otherBody, cookies, testOrigin), http.StatusBadRequest, "invalid") twiceType, twiceBody := multipartForm(t, [2]string{"html", draft}, [2]string{"html", draft}) assertRefusal(t, "a multipart form with html twice", post(twiceType, twiceBody, cookies, testOrigin), http.StatusBadRequest, "invalid") // A small html part, its closing boundary, then megabytes of // epilogue: the multipart parser stops at the boundary, but the // request is still over the limit and is refused, with its length // declared or not. Under the limit, an epilogue is harmless. epType, epBody := multipartForm(t, [2]string{"html", draft}) small := append(append([]byte{}, epBody...), "\r\nepilogue\r\n"...) huge := append(append([]byte{}, epBody...), bytes.Repeat([]byte("x"), 3<<20)...) for _, unknown := range []bool{false, true} { unknownLength = unknown what := fmt.Sprintf(" (length unknown: %t)", unknown) assertRefusal(t, "a multipart preview with a huge epilogue"+what, post(epType, huge, cookies, testOrigin), http.StatusRequestEntityTooLarge, "too_large") if rec := post(epType, small, cookies, testOrigin); rec.Code != http.StatusOK || rec.Body.String() != draft { t.Errorf("a multipart preview with a small epilogue%s: status %d %q, want 200 and the draft", what, rec.Code, rec.Body) } if rec := post(epType, epBody, cookies, testOrigin); rec.Code != http.StatusOK { t.Errorf("a multipart preview%s: status %d, want 200", what, rec.Code) } } unknownLength = false assertRefusal(t, "a JSON preview", post("application/json", []byte(`{"html":"x"}`), cookies, testOrigin), http.StatusUnsupportedMediaType, "unsupported_type") if !strings.Contains(sealedPolicy, "sandbox allow-scripts;") { t.Fatal("the sealed policy lost its sandbox") } }