| 1 | package slides |
| 2 | |
| 3 | // scenes.go is a scene's code getting into a deck and back out of it, |
| 4 | // sealed (scenes and clips spec §3, §8.4, §8.6). |
| 5 | // |
| 6 | // POST /d/{sqid}/uploads, /d/{sqid}/assets a bundle, as a picture goes in |
| 7 | // GET {surface}/scenes/{id}/{ref} the bundle, sealed |
| 8 | // POST /d/{sqid}/scenes/preview unsaved code, sealed |
| 9 | // |
| 10 | // A bundle is an asset of kind scene: one HTML document of at most |
| 11 | // 2 MiB, every script and style inline. It goes in through the pictures' |
| 12 | // own flow (assets.go): signed as text/html, PUT to the staging key, |
| 13 | // then registered, which reads the bytes back, checks they are one HTML |
| 14 | // document and puts them back under their own hash. What registration |
| 15 | // writes is a SceneBundle row rather than a DeckAsset one, so a bundle |
| 16 | // is never a picture: the picture routes answer 404 for its ref. |
| 17 | // |
| 18 | // The bundle comes back only through the sealed routes, one per |
| 19 | // surface, each behind the same capability the surface's pictures are, |
| 20 | // and only when the deck's scene {id} names {ref} as its code. Always |
| 21 | // from this app, never a redirect to the bucket, because the sealed |
| 22 | // policy travels on this app's answer and nowhere else. |
| 23 | // |
| 24 | // THE SEALED POLICY (SealedPolicy, serving.go) is what makes running an |
| 25 | // agent's code inside a page of this app safe. `sandbox allow-scripts` |
| 26 | // without allow-same-origin gives the document an opaque origin: no |
| 27 | // cookies, no storage, nothing of the page around it, no forms, no |
| 28 | // popups, no navigating the page. default-src 'none' with only inline |
| 29 | // script and style and data:/blob: pictures, fonts and media leaves it |
| 30 | // no network at all. frame-ancestors 'self' lets this app's own pages |
| 31 | // frame it and nobody else's. It replaces the app-wide policy rather |
| 32 | // than joining it: a browser enforces every policy it is sent, so a |
| 33 | // second one could only narrow this one, and Slides' own would take the |
| 34 | // sandbox's scripts away (TestTheSealedPolicyIsTheOneFramingException). |
| 35 | |
| 36 | import ( |
| 37 | "bytes" |
| 38 | "errors" |
| 39 | "io" |
| 40 | "mime" |
| 41 | "net/http" |
| 42 | "strings" |
| 43 | "unicode/utf8" |
| 44 | |
| 45 | "github.com/go-chi/chi/v5" |
| 46 | |
| 47 | "amadan.net/oficina/slides/internal/slides/deck" |
| 48 | "amadan.net/rastrillo/rastrillo/blobs" |
| 49 | ) |
| 50 | |
| 51 | // sceneType is a bundle's media type: what the upload is signed as and |
| 52 | // what the sealed routes answer with. |
| 53 | const sceneType = "text/html" |
| 54 | |
| 55 | // maxSceneBytes is the most a bundle may be (spec §2): 2 MiB, held at |
| 56 | // the sign, the development PUT, registration and the preview. |
| 57 | const maxSceneBytes = 2 << 20 |
| 58 | |
| 59 | // sniffScene reports whether raw is one HTML document as a bundle must |
| 60 | // be: UTF-8 throughout, and opening, after an optional byte-order mark |
| 61 | // and white space, with <!doctype html or <html in any case. |
| 62 | func sniffScene(raw []byte) bool { |
| 63 | if !utf8.Valid(raw) { |
| 64 | return false |
| 65 | } |
| 66 | head := bytes.TrimPrefix(raw, []byte("\xef\xbb\xbf")) |
| 67 | head = bytes.TrimLeft(head, " \t\n\f\r") |
| 68 | if len(head) > 16 { |
| 69 | head = head[:16] |
| 70 | } |
| 71 | head = bytes.ToLower(head) |
| 72 | for _, open := range []string{"<!doctype html", "<html"} { |
| 73 | if rest, ok := bytes.CutPrefix(head, []byte(open)); ok { |
| 74 | return len(rest) == 0 || strings.IndexByte(" \t\n\f\r>", rest[0]) >= 0 |
| 75 | } |
| 76 | } |
| 77 | return false |
| 78 | } |
| 79 | |
| 80 | // sceneFail is a refusal of a bundle or a preview: a fixed code for a |
| 81 | // program and a short English sentence for the developer reading the |
| 82 | // answer, as the core's API diagnostics are. Not catalog words: the |
| 83 | // editor's code panel will map the codes to its own approved ones; the |
| 84 | // pictures' catalog messages all say "image". |
| 85 | func sceneFail(w http.ResponseWriter, status int, code string) { |
| 86 | writeAssetJSON(w, status, map[string]string{"error": code, "message": sceneFailures[code]}) |
| 87 | } |
| 88 | |
| 89 | // sceneFailures is the developer's sentence for each code sceneFail |
| 90 | // answers. |
| 91 | var sceneFailures = map[string]string{ |
| 92 | "too_large": "A scene's code may be at most 2 MiB, and a preview request at most 2 MiB plus 64 KiB.", |
| 93 | "not_html": "A scene's code must be one UTF-8 HTML document opening with <!doctype html> or <html>.", |
| 94 | "not_found": "No upload staged by you for this deck has that ref, or its bytes never arrived.", |
| 95 | "hash_mismatch": "The bytes that arrived do not have the hash the upload declared.", |
| 96 | "already_verified": "That upload address is already in use.", |
| 97 | "unsupported_type": "A preview is text/html, or a form with one field, html.", |
| 98 | "invalid": "A preview form carries one field, html, and nothing else.", |
| 99 | "internal": "The scene's code could not be stored. Try again.", |
| 100 | } |
| 101 | |
| 102 | // registerScene is registerAsset for a receipt staged as text/html: read |
| 103 | // the bytes back, refuse anything but one HTML document of at most |
| 104 | // 2 MiB, put them back under their own hash and record the bundle for |
| 105 | // this deck. It answers {kind, ref}; the client names the ref as a |
| 106 | // scene's code in add_scene or set_scene, which is what makes it |
| 107 | // servable (serveScene), as register_asset does for a picture. |
| 108 | func (a *app) registerScene(w http.ResponseWriter, r *http.Request, u User, d Deck, store blobs.Store, up AssetUpload) { |
| 109 | object := up.ObjectKey |
| 110 | if object == "" { |
| 111 | sceneFail(w, http.StatusNotFound, "not_found") |
| 112 | return |
| 113 | } |
| 114 | raw, err := a.readObject(r.Context(), store, object, maxSceneBytes) |
| 115 | if err != nil { |
| 116 | switch { |
| 117 | case errors.Is(err, blobs.ErrNotFound): |
| 118 | sceneFail(w, http.StatusNotFound, "not_found") |
| 119 | case errors.Is(err, errAssetTooLarge): |
| 120 | sceneFail(w, http.StatusRequestEntityTooLarge, "too_large") |
| 121 | default: |
| 122 | a.logger.Error("slides: read an uploaded scene", "deck", d.Sqid, "err", err) |
| 123 | sceneFail(w, http.StatusInternalServerError, "internal") |
| 124 | } |
| 125 | return |
| 126 | } |
| 127 | if !sniffScene(raw) { |
| 128 | sceneFail(w, http.StatusUnprocessableEntity, "not_html") |
| 129 | return |
| 130 | } |
| 131 | ref, err := a.keepScene(r.Context(), u, d, store, raw) |
| 132 | if err != nil { |
| 133 | if a.guardRefused(w, r, err) { |
| 134 | return |
| 135 | } |
| 136 | a.logger.Error("slides: keep an uploaded scene", "deck", d.Sqid, "err", err) |
| 137 | sceneFail(w, http.StatusInternalServerError, "internal") |
| 138 | return |
| 139 | } |
| 140 | a.spendUpload(r, d, up, object, ref) |
| 141 | writeAssetJSON(w, http.StatusOK, map[string]any{"kind": "scene", "ref": ref}) |
| 142 | } |
| 143 | |
| 144 | // --- GET {surface}/scenes/{id}/{ref} --- |
| 145 | |
| 146 | // deckScene serves a scene's bundle to a signed-in reader of the deck. |
| 147 | func (a *app) deckScene(w http.ResponseWriter, r *http.Request) { |
| 148 | u, ok := a.viewer(w, r) |
| 149 | if !ok { |
| 150 | return |
| 151 | } |
| 152 | d, ok := a.deckFor(w, r, u) |
| 153 | if !ok { |
| 154 | return |
| 155 | } |
| 156 | a.serveScene(w, r, d) |
| 157 | } |
| 158 | |
| 159 | // sharedScene serves it to somebody holding a share link. |
| 160 | func (a *app) sharedScene(w http.ResponseWriter, r *http.Request) { |
| 161 | d, _, ok := a.deckForShareLink(w, r, chi.URLParam(r, "token")) |
| 162 | if !ok { |
| 163 | return |
| 164 | } |
| 165 | a.serveScene(w, r, d) |
| 166 | } |
| 167 | |
| 168 | // presentScene serves it to a projector, a presenter's window or an |
| 169 | // audience following along (presentation.go). |
| 170 | func (a *app) presentScene(w http.ResponseWriter, r *http.Request) { |
| 171 | p, ok := a.presentationFor(w, r) |
| 172 | if !ok { |
| 173 | return |
| 174 | } |
| 175 | d, ok := a.deckOf(w, r, p) |
| 176 | if !ok { |
| 177 | return |
| 178 | } |
| 179 | a.serveScene(w, r, d) |
| 180 | } |
| 181 | |
| 182 | // serveScene is the one body behind all three: the bundle was registered |
| 183 | // for this deck (SceneBundle) AND the deck's scene id names it as its |
| 184 | // code, as serveAsset asks of a picture; then the bytes, sealed. Every |
| 185 | // other answer is the same 404, so a reader learns nothing about what |
| 186 | // other decks hold. |
| 187 | func (a *app) serveScene(w http.ResponseWriter, r *http.Request, d Deck) { |
| 188 | id, ref := chi.URLParam(r, "id"), chi.URLParam(r, "ref") |
| 189 | store := a.cfg.Blobs |
| 190 | if !deck.SceneID(id) || !assetRefPattern.MatchString(ref) || store == nil { |
| 191 | a.notFound(w, r) |
| 192 | return |
| 193 | } |
| 194 | var verified int64 |
| 195 | if err := a.db.G.WithContext(r.Context()).Model(&SceneBundle{}). |
| 196 | Where("deck_id = ? AND ref = ?", d.ID, ref).Count(&verified).Error; err != nil { |
| 197 | a.fail(w, r, "look up a verified scene", err) |
| 198 | return |
| 199 | } |
| 200 | if verified == 0 { |
| 201 | a.notFound(w, r) |
| 202 | return |
| 203 | } |
| 204 | h, view, err := a.openDeck(r.Context(), d) |
| 205 | if err != nil { |
| 206 | a.fail(w, r, "open a deck to serve a scene", err) |
| 207 | return |
| 208 | } |
| 209 | h.Close(r.Context()) |
| 210 | if scene, ok := view.Scenes[id]; !ok || scene.Code != ref { |
| 211 | a.notFound(w, r) |
| 212 | return |
| 213 | } |
| 214 | raw, err := a.readObject(r.Context(), store, ref, maxSceneBytes) |
| 215 | if err != nil { |
| 216 | if errors.Is(err, blobs.ErrNotFound) || errors.Is(err, errAssetTooLarge) { |
| 217 | a.notFound(w, r) |
| 218 | return |
| 219 | } |
| 220 | a.fail(w, r, "read a scene", err) |
| 221 | return |
| 222 | } |
| 223 | // The bytes are judged again, as serveAsset judges a picture's: the |
| 224 | // row says they were judged once, and this keeps the sealed route |
| 225 | // from ever answering text/html for anything else. |
| 226 | if !sniffScene(raw) { |
| 227 | a.notFound(w, r) |
| 228 | return |
| 229 | } |
| 230 | sealedHeaders(w) |
| 231 | // Content-addressed, so a year is honest; private, because the |
| 232 | // address is the deck's capability, not the object's. |
| 233 | w.Header().Set("Cache-Control", "private, max-age=31536000, immutable") |
| 234 | w.Header().Set("ETag", `"`+ref+`"`) |
| 235 | if match := r.Header.Get("If-None-Match"); match != "" && strings.Contains(match, `"`+ref+`"`) { |
| 236 | w.WriteHeader(http.StatusNotModified) |
| 237 | return |
| 238 | } |
| 239 | w.Write(raw) |
| 240 | } |
| 241 | |
| 242 | // sealedHeaders is the header set every sealed answer carries: the |
| 243 | // sealed policy in place of the app's (never beside it), no sniffing, |
| 244 | // no referrer, and framing by this app's own pages. X-Frame-Options is |
| 245 | // rastrillo's DENY otherwise, which a browser reading only that header |
| 246 | // would hold against the frame-ancestors the policy allows. |
| 247 | func sealedHeaders(w http.ResponseWriter) { |
| 248 | h := w.Header() |
| 249 | h.Set("Content-Type", "text/html; charset=utf-8") |
| 250 | h.Set("Content-Security-Policy", SealedPolicy) |
| 251 | h.Set("X-Content-Type-Options", "nosniff") |
| 252 | h.Set("Referrer-Policy", "no-referrer") |
| 253 | h.Set("X-Frame-Options", "SAMEORIGIN") |
| 254 | } |
| 255 | |
| 256 | // --- POST /d/{sqid}/scenes/preview --- |
| 257 | |
| 258 | // maxPreviewRequest is the most a preview request's body may be, however |
| 259 | // it is encoded: the 2 MiB of text, and 64 KiB for a form's field name, |
| 260 | // boundaries and part headers. A form posted url-encoded grows with |
| 261 | // every byte it escapes, so the editor posts its preview as |
| 262 | // multipart/form-data, which carries the text as it is. |
| 263 | const maxPreviewRequest = maxSceneBytes + 64<<10 |
| 264 | |
| 265 | // previewScene answers the code panel's unsaved text under the sealed |
| 266 | // policy, so a draft runs exactly as the saved bundle will and is never |
| 267 | // stored. The editor submits a form into a named frame, so the text |
| 268 | // comes as a form's one html field (multipart or url-encoded) or, from |
| 269 | // a script, as a text/html body. Signed-in people of the deck only; |
| 270 | // csrf.Protect has already turned away anything not posted from this |
| 271 | // app's own pages. |
| 272 | func (a *app) previewScene(w http.ResponseWriter, r *http.Request) { |
| 273 | u, ok := a.viewer(w, r) |
| 274 | if !ok { |
| 275 | return |
| 276 | } |
| 277 | if _, ok := a.deckFor(w, r, u); !ok { |
| 278 | return |
| 279 | } |
| 280 | r.Body = http.MaxBytesReader(w, r.Body, maxPreviewRequest) |
| 281 | media, _, _ := mime.ParseMediaType(r.Header.Get("Content-Type")) |
| 282 | var html []byte |
| 283 | switch media { |
| 284 | case sceneType: |
| 285 | body, err := io.ReadAll(r.Body) |
| 286 | if err != nil { |
| 287 | previewFail(w, err) |
| 288 | return |
| 289 | } |
| 290 | html = body |
| 291 | case "application/x-www-form-urlencoded": |
| 292 | if err := r.ParseForm(); err != nil { |
| 293 | previewFail(w, err) |
| 294 | return |
| 295 | } |
| 296 | if len(r.PostForm) != 1 || len(r.PostForm["html"]) != 1 { |
| 297 | sceneFail(w, http.StatusBadRequest, "invalid") |
| 298 | return |
| 299 | } |
| 300 | html = []byte(r.PostForm.Get("html")) |
| 301 | case "multipart/form-data": |
| 302 | field, err := previewField(r) |
| 303 | if err != nil { |
| 304 | previewFail(w, err) |
| 305 | return |
| 306 | } |
| 307 | html = field |
| 308 | default: |
| 309 | sceneFail(w, http.StatusUnsupportedMediaType, "unsupported_type") |
| 310 | return |
| 311 | } |
| 312 | if len(html) > maxSceneBytes { |
| 313 | sceneFail(w, http.StatusRequestEntityTooLarge, "too_large") |
| 314 | return |
| 315 | } |
| 316 | sealedHeaders(w) |
| 317 | w.Header().Set("Cache-Control", "no-store") |
| 318 | w.Write(html) |
| 319 | } |
| 320 | |
| 321 | // previewFail answers a preview body that could not be read: too large, |
| 322 | // or not a body at all. |
| 323 | func previewFail(w http.ResponseWriter, err error) { |
| 324 | var tooBig *http.MaxBytesError |
| 325 | if errors.As(err, &tooBig) { |
| 326 | sceneFail(w, http.StatusRequestEntityTooLarge, "too_large") |
| 327 | return |
| 328 | } |
| 329 | sceneFail(w, http.StatusBadRequest, "invalid") |
| 330 | } |
| 331 | |
| 332 | // errPreviewFields is a multipart preview with any part but one html. |
| 333 | var errPreviewFields = errors.New("slides: a preview form carries one field, html") |
| 334 | |
| 335 | // previewField reads a multipart preview's one html field, part by part |
| 336 | // so nothing goes to disk, refusing a form with any other part or a |
| 337 | // second html. |
| 338 | func previewField(r *http.Request) ([]byte, error) { |
| 339 | parts, err := r.MultipartReader() |
| 340 | if err != nil { |
| 341 | return nil, err |
| 342 | } |
| 343 | var html []byte |
| 344 | seen := false |
| 345 | for { |
| 346 | part, err := parts.NextPart() |
| 347 | if errors.Is(err, io.EOF) { |
| 348 | break |
| 349 | } |
| 350 | if err != nil { |
| 351 | return nil, err |
| 352 | } |
| 353 | if part.FormName() != "html" || seen { |
| 354 | return nil, errPreviewFields |
| 355 | } |
| 356 | seen = true |
| 357 | if html, err = io.ReadAll(part); err != nil { |
| 358 | return nil, err |
| 359 | } |
| 360 | } |
| 361 | if !seen { |
| 362 | return nil, errPreviewFields |
| 363 | } |
| 364 | // The parser stops at the closing boundary, and an epilogue may |
| 365 | // follow it. The request is read through to its end, so one past the |
| 366 | // limit is refused (MaxBytesReader trips) rather than answered. |
| 367 | if _, err := io.Copy(io.Discard, r.Body); err != nil { |
| 368 | return nil, err |
| 369 | } |
| 370 | return html, nil |
| 371 | } |
| 372 | |