| 1 | package slidestest |
| 2 | |
| 3 | // A scene's bundle, end to end (scenes and clips spec §3, §8.4, §8.6; |
| 4 | // internal/slides/scenes.go): uploaded and registered as an asset of |
| 5 | // kind scene, served only through the sealed routes of the deck whose |
| 6 | // scene names it, under the sealed policy and nothing else, and the |
| 7 | // editor's preview of unsaved code under the same policy. |
| 8 | |
| 9 | import ( |
| 10 | "bytes" |
| 11 | "fmt" |
| 12 | "io" |
| 13 | "mime/multipart" |
| 14 | "net/http" |
| 15 | "net/http/httptest" |
| 16 | "net/url" |
| 17 | "strings" |
| 18 | "testing" |
| 19 | |
| 20 | slides "amadan.net/oficina/slides/internal/slides" |
| 21 | ) |
| 22 | |
| 23 | // sealedPolicy is the plan's Global Constraints header, spelled out |
| 24 | // here rather than read from slides.SealedPolicy, so a change to the |
| 25 | // constant is a failing test rather than a quiet one. |
| 26 | const sealedPolicy = "sandbox allow-scripts; default-src 'none'; script-src 'unsafe-inline'; " + |
| 27 | "style-src 'unsafe-inline'; img-src data: blob:; font-src data:; media-src data: blob:; frame-ancestors 'self'" |
| 28 | |
| 29 | // sceneBundle is the smallest bundle there is: one HTML document that |
| 30 | // answers ready. |
| 31 | var sceneBundle = []byte("<!doctype html>\n<html><body><script>parent.postMessage({type: 'ready'}, '*')</script></body></html>\n") |
| 32 | |
| 33 | // uploadScene runs the upload flow for a bundle (sign as text/html, |
| 34 | // PUT, register) and returns the ref registration answered with. |
| 35 | func uploadScene(t *testing.T, a *testApp, deck string, cookies []*http.Cookie, body []byte) string { |
| 36 | t.Helper() |
| 37 | key := stageUpload(t, a, deck, cookies, "scene.html", "text/html", body) |
| 38 | reg := postJSON(t, a, deck+"/assets", fmt.Sprintf(`{"ref":%q,"name":"scene.html"}`, key), cookies) |
| 39 | if reg.Code != http.StatusOK { |
| 40 | t.Fatalf("POST %s/assets (a scene): status %d, want 200\n%s", deck, reg.Code, reg.Body) |
| 41 | } |
| 42 | out := jsonBody(t, reg) |
| 43 | if out["kind"] != "scene" { |
| 44 | t.Errorf("registering a bundle answered kind %v, want scene", out["kind"]) |
| 45 | } |
| 46 | ref, _ := out["ref"].(string) |
| 47 | if ref != hashOf(body) { |
| 48 | t.Fatalf("registering a bundle answered ref %q, want the hash of its bytes", ref) |
| 49 | } |
| 50 | return ref |
| 51 | } |
| 52 | |
| 53 | // addScene puts a two-state scene whose code is ref into the deck over |
| 54 | // the API and returns its id. |
| 55 | func addScene(t *testing.T, a *testApp, token, sqid, ref string) string { |
| 56 | t.Helper() |
| 57 | out := apiJSON(t, a, http.MethodPost, "/api/v1/decks/"+sqid+"/ops", token, |
| 58 | `{"ops":[{"op":"add_scene","name":"Boxes","code":"`+ref+`","states":[`+ |
| 59 | `{"id":"one","name":"One","description":"One box"},{"id":"two","name":"Two","description":"Two boxes"}],`+ |
| 60 | `"words":{"one":"First","two":"Second"}}]}`, http.StatusOK) |
| 61 | id, _ := out["ids"].(map[string]any)["0"].(string) |
| 62 | if id == "" { |
| 63 | t.Fatalf("add_scene minted no id: %v", out) |
| 64 | } |
| 65 | return id |
| 66 | } |
| 67 | |
| 68 | // TestTheSceneRouteSealsItsDocument: through the production stack, the |
| 69 | // bundle comes back byte for byte with the sealed policy as its only |
| 70 | // policy (the app-wide one would only narrow it, and break the |
| 71 | // sandbox's scripts), framing allowed to this app alone, no sniffing, |
| 72 | // no referrer, and a year's private cache for a content address. |
| 73 | func TestTheSceneRouteSealsItsDocument(t *testing.T) { |
| 74 | if slides.SealedPolicy != sealedPolicy { |
| 75 | t.Fatalf("slides.SealedPolicy = %q, want the plan's %q", slides.SealedPolicy, sealedPolicy) |
| 76 | } |
| 77 | a := newAppWithStore(t, dirStore(t)) |
| 78 | cookies := signedIn(t, a, allowedAddress) |
| 79 | token := mintAgent(t, a, cookies, "scenes") |
| 80 | sqid := apiDeck(t, a, token, "Sealed") |
| 81 | ref := uploadScene(t, a, "/d/"+sqid, cookies, sceneBundle) |
| 82 | id := addScene(t, a, token, sqid, ref) |
| 83 | |
| 84 | h := productionHandler(t, a) |
| 85 | rec := get(t, h, "/d/"+sqid+"/scenes/"+id+"/"+ref, cookies...) |
| 86 | if rec.Code != http.StatusOK { |
| 87 | t.Fatalf("GET the scene: status %d, want 200\n%s", rec.Code, rec.Body) |
| 88 | } |
| 89 | if !bytes.Equal(rec.Body.Bytes(), sceneBundle) { |
| 90 | t.Errorf("the scene came back as %q, want the bytes that went up", rec.Body) |
| 91 | } |
| 92 | assertSealed(t, "the scene route", rec) |
| 93 | if got := rec.Header().Get("Cache-Control"); got != "private, max-age=31536000, immutable" { |
| 94 | t.Errorf("Cache-Control = %q, want a year, private and immutable", got) |
| 95 | } |
| 96 | if got := rec.Header().Get("ETag"); got != `"`+ref+`"` { |
| 97 | t.Errorf("ETag = %q, want the ref", got) |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | // assertSealed checks the headers every sealed answer carries. |
| 102 | func assertSealed(t *testing.T, what string, rec *httptest.ResponseRecorder) { |
| 103 | t.Helper() |
| 104 | if got := rec.Header().Values("Content-Security-Policy"); len(got) != 1 || got[0] != sealedPolicy { |
| 105 | t.Errorf("%s: CSP = %q, want exactly the sealed policy", what, got) |
| 106 | } |
| 107 | for header, want := range map[string]string{ |
| 108 | "Content-Type": "text/html; charset=utf-8", |
| 109 | "X-Content-Type-Options": "nosniff", |
| 110 | "Referrer-Policy": "no-referrer", |
| 111 | // rastrillo's DENY would contradict frame-ancestors 'self' in a |
| 112 | // browser that reads only the older header. |
| 113 | "X-Frame-Options": "SAMEORIGIN", |
| 114 | } { |
| 115 | if got := rec.Header().Get(header); got != want { |
| 116 | t.Errorf("%s: %s = %q, want %q", what, header, got, want) |
| 117 | } |
| 118 | } |
| 119 | } |
| 120 | |
| 121 | // TestASceneIsServedOnlyThroughItsDeck: the bundle is served on the |
| 122 | // three surfaces only when the deck's scene names it as its code and |
| 123 | // the bundle was registered for that deck; never by the picture |
| 124 | // routes, never for another deck, a picture, an unverified upload or a |
| 125 | // scene that names other code; and always from this app, never a |
| 126 | // redirect to the bucket, which would lose the sealed policy. |
| 127 | func TestASceneIsServedOnlyThroughItsDeck(t *testing.T) { |
| 128 | a := newAppWithStore(t, dirStore(t)) |
| 129 | cookies := signedIn(t, a, allowedAddress) |
| 130 | token := mintAgent(t, a, cookies, "scenes") |
| 131 | sqid := apiDeck(t, a, token, "Mine") |
| 132 | deck := "/d/" + sqid |
| 133 | ref := uploadScene(t, a, deck, cookies, sceneBundle) |
| 134 | id := addScene(t, a, token, sqid, ref) |
| 135 | scene := "/scenes/" + id + "/" + ref |
| 136 | |
| 137 | // The three surfaces, each with its own capability. |
| 138 | if rec := mustGet(t, a, deck+scene, http.StatusOK, cookies); !bytes.Equal(rec.Body.Bytes(), sceneBundle) { |
| 139 | t.Errorf("GET %s%s: the bytes differ", deck, scene) |
| 140 | } |
| 141 | share := mintShareLink(t, a, deck, cookies) |
| 142 | mustGet(t, a, "/s/"+share+scene, http.StatusOK, nil) |
| 143 | out := apiJSON(t, a, http.MethodPost, "/api/v1/decks/"+sqid+"/present", token, "", http.StatusOK) |
| 144 | session, _ := out["session"].(string) |
| 145 | mustGet(t, a, "/p/"+session+scene, http.StatusOK, nil) |
| 146 | |
| 147 | notFound := func(what, target string, cookies ...*http.Cookie) { |
| 148 | t.Helper() |
| 149 | if rec := get(t, a, target, cookies...); rec.Code != http.StatusNotFound { |
| 150 | t.Errorf("%s: GET %s = %d, want 404", what, target, rec.Code) |
| 151 | } |
| 152 | } |
| 153 | // Not by the picture routes, even once the deck's assets map names |
| 154 | // the ref. |
| 155 | apiJSON(t, a, http.MethodPost, "/api/v1/decks/"+sqid+"/ops", token, |
| 156 | `{"ops":[{"op":"register_asset","id":"sceneasasset","ref":"`+ref+`","name":"x.svg","width":1,"height":1,"alt":"x"}]}`, http.StatusOK) |
| 157 | notFound("a scene as a picture", deck+"/assets/"+ref, cookies...) |
| 158 | notFound("a scene as a shared picture", "/s/"+share+"/assets/"+ref) |
| 159 | notFound("a scene as a presented picture", "/p/"+session+"/assets/"+ref) |
| 160 | |
| 161 | // Not under another scene id, nor a ref the scene does not name. |
| 162 | notFound("an unknown scene", deck+"/scenes/abcdefghijkm/"+ref, cookies...) |
| 163 | notFound("a malformed scene id", deck+"/scenes/ABC/"+ref, cookies...) |
| 164 | other := uploadScene(t, a, deck, cookies, []byte("<!DOCTYPE html><p>other</p>")) |
| 165 | notFound("a registered bundle the scene does not name", deck+"/scenes/"+id+"/"+other, cookies...) |
| 166 | |
| 167 | // Not for another deck, even one whose scene names the same code: |
| 168 | // the bundle was registered for this deck, not that one. |
| 169 | theirs := apiDeck(t, a, token, "Other") |
| 170 | theirID := addScene(t, a, token, theirs, ref) |
| 171 | notFound("another deck naming the same code", "/d/"+theirs+"/scenes/"+theirID+"/"+ref, cookies...) |
| 172 | otherShare := mintShareLink(t, a, "/d/"+theirs, cookies) |
| 173 | notFound("another deck's share link", "/s/"+otherShare+"/scenes/"+theirID+"/"+ref) |
| 174 | notFound("another deck's share link, this deck's scene", "/s/"+otherShare+scene) |
| 175 | notFound("an unknown share link", "/s/nosuchtoken"+scene) |
| 176 | notFound("an unknown presentation", "/p/nosuchsess"+scene) |
| 177 | |
| 178 | // Not a picture named as a scene's code. |
| 179 | picture := upload(t, a, deck, cookies, "dot.png", "image/png", onePixelPNG, "A dot") |
| 180 | pictureRef := picture["ref"].(string) |
| 181 | pictureScene := addScene(t, a, token, sqid, pictureRef) |
| 182 | notFound("a picture as a scene", deck+"/scenes/"+pictureScene+"/"+pictureRef, cookies...) |
| 183 | |
| 184 | // Not a bundle staged and never registered, however firmly the deck |
| 185 | // names it: blobs.Dir holds the staged bytes under their own hash. |
| 186 | unverified := []byte("<!doctype html><script>parent.postMessage('unverified', '*')</script>") |
| 187 | stageUpload(t, a, deck, cookies, "u.html", "text/html", unverified) |
| 188 | unverifiedScene := addScene(t, a, token, sqid, hashOf(unverified)) |
| 189 | notFound("an unverified bundle", deck+"/scenes/"+unverifiedScene+"/"+hashOf(unverified), cookies...) |
| 190 | |
| 191 | // Not to somebody signed out. |
| 192 | if rec := get(t, a, deck+scene); rec.Code == http.StatusOK { |
| 193 | t.Errorf("GET %s%s signed out = 200", deck, scene) |
| 194 | } |
| 195 | |
| 196 | // On a store that presigns, the bytes still come from this app. |
| 197 | store := &presigningStore{Store: dirStore(t)} |
| 198 | b := newAppWithStore(t, store) |
| 199 | bCookies := signedIn(t, b, allowedAddress) |
| 200 | bToken := mintAgent(t, b, bCookies, "scenes") |
| 201 | bSqid := apiDeck(t, b, bToken, "Bucket") |
| 202 | signed := jsonBody(t, postJSON(t, b, "/d/"+bSqid+"/uploads", |
| 203 | fmt.Sprintf(`{"name":"s.html","size":%d,"type":"text/html","hash":%q}`, len(sceneBundle), hashOf(sceneBundle)), bCookies)) |
| 204 | staged, _ := signed["ref"].(string) |
| 205 | store.putDirect(staged, sceneBundle) |
| 206 | reg := postJSON(t, b, "/d/"+bSqid+"/assets", fmt.Sprintf(`{"ref":%q}`, staged), bCookies) |
| 207 | if reg.Code != http.StatusOK { |
| 208 | t.Fatalf("registering on a presigning store: status %d\n%s", reg.Code, reg.Body) |
| 209 | } |
| 210 | bID := addScene(t, b, bToken, bSqid, hashOf(sceneBundle)) |
| 211 | rec := get(t, b, "/d/"+bSqid+"/scenes/"+bID+"/"+hashOf(sceneBundle), bCookies...) |
| 212 | if rec.Code != http.StatusOK || !bytes.Equal(rec.Body.Bytes(), sceneBundle) { |
| 213 | t.Errorf("a scene on a presigning store: status %d (Location %q), want 200 and the bytes", rec.Code, rec.Header().Get("Location")) |
| 214 | } |
| 215 | } |
| 216 | |
| 217 | // TestTheBundleMustBeHTML: a bundle is one HTML document of at most |
| 218 | // 2 MiB, judged by its bytes; anything else is refused at sign or at |
| 219 | // registration, and a refusal records nothing. |
| 220 | func TestTheBundleMustBeHTML(t *testing.T) { |
| 221 | a := newAppWithStore(t, dirStore(t)) |
| 222 | cookies := signedIn(t, a, allowedAddress) |
| 223 | deck := createDeck(t, a, cookies, "Bundles") |
| 224 | |
| 225 | // Signing refuses a size over the limit before any bytes move. |
| 226 | rec := postJSON(t, a, deck+"/uploads", |
| 227 | fmt.Sprintf(`{"name":"big.html","size":%d,"type":"text/html","hash":%q}`, 2<<20+1, hashOf(sceneBundle)), cookies) |
| 228 | assertRefusal(t, "signing a 2 MiB + 1 bundle", rec, http.StatusRequestEntityTooLarge, "too_large") |
| 229 | |
| 230 | refused := func(name string, body []byte) { |
| 231 | t.Helper() |
| 232 | key := stageUpload(t, a, deck, cookies, "x.html", "text/html", body) |
| 233 | reg := postJSON(t, a, deck+"/assets", fmt.Sprintf(`{"ref":%q}`, key), cookies) |
| 234 | assertRefusal(t, name, reg, http.StatusUnprocessableEntity, "not_html") |
| 235 | } |
| 236 | refused("a PNG", onePixelPNG) |
| 237 | refused("plain text", []byte("hello, world")) |
| 238 | refused("an HTML fragment", []byte("<p>no document</p>")) |
| 239 | refused("an SVG", []byte(`<svg xmlns="http://www.w3.org/2000/svg"></svg>`)) |
| 240 | refused("not UTF-8", []byte("<!doctype html><p>\xff\xfe</p>")) |
| 241 | refused("a doctype that is not html", []byte("<!doctype htmlx><p>x</p>")) |
| 242 | refused("empty after the mark", []byte("\xef\xbb\xbf ")) |
| 243 | if n := scalar(t, a, "SELECT count(*) FROM scene_bundles"); n != "0" { |
| 244 | t.Errorf("refused bundles left %s scene_bundles rows, want 0", n) |
| 245 | } |
| 246 | |
| 247 | // The shapes a document may open with: a byte-order mark, white |
| 248 | // space, either opening in any case. |
| 249 | for _, body := range []string{ |
| 250 | "\xef\xbb\xbf\n\t <!DOCTYPE HTML>\n<p>a</p>", |
| 251 | "<html lang=\"en\"><body>b</body></html>", |
| 252 | " <HTML>\n<body>c</body></HTML>", |
| 253 | "<!doctype html>", |
| 254 | } { |
| 255 | uploadScene(t, a, deck, cookies, []byte(body)) |
| 256 | } |
| 257 | |
| 258 | // Over the limit once it has landed: refused at the PUT on the |
| 259 | // development path... |
| 260 | big := append([]byte("<!doctype html>"), bytes.Repeat([]byte(" "), 2<<20)...) |
| 261 | signed := jsonBody(t, postJSON(t, a, deck+"/uploads", |
| 262 | fmt.Sprintf(`{"name":"big.html","size":%d,"type":"text/html","hash":%q}`, 100, hashOf(big)), cookies)) |
| 263 | assertRefusal(t, "PUT a bundle over 2 MiB", putBytes(t, a, signed["url"].(string), "text/html", big, cookies), http.StatusRequestEntityTooLarge, "too_large") |
| 264 | // ...and at registration on a bucket, where the PUT never came here. |
| 265 | store := &presigningStore{Store: dirStore(t)} |
| 266 | b := newAppWithStore(t, store) |
| 267 | bCookies := signedIn(t, b, allowedAddress) |
| 268 | bDeck := createDeck(t, b, bCookies, "Bucket") |
| 269 | staged := jsonBody(t, postJSON(t, b, bDeck+"/uploads", |
| 270 | fmt.Sprintf(`{"name":"big.html","size":%d,"type":"text/html","hash":%q}`, 100, hashOf(big)), bCookies))["ref"].(string) |
| 271 | store.putDirect(staged, big) |
| 272 | assertRefusal(t, "registering a landed bundle over 2 MiB", |
| 273 | postJSON(t, b, bDeck+"/assets", fmt.Sprintf(`{"ref":%q}`, staged), bCookies), http.StatusRequestEntityTooLarge, "too_large") |
| 274 | |
| 275 | // And the other way round: an HTML document uploaded as a picture |
| 276 | // is not a picture, even with an <svg> in its head. |
| 277 | page := []byte(`<!doctype html><html><body><svg xmlns="http://www.w3.org/2000/svg"></svg></body></html>`) |
| 278 | key := stageUpload(t, a, deck, cookies, "x.svg", "image/svg+xml", page) |
| 279 | reg := postJSON(t, a, deck+"/assets", fmt.Sprintf(`{"ref":%q,"alt":"x"}`, key), cookies) |
| 280 | if reg.Code != http.StatusUnprocessableEntity || jsonBody(t, reg)["error"] != "not_an_image" { |
| 281 | t.Errorf("an HTML document as a picture: status %d %s, want 422 not_an_image", reg.Code, reg.Body) |
| 282 | } |
| 283 | } |
| 284 | |
| 285 | // assertRefusal checks a refusal of a bundle or a preview: the status, |
| 286 | // a fixed code for a program, and a message for a developer. The |
| 287 | // editor's words for one come later, from the catalog (Task 6). |
| 288 | func assertRefusal(t *testing.T, what string, rec *httptest.ResponseRecorder, status int, code string) { |
| 289 | t.Helper() |
| 290 | if rec.Code != status { |
| 291 | t.Errorf("%s: status %d, want %d\n%s", what, rec.Code, status, rec.Body) |
| 292 | return |
| 293 | } |
| 294 | out := jsonBody(t, rec) |
| 295 | if out["error"] != code { |
| 296 | t.Errorf("%s: error = %v, want %s", what, out["error"], code) |
| 297 | } |
| 298 | if msg, _ := out["message"].(string); msg == "" || strings.HasPrefix(msg, "slides.") { |
| 299 | t.Errorf("%s: message = %q, want a sentence for a developer", what, msg) |
| 300 | } |
| 301 | } |
| 302 | |
| 303 | // multipartForm is a form posted as multipart/form-data, as a browser |
| 304 | // sends one with that enctype: its fields in order, and the |
| 305 | // Content-Type with the boundary. |
| 306 | func multipartForm(t *testing.T, fields ...[2]string) (string, []byte) { |
| 307 | t.Helper() |
| 308 | var buf bytes.Buffer |
| 309 | w := multipart.NewWriter(&buf) |
| 310 | for _, f := range fields { |
| 311 | if err := w.WriteField(f[0], f[1]); err != nil { |
| 312 | t.Fatal(err) |
| 313 | } |
| 314 | } |
| 315 | if err := w.Close(); err != nil { |
| 316 | t.Fatal(err) |
| 317 | } |
| 318 | return w.FormDataContentType(), buf.Bytes() |
| 319 | } |
| 320 | |
| 321 | // TestThePreviewAnswersUnderTheSealedPolicy: the code panel's preview |
| 322 | // posts unsaved text, as text/html or as a form's one html field (the |
| 323 | // editor submits a form into a named frame), and gets it back under |
| 324 | // the sealed policy, never cached. Signed-in people of the deck only, |
| 325 | // same-origin only, the text at most 2 MiB and the whole request at |
| 326 | // most 2 MiB + 64 KiB. |
| 327 | func TestThePreviewAnswersUnderTheSealedPolicy(t *testing.T) { |
| 328 | a := newSharedApp(t) |
| 329 | cookies := signedIn(t, a, allowedAddress) |
| 330 | deck := createDeck(t, a, cookies, "Preview") |
| 331 | h := productionHandler(t, a) |
| 332 | draft := "<!doctype html><p>draft</p><script>parent.postMessage({type:'ready'}, '*')</script>" |
| 333 | |
| 334 | // unknownLength posts with no Content-Length, as a chunked request |
| 335 | // arrives: the body is a plain reader and ContentLength is -1. |
| 336 | unknownLength := false |
| 337 | post := func(contentType string, body []byte, cookies []*http.Cookie, origin string) *httptest.ResponseRecorder { |
| 338 | req := httptest.NewRequest(http.MethodPost, deck+"/scenes/preview", bytes.NewReader(body)) |
| 339 | if unknownLength { |
| 340 | req.Body = io.NopCloser(struct{ io.Reader }{bytes.NewReader(body)}) |
| 341 | req.ContentLength = -1 |
| 342 | } |
| 343 | req.Header.Set("Content-Type", contentType) |
| 344 | req.Header.Set("Origin", origin) |
| 345 | if origin == testOrigin { |
| 346 | req.Header.Set("Sec-Fetch-Site", "same-origin") |
| 347 | } else { |
| 348 | req.Header.Set("Sec-Fetch-Site", "cross-site") |
| 349 | } |
| 350 | for _, c := range cookies { |
| 351 | req.AddCookie(c) |
| 352 | } |
| 353 | rec := httptest.NewRecorder() |
| 354 | h.ServeHTTP(rec, req) |
| 355 | return rec |
| 356 | } |
| 357 | |
| 358 | multiType, multiBody := multipartForm(t, [2]string{"html", draft}) |
| 359 | for _, c := range []struct { |
| 360 | name, contentType string |
| 361 | body []byte |
| 362 | }{ |
| 363 | {"text/html", "text/html; charset=utf-8", []byte(draft)}, |
| 364 | {"a form", "application/x-www-form-urlencoded", []byte(url.Values{"html": {draft}}.Encode())}, |
| 365 | {"a multipart form", multiType, multiBody}, |
| 366 | } { |
| 367 | rec := post(c.contentType, c.body, cookies, testOrigin) |
| 368 | if rec.Code != http.StatusOK { |
| 369 | t.Errorf("preview as %s: status %d, want 200\n%s", c.name, rec.Code, rec.Body) |
| 370 | continue |
| 371 | } |
| 372 | if rec.Body.String() != draft { |
| 373 | t.Errorf("preview as %s answered %q, want the draft", c.name, rec.Body) |
| 374 | } |
| 375 | assertSealed(t, "the preview as "+c.name, rec) |
| 376 | if got := rec.Header().Get("Cache-Control"); got != "no-store" { |
| 377 | t.Errorf("preview as %s: Cache-Control = %q, want no-store", c.name, got) |
| 378 | } |
| 379 | } |
| 380 | |
| 381 | if rec := post("text/html", []byte(draft), cookies, "https://elsewhere.test"); rec.Code == http.StatusOK { |
| 382 | t.Error("a cross-site preview was answered") |
| 383 | } |
| 384 | if rec := post("text/html", []byte(draft), nil, testOrigin); rec.Code == http.StatusOK { |
| 385 | t.Error("a signed-out preview was answered") |
| 386 | } |
| 387 | theirs := signedIn(t, a, otherAddress) |
| 388 | if rec := post("text/html", []byte(draft), theirs, testOrigin); rec.Code != http.StatusNotFound { |
| 389 | t.Errorf("a preview on somebody else's deck: status %d, want 404", rec.Code) |
| 390 | } |
| 391 | big := append([]byte("<!doctype html>"), bytes.Repeat([]byte(" "), 2<<20)...) |
| 392 | assertRefusal(t, "a preview over 2 MiB", post("text/html", big, cookies, testOrigin), http.StatusRequestEntityTooLarge, "too_large") |
| 393 | assertRefusal(t, "a form preview over 2 MiB", |
| 394 | post("application/x-www-form-urlencoded", []byte(url.Values{"html": {string(big)}}.Encode()), cookies, testOrigin), |
| 395 | http.StatusRequestEntityTooLarge, "too_large") |
| 396 | bigType, bigBody := multipartForm(t, [2]string{"html", string(big)}) |
| 397 | assertRefusal(t, "a multipart preview over 2 MiB", post(bigType, bigBody, cookies, testOrigin), http.StatusRequestEntityTooLarge, "too_large") |
| 398 | // The whole request is held to 2 MiB + 64 KiB, whatever it decodes |
| 399 | // to: a form of 1 MiB of text, percent-encoded to three times that, |
| 400 | // is refused before it is read. |
| 401 | wide := strings.Repeat("<", 1<<20) |
| 402 | assertRefusal(t, "a form whose encoding is over the request limit", |
| 403 | post("application/x-www-form-urlencoded", []byte(url.Values{"html": {wide}}.Encode()), cookies, testOrigin), |
| 404 | http.StatusRequestEntityTooLarge, "too_large") |
| 405 | // A form carries the html field and nothing else. |
| 406 | assertRefusal(t, "a form with another field", |
| 407 | post("application/x-www-form-urlencoded", []byte(url.Values{"html": {draft}, "other": {"x"}}.Encode()), cookies, testOrigin), |
| 408 | http.StatusBadRequest, "invalid") |
| 409 | otherType, otherBody := multipartForm(t, [2]string{"html", draft}, [2]string{"other", "x"}) |
| 410 | assertRefusal(t, "a multipart form with another field", post(otherType, otherBody, cookies, testOrigin), http.StatusBadRequest, "invalid") |
| 411 | twiceType, twiceBody := multipartForm(t, [2]string{"html", draft}, [2]string{"html", draft}) |
| 412 | assertRefusal(t, "a multipart form with html twice", post(twiceType, twiceBody, cookies, testOrigin), http.StatusBadRequest, "invalid") |
| 413 | // A small html part, its closing boundary, then megabytes of |
| 414 | // epilogue: the multipart parser stops at the boundary, but the |
| 415 | // request is still over the limit and is refused, with its length |
| 416 | // declared or not. Under the limit, an epilogue is harmless. |
| 417 | epType, epBody := multipartForm(t, [2]string{"html", draft}) |
| 418 | small := append(append([]byte{}, epBody...), "\r\nepilogue\r\n"...) |
| 419 | huge := append(append([]byte{}, epBody...), bytes.Repeat([]byte("x"), 3<<20)...) |
| 420 | for _, unknown := range []bool{false, true} { |
| 421 | unknownLength = unknown |
| 422 | what := fmt.Sprintf(" (length unknown: %t)", unknown) |
| 423 | assertRefusal(t, "a multipart preview with a huge epilogue"+what, post(epType, huge, cookies, testOrigin), http.StatusRequestEntityTooLarge, "too_large") |
| 424 | if rec := post(epType, small, cookies, testOrigin); rec.Code != http.StatusOK || rec.Body.String() != draft { |
| 425 | t.Errorf("a multipart preview with a small epilogue%s: status %d %q, want 200 and the draft", what, rec.Code, rec.Body) |
| 426 | } |
| 427 | if rec := post(epType, epBody, cookies, testOrigin); rec.Code != http.StatusOK { |
| 428 | t.Errorf("a multipart preview%s: status %d, want 200", what, rec.Code) |
| 429 | } |
| 430 | } |
| 431 | unknownLength = false |
| 432 | assertRefusal(t, "a JSON preview", post("application/json", []byte(`{"html":"x"}`), cookies, testOrigin), http.StatusUnsupportedMediaType, "unsupported_type") |
| 433 | if !strings.Contains(sealedPolicy, "sandbox allow-scripts;") { |
| 434 | t.Fatal("the sealed policy lost its sandbox") |
| 435 | } |
| 436 | } |
| 437 | |