oficina / slides Public

Slides: scene bundles, the sealed routes, the preview and the contract

Task 3 of the scenes plan.

- A bundle is an asset of kind scene: signed as text/html, at most
  2 MiB, registered only when the bytes are one UTF-8 HTML document.
  Registration records a SceneBundle row (new table), so a bundle is
  never a picture and the picture routes answer 404 for its ref.
- GET /d, /s and /p .../scenes/{id}/{ref} serve the bundle when the
  deck's scene names it, under the sealed policy alone, nosniff,
  no-referrer, a year's private cache; always streamed, never a
  redirect to the bucket.
- POST /d/{sqid}/scenes/preview answers unsaved code under the same
  policy, as text/html or a form's html field, no-store.
- The sealed policy is the one framing exception: the app serves three
  policies (serving_test).
- docs/scenes.md, the contract, and docs/scenes/example.html; the
  example scene id in docs/api.md is valid base32 now.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev f7deb8133a2f167a3b05d2c5f8edc38dea929d0d parent c396bb3
16 files changed, +1,483 −48
  • docs/api.md +5 −1
  • docs/scenes.md +198 −0
  • docs/scenes/example.html +40 −0
  • internal/slides/app.go +9 −0
  • internal/slides/assets.go +93 −46
  • internal/slides/decks.go +3 −0
  • internal/slides/migrations/0013_create_scene_bundles.sql +4 −0
  • internal/slides/migrations/schema.sql +4 −0
  • internal/slides/models.go +15 −0
  • internal/slides/scenes.go +311 −0
  • internal/slides/serving.go +15 −0
  • internal/slidestest/assets_test.go +3 −1
  • internal/slidestest/browser_test.go +12 −0
  • internal/slidestest/scenes_browser_test.go +328 −0
  • internal/slidestest/scenes_serving_test.go +367 −0
  • internal/slidestest/serving_test.go +76 −0
diff --git a/docs/api.md b/docs/api.md
index 8093db2..5ebb644 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -595,7 +595,7 @@ A scene is code that draws a set of named states; slides show it
through `scene` blocks. In the deck's JSON each scene is:
```json
-"scenes": {"k7m2xq9dwbcd": {"name": "The world", "author": "agent:7",
+"scenes": {"k7m2xqrdwbcd": {"name": "The world", "author": "agent:7",
"code": "<64 hex digits>",
"states": [{"id": "field", "name": "Field", "description": "An empty field"}],
"words": {"title": "Vienna"}, "data": {"pieces": []},
@@ -668,6 +668,10 @@ thing to build and is not built.
Limits, on all three: 20 MiB per image, and PNG, JPEG, WebP or SVG.
+A scene's code goes up the same way: sign it as `text/html` (2 MiB at
+most), and registration answers `{"kind": "scene", "ref": "…"}` for the
+scene's `code`. [scenes.md](scenes.md) says what a bundle must be.
+
### `POST /d/{sqid}/uploads` — where do these bytes go
```json
diff --git a/docs/scenes.md b/docs/scenes.md
new file mode 100644
index 0000000..cc4fb7a
--- /dev/null
+++ b/docs/scenes.md
@@ -0,0 +1,198 @@
+# Writing a scene
+
+A scene is one HTML document that draws a set of named states: a map
+that zooms from a field to a city, a diagram that gains a box per step.
+A slide shows it through a `scene` block, and each press moves it one
+state on. Slides runs the document in a sealed frame, tells it which
+state to show, and keeps the presses, the stills and everything else.
+The scene draws.
+
+[`scenes/example.html`](scenes/example.html) is a whole scene in 40
+lines: a coloured box per state, each labelled from the scene's words.
+Start from it.
+
+## The bundle
+
+A scene's code is one HTML document, called its bundle:
+
+- UTF-8, opening with `<!doctype html>` or `<html>` (a byte-order mark
+ and white space before it are fine);
+- at most 2 MiB;
+- every script, style, picture and font inline. Pictures and fonts can
+ be `data:` URLs, or `blob:` URLs the script makes.
+
+Upload it as you upload a picture ([api.md](api.md#getting-the-bytes-there)),
+with `"type": "text/html"`. Registration reads it back, refuses anything
+that isn't one HTML document (`not_html`) or is over 2 MiB
+(`too_large`), and answers `{"kind": "scene", "ref": "…"}`. That `ref`
+is the scene's `code` in `add_scene` or `set_scene`. A bundle refusal
+carries an `error` code and no `message`.
+
+The bundle is served only to the deck whose scene names it, on the
+same three surfaces as its pictures:
+`/d/{sqid}/scenes/{id}/{ref}`, `/s/{token}/scenes/{id}/{ref}` and
+`/p/{session}/scenes/{id}/{ref}`. The picture routes never serve it.
+
+## What the frame forbids
+
+The bundle is served with this header and no other policy:
+
+```
+Content-Security-Policy: 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'
+```
+
+So the scene runs with an origin of its own that matches nothing. It
+cannot:
+
+- make any request: `fetch`, `XMLHttpRequest`, `WebSocket`,
+ `EventSource`, `navigator.sendBeacon`, or an `<img>`, `<link>`,
+ `<script src>` or font pointing at a URL;
+- read or write cookies, `localStorage`, `sessionStorage`, IndexedDB or
+ the Cache API (each throws `SecurityError`);
+- submit a form, open a window, or navigate the page it sits in;
+- reach the page around it: `parent.document` and `parent.location`
+ throw;
+- use `eval`, `new Function`, workers or WebAssembly.
+
+What it can do is draw: HTML, CSS, SVG, canvas, WebGL, animations, and
+`postMessage` to its parent.
+
+## The conversation
+
+Slides sends two kinds of message, and the scene answers one.
+
+**`init`**, once, after the frame loads:
+
+```js
+{type: "init", state: "field", size: {w: 960, h: 540},
+ words: {title: "Vienna"}, data: {…}, reducedMotion: false, fonts: […]}
+```
+
+- `state`: the id of the state to draw first.
+- `size`: the frame's size in CSS pixels. The frame is the scene's
+ whole viewport, so a scene laid out in `vw`, `vh` or percentages
+ needs nothing more; a `resize` event says when it changes.
+- `words`: the scene's labels, key to text.
+- `data`: the scene's model, any JSON value.
+- `reducedMotion`: whether the reader asked for less motion.
+- `fonts`: the faces the scene asked for (below).
+
+**`state`**, whenever the slide moves:
+
+```js
+{type: "state", state: "city", animate: true}
+```
+
+With `animate: true` the scene moves from where it is to the new state.
+With `animate: false` (a jump, or going back several presses) it draws
+the new state at once.
+
+**`ready`**, from the scene, once the first state is drawn:
+
+```js
+parent.postMessage({type: "ready"}, "*");
+```
+
+Send it once. Slides ignores any later one, and any other message.
+
+Both sides check where a message came from. Slides takes only messages
+whose source is the frame's own window; a scene should take only
+messages whose `event.source` is `parent`. Post to `"*"`: the scene's
+origin matches nothing, so no other target origin works.
+
+## Words, data and fonts
+
+A scene's words and data live in the deck, not in its code. People
+change a label or a value in the editor, and agents change them with
+`set_scene`, without touching the bundle. Draw every piece of text from
+`words`, and everything that varies between states from `data`. A good
+shape for `data` is the scene's pieces plus a table of what each state
+shows. Work out anything costly, such as routes, when the data is made,
+never while the scene runs.
+
+The frame can't load the deck's fonts. To use one, list its family
+names, as the deck's fonts list them, in `data.fonts`:
+
+```json
+"data": {"fonts": ["Brand", "Brand Mono"], …}
+```
+
+`init` then carries each face of those families as a `data:` URL:
+
+```js
+fonts: [{family: "Brand", src: "data:font/woff2;base64,…",
+ weight: "400", style: "normal"}, …]
+```
+
+Add each one before drawing text:
+
+```js
+for (const f of msg.fonts) {
+ const face = new FontFace(f.family, `url(${f.src})`, {weight: f.weight, style: f.style});
+ document.fonts.add(await face.load());
+}
+```
+
+`weight` is a CSS weight or, for a variable face, a range such as
+`"100 900"`. Families the deck doesn't hold are not sent; system font
+names still work in CSS.
+
+## Reduced motion
+
+When `reducedMotion` is true, draw every state change as `animate:
+false` would: no movement, at most a short fade. Slides still sends
+`animate: true` on a press, so the scene decides. Readers who asked for
+less motion see the state's still until the new state has settled.
+
+## Ready within 3 seconds
+
+If `ready` hasn't arrived 3 seconds after `init`, Slides shows the
+state's still instead of the scene. A scene that throws, hangs or never
+answers costs the reader nothing else: presses still count and the talk
+moves on. Load fonts and build what you draw before answering, and
+keep that under a second.
+
+## Stills
+
+Give every state a still picture, PNG or WebP, at most 4 MiB. The PDF,
+thumbnails, the phone view, the presenter's Next preview and readers
+with scripts off show the still, not the scene. A state with no still
+shows a plain panel with the scene's name and the state's description.
+
+## Limits
+
+| What | Limit |
+|---|---|
+| Bundle | one HTML document, 2 MiB |
+| `data` | 960 KiB as compact JSON |
+| Still | PNG or WebP, 4 MiB |
+| `ready` | 3 seconds after `init` |
+
+## Trying a scene
+
+The editor's code panel previews unsaved code by posting it to
+`POST /d/{sqid}/scenes/preview`, which answers it under the same
+policy and stores nothing. It takes a `text/html` body or a form with an
+`html` field, at most 2 MiB, from a signed-in person who can open the
+deck.
+
+## The example
+
+[`scenes/example.html`](scenes/example.html) expects `data.states` to
+list the states in order with a colour each, and a word per state:
+
+```sh
+-d '{"ops":[{"op":"add_scene","name":"Boxes","code":"<ref>",
+ "states":[{"id":"one","name":"One","description":"A red box"},
+ {"id":"two","name":"Two","description":"A red box and a blue box"}],
+ "words":{"one":"First","two":"Second"},
+ "data":{"states":[{"id":"one","colour":"#c0392b"},
+ {"id":"two","colour":"#2471a3"}]}}]}'
+```
+
+On `init` it draws a box for each state and hides the ones after the
+current state; on `state` it shows or hides boxes, sliding them in when
+told to animate and motion is allowed. It answers `ready` after the
+first `init`.
diff --git a/docs/scenes/example.html b/docs/scenes/example.html
new file mode 100644
index 0000000..a96b069
--- /dev/null
+++ b/docs/scenes/example.html
@@ -0,0 +1,40 @@
+<!doctype html>
+<html lang="en">
+<meta charset="utf-8">
+<title>Boxes</title>
+<style>
+ html, body { margin: 0; height: 100%; font: 600 5vh system-ui, sans-serif; }
+ main { height: 100%; display: flex; gap: 3vw; align-items: center; justify-content: center; }
+ .box { width: 20vw; height: 20vw; display: grid; place-items: center; color: #fff;
+ border-radius: 1vw; transition: opacity 0.6s, transform 0.6s; }
+ .box[hidden] { display: grid; opacity: 0; transform: translateY(5vh); }
+ .still .box { transition: none; }
+</style>
+<main></main>
+<script>
+ // One box per state in data.states ({id, colour}), labelled from words.
+ // A state shows its own box and every box before it.
+ const main = document.querySelector('main');
+ let scene = null;
+ function draw(state, animate) {
+ const at = scene.data.states.findIndex((s) => s.id === state);
+ main.classList.toggle('still', !animate || scene.reducedMotion);
+ main.querySelectorAll('.box').forEach((box, i) => { box.hidden = i > at; });
+ }
+ addEventListener('message', (e) => {
+ if (e.source !== parent || !e.data) return;
+ if (e.data.type === 'init') {
+ const first = scene === null;
+ scene = e.data;
+ main.replaceChildren(...scene.data.states.map((s) => {
+ const box = document.createElement('div');
+ box.className = 'box';
+ box.style.background = s.colour;
+ box.textContent = scene.words[s.id] ?? s.id;
+ return box;
+ }));
+ draw(scene.state, false);
+ if (first) parent.postMessage({type: 'ready'}, '*');
+ } else if (e.data.type === 'state' && scene) draw(e.data.state, e.data.animate);
+ });
+</script>
diff --git a/internal/slides/app.go b/internal/slides/app.go
index d98fce3..40a977c 100644
--- a/internal/slides/app.go
+++ b/internal/slides/app.go
@@ -158,6 +158,8 @@ func New(d *db.DB, cfg Config) (*http.ServeMux, *app, error) {
r.Get("/s/{token}/assets/{ref}", a.sharedAsset)
// And its uploaded fonts, the same way (deckfonts.go).
r.Get("/s/{token}/fonts/{ref}", a.sharedFont)
+ // And its scenes' code, sealed (scenes.go).
+ r.Get("/s/{token}/scenes/{id}/{ref}", a.sharedScene)
// And the thumbnails, for the same reason (thumbs.go).
r.Get("/s/{token}/slides/{file}", a.sharedSlideThumb)
// And the presentation stream, when the link's deck is being
@@ -181,6 +183,7 @@ func New(d *db.DB, cfg Config) (*http.ServeMux, *app, error) {
r.Get("/p/{session}/remote", a.remote)
r.Get("/p/{session}/assets/{ref}", a.presentAsset)
r.Get("/p/{session}/fonts/{ref}", a.presentFont)
+ r.Get("/p/{session}/scenes/{id}/{ref}", a.presentScene)
r.Get("/p/{session}/slides/{file}", a.presentSlideThumb)
r.Post("/p/{session}/command", a.presentCommand)
// Pairing a phone from the presenter window's menu: the signed-in
@@ -239,6 +242,12 @@ func New(d *db.DB, cfg Config) (*http.ServeMux, *app, error) {
// fonts served to its readers, as its pictures are.
r.Post("/d/{sqid}/fonts", a.pickDeckFont)
r.Get("/d/{sqid}/fonts/{ref}", a.deckFont)
+ // Scenes (scenes.go): a scene's code, sealed, to the deck's
+ // readers as its pictures are; and the code panel's preview of
+ // unsaved code, sealed the same way and never stored. A bundle
+ // goes in through the uploads and assets routes above.
+ r.Get("/d/{sqid}/scenes/{id}/{ref}", a.deckScene)
+ r.Post("/d/{sqid}/scenes/preview", a.previewScene)
// Exporting to PDF (exports.go, spec §4.3). deckFor's audience,
// like presenting: anybody who can read the deck can take a
// copy of it away. The status page, its fragment and its SSE
diff --git a/internal/slides/assets.go b/internal/slides/assets.go
index cde07d9..befd47c 100644
--- a/internal/slides/assets.go
+++ b/internal/slides/assets.go
@@ -10,6 +10,10 @@
// POST /d/{sqid}/assets verify what landed, hand back the record
// GET /d/{sqid}/assets/{ref} the bytes, by the deck's own capability
//
+// A scene's bundle goes in through the same sign, PUT and register, as
+// an asset of kind scene signed as text/html, and comes back only
+// through scenes.go's sealed routes, never this GET.
+//
// STAGE, THEN PROMOTE (codex 1, codex 2). The browser never names the
// address its bytes will live at. The first endpoint mints a staging
// key of this app's own — models.go's AssetUpload says how it is built
@@ -271,12 +275,18 @@ func (a *app) signUpload(w http.ResponseWriter, r *http.Request) {
assetFail(w, r, http.StatusUnprocessableEntity, "invalid", "invalid")
return
}
- if _, allowed := assetTypes[strings.ToLower(strings.TrimSpace(body.Type))]; !allowed {
+ // A picture, or a scene's bundle (scenes.go), which is held to its
+ // own size and refused in codes rather than the pictures' words.
+ kind := strings.ToLower(strings.TrimSpace(body.Type))
+ limit, refuse := int64(maxAssetBytes), assetRefusal(w, r, kind)
+ if kind == sceneType {
+ limit = maxSceneBytes
+ } else if _, allowed := assetTypes[kind]; !allowed {
assetFail(w, r, http.StatusUnprocessableEntity, "unsupported_type", "type")
return
}
- if body.Size <= 0 || body.Size > maxAssetBytes {
- assetFail(w, r, http.StatusRequestEntityTooLarge, "too_large", "toolarge")
+ if body.Size <= 0 || body.Size > limit {
+ refuse(http.StatusRequestEntityTooLarge, "too_large", "toolarge")
return
}
// The declared hash is still held to the shape a ref has, because a
@@ -287,7 +297,6 @@ func (a *app) signUpload(w http.ResponseWriter, r *http.Request) {
return
}
- kind := strings.ToLower(strings.TrimSpace(body.Type))
key, err := newStagingKey(d.ID, actorFor(u))
if err != nil {
a.fail(w, r, "mint a staging key", err)
@@ -298,17 +307,21 @@ func (a *app) signUpload(w http.ResponseWriter, r *http.Request) {
// somebody reintroduces a caller-chosen key — which is the mistake
// codex 1 found, and this is the line that would catch it coming
// back. Checked across every deck, not just this one: an address
- // verified anywhere is an address in use.
+ // verified anywhere is an address in use, a scene's bundle included.
var verified int64
- if err := a.db.G.WithContext(r.Context()).Model(&DeckAsset{}).
- Where("ref = ?", key).Count(&verified).Error; err != nil {
- a.fail(w, r, "check whether an upload address is already verified", err)
- return
+ for _, model := range []any{&DeckAsset{}, &SceneBundle{}} {
+ var n int64
+ if err := a.db.G.WithContext(r.Context()).Model(model).
+ Where("ref = ?", key).Count(&n).Error; err != nil {
+ a.fail(w, r, "check whether an upload address is already verified", err)
+ return
+ }
+ verified += n
}
if verified > 0 {
a.logger.Error("slides: refused to sign a PUT for a verified address",
"deck", d.Sqid, "ref", key)
- assetFail(w, r, http.StatusConflict, "already_verified", "failed")
+ refuse(http.StatusConflict, "already_verified", "failed")
return
}
@@ -336,7 +349,7 @@ func (a *app) signUpload(w http.ResponseWriter, r *http.Request) {
url, err := p.PresignPut(key, presignTTL)
if err != nil {
a.logger.Error("slides: presign an upload", "deck", d.Sqid, "err", err)
- assetFail(w, r, http.StatusInternalServerError, "internal", "failed")
+ refuse(http.StatusInternalServerError, "internal", "failed")
return
}
out["url"] = url
@@ -406,16 +419,20 @@ func (a *app) putUpload(w http.ResponseWriter, r *http.Request) {
return
}
- r.Body = http.MaxBytesReader(w, r.Body, maxAssetBytes)
+ limit, refuse := int64(maxAssetBytes), assetRefusal(w, r, up.ContentType)
+ if up.ContentType == sceneType {
+ limit = maxSceneBytes
+ }
+ r.Body = http.MaxBytesReader(w, r.Body, limit)
stored, err := store.Put(r.Context(), r.Body, r.Header.Get("Content-Type"))
if err != nil {
var tooBig *http.MaxBytesError
if errors.As(err, &tooBig) {
- assetFail(w, r, http.StatusRequestEntityTooLarge, "too_large", "toolarge")
+ refuse(http.StatusRequestEntityTooLarge, "too_large", "toolarge")
return
}
a.logger.Error("slides: store an upload", "err", err)
- assetFail(w, r, http.StatusInternalServerError, "internal", "failed")
+ refuse(http.StatusInternalServerError, "internal", "failed")
return
}
// The store hashed what it read, and the client said what it was
@@ -423,7 +440,7 @@ func (a *app) putUpload(w http.ResponseWriter, r *http.Request) {
// it is no longer a security question, because what registration
// promotes is addressed by the bytes this app read either way.
if up.DeclaredHash != "" && stored.Hash != up.DeclaredHash {
- assetFail(w, r, http.StatusUnprocessableEntity, "hash_mismatch", "invalid")
+ refuse(http.StatusUnprocessableEntity, "hash_mismatch", "invalid")
return
}
// Where the bytes actually landed. blobs.Dir is content-addressed
@@ -506,14 +523,6 @@ func (a *app) registerAsset(w http.ResponseWriter, r *http.Request) {
assetFail(w, r, http.StatusUnprocessableEntity, "invalid", "invalid")
return
}
- // §2.4 makes alt required unless the block is marked decorative.
- // Checked here as well as in the inspector, because the inspector
- // is a courtesy and this is the gate.
- alt := strings.TrimSpace(body.Alt)
- if alt == "" && !body.Decorative {
- assetFail(w, r, http.StatusUnprocessableEntity, "alt_required", "altrequired")
- return
- }
// The receipt. Everything after this point is about bytes THIS
// principal staged for THIS deck; a `ref` that names anything else
@@ -527,6 +536,21 @@ func (a *app) registerAsset(w http.ResponseWriter, r *http.Request) {
assetFail(w, r, http.StatusNotFound, "not_found", "missing")
return
}
+ // A receipt signed as text/html is a scene's bundle, judged as one
+ // and recorded apart from the pictures (scenes.go).
+ if up.ContentType == sceneType {
+ a.registerScene(w, r, u, d, store, up)
+ return
+ }
+ // §2.4 makes alt required unless the block is marked decorative.
+ // Checked here as well as in the inspector, because the inspector
+ // is a courtesy and this is the gate. A refusal spends nothing: the
+ // receipt is there for the registration that gets it right.
+ alt := strings.TrimSpace(body.Alt)
+ if alt == "" && !body.Decorative {
+ assetFail(w, r, http.StatusUnprocessableEntity, "alt_required", "altrequired")
+ return
+ }
// Where the bytes are: the staging key on a presigning store, where
// the browser wrote them itself, or whatever key blobs.Dir chose
// when the PUT came through this app. Empty means the PUT never
@@ -552,8 +576,10 @@ func (a *app) registerAsset(w http.ResponseWriter, r *http.Request) {
return
}
+ // An HTML document is never a picture, even one with an <svg> in its
+ // head, which sniffImage alone would take for one.
kind := sniffImage(raw)
- if kind == "" {
+ if kind == "" || sniffScene(raw) {
assetFail(w, r, http.StatusUnprocessableEntity, "not_an_image", "notimage")
return
}
@@ -602,26 +628,7 @@ func (a *app) registerAsset(w http.ResponseWriter, r *http.Request) {
return
}
- // The receipt is spent, and the staged copy goes. Both after the
- // verification row, so a failure here costs a stale row and a
- // staged object rather than a picture that can never be served.
- //
- // The delete is skipped when the staged key IS the final one, which
- // is the ordinary development case: blobs.Dir stored the bytes
- // under their own hash, sanitising changed nothing, and the object
- // the browser uploaded is the promoted object. Deleting it there
- // would delete the picture.
- now := time.Now().UTC()
- if err := a.db.G.WithContext(r.Context()).Model(&AssetUpload{}).
- Where("id = ? AND consumed_at IS NULL", up.ID).
- Update("consumed_at", now).Error; err != nil {
- a.logger.Error("slides: spend an upload receipt", "deck", d.Sqid, "upload", up.ID, "err", err)
- }
- if object != ref {
- if err := store.Delete(r.Context(), object); err != nil {
- a.logger.Error("slides: discard a staged upload", "deck", d.Sqid, "ref", object, "err", err)
- }
- }
+ a.spendUpload(r, d, up, object, ref)
id, err := newID()
if err != nil {
@@ -638,6 +645,40 @@ func (a *app) registerAsset(w http.ResponseWriter, r *http.Request) {
})
}
+// spendUpload spends a registered upload's receipt and discards its
+// staged copy, the last step of registering a picture or a scene's
+// bundle. Both after the verification row, so a failure here costs a
+// stale row and a staged object rather than an asset that can never be
+// served.
+//
+// The delete is skipped when the staged key IS the final one, which is
+// the ordinary development case: blobs.Dir stored the bytes under their
+// own hash, sanitising changed nothing, and the object the browser
+// uploaded is the promoted object. Deleting it there would delete the
+// asset.
+func (a *app) spendUpload(r *http.Request, d Deck, up AssetUpload, object, ref string) {
+ if err := a.db.G.WithContext(r.Context()).Model(&AssetUpload{}).
+ Where("id = ? AND consumed_at IS NULL", up.ID).
+ Update("consumed_at", time.Now().UTC()).Error; err != nil {
+ a.logger.Error("slides: spend an upload receipt", "deck", d.Sqid, "upload", up.ID, "err", err)
+ }
+ if object != ref {
+ if err := a.cfg.Blobs.Delete(r.Context(), object); err != nil {
+ a.logger.Error("slides: discard a staged upload", "deck", d.Sqid, "ref", object, "err", err)
+ }
+ }
+}
+
+// assetRefusal is how an upload of kind is refused: in the pictures'
+// words (assetFail), or for a scene's bundle in a code alone
+// (sceneFail).
+func assetRefusal(w http.ResponseWriter, r *http.Request, kind string) func(status int, code, messageKey string) {
+ if kind == sceneType {
+ return func(status int, code, _ string) { sceneFail(w, status, code) }
+ }
+ return func(status int, code, messageKey string) { assetFail(w, r, status, code, messageKey) }
+}
+
// errAssetTooLarge is an object in the store that is bigger than §2.7
// allows. Reachable even though signUpload refuses the size: a
// presigned PUT goes straight to the bucket, so what actually landed is
@@ -652,16 +693,22 @@ var errAssetTooLarge = errors.New("slides: this object is larger than an asset m
// job reads assets too (exports.go), and a job outlives the request
// that started it by definition.
func (a *app) readAsset(ctx context.Context, store blobs.Store, ref string) ([]byte, error) {
+ return a.readObject(ctx, store, ref, maxAssetBytes)
+}
+
+// readObject is readAsset with the limit given: a scene's bundle is held
+// to its own 2 MiB (scenes.go).
+func (a *app) readObject(ctx context.Context, store blobs.Store, ref string, limit int64) ([]byte, error) {
rc, err := store.Get(ctx, ref)
if err != nil {
return nil, err
}
defer rc.Close()
- raw, err := io.ReadAll(io.LimitReader(rc, maxAssetBytes+1))
+ raw, err := io.ReadAll(io.LimitReader(rc, limit+1))
if err != nil {
return nil, err
}
- if len(raw) > maxAssetBytes {
+ if int64(len(raw)) > limit {
return nil, errAssetTooLarge
}
return raw, nil
diff --git a/internal/slides/decks.go b/internal/slides/decks.go
index 7889de4..8eeb261 100644
--- a/internal/slides/decks.go
+++ b/internal/slides/decks.go
@@ -1480,6 +1480,9 @@ func deleteDeckTx(tx *gorm.DB, d Deck, live *[]Presentation, fonts *[]string) er
if err := tx.Where("deck_id = ?", d.ID).Delete(&DeckAsset{}).Error; err != nil {
return err
}
+ if err := tx.Where("deck_id = ?", d.ID).Delete(&SceneBundle{}).Error; err != nil {
+ return err
+ }
// And the upload receipts (models.go's AssetUpload): a receipt
// is registrable only into the deck it was staged for, so one
// whose deck is gone is a row nothing can ever spend.
diff --git a/internal/slides/migrations/0013_create_scene_bundles.sql b/internal/slides/migrations/0013_create_scene_bundles.sql
new file mode 100644
index 0000000..1adff9a
--- /dev/null
+++ b/internal/slides/migrations/0013_create_scene_bundles.sql
@@ -0,0 +1,4 @@
+CREATE TABLE `scene_bundles` (`id` integer PRIMARY KEY AUTOINCREMENT,`deck_id` integer,`ref` text,`created_at` datetime);
+
+CREATE UNIQUE INDEX `idx_scene_bundles_deck_ref` ON `scene_bundles`(`deck_id`,`ref`);
+
diff --git a/internal/slides/migrations/schema.sql b/internal/slides/migrations/schema.sql
index 421dea9..7b12f70 100644
--- a/internal/slides/migrations/schema.sql
+++ b/internal/slides/migrations/schema.sql
@@ -25,6 +25,8 @@ CREATE TABLE `presentation_presses` (`presentation_id` integer,`press_id` text,`
CREATE TABLE `presentations` (`id` integer PRIMARY KEY AUTOINCREMENT,`sqid` text,`deck_id` integer,`actor` text,`slide` integer,`blackout` numeric,`code` text,`remote_token_hash` text,`started_at` datetime,`ended_at` datetime, `slide_id` text, `step` integer, `mode` text, `seq` integer, `positional` numeric, `timer_at` datetime);
+CREATE TABLE `scene_bundles` (`id` integer PRIMARY KEY AUTOINCREMENT,`deck_id` integer,`ref` text,`created_at` datetime);
+
CREATE TABLE `share_links` (`id` integer PRIMARY KEY AUTOINCREMENT,`deck_id` integer,`token_hash` text,`actor` text,`views` integer,`created_at` datetime,`revoked_at` datetime);
CREATE TABLE `users` (`id` integer PRIMARY KEY AUTOINCREMENT,`email` text,`name` text,`colour` text,`created_at` datetime);
@@ -67,6 +69,8 @@ CREATE INDEX `idx_presentations_deck_id` ON `presentations`(`deck_id`);
CREATE UNIQUE INDEX `idx_presentations_sqid` ON `presentations`(`sqid`);
+CREATE UNIQUE INDEX `idx_scene_bundles_deck_ref` ON `scene_bundles`(`deck_id`,`ref`);
+
CREATE INDEX `idx_share_links_deck_id` ON `share_links`(`deck_id`);
CREATE UNIQUE INDEX `idx_share_links_token_hash` ON `share_links`(`token_hash`);
diff --git a/internal/slides/models.go b/internal/slides/models.go
index b7826b5..aa1ba60 100644
--- a/internal/slides/models.go
+++ b/internal/slides/models.go
@@ -22,6 +22,7 @@ var Models = []any{
&Agent{},
&LibraryFont{},
&DeckFont{},
+ &SceneBundle{},
}
// User is a person who has signed in here — spec §6.1's
@@ -189,6 +190,20 @@ type DeckAsset struct {
CreatedAt time.Time
}
+// SceneBundle is DeckAsset's twin for a scene's code (scenes.go):
+// registerAsset writes one after reading the bytes back and finding one
+// HTML document of at most 2 MiB. A table of its own rather than a row
+// in deck_assets, so a bundle is never a picture: the picture routes,
+// thumbnails and the PDF read deck_assets and never see one, and the
+// sealed scene routes read this and never see a picture. Deleting the
+// deck deletes its rows.
+type SceneBundle struct {
+ ID int64
+ DeckID int64 `gorm:"uniqueIndex:idx_scene_bundles_deck_ref"`
+ Ref string `gorm:"uniqueIndex:idx_scene_bundles_deck_ref"`
+ CreatedAt time.Time
+}
+
// AssetUpload is the RECEIPT for one upload this app itself signed —
// spec §2.7 as amended by codex 1 and codex 2. It is what makes an
// upload a thing that happened rather than a ref somebody knows.
diff --git a/internal/slides/scenes.go b/internal/slides/scenes.go
new file mode 100644
index 0000000..a4b7661
--- /dev/null
+++ b/internal/slides/scenes.go
@@ -0,0 +1,311 @@
+package slides
+
+// scenes.go is a scene's code getting into a deck and back out of it,
+// sealed (scenes and clips spec §3, §8.4, §8.6).
+//
+// POST /d/{sqid}/uploads, /d/{sqid}/assets a bundle, as a picture goes in
+// GET {surface}/scenes/{id}/{ref} the bundle, sealed
+// POST /d/{sqid}/scenes/preview unsaved code, sealed
+//
+// A bundle is an asset of kind scene: one HTML document of at most
+// 2 MiB, every script and style inline. It goes in through the pictures'
+// own flow (assets.go): signed as text/html, PUT to the staging key,
+// then registered, which reads the bytes back, checks they are one HTML
+// document and puts them back under their own hash. What registration
+// writes is a SceneBundle row rather than a DeckAsset one, so a bundle
+// is never a picture: the picture routes answer 404 for its ref.
+//
+// The bundle comes back only through the sealed routes, one per
+// surface, each behind the same capability the surface's pictures are,
+// and only when the deck's scene {id} names {ref} as its code. Always
+// from this app, never a redirect to the bucket, because the sealed
+// policy travels on this app's answer and nowhere else.
+//
+// THE SEALED POLICY (SealedPolicy, serving.go) is what makes running an
+// agent's code inside a page of this app safe. `sandbox allow-scripts`
+// without allow-same-origin gives the document an opaque origin: no
+// cookies, no storage, nothing of the page around it, no forms, no
+// popups, no navigating the page. default-src 'none' with only inline
+// script and style and data:/blob: pictures, fonts and media leaves it
+// no network at all. frame-ancestors 'self' lets this app's own pages
+// frame it and nobody else's. It replaces the app-wide policy rather
+// than joining it: a browser enforces every policy it is sent, so a
+// second one could only narrow this one, and Slides' own would take the
+// sandbox's scripts away (TestTheSealedPolicyIsTheOneFramingException).
+
+import (
+ "bytes"
+ "errors"
+ "io"
+ "mime"
+ "net/http"
+ "strings"
+ "time"
+ "unicode/utf8"
+
+ "github.com/go-chi/chi/v5"
+ "gorm.io/gorm"
+ "gorm.io/gorm/clause"
+
+ "amadan.net/oficina/slides/internal/slides/deck"
+ "amadan.net/rastrillo/rastrillo/blobs"
+)
+
+// sceneType is a bundle's media type: what the upload is signed as and
+// what the sealed routes answer with.
+const sceneType = "text/html"
+
+// maxSceneBytes is the most a bundle may be (spec §2): 2 MiB, held at
+// the sign, the development PUT, registration and the preview.
+const maxSceneBytes = 2 << 20
+
+// sniffScene reports whether raw is one HTML document as a bundle must
+// be: UTF-8 throughout, and opening, after an optional byte-order mark
+// and white space, with <!doctype html or <html in any case.
+func sniffScene(raw []byte) bool {
+ if !utf8.Valid(raw) {
+ return false
+ }
+ head := bytes.TrimPrefix(raw, []byte("\xef\xbb\xbf"))
+ head = bytes.TrimLeft(head, " \t\n\f\r")
+ if len(head) > 16 {
+ head = head[:16]
+ }
+ head = bytes.ToLower(head)
+ for _, open := range []string{"<!doctype html", "<html"} {
+ if rest, ok := bytes.CutPrefix(head, []byte(open)); ok {
+ return len(rest) == 0 || strings.IndexByte(" \t\n\f\r>", rest[0]) >= 0
+ }
+ }
+ return false
+}
+
+// sceneFail is a refusal of a bundle: a fixed code and no words. The
+// editor that shows one (the code panel) brings its own from the
+// catalog; the pictures' messages all say "image".
+func sceneFail(w http.ResponseWriter, status int, code string) {
+ writeAssetJSON(w, status, map[string]string{"error": code})
+}
+
+// registerScene is registerAsset for a receipt staged as text/html: read
+// the bytes back, refuse anything but one HTML document of at most
+// 2 MiB, put them back under their own hash and record the bundle for
+// this deck. It answers {kind, ref}; the client names the ref as a
+// scene's code in add_scene or set_scene, which is what makes it
+// servable (serveScene), as register_asset does for a picture.
+func (a *app) registerScene(w http.ResponseWriter, r *http.Request, u User, d Deck, store blobs.Store, up AssetUpload) {
+ object := up.ObjectKey
+ if object == "" {
+ sceneFail(w, http.StatusNotFound, "not_found")
+ return
+ }
+ raw, err := a.readObject(r.Context(), store, object, maxSceneBytes)
+ if err != nil {
+ switch {
+ case errors.Is(err, blobs.ErrNotFound):
+ sceneFail(w, http.StatusNotFound, "not_found")
+ case errors.Is(err, errAssetTooLarge):
+ sceneFail(w, http.StatusRequestEntityTooLarge, "too_large")
+ default:
+ a.logger.Error("slides: read an uploaded scene", "deck", d.Sqid, "err", err)
+ sceneFail(w, http.StatusInternalServerError, "internal")
+ }
+ return
+ }
+ if !sniffScene(raw) {
+ sceneFail(w, http.StatusUnprocessableEntity, "not_html")
+ return
+ }
+ stored, err := store.Put(r.Context(), bytes.NewReader(raw), sceneType)
+ if err != nil {
+ a.logger.Error("slides: promote a staged scene", "deck", d.Sqid, "err", err)
+ sceneFail(w, http.StatusInternalServerError, "internal")
+ return
+ }
+ ref := stored.Hash
+ if err := a.guarded(r.Context(), a.deckGuard(r.Context(), u, d), func(db *gorm.DB) error {
+ return db.Clauses(clause.OnConflict{DoNothing: true}).
+ Create(&SceneBundle{DeckID: d.ID, Ref: ref, CreatedAt: time.Now().UTC()}).Error
+ }); err != nil {
+ if a.guardRefused(w, r, err) {
+ return
+ }
+ a.fail(w, r, "record a verified scene", err)
+ return
+ }
+ a.spendUpload(r, d, up, object, ref)
+ writeAssetJSON(w, http.StatusOK, map[string]any{"kind": "scene", "ref": ref})
+}
+
+// --- GET {surface}/scenes/{id}/{ref} ---
+
+// deckScene serves a scene's bundle to a signed-in reader of the deck.
+func (a *app) deckScene(w http.ResponseWriter, r *http.Request) {
+ u, ok := a.viewer(w, r)
+ if !ok {
+ return
+ }
+ d, ok := a.deckFor(w, r, u)
+ if !ok {
+ return
+ }
+ a.serveScene(w, r, d)
+}
+
+// sharedScene serves it to somebody holding a share link.
+func (a *app) sharedScene(w http.ResponseWriter, r *http.Request) {
+ d, _, ok := a.deckForShareLink(w, r, chi.URLParam(r, "token"))
+ if !ok {
+ return
+ }
+ a.serveScene(w, r, d)
+}
+
+// presentScene serves it to a projector, a presenter's window or an
+// audience following along (presentation.go).
+func (a *app) presentScene(w http.ResponseWriter, r *http.Request) {
+ p, ok := a.presentationFor(w, r)
+ if !ok {
+ return
+ }
+ d, ok := a.deckOf(w, r, p)
+ if !ok {
+ return
+ }
+ a.serveScene(w, r, d)
+}
+
+// serveScene is the one body behind all three: the bundle was registered
+// for this deck (SceneBundle) AND the deck's scene id names it as its
+// code, as serveAsset asks of a picture; then the bytes, sealed. Every
+// other answer is the same 404, so a reader learns nothing about what
+// other decks hold.
+func (a *app) serveScene(w http.ResponseWriter, r *http.Request, d Deck) {
+ id, ref := chi.URLParam(r, "id"), chi.URLParam(r, "ref")
+ store := a.cfg.Blobs
+ if !deck.SceneID(id) || !assetRefPattern.MatchString(ref) || store == nil {
+ a.notFound(w, r)
+ return
+ }
+ var verified int64
+ if err := a.db.G.WithContext(r.Context()).Model(&SceneBundle{}).
+ Where("deck_id = ? AND ref = ?", d.ID, ref).Count(&verified).Error; err != nil {
+ a.fail(w, r, "look up a verified scene", err)
+ return
+ }
+ if verified == 0 {
+ a.notFound(w, r)
+ return
+ }
+ h, view, err := a.openDeck(r.Context(), d)
+ if err != nil {
+ a.fail(w, r, "open a deck to serve a scene", err)
+ return
+ }
+ h.Close(r.Context())
+ if scene, ok := view.Scenes[id]; !ok || scene.Code != ref {
+ a.notFound(w, r)
+ return
+ }
+ raw, err := a.readObject(r.Context(), store, ref, maxSceneBytes)
+ if err != nil {
+ if errors.Is(err, blobs.ErrNotFound) || errors.Is(err, errAssetTooLarge) {
+ a.notFound(w, r)
+ return
+ }
+ a.fail(w, r, "read a scene", err)
+ return
+ }
+ // The bytes are judged again, as serveAsset judges a picture's: the
+ // row says they were judged once, and this keeps the sealed route
+ // from ever answering text/html for anything else.
+ if !sniffScene(raw) {
+ a.notFound(w, r)
+ return
+ }
+ sealedHeaders(w)
+ // Content-addressed, so a year is honest; private, because the
+ // address is the deck's capability, not the object's.
+ w.Header().Set("Cache-Control", "private, max-age=31536000, immutable")
+ w.Header().Set("ETag", `"`+ref+`"`)
+ if match := r.Header.Get("If-None-Match"); match != "" && strings.Contains(match, `"`+ref+`"`) {
+ w.WriteHeader(http.StatusNotModified)
+ return
+ }
+ w.Write(raw)
+}
+
+// sealedHeaders is the header set every sealed answer carries: the
+// sealed policy in place of the app's (never beside it), no sniffing,
+// no referrer, and framing by this app's own pages. X-Frame-Options is
+// rastrillo's DENY otherwise, which a browser reading only that header
+// would hold against the frame-ancestors the policy allows.
+func sealedHeaders(w http.ResponseWriter) {
+ h := w.Header()
+ h.Set("Content-Type", "text/html; charset=utf-8")
+ h.Set("Content-Security-Policy", SealedPolicy)
+ h.Set("X-Content-Type-Options", "nosniff")
+ h.Set("Referrer-Policy", "no-referrer")
+ h.Set("X-Frame-Options", "SAMEORIGIN")
+}
+
+// --- POST /d/{sqid}/scenes/preview ---
+
+// previewScene answers the code panel's unsaved text under the sealed
+// policy, so a draft runs exactly as the saved bundle will and is never
+// stored. The editor submits a form into a named frame, so the text
+// comes as a form's html field or, from a script, as a text/html body.
+// Signed-in people of the deck only; csrf.Protect has already turned
+// away anything not posted from this app's own pages.
+func (a *app) previewScene(w http.ResponseWriter, r *http.Request) {
+ u, ok := a.viewer(w, r)
+ if !ok {
+ return
+ }
+ if _, ok := a.deckFor(w, r, u); !ok {
+ return
+ }
+ media, _, _ := mime.ParseMediaType(r.Header.Get("Content-Type"))
+ var html []byte
+ switch media {
+ case sceneType:
+ r.Body = http.MaxBytesReader(w, r.Body, maxSceneBytes)
+ body, err := io.ReadAll(r.Body)
+ if err != nil {
+ previewFail(w, err)
+ return
+ }
+ html = body
+ case "application/x-www-form-urlencoded":
+ // Percent-encoding at most triples a byte, so this is room for
+ // 2 MiB of text however it was encoded; the text itself is held
+ // to 2 MiB below.
+ r.Body = http.MaxBytesReader(w, r.Body, 3*maxSceneBytes+4<<10)
+ if err := r.ParseForm(); err != nil {
+ previewFail(w, err)
+ return
+ }
+ html = []byte(r.PostForm.Get("html"))
+ default:
+ sceneFail(w, http.StatusUnsupportedMediaType, "unsupported_type")
+ return
+ }
+ if len(html) > maxSceneBytes {
+ sceneFail(w, http.StatusRequestEntityTooLarge, "too_large")
+ return
+ }
+ sealedHeaders(w)
+ w.Header().Set("Cache-Control", "no-store")
+ w.Write(html)
+}
+
+// previewFail answers a preview body that could not be read: too large,
+// or not a body at all.
+func previewFail(w http.ResponseWriter, err error) {
+ var tooBig *http.MaxBytesError
+ if errors.As(err, &tooBig) {
+ sceneFail(w, http.StatusRequestEntityTooLarge, "too_large")
+ return
+ }
+ sceneFail(w, http.StatusBadRequest, "invalid")
+}
diff --git a/internal/slides/serving.go b/internal/slides/serving.go
index 7c12928..6d4a958 100644
--- a/internal/slides/serving.go
+++ b/internal/slides/serving.go
@@ -50,6 +50,21 @@ import (
const ContentSecurityPolicy = "default-src 'self'; style-src 'self' 'unsafe-inline'; " +
"img-src 'self' data:; frame-ancestors 'none'; base-uri 'self'; form-action 'self'"
+// SealedPolicy is the policy a scene's code runs under (scenes and
+// clips spec §3), and the one page policy that is not
+// ContentSecurityPolicy: the sealed routes (scenes.go) set it in place
+// of the app's, never beside it, because a second policy could only
+// narrow the first and Slides' own would refuse the inline scripts a
+// scene is made of. The sandbox without allow-same-origin gives the
+// document an opaque origin (no cookies, storage, forms, popups or top
+// navigation, nothing of the page around it); default-src 'none' with
+// inline script and style and data:/blob: pictures, fonts and media
+// leaves it no network; frame-ancestors 'self' lets this app's pages,
+// and only them, frame it. TestTheSealedPolicyIsTheOneFramingException
+// keeps the app at three policies with this the only one that frames.
+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'"
+
// ServeOptions completes opts with what Slides serves: mux (New's), the
// locales, its error page and its CSP. main passes the result to
// rastrillo.Serve, and the CSP tests pass it to rastrillo.Handler, so
diff --git a/internal/slidestest/assets_test.go b/internal/slidestest/assets_test.go
index 678e019..1ae2a25 100644
--- a/internal/slidestest/assets_test.go
+++ b/internal/slidestest/assets_test.go
@@ -359,7 +359,9 @@ func TestUploadLimits(t *testing.T) {
code string
}{
{"a GIF", `{"name":"x.gif","size":10,"type":"image/gif","hash":"` + hash + `"}`, http.StatusUnprocessableEntity, "unsupported_type"},
- {"an HTML file", `{"name":"x.html","size":10,"type":"text/html","hash":"` + hash + `"}`, http.StatusUnprocessableEntity, "unsupported_type"},
+ // text/html is a scene's bundle (scenes_serving_test.go), not
+ // a picture; a text file is neither.
+ {"a text file", `{"name":"x.txt","size":10,"type":"text/plain","hash":"` + hash + `"}`, http.StatusUnprocessableEntity, "unsupported_type"},
{"over 20 MiB", `{"name":"x.png","size":20971521,"type":"image/png","hash":"` + hash + `"}`, http.StatusRequestEntityTooLarge, "too_large"},
{"nothing at all", `{"name":"x.png","size":0,"type":"image/png","hash":"` + hash + `"}`, http.StatusRequestEntityTooLarge, "too_large"},
{"a ref with a slash", `{"name":"x.png","size":10,"type":"image/png","hash":"a/b"}`, http.StatusUnprocessableEntity, "invalid"},
diff --git a/internal/slidestest/browser_test.go b/internal/slidestest/browser_test.go
index f147438..693eb84 100644
--- a/internal/slidestest/browser_test.go
+++ b/internal/slidestest/browser_test.go
@@ -70,6 +70,15 @@ func newRigWith(t *testing.T, store blobs.Store) (*harness.Rig, *fakeMailer) {
// behind the same serving stack, so a test can make what it needs over
// HTTP (signedIn, an agent, a deck) before the browser looks at it.
func newRigApp(t *testing.T, store blobs.Store) (*harness.Rig, *testApp) {
+ t.Helper()
+ return newRigAppWrapped(t, store, nil)
+}
+
+// newRigAppWrapped is newRigApp with wrap put around the whole serving
+// stack, outermost, so a test can see every request the browser makes
+// of the server (scenes_browser_test.go's request log). Nil wraps
+// nothing.
+func newRigAppWrapped(t *testing.T, store blobs.Store, wrap func(http.Handler) http.Handler) (*harness.Rig, *testApp) {
t.Helper()
mailer := &fakeMailer{}
served := &testApp{mailer: mailer}
@@ -109,6 +118,9 @@ func newRigApp(t *testing.T, store blobs.Store) (*harness.Rig, *testApp) {
}
t.Cleanup(func() { _ = closeFn() })
served.Handler, served.db, served.mux, served.app = h, d, mux, a
+ if wrap != nil {
+ return wrap(h)
+ }
return h
})
return rig, served
diff --git a/internal/slidestest/scenes_browser_test.go b/internal/slidestest/scenes_browser_test.go
new file mode 100644
index 0000000..99f221a
--- /dev/null
+++ b/internal/slidestest/scenes_browser_test.go
@@ -0,0 +1,328 @@
+//go:build browser
+
+package slidestest
+
+// The sealed frame in a real Chromium (scenes and clips spec §3, Review
+// Focus 2): a scene runs inside a page of this app and reaches nothing
+// but the page's messages, and the example in docs/scenes.md keeps the
+// contract.
+
+import (
+ "context"
+ "fmt"
+ "net/http"
+ "os"
+ "sort"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/chromedp/cdproto/cdp"
+ "github.com/chromedp/cdproto/network"
+ "github.com/chromedp/chromedp"
+)
+
+// hostileScene tries every way out it can think of, then posts what
+// happened to each try back to the page. Every URL it aims at this app
+// carries scene-probe, so the server's request log can say whether any
+// of them arrived. A try reports "refused: ..." when it visibly failed
+// and "reached: ..." when it visibly worked; "tried" is a try whose
+// failure only shows outside the frame (the page's URL, the server's
+// log), which the test checks there.
+const hostileScene = `<!doctype html>
+<html><head><meta charset="utf-8"><title>hostile</title></head>
+<body><script>
+const out = {};
+const wait = (p, ms) => Promise.race([p, new Promise((r) => setTimeout(() => r('refused: no answer'), ms))]);
+const attempt = async (name, fn) => {
+ try { out[name] = String(await fn()); } catch (e) { out[name] = 'refused: ' + ((e && e.name) || e); }
+};
+(async () => {
+ await attempt('fetch this app', async () => 'reached: ' + (await fetch('/?scene-probe=fetch')).status);
+ await attempt('fetch elsewhere', async () => 'reached: ' + (await fetch('https://example.com/?scene-probe=fetch')).status);
+ await attempt('XMLHttpRequest', () => wait(new Promise((res) => {
+ const x = new XMLHttpRequest();
+ x.open('GET', '/?scene-probe=xhr');
+ x.onload = () => res('reached: ' + x.status);
+ x.onerror = () => res('refused: error');
+ x.send();
+ }), 2000));
+ await attempt('read document.cookie', () => { const c = document.cookie; return c ? 'reached: ' + c : 'refused: empty'; });
+ await attempt('write document.cookie', () => {
+ document.cookie = 'scene=1; path=/';
+ return document.cookie.includes('scene=1') ? 'reached' : 'refused: not kept';
+ });
+ await attempt('localStorage', () => { localStorage.setItem('scene', '1'); return 'reached'; });
+ await attempt('sessionStorage', () => { sessionStorage.setItem('scene', '1'); return 'reached'; });
+ await attempt('indexedDB.open', () => wait(new Promise((res) => {
+ const q = indexedDB.open('scene');
+ q.onsuccess = () => res('reached');
+ q.onerror = () => res('refused: error');
+ }), 2000));
+ await attempt('parent.document', () => 'reached: ' + parent.document.title);
+ await attempt('parent.location', () => 'reached: ' + parent.location.href);
+ await attempt('window.open', () => (window.open('/?scene-probe=open') ? 'reached' : 'refused: no window'));
+ await attempt('navigator.sendBeacon', () => (navigator.sendBeacon('/?scene-probe=beacon', 'x') ? 'tried' : 'refused: not queued'));
+ await attempt('WebSocket', () => wait(new Promise((res) => {
+ const s = new WebSocket('ws://' + location.host + '/?scene-probe=ws');
+ s.onopen = () => res('reached');
+ s.onerror = () => res('refused: error');
+ }), 2000));
+ await attempt('img src', () => wait(new Promise((res) => {
+ const i = new Image();
+ i.onload = () => res('reached');
+ i.onerror = () => res('refused: error');
+ i.src = '/?scene-probe=img';
+ document.body.append(i);
+ }), 2000));
+ await attempt('top.location', () => { top.location = '/?scene-probe=top'; return 'tried'; });
+ await attempt('form post', () => {
+ const f = document.createElement('form');
+ f.method = 'post';
+ f.action = '/?scene-probe=form';
+ const i = document.createElement('input');
+ i.name = 'x';
+ i.value = '1';
+ f.append(i);
+ document.body.append(f);
+ f.submit();
+ return 'tried';
+ });
+ // Long enough for a navigation the tries above started to have taken
+ // this document away, so no answer at all is its own failure.
+ setTimeout(() => parent.postMessage({type: 'probes', out}, '*'), 500);
+})();
+</script></body></html>
+`
+
+// requestLog is every request the server saw, as method and URI.
+type requestLog struct {
+ mu sync.Mutex
+ seen []string
+}
+
+func (l *requestLog) wrap(h http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ l.mu.Lock()
+ l.seen = append(l.seen, r.Method+" "+r.URL.RequestURI())
+ l.mu.Unlock()
+ h.ServeHTTP(w, r)
+ })
+}
+
+func (l *requestLog) matching(s string) []string {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ var out []string
+ for _, r := range l.seen {
+ if strings.Contains(r, s) {
+ out = append(out, r)
+ }
+ }
+ return out
+}
+
+// browserCookies is every cookie the browser holds for origin, as
+// name=value, sorted.
+func browserCookies(origin string, out *[]string) chromedp.Action[chromedp.Void] {
+ return chromedp.Func(func(ctx context.Context, t *chromedp.Target) error {
+ res, err := cdp.Call(ctx, t, network.GetCookies, network.GetCookiesParams{URLs: []string{origin + "/"}})
+ if err != nil {
+ return err
+ }
+ *out = nil
+ for _, c := range res.Cookies {
+ *out = append(*out, c.Name+"="+c.Value)
+ }
+ sort.Strings(*out)
+ return nil
+ })
+}
+
+// pageState is what a scene must leave as it found it: the page's
+// address, its document and its own storage.
+type pageState struct {
+ URL, DOM, Storage string
+}
+
+const pageStateJS = `({
+ URL: location.href,
+ DOM: document.documentElement.outerHTML,
+ Storage: JSON.stringify([Object.entries(localStorage), Object.entries(sessionStorage)]),
+})`
+
+func TestASceneCannotReachAnything(t *testing.T) {
+ log := &requestLog{}
+ rig, app := newRigAppWrapped(t, dirStore(t), log.wrap)
+ cookies := signedIn(t, app, allowedAddress)
+ token := mintAgent(t, app, cookies, "scenes")
+ sqid := apiDeck(t, app, token, "Hostile")
+ ref := uploadScene(t, app, "/d/"+sqid, cookies, []byte(hostileScene))
+ id := addScene(t, app, token, sqid, ref)
+
+ // The browser signed in too, so there is a session cookie to steal.
+ browserSignIn(t, rig, app.mailer)
+ rig.Run(chromedp.Navigate(rig.Origin + "/d/" + sqid + "?slide=1"))
+ rig.Screen("[slides-slide]", "the viewer, before the scene")
+
+ var before, after []string
+ rig.Run(
+ browserCookies(rig.Origin, &before),
+ // The page puts something of its own in storage, so "unchanged"
+ // is about something.
+ evalValue(nil, `localStorage.setItem('page', 'mine'); sessionStorage.setItem('page', 'mine')`),
+ )
+ if len(before) == 0 {
+ t.Fatal("the signed-in browser holds no cookie")
+ }
+
+ // The frame goes in, and the page is read straight after: the frame
+ // is the one change the test itself makes.
+ var ran struct {
+ Out map[string]string
+ Before pageState
+ }
+ rig.Run(evalInto(&ran, fmt.Sprintf(`new Promise((resolve) => {
+ const f = document.createElement('iframe');
+ f.title = 'scene';
+ f.src = %q;
+ document.body.append(f);
+ const before = %s;
+ addEventListener('message', (e) => {
+ if (e.source === f.contentWindow && e.data && e.data.type === 'probes') resolve({Out: e.data.out, Before: before});
+ });
+ setTimeout(() => resolve({Out: null, Before: before}), 20000);
+ })`, "/d/"+sqid+"/scenes/"+id+"/"+ref, pageStateJS), awaitPromise))
+ out := ran.Out
+ if out == nil {
+ t.Fatal("the scene never reported: a try took its document away")
+ }
+ // A moment for anything a try set off to land.
+ var page pageState
+ rig.Run(
+ chromedp.Sleep(500*time.Millisecond),
+ evalInto(&page, pageStateJS),
+ browserCookies(rig.Origin, &after),
+ )
+
+ tries := []string{
+ "fetch this app", "fetch elsewhere", "XMLHttpRequest", "read document.cookie",
+ "write document.cookie", "localStorage", "sessionStorage", "indexedDB.open",
+ "parent.document", "parent.location", "window.open", "navigator.sendBeacon",
+ "WebSocket", "img src", "top.location", "form post",
+ }
+ outside := map[string]bool{"navigator.sendBeacon": true, "top.location": true, "form post": true}
+ for _, name := range tries {
+ got, ok := out[name]
+ switch {
+ case !ok:
+ t.Errorf("%s: no outcome reported", name)
+ case strings.HasPrefix(got, "refused"):
+ case outside[name] && got == "tried":
+ default:
+ t.Errorf("%s: %s, want refused", name, got)
+ }
+ }
+ t.Logf("outcomes: %v", out)
+
+ // The log saw the scene's own document arrive, so it was listening.
+ if len(log.matching("/scenes/"+id+"/"+ref)) != 1 {
+ t.Errorf("the request log saw the scene's document %d times, want once", len(log.matching("/scenes/"+id+"/"+ref)))
+ }
+ if hits := log.matching("scene-probe"); len(hits) > 0 {
+ t.Errorf("the server saw requests from the scene: %v", hits)
+ }
+ if strings.Join(before, "; ") != strings.Join(after, "; ") {
+ t.Errorf("the cookies changed: %v, then %v", before, after)
+ }
+ if want := rig.Origin + "/d/" + sqid + "?slide=1"; page.URL != want || ran.Before.URL != want {
+ t.Errorf("the page is at %q, want %q", page.URL, want)
+ }
+ if page.Storage != ran.Before.Storage || !strings.Contains(page.Storage, `"page","mine"`) {
+ t.Errorf("the page's storage changed: %s, then %s", ran.Before.Storage, page.Storage)
+ }
+ if page.DOM != ran.Before.DOM {
+ t.Errorf("the page's document changed:\nbefore %s\nafter %s", ran.Before.DOM, page.DOM)
+ }
+}
+
+// TestTheExampleSceneAnswersReady: docs/scenes/example.html, posted to
+// the preview as the code panel posts it (a form into a named frame),
+// says nothing until it is told init, then answers ready once, within
+// the 3 seconds, and takes a state change without saying it again or
+// putting anything wrong on the page.
+func TestTheExampleSceneAnswersReady(t *testing.T) {
+ example, err := os.ReadFile("../../docs/scenes/example.html")
+ if err != nil {
+ t.Fatalf("read the example: %v", err)
+ }
+ if n := strings.Count(string(example), "\n"); n > 40 {
+ t.Errorf("the example is %d lines, want 40 at most", n)
+ }
+ rig, mailer := newRig(t)
+ browserSignIn(t, rig, mailer)
+ var deck string
+ rig.Run(evalInto(&deck, `(document.querySelector('a[href^="/d/"]')?.getAttribute('href') ?? '').replace(/\/edit$/, '')`))
+ if deck == "" {
+ t.Fatal("the deck list links no deck")
+ }
+ rig.Run(chromedp.Navigate(rig.Origin + deck + "?slide=1"))
+ rig.Screen("[slides-slide]", "the viewer")
+
+ var got struct {
+ Early, Ready, AfterState int
+ Millis float64
+ }
+ rig.Run(evalInto(&got, fmt.Sprintf(`(async (html, preview) => {
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+ const f = document.createElement('iframe');
+ f.name = 'scene-preview';
+ f.title = 'scene';
+ f.style.cssText = 'width: 640px; height: 360px';
+ document.body.append(f);
+ await sleep(100);
+ const messages = [];
+ addEventListener('message', (e) => { if (e.source === f.contentWindow) messages.push(e.data); });
+ const loaded = new Promise((r) => f.addEventListener('load', r, {once: true}));
+ const form = document.createElement('form');
+ form.method = 'post';
+ form.action = preview;
+ form.target = 'scene-preview';
+ form.hidden = true;
+ const field = document.createElement('textarea');
+ field.name = 'html';
+ field.value = html;
+ form.append(field);
+ document.body.append(form);
+ form.submit();
+ await loaded;
+ await sleep(300);
+ const early = messages.length;
+ const readies = () => messages.filter((m) => m && m.type === 'ready').length;
+ const start = performance.now();
+ f.contentWindow.postMessage({
+ type: 'init', state: 'one', size: {w: 640, h: 360},
+ words: {one: 'First', two: 'Second', three: 'Third'},
+ data: {states: [{id: 'one', colour: '#c0392b'}, {id: 'two', colour: '#2471a3'}, {id: 'three', colour: '#1e8449'}]},
+ reducedMotion: false, fonts: [],
+ }, '*');
+ while (readies() === 0 && performance.now() - start < 3000) await sleep(20);
+ const millis = performance.now() - start;
+ const ready = readies();
+ f.contentWindow.postMessage({type: 'state', state: 'two', animate: true}, '*');
+ f.contentWindow.postMessage({type: 'state', state: 'three', animate: false}, '*');
+ await sleep(500);
+ return {Early: early, Ready: ready, AfterState: readies(), Millis: millis};
+ })(%q, %q)`, example, deck+"/scenes/preview"), awaitPromise))
+ if got.Early != 0 {
+ t.Errorf("the example said %d things before init, want nothing", got.Early)
+ }
+ if got.Ready != 1 || got.Millis >= 3000 {
+ t.Errorf("the example answered ready %d times in %.0f ms, want once inside 3 s", got.Ready, got.Millis)
+ }
+ if got.AfterState != 1 {
+ t.Errorf("after two states the example has said ready %d times, want once", got.AfterState)
+ }
+ rig.Screen("[slides-slide]", "the example scene ran")
+}
diff --git a/internal/slidestest/scenes_serving_test.go b/internal/slidestest/scenes_serving_test.go
new file mode 100644
index 0000000..dd832ab
--- /dev/null
+++ b/internal/slidestest/scenes_serving_test.go
@@ -0,0 +1,367 @@
+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"
+ "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("<!doctype html>\n<html><body><script>parent.postMessage({type: 'ready'}, '*')</script></body></html>\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("<!DOCTYPE html><p>other</p>"))
+ 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("<!doctype html><script>parent.postMessage('unverified', '*')</script>")
+ 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)
+ if rec.Code != http.StatusRequestEntityTooLarge || jsonBody(t, rec)["error"] != "too_large" {
+ t.Errorf("signing a 2 MiB + 1 bundle: status %d %s, want 413 too_large", rec.Code, rec.Body)
+ }
+
+ 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)
+ if reg.Code != http.StatusUnprocessableEntity {
+ t.Errorf("%s: status %d, want 422\n%s", name, reg.Code, reg.Body)
+ return
+ }
+ if out := jsonBody(t, reg); out["error"] != "not_html" {
+ t.Errorf("%s: error = %v, want not_html", name, out["error"])
+ }
+ }
+ refused("a PNG", onePixelPNG)
+ refused("plain text", []byte("hello, world"))
+ refused("an HTML fragment", []byte("<p>no document</p>"))
+ refused("an SVG", []byte(`<svg xmlns="http://www.w3.org/2000/svg"></svg>`))
+ refused("not UTF-8", []byte("<!doctype html><p>\xff\xfe</p>"))
+ refused("a doctype that is not html", []byte("<!doctype htmlx><p>x</p>"))
+ 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 <!DOCTYPE HTML>\n<p>a</p>",
+ "<html lang=\"en\"><body>b</body></html>",
+ " <HTML>\n<body>c</body></HTML>",
+ "<!doctype html>",
+ } {
+ 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("<!doctype html>"), 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))
+ if put := putBytes(t, a, signed["url"].(string), "text/html", big, cookies); put.Code != http.StatusRequestEntityTooLarge {
+ t.Errorf("PUT a bundle over 2 MiB: status %d, want 413", put.Code)
+ }
+ // ...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)
+ if reg := postJSON(t, b, bDeck+"/assets", fmt.Sprintf(`{"ref":%q}`, staged), bCookies); reg.Code != http.StatusRequestEntityTooLarge || jsonBody(t, reg)["error"] != "too_large" {
+ t.Errorf("registering a landed bundle over 2 MiB: status %d %s, want 413 too_large", reg.Code, reg.Body)
+ }
+
+ // And the other way round: an HTML document uploaded as a picture
+ // is not a picture, even with an <svg> in its head.
+ page := []byte(`<!doctype html><html><body><svg xmlns="http://www.w3.org/2000/svg"></svg></body></html>`)
+ 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)
+ }
+}
+
+// TestThePreviewAnswersUnderTheSealedPolicy: the code panel's preview
+// posts unsaved text, as text/html or as a form's 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, 2 MiB at most.
+func TestThePreviewAnswersUnderTheSealedPolicy(t *testing.T) {
+ a := newSharedApp(t)
+ cookies := signedIn(t, a, allowedAddress)
+ deck := createDeck(t, a, cookies, "Preview")
+ h := productionHandler(t, a)
+ draft := "<!doctype html><p>draft</p><script>parent.postMessage({type:'ready'}, '*')</script>"
+
+ post := func(contentType string, body []byte, cookies []*http.Cookie, origin string) *httptest.ResponseRecorder {
+ req := httptest.NewRequest(http.MethodPost, deck+"/scenes/preview", bytes.NewReader(body))
+ 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
+ }
+
+ 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())},
+ } {
+ 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("<!doctype html>"), bytes.Repeat([]byte(" "), 2<<20)...)
+ if rec := post("text/html", big, cookies, testOrigin); rec.Code != http.StatusRequestEntityTooLarge {
+ t.Errorf("a preview over 2 MiB: status %d, want 413", rec.Code)
+ }
+ if rec := post("application/x-www-form-urlencoded", []byte(url.Values{"html": {string(big)}}.Encode()), cookies, testOrigin); rec.Code != http.StatusRequestEntityTooLarge {
+ t.Errorf("a form preview over 2 MiB: status %d, want 413", rec.Code)
+ }
+ if rec := post("application/json", []byte(`{"html":"x"}`), cookies, testOrigin); rec.Code != http.StatusUnsupportedMediaType {
+ t.Errorf("a JSON preview: status %d, want 415", rec.Code)
+ }
+ if !strings.Contains(sealedPolicy, "sandbox allow-scripts;") {
+ t.Fatal("the sealed policy lost its sandbox")
+ }
+}
diff --git a/internal/slidestest/serving_test.go b/internal/slidestest/serving_test.go
index f1c77f9..0f5d7f3 100644
--- a/internal/slidestest/serving_test.go
+++ b/internal/slidestest/serving_test.go
@@ -128,3 +128,79 @@ func TestTheConfirmDoorKeepsEveryPolicy(t *testing.T) {
}
}
}
+
+// TestTheSealedPolicyIsTheOneFramingException: the app's pages are
+// served under three policies and no more — Slides' own, rauth's added
+// frame-ancestors 'none' on the confirm door, and the sealed policy a
+// scene runs under (scenes and clips spec §8.6) — and the sealed one,
+// alone, lets a page of this app frame the document. The sealed
+// answers carry exactly one policy, because a second one from the
+// middleware could only take the sandbox's scripts away.
+func TestTheSealedPolicyIsTheOneFramingException(t *testing.T) {
+ a := newAppWithStore(t, dirStore(t))
+ cookies := signedIn(t, a, allowedAddress)
+ token := mintAgent(t, a, cookies, "scenes")
+ sqid := apiDeck(t, a, token, "Policies")
+ ref := uploadScene(t, a, "/d/"+sqid, cookies, sceneBundle)
+ id := addScene(t, a, token, sqid, ref)
+ h := productionHandler(t, a)
+
+ seen := map[string][]string{}
+ note := func(what string, rec *httptest.ResponseRecorder) {
+ t.Helper()
+ if rec.Code != http.StatusOK {
+ t.Fatalf("%s: status %d", what, rec.Code)
+ }
+ seen[what] = rec.Header().Values("Content-Security-Policy")
+ }
+ note("the viewer", get(t, h, "/d/"+sqid+"?slide=1", cookies...))
+ note("the editor", get(t, h, "/d/"+sqid+"/edit", cookies...))
+ note("the scene", get(t, h, "/d/"+sqid+"/scenes/"+id+"/"+ref, cookies...))
+ req := httptest.NewRequest(http.MethodPost, "/d/"+sqid+"/scenes/preview", strings.NewReader(string(sceneBundle)))
+ req.Header.Set("Content-Type", "text/html")
+ req.Header.Set("Origin", testOrigin)
+ req.Header.Set("Sec-Fetch-Site", "same-origin")
+ for _, c := range cookies {
+ req.AddCookie(c)
+ }
+ rec := httptest.NewRecorder()
+ h.ServeHTTP(rec, req)
+ note("the preview", rec)
+ b := newApp(t)
+ confirm := httptest.NewRecorder()
+ productionHandler(t, b).ServeHTTP(confirm, httptest.NewRequest(http.MethodGet, strings.TrimPrefix(mailedLink(t, b, allowedAddress), testOrigin), nil))
+ note("the confirm door", confirm)
+
+ want := map[string][]string{
+ "the viewer": {slides.ContentSecurityPolicy},
+ "the editor": {slides.ContentSecurityPolicy},
+ "the scene": {slides.SealedPolicy},
+ "the preview": {slides.SealedPolicy},
+ "the confirm door": {slides.ContentSecurityPolicy, "frame-ancestors 'none'"},
+ }
+ distinct := map[string]bool{}
+ for what, got := range seen {
+ if strings.Join(got, "\n") != strings.Join(want[what], "\n") {
+ t.Errorf("%s: CSP = %q, want %q", what, got, want[what])
+ }
+ for _, p := range got {
+ distinct[p] = true
+ }
+ }
+ if len(distinct) != 3 {
+ t.Errorf("the pages are served under %d policies, want 3: %v", len(distinct), distinct)
+ }
+ for p := range distinct {
+ framing := directives(p)["frame-ancestors"]
+ if p == slides.SealedPolicy {
+ if framing != "'self'" {
+ t.Errorf("the sealed policy's frame-ancestors = %q, want 'self'", framing)
+ }
+ } else if framing != "'none'" {
+ t.Errorf("%q: frame-ancestors = %q, want 'none'", p, framing)
+ }
+ }
+ if s := directives(slides.SealedPolicy)["sandbox"]; s != "allow-scripts" {
+ t.Errorf("the sealed policy's sandbox = %q, want allow-scripts and nothing else", s)
+ }
+}