Slides: an agent adds a picture with POST /api/v1/decks/{sqid}/assets
The body is the image: a PNG, JPEG or WebP by its magic, at most 20 MiB, whose header decodes within the 30000-pixel bound. The bytes are stored under their SHA-256 as browser uploads are, the deck_assets row is written so every surface serves them, and register_asset (width, height, ?alt=) is applied as the agent, built from the document it lands on (applyAgentOpsFrom, from feat/scenes). The same bytes twice answer 200 with the existing asset and write nothing; a new one answers 201 with id, ref, width and height. Refusals: not_found, too_large, not_an_image (SVG included), no_store. docs/api.md documents it with a curl and an add_block example in place of "An agent cannot add a picture today"; AGENTS.md says where it lives. The team-mode write-route test covers the new route.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
6 files changed,
+587
−32
AGENTS.md+12 −2docs/api.md+63 −17internal/slides/agent_assets.go+172 −0internal/slides/api.go+41 −13internal/slides/team_guard_test.go+3 −0internal/slidestest/agent_assets_test.go+296 −0
diff --git a/AGENTS.md b/AGENTS.md| index 0be4979..94be005 100644 |
| --- a/AGENTS.md |
| +++ b/AGENTS.md |
| @@ -172,6 +172,14 @@ seeded on first sign-in — and comes back out as a PDF. |
| `0008_create_asset_uploads.sql`): one deck, one actor, single use, two |
| hours. A ref alone registers nothing, and no PUT is ever signed for an |
| address something is already served from (spec §2.7, codex 1 and 2). |
| + An agent uploads with the bearer instead (`agent_assets.go`, |
| + `POST /api/v1/decks/{sqid}/assets`): the bytes are the body, at most |
| + 20 MiB, a PNG, JPEG or WebP by its magic that `image.DecodeConfig` |
| + reads within `maxAssetDimension` (no SVG), stored under their hash, |
| + the `deck_assets` row written, then `register_asset` (with width, |
| + height and `?alt=`) applied as the agent through `applyAgentOpsFrom`, |
| + which builds the batch from the document it lands on. The same bytes |
| + twice are one asset: 200 with the existing id, nothing written. |
| - **The font library** (`library.go`, `fonts.html`, estilo's `typeface` |
| package): `/fonts` is a person's own set of fonts, uploaded through |
| the app (TTF, OTF, WOFF, WOFF2; `typeface.Inspect` reads the family, |
| @@ -280,6 +288,7 @@ plus `templates/` — with one file per screen area beside them (`auth.go`, |
| `decks.go`, `viewer.go`, `share.go`, `presentation.go`, `sample.go`, |
| `live.go`, `editor.go`, `snapshot.go`, `assets.go`, `svg.go`, |
| `thumbs.go`, `export.go`, `exports.go`, `api.go`, `agents.go`, |
| +`agent_assets.go`, |
| `assets_embed.go`, and team mode's `team_*.go`) and one |
| package per concern nested underneath: `core` (the wazero host), `deck` |
| (Go types for the core's JSON view), `render` (slide HTML), `layout` |
| @@ -443,8 +452,9 @@ deck's `assets` map refers to *this* ref before it serves a byte; |
| without that, any capability for any deck would fetch any object in the |
| bucket. It costs an `openDeck` per image request, which is known and |
| noted rather than forgotten. It also requires a `deck_assets` row for |
| -the pair, written only by `registerAsset` after it read, sniffed and |
| -sanitised the bytes: `register_asset` is an op any member can apply with |
| +the pair, written only by `registerAsset` (or the agent's upload, |
| +`apiPostAsset`) after it read, sniffed and sanitised or decoded the |
| +bytes: `register_asset` is an op any member can apply with |
| any ref, and a presigned PUT lands whatever the browser sent, so the map |
| alone would let an unverified object be served. |
diff --git a/docs/api.md b/docs/api.md| index 6d6fe0e..91274ee 100644 |
| --- a/docs/api.md |
| +++ b/docs/api.md |
| @@ -62,7 +62,8 @@ takes effect without anybody hunting down tokens. |
| Requests with a body send JSON and say so: |
| `Content-Type: application/json`. Anything else is a 415. A body over |
| -1 MiB is a 413. |
| +1 MiB is a 413. The one exception is adding a picture, whose body is |
| +the image itself (see `POST /api/v1/decks/{sqid}/assets`). |
| Every answer with a body is JSON. Every error is: |
| @@ -80,7 +81,7 @@ Every answer with a body is JSON. Every error is: |
| | 404 | `not_found` | No such deck, slide or path — including a deck the operator cannot see. A deck that is not yours does not exist. | |
| | 405 | `method_not_allowed` | Right path, wrong verb. | |
| | 409 | `conflict` | Somebody else wrote to the deck while this batch was landing, twice. Re-read the deck and decide what your batch now means. | |
| -| 413 | `too_large` | The body is over 1 MiB. | |
| +| 413 | `too_large` | The body is over 1 MiB (a picture: over 20 MiB). | |
| | 415 | `unsupported_media_type` | The body is not `application/json`. | |
| | 422 | `invalid` | The request was read and refused. `message` says why; `op` is the index of the operation at fault, when the failure was about one. A body carrying anything after its JSON value is refused here too, rather than half-read. | |
| | 429 | `busy` | You already have four exports running. Wait for one to finish; nothing was started. | |
| @@ -239,6 +240,52 @@ It is not a substitute for reading the document: a picture is for |
| looking at what you made, and `GET /api/v1/decks/{sqid}` is for knowing |
| what is in it. |
| +### `POST /api/v1/decks/{sqid}/assets` — add a picture |
| + |
| +The body is the image: a PNG, JPEG or WebP, at most 20 MiB, that |
| +decodes and is no more than 30000 pixels either way. The type is read |
| +from the bytes, not from `Content-Type`, so send whatever header your |
| +client likes. `?alt=` gives the picture its description, which a screen |
| +reader says in place of it; leave it out only for a picture that is |
| +decoration. The same bearer and the same decks as |
| +`POST /api/v1/decks/{sqid}/ops`. |
| + |
| +```sh |
| +curl -X POST -H "Authorization: Bearer $SLIDES_TOKEN" \ |
| + --data-binary @roadmap.png \ |
| + "https://slides.example/api/v1/decks/k7m2xq9dwb/assets?alt=Three%20phases%2C%20each%20with%20a%20date" |
| +``` |
| + |
| +```json |
| +{"id": "b3k9xw2mq7tz", "ref": "9f2c1e...ab", "width": 1600, "height": 900} |
| +``` |
| + |
| +The server keeps the bytes under their SHA-256 (`ref`), as it does a |
| +picture uploaded in the editor, and applies `register_asset` to the |
| +deck as you, so anybody with the deck open sees it at once. `id` is the |
| +asset's id in the deck: an image block names it as `props.asset`. |
| + |
| +The answer is `201` for a new picture. Send the same bytes to the same |
| +deck again and the answer is `200` with the asset already there, its |
| +`id` and `ref` unchanged; nothing is added. |
| + |
| +Then put it on a slide. Here `$S` is a slide made with the |
| +`image-full` template, whose `media` region takes a picture; on a |
| +canvas slide give a `box` instead, as under `add_block` below. |
| + |
| +```sh |
| +curl -X POST -H "Authorization: Bearer $SLIDES_TOKEN" \ |
| + -H "Content-Type: application/json" \ |
| + -d '{"ops":[{"op":"add_block","slide":"'"$S"'","type":"image", |
| + "region":"media","props":{"asset":"b3k9xw2mq7tz"}}]}' \ |
| + https://slides.example/api/v1/decks/k7m2xq9dwb/ops |
| +``` |
| + |
| +Refusals are `{"error": "…", "message": "…"}`: `not_found` (no such |
| +deck, or not yours; 404), `too_large` (413), `not_an_image` (422: |
| +anything else, including SVG and bytes that only start like a picture), |
| +and `no_store` (503: this instance has nowhere to keep pictures). |
| + |
| ### `POST /api/v1/decks/{sqid}/export` — make a PDF |
| ```sh |
| @@ -560,9 +607,10 @@ layout, never a replacement for it. |
| ### Assets |
| -**`register_asset`** — name an image the deck can use. The bytes go up |
| -separately (see "Getting the bytes there" below); this records the |
| -result. `ref` is the object store's address for those bytes — a hex |
| +**`register_asset`** — name an image the deck can use. An agent does |
| +not need it: `POST /api/v1/decks/{sqid}/assets` uploads the picture and |
| +applies this for you. The editor's upload applies it itself (see |
| +"Getting the bytes there" below). `ref` is the object store's address for those bytes — a hex |
| SHA-256, because the store is content-addressed. |
| ```sh |
| @@ -582,18 +630,16 @@ which is content-addressed and shared. |
| ## Getting the bytes there |
| -Images never travel through this API. They go browser-to-bucket, and |
| -three endpoints on the *signed-in* surface arrange it. They take a |
| -session cookie rather than a bearer token, because they are what the |
| -editor's own upload uses. |
| - |
| -**An agent cannot add a picture today.** It can name a ref in a |
| -`register_asset` op, and the document will hold it, but no surface will |
| -serve those bytes: serving requires a verification row, and a |
| -verification row is only ever written by the registration endpoint |
| -below, for an upload it signed itself. Naming an address is not a way |
| -to publish one. A bearer-authenticated upload is the obvious next |
| -thing to build and is not built. |
| +This section is the editor's upload: three endpoints on the |
| +*signed-in* surface, which take a session cookie rather than a bearer |
| +token. **An agent adds a picture with |
| +`POST /api/v1/decks/{sqid}/assets`** (above) and needs none of this. |
| + |
| +A ref named in a `register_asset` op is held by the document, but no |
| +surface serves bytes until the server has read and checked them itself: |
| +serving requires a verification row, written only by the registration |
| +endpoint below or by the agent's upload. Naming an address is not a |
| +way to publish one. |
| Limits, on all three: 20 MiB per image, and PNG, JPEG, WebP or SVG. |
diff --git a/internal/slides/agent_assets.go b/internal/slides/agent_assets.go| new file mode 100644 |
| index 0000000..36cb5f8 |
| --- /dev/null |
| +++ b/internal/slides/agent_assets.go |
| @@ -0,0 +1,172 @@ |
| +// agent_assets.go is how an agent puts a picture in a deck, over the |
| +// bearer API: |
| +// |
| +// POST /api/v1/decks/{sqid}/assets?alt=<description> |
| +// |
| +// The body is the image itself, not JSON and not a signed upload: an |
| +// agent has no browser to PUT to a bucket, and the registration endpoint |
| +// in assets.go only verifies bytes a session staged. So this route does |
| +// that endpoint's work on bytes it read itself. It judges them by what |
| +// they are rather than by any header (a PNG, JPEG or WebP that decodes, |
| +// within the size a picture may be), stores them under their own hash, |
| +// writes the DeckAsset row that serveAsset requires, and applies |
| +// `register_asset` through the ops path as the agent, so live editors |
| +// see it and it has a seq, an actor and an undo step like any other |
| +// change. |
| +// |
| +// SVG is refused here, though the browser path takes it through |
| +// svg.go's sanitiser: a sanitised SVG has no pixel size to answer with, |
| +// and an agent that has an SVG can as well send the picture of it. |
| +// |
| +// The same bytes twice for one deck are one asset: the second upload |
| +// finds the ref already in the deck's map and answers it with 200, |
| +// writing nothing to the document. |
| +package slides |
| + |
| +import ( |
| + "bytes" |
| + "encoding/json" |
| + "errors" |
| + "image" |
| + "io" |
| + "net/http" |
| + "slices" |
| + "time" |
| + |
| + "gorm.io/gorm" |
| + "gorm.io/gorm/clause" |
| + |
| + "amadan.net/oficina/slides/internal/slides/deck" |
| +) |
| + |
| +// apiAssetMessages is the developer's sentence for each refusal this |
| +// route adds to the API's own. |
| +var apiAssetMessages = map[string]string{ |
| + errTooLarge: "A picture may be at most 20 MiB.", |
| + "not_an_image": "A picture is a PNG, JPEG or WebP that decodes, at most 30000 pixels either way. SVG is not taken here.", |
| + "no_store": "This instance has no object store to keep pictures in.", |
| +} |
| + |
| +// apiAssetFail answers one refusal with its code and its sentence. |
| +func (a *app) apiAssetFail(w http.ResponseWriter, status int, code string) { |
| + a.writeJSON(w, status, map[string]string{"error": code, "message": apiAssetMessages[code]}) |
| +} |
| + |
| +// errAssetKnown is a batch not built because the deck already registers |
| +// the ref: the upload is a duplicate, and there is nothing to write. |
| +var errAssetKnown = errors.New("slides: the deck already registers this picture") |
| + |
| +// apiPostAsset serves POST /api/v1/decks/{sqid}/assets. |
| +func (a *app) apiPostAsset(w http.ResponseWriter, r *http.Request) { |
| + p, ok := a.apiPrincipal(w, r) |
| + if !ok { |
| + return |
| + } |
| + d, ok := a.apiDeckFor(w, r, p) |
| + if !ok { |
| + return |
| + } |
| + store := a.cfg.Blobs |
| + if store == nil { |
| + a.apiAssetFail(w, http.StatusServiceUnavailable, "no_store") |
| + return |
| + } |
| + |
| + raw, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxAssetBytes)) |
| + if err != nil { |
| + var tooBig *http.MaxBytesError |
| + if errors.As(err, &tooBig) { |
| + a.apiAssetFail(w, http.StatusRequestEntityTooLarge, errTooLarge) |
| + return |
| + } |
| + apiFail(w, http.StatusBadRequest, errInvalid) |
| + return |
| + } |
| + // Judged by its bytes: one of the three raster types by its magic, |
| + // then a header that decodes to a size a picture may be. The size is |
| + // what the image says it is, which is the only size there is for an |
| + // agent to be held to. |
| + kind := sniffImage(raw) |
| + if kind != "image/png" && kind != "image/jpeg" && kind != "image/webp" { |
| + a.apiAssetFail(w, http.StatusUnprocessableEntity, "not_an_image") |
| + return |
| + } |
| + cfg, _, err := image.DecodeConfig(bytes.NewReader(raw)) |
| + if err != nil || cfg.Width < 1 || cfg.Height < 1 || cfg.Width > maxAssetDimension || cfg.Height > maxAssetDimension { |
| + a.apiAssetFail(w, http.StatusUnprocessableEntity, "not_an_image") |
| + return |
| + } |
| + alt := trimTo(r.URL.Query().Get("alt"), maxAssetAlt) |
| + |
| + // Content-addressed, as registerAsset promotes a browser's upload: |
| + // the ref is the SHA-256 of these bytes. |
| + stored, err := store.Put(r.Context(), bytes.NewReader(raw), kind) |
| + if err != nil { |
| + a.logger.Error("slides: keep an agent's picture", "deck", d.Sqid, "err", err) |
| + apiFail(w, http.StatusInternalServerError, errInternal) |
| + return |
| + } |
| + ref := stored.Hash |
| + |
| + // The verification row serveAsset requires, as registerAsset writes |
| + // it. Before the op, so a picture the deck names is always one it |
| + // can serve; a row whose op then fails serves nothing, since the |
| + // deck's map does not name the ref. |
| + g := a.deckGuard(r.Context(), p.operator, d) |
| + if err := a.guarded(r.Context(), g, func(db *gorm.DB) error { |
| + return db.Clauses(clause.OnConflict{DoNothing: true}). |
| + Create(&DeckAsset{DeckID: d.ID, Ref: ref, CreatedAt: time.Now().UTC()}).Error |
| + }); err != nil { |
| + if guardRefusedJSON(w, err) { |
| + return |
| + } |
| + a.logger.Error("slides: record an agent's verified picture", "deck", d.Sqid, "err", err) |
| + apiFail(w, http.StatusInternalServerError, errInternal) |
| + return |
| + } |
| + |
| + assetID, err := newID() |
| + if err != nil { |
| + apiFail(w, http.StatusInternalServerError, errInternal) |
| + return |
| + } |
| + // Built from the document the write lands on, so a duplicate is |
| + // judged against the deck as it is at the write, not as it was when |
| + // the request began. |
| + existing := "" |
| + build := func(view *deck.Deck) ([]map[string]json.RawMessage, error) { |
| + ids := make([]string, 0, len(view.Assets)) |
| + for id, asset := range view.Assets { |
| + if asset.Ref == ref { |
| + ids = append(ids, id) |
| + } |
| + } |
| + if len(ids) > 0 { |
| + slices.Sort(ids) |
| + existing = ids[0] |
| + return nil, errAssetKnown |
| + } |
| + return []map[string]json.RawMessage{opOf(map[string]any{ |
| + "op": "register_asset", "id": assetID, "ref": ref, |
| + "width": cfg.Width, "height": cfg.Height, "alt": alt, |
| + })}, nil |
| + } |
| + _, _, err = a.applyAgentOpsFrom(r.Context(), &d, p.actor(), build, g) |
| + switch { |
| + case err == nil: |
| + a.writeJSON(w, http.StatusCreated, map[string]any{"id": assetID, "ref": ref, "width": cfg.Width, "height": cfg.Height}) |
| + case errors.Is(err, errAssetKnown): |
| + a.writeJSON(w, http.StatusOK, map[string]any{"id": existing, "ref": ref, "width": cfg.Width, "height": cfg.Height}) |
| + default: |
| + a.apiOpsFailed(w, d, err) |
| + } |
| +} |
| + |
| +// opOf is one op of a batch, from the values it carries. |
| +func opOf(fields map[string]any) map[string]json.RawMessage { |
| + op := make(map[string]json.RawMessage, len(fields)) |
| + for k, v := range fields { |
| + op[k], _ = json.Marshal(v) |
| + } |
| + return op |
| +} |
diff --git a/internal/slides/api.go b/internal/slides/api.go| index ee0ad86..6d49f99 100644 |
| --- a/internal/slides/api.go |
| +++ b/internal/slides/api.go |
| @@ -77,9 +77,9 @@ const ( |
| // maxAPIBody is the largest request body this surface reads. A mebibyte |
| // is far more than any batch of operations needs — the biggest thing an |
| // op carries is a slide's Markdown — and it is the bound that stops an |
| -// unbounded read from being the way to take the process down. Asset |
| -// bytes never come through here (spec §7.2: a presigned upload, then |
| -// register_asset naming the result). |
| +// unbounded read from being the way to take the process down. A |
| +// picture's bytes come through POST .../assets instead, which reads at |
| +// most maxAssetBytes (agent_assets.go). |
| const maxAPIBody = 1 << 20 |
| // apiRouter is the whole drive surface, gated by the bearer and |
| @@ -95,6 +95,8 @@ func (a *app) apiRouter() http.Handler { |
| r.Post(apiPrefix+"/decks", a.apiCreateDeck) |
| r.Get(apiPrefix+"/decks/{sqid}", a.apiGetDeck) |
| r.Post(apiPrefix+"/decks/{sqid}/ops", a.apiOps) |
| + // A picture, the bytes as the body (agent_assets.go). |
| + r.Post(apiPrefix+"/decks/{sqid}/assets", a.apiPostAsset) |
| // {file} rather than {id}.html: chi can match a static tail inside |
| // a segment, but the extension is part of what this endpoint means |
| // — it is the HTML rendering of a slide, and the .svg thumbnail of |
| @@ -501,9 +503,18 @@ func (a *app) apiOps(w http.ResponseWriter, r *http.Request) { |
| } |
| ids, err := a.applyAgentOps(r.Context(), &d, p.actor(), body.Ops, a.deckGuard(r.Context(), p.operator, d)) |
| + if err != nil { |
| + a.apiOpsFailed(w, d, err) |
| + return |
| + } |
| + a.writeJSON(w, http.StatusOK, map[string]any{"seq": d.Seq, "ids": ids}) |
| +} |
| + |
| +// apiOpsFailed answers a batch the deck refused: the guard's answer, a |
| +// lost race twice over, the core's account of the op it refused, or a |
| +// 500. |
| +func (a *app) apiOpsFailed(w http.ResponseWriter, d Deck, err error) { |
| switch { |
| - case err == nil: |
| - a.writeJSON(w, http.StatusOK, map[string]any{"seq": d.Seq, "ids": ids}) |
| case guardRefusedJSON(w, err): |
| case errors.Is(err, errDeckBusy): |
| // Two attempts have already been made; a third would be |
| @@ -539,17 +550,34 @@ func (a *app) apiOps(w http.ResponseWriter, r *http.Request) { |
| // already written into the ops, so it mints nothing new and the caller |
| // is told the same ids either way. |
| func (a *app) applyAgentOps(ctx context.Context, d *Deck, actor string, ops []map[string]json.RawMessage, g writeGuard) (map[string]string, error) { |
| + ids, _, err := a.applyAgentOpsFrom(ctx, d, actor, func(*deck.Deck) ([]map[string]json.RawMessage, error) { return ops, nil }, g) |
| + return ids, err |
| +} |
| + |
| +// applyAgentOpsFrom is applyAgentOps for a batch that depends on the |
| +// document it lands on: build is given the view each attempt opened, so |
| +// whatever it checked is what the write is made against. The optimistic |
| +// lock refuses the write if the deck has moved since that open, and the |
| +// retry builds again from the newer one. An error from build is |
| +// returned as it is, with nothing written. It answers the document as |
| +// the write left it. |
| +func (a *app) applyAgentOpsFrom(ctx context.Context, d *Deck, actor string, build func(*deck.Deck) ([]map[string]json.RawMessage, error), g writeGuard) (map[string]string, *deck.Deck, error) { |
| var ids map[string]string |
| var lastErr error |
| for attempt := 0; attempt < 2; attempt++ { |
| h, view, err := a.openDeck(ctx, *d) |
| if err != nil { |
| - return nil, err |
| + return nil, nil, err |
| + } |
| + ops, err := build(view) |
| + if err != nil { |
| + h.Close(ctx) |
| + return nil, nil, err |
| } |
| minted, err := mintOpIDs(ops, view) |
| if err != nil { |
| h.Close(ctx) |
| - return nil, err |
| + return nil, nil, err |
| } |
| if attempt == 0 { |
| ids = minted |
| @@ -557,23 +585,23 @@ func (a *app) applyAgentOps(ctx context.Context, d *Deck, actor string, ops []ma |
| encoded, err := json.Marshal(ops) |
| if err != nil { |
| h.Close(ctx) |
| - return nil, fmt.Errorf("slides: encode ops: %w", err) |
| + return nil, nil, fmt.Errorf("slides: encode ops: %w", err) |
| } |
| - _, err = a.applyOps(ctx, h, d, actor, encoded, metaRowUpdates(ops), g) |
| + after, err := a.applyOps(ctx, h, d, actor, encoded, metaRowUpdates(ops), g) |
| h.Close(ctx) |
| if err == nil { |
| - return ids, nil |
| + return ids, after, nil |
| } |
| lastErr = err |
| if !errors.Is(err, errDeckBusy) { |
| - return nil, err |
| + return nil, nil, err |
| } |
| // Our copy's Seq is what just lost; re-read it before retrying. |
| if err := a.db.G.WithContext(ctx).First(d, d.ID).Error; err != nil { |
| - return nil, fmt.Errorf("slides: reload deck %s: %w", d.Sqid, err) |
| + return nil, nil, fmt.Errorf("slides: reload deck %s: %w", d.Sqid, err) |
| } |
| } |
| - return nil, lastErr |
| + return nil, nil, lastErr |
| } |
| // metaRowUpdates is the decks row's share of a batch: the title and |
diff --git a/internal/slides/team_guard_test.go b/internal/slides/team_guard_test.go| index 2c3914b..249d3d7 100644 |
| --- a/internal/slides/team_guard_test.go |
| +++ b/internal/slides/team_guard_test.go |
| @@ -224,6 +224,9 @@ func TestTeamEveryWriteRouteRefusesALapseBeforeCommit(t *testing.T) { |
| {"api present", nil, func() *httptest.ResponseRecorder { |
| return f.api(token, "POST", apiPrefix+"/decks/"+plan.Sqid+"/present", "") |
| }}, |
| + {"api asset", nil, func() *httptest.ResponseRecorder { |
| + return f.api(token, "POST", apiPrefix+"/decks/"+plan.Sqid+"/assets", string(png)) |
| + }}, |
| } |
| for _, route := range routes { |
| if route.setup != nil { |
diff --git a/internal/slidestest/agent_assets_test.go b/internal/slidestest/agent_assets_test.go| new file mode 100644 |
| index 0000000..591f42e |
| --- /dev/null |
| +++ b/internal/slidestest/agent_assets_test.go |
| @@ -0,0 +1,296 @@ |
| +package slidestest |
| + |
| +// An agent's pictures through the drive API (internal/slides/agent_assets.go): |
| +// POST /api/v1/decks/{sqid}/assets takes the image bytes as the body, |
| +// judges them, keeps them under their own hash, verifies them for the |
| +// deck and registers them as an asset of it, as the agent. |
| + |
| +import ( |
| + "bytes" |
| + "encoding/binary" |
| + "encoding/hex" |
| + "encoding/json" |
| + "fmt" |
| + "hash/crc32" |
| + "image" |
| + "image/color" |
| + "image/jpeg" |
| + "image/png" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/url" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +// webpPicture is a 4 by 3 lossless WebP of one flat colour (the export |
| +// test's fixture): Go has no WebP encoder, so the bytes are written out. |
| +func webpPicture(t *testing.T) []byte { |
| + t.Helper() |
| + raw, err := hex.DecodeString("524946461e000000574542505650384c110000002f0380000007508f2217a5ff8188e87f0000") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return raw |
| +} |
| + |
| +// jpegPicture is a w by h JPEG of one colour. |
| +func jpegPicture(t *testing.T, w, h int) []byte { |
| + t.Helper() |
| + img := image.NewRGBA(image.Rect(0, 0, w, h)) |
| + for i := range img.Pix { |
| + img.Pix[i] = 0x80 |
| + } |
| + img.Set(0, 0, color.Black) |
| + var buf bytes.Buffer |
| + if err := jpeg.Encode(&buf, img, nil); err != nil { |
| + t.Fatal(err) |
| + } |
| + return buf.Bytes() |
| +} |
| + |
| +// postPicture is one upload: the bytes as the body, under the token. |
| +func postPicture(t *testing.T, a *testApp, sqid, token, query string, body []byte) *httptest.ResponseRecorder { |
| + t.Helper() |
| + req := httptest.NewRequest(http.MethodPost, "/api/v1/decks/"+sqid+"/assets"+query, bytes.NewReader(body)) |
| + req.Header.Set("Authorization", "Bearer "+token) |
| + req.Header.Set("Content-Type", "application/octet-stream") |
| + return send(t, a, req) |
| +} |
| + |
| +func jsonObject(t *testing.T, rec *httptest.ResponseRecorder) map[string]any { |
| + t.Helper() |
| + if ct := rec.Header().Get("Content-Type"); !strings.HasPrefix(ct, "application/json") { |
| + t.Fatalf("Content-Type = %q, want JSON\n%s", ct, rec.Body) |
| + } |
| + var out map[string]any |
| + if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil { |
| + t.Fatalf("body is not a JSON object: %v\n%s", err, rec.Body) |
| + } |
| + return out |
| +} |
| + |
| +type agentAsset struct { |
| + Ref string `json:"ref"` |
| + Name string `json:"name"` |
| + Width int `json:"width"` |
| + Height int `json:"height"` |
| + Alt string `json:"alt"` |
| +} |
| + |
| +// deckAssets is the deck's assets as an agent reads them. |
| +func deckAssets(t *testing.T, a *testApp, token, sqid string) map[string]agentAsset { |
| + t.Helper() |
| + rec := send(t, a, bearerRequest(t, http.MethodGet, "/api/v1/decks/"+sqid, token, "")) |
| + if rec.Code != http.StatusOK { |
| + t.Fatalf("GET deck: status %d\n%s", rec.Code, rec.Body) |
| + } |
| + var view struct { |
| + Assets map[string]agentAsset `json:"assets"` |
| + } |
| + if err := json.Unmarshal(rec.Body.Bytes(), &view); err != nil { |
| + t.Fatal(err) |
| + } |
| + return view.Assets |
| +} |
| + |
| +// agentPictures is an app with a store, a signed-in person, their |
| +// agent's token and a deck. |
| +func agentPictures(t *testing.T) (a *testApp, cookies []*http.Cookie, token, sqid string) { |
| + t.Helper() |
| + cfg, mailer := newConfig(t) |
| + cfg.AllowedAddresses = []string{allowedAddress, otherAddress} |
| + cfg.Blobs = dirStore(t) |
| + a = newAppWith(t, cfg, mailer) |
| + cookies = signedIn(t, a, allowedAddress) |
| + token = mintAgent(t, a, cookies, "pictures") |
| + return a, cookies, token, apiDeck(t, a, token, "Pictures") |
| +} |
| + |
| +// TestAnAgentUploadsAPictureAndASlideDrawsIt: a PNG, a WebP and a JPEG go up, |
| +// come back 201 with their hash and size, are registered as the |
| +// agent's change, are served by the deck's picture route, and are drawn |
| +// by the slide's HTML and its thumbnail once an image block names them. |
| +func TestAnAgentUploadsAPictureAndASlideDrawsIt(t *testing.T) { |
| + a, cookies, token, sqid := agentPictures(t) |
| + for _, pic := range []struct { |
| + name string |
| + body []byte |
| + width, height int |
| + }{ |
| + {"png", onePixelPNG, 1, 1}, |
| + {"webp", webpPicture(t), 4, 3}, |
| + {"jpeg", jpegPicture(t, 5, 2), 5, 2}, |
| + } { |
| + alt := "A " + pic.name + " picture" |
| + rec := postPicture(t, a, sqid, token, "?alt="+url.QueryEscape(alt), pic.body) |
| + if rec.Code != http.StatusCreated { |
| + t.Fatalf("%s: status %d, want 201\n%s", pic.name, rec.Code, rec.Body) |
| + } |
| + out := jsonObject(t, rec) |
| + ref := hashOf(pic.body) |
| + if out["ref"] != ref || out["width"] != float64(pic.width) || out["height"] != float64(pic.height) { |
| + t.Fatalf("%s: answered %v, want ref %s and %dx%d", pic.name, out, ref, pic.width, pic.height) |
| + } |
| + id, _ := out["id"].(string) |
| + if id == "" { |
| + t.Fatalf("%s: no asset id in %v", pic.name, out) |
| + } |
| + |
| + got, ok := deckAssets(t, a, token, sqid)[id] |
| + if !ok || got != (agentAsset{Ref: ref, Name: got.Name, Width: pic.width, Height: pic.height, Alt: alt}) { |
| + t.Fatalf("%s: the deck's asset %s is %+v (present %v)", pic.name, id, got, ok) |
| + } |
| + |
| + var actor string |
| + if err := a.db.G.Raw("SELECT actor FROM deck_updates WHERE deck_id = (SELECT id FROM decks WHERE sqid = ?) ORDER BY seq DESC LIMIT 1", sqid).Scan(&actor).Error; err != nil { |
| + t.Fatal(err) |
| + } |
| + if !strings.HasPrefix(actor, "agent:") { |
| + t.Errorf("%s: the registration's actor is %q, want the agent", pic.name, actor) |
| + } |
| + |
| + served := mustGet(t, a, "/d/"+sqid+"/assets/"+ref, http.StatusOK, cookies) |
| + if !bytes.Equal(served.Body.Bytes(), pic.body) { |
| + t.Errorf("%s: the served bytes differ from what went up", pic.name) |
| + } |
| + |
| + slide := apiJSON(t, a, http.MethodPost, "/api/v1/decks/"+sqid+"/ops", token, |
| + `{"ops":[{"op":"add_slide","layout":"flow","template":"image-full"}]}`, http.StatusOK) |
| + slideID := slide["ids"].(map[string]any)["0"].(string) |
| + apiJSON(t, a, http.MethodPost, "/api/v1/decks/"+sqid+"/ops", token, |
| + fmt.Sprintf(`{"ops":[{"op":"add_block","slide":%q,"type":"image","region":"media","props":{"asset":%q}}]}`, |
| + slideID, id), http.StatusOK) |
| + page := mustGet(t, a, "/d/"+sqid+"/slides/"+slideID+".html", http.StatusOK, cookies).Body.String() |
| + if !strings.Contains(page, `src="/d/`+sqid+`/assets/`+ref+`"`) { |
| + t.Errorf("%s: the slide's HTML does not draw the picture:\n%s", pic.name, page) |
| + } |
| + thumb := mustGet(t, a, "/d/"+sqid+"/slides/"+slideID+".svg", http.StatusOK, cookies).Body.String() |
| + // Inlined, since an SVG in an <img> fetches nothing: a WebP as |
| + // a PNG, the others as they are. |
| + inline := "data:image/png;base64," |
| + if pic.name == "jpeg" { |
| + inline = "data:image/jpeg;base64," |
| + } |
| + if !strings.Contains(thumb, inline) { |
| + t.Errorf("%s: the slide's SVG does not draw the picture:\n%s", pic.name, thumb) |
| + } |
| + } |
| +} |
| + |
| +// TestTheSamePictureTwiceIsOneAsset: the second upload answers 200 with |
| +// the first one's ref and id, and the deck still has one asset. |
| +func TestTheSamePictureTwiceIsOneAsset(t *testing.T) { |
| + a, _, token, sqid := agentPictures(t) |
| + first := postPicture(t, a, sqid, token, "", onePixelPNG) |
| + if first.Code != http.StatusCreated { |
| + t.Fatalf("first: status %d\n%s", first.Code, first.Body) |
| + } |
| + var seq int64 |
| + readSeq := func() int64 { |
| + var s int64 |
| + if err := a.db.G.Raw("SELECT seq FROM decks WHERE sqid = ?", sqid).Scan(&s).Error; err != nil { |
| + t.Fatal(err) |
| + } |
| + return s |
| + } |
| + seq = readSeq() |
| + second := postPicture(t, a, sqid, token, "?alt=Again", onePixelPNG) |
| + if second.Code != http.StatusOK { |
| + t.Fatalf("second: status %d, want 200\n%s", second.Code, second.Body) |
| + } |
| + a1, a2 := jsonObject(t, first), jsonObject(t, second) |
| + if a1["ref"] != a2["ref"] || a1["id"] != a2["id"] || a2["width"] != float64(1) { |
| + t.Errorf("the duplicate answered %v, the first %v", a2, a1) |
| + } |
| + if assets := deckAssets(t, a, token, sqid); len(assets) != 1 { |
| + t.Errorf("the deck has %d assets after the same picture twice: %+v", len(assets), assets) |
| + } |
| + if readSeq() != seq { |
| + t.Error("the duplicate wrote to the document") |
| + } |
| +} |
| + |
| +// TestWhatIsNotAPictureIsRefused: over 20 MiB is 413; anything that is |
| +// not a PNG, JPEG or WebP that decodes at a size pictures allow is 422. |
| +// Nothing is registered. |
| +func TestWhatIsNotAPictureIsRefused(t *testing.T) { |
| + a, _, token, sqid := agentPictures(t) |
| + big := append(append([]byte{}, onePixelPNG...), bytes.Repeat([]byte{0}, 20<<20)...) |
| + // A PNG whose header, checksum right, declares 40000 x 1: it decodes |
| + // as far as its size, which is over the 30000 a picture may be. |
| + wide := append([]byte{}, onePixelPNG...) |
| + wide[16], wide[17], wide[18], wide[19] = 0, 0, 0x9c, 0x40 |
| + binary.BigEndian.PutUint32(wide[29:33], crc32.ChecksumIEEE(wide[12:29])) |
| + if cfg, err := png.DecodeConfig(bytes.NewReader(wide)); err != nil || cfg.Width != 40000 { |
| + t.Fatalf("the wide PNG is not a valid header of width 40000: %v %+v", err, cfg) |
| + } |
| + for name, c := range map[string]struct { |
| + body []byte |
| + status int |
| + code string |
| + }{ |
| + "too big": {big, http.StatusRequestEntityTooLarge, "too_large"}, |
| + "text": {[]byte("hello, this is not a picture"), http.StatusUnprocessableEntity, "not_an_image"}, |
| + "html": {[]byte("<!doctype html><title>x</title>"), http.StatusUnprocessableEntity, "not_an_image"}, |
| + "svg": {[]byte(`<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1"/>`), http.StatusUnprocessableEntity, "not_an_image"}, |
| + "fake png": {[]byte("\x89PNG\r\n\x1a\nnot really a png at all"), http.StatusUnprocessableEntity, "not_an_image"}, |
| + "fake jpeg": {[]byte("\xff\xd8\xff\xe0 not really"), http.StatusUnprocessableEntity, "not_an_image"}, |
| + "fake webp": {[]byte("RIFF\x00\x00\x00\x00WEBPnot really"), http.StatusUnprocessableEntity, "not_an_image"}, |
| + "a broken png": {onePixelPNG[:20], http.StatusUnprocessableEntity, "not_an_image"}, |
| + "empty": {nil, http.StatusUnprocessableEntity, "not_an_image"}, |
| + "too many pixels": {wide, http.StatusUnprocessableEntity, "not_an_image"}, |
| + } { |
| + rec := postPicture(t, a, sqid, token, "", c.body) |
| + if rec.Code != c.status { |
| + t.Errorf("%s: status %d, want %d\n%s", name, rec.Code, c.status, rec.Body) |
| + continue |
| + } |
| + out := jsonObject(t, rec) |
| + if out["error"] != c.code || out["message"] == nil || out["message"] == "" { |
| + t.Errorf("%s: answered %v, want error %s with a message", name, out, c.code) |
| + } |
| + } |
| + if assets := deckAssets(t, a, token, sqid); len(assets) != 0 { |
| + t.Errorf("a refused picture was registered: %+v", assets) |
| + } |
| +} |
| + |
| +// TestPicturesAreRefusedForDecksThatAreNotYours: another person's deck |
| +// and a deck that does not exist are 404, a bad token 401, as the rest |
| +// of the API answers them. |
| +func TestPicturesAreRefusedForDecksThatAreNotYours(t *testing.T) { |
| + a, _, token, sqid := agentPictures(t) |
| + theirs := mintAgent(t, a, signedIn(t, a, otherAddress), "theirs") |
| + for name, c := range map[string]struct { |
| + token, sqid string |
| + status int |
| + }{ |
| + "another person's deck": {theirs, sqid, http.StatusNotFound}, |
| + "no such deck": {token, "zzzzzzzzzz", http.StatusNotFound}, |
| + "a bad token": {"sl_not-a-real-token", sqid, http.StatusUnauthorized}, |
| + } { |
| + rec := postPicture(t, a, c.sqid, c.token, "", onePixelPNG) |
| + if rec.Code != c.status { |
| + t.Errorf("%s: status %d, want %d\n%s", name, rec.Code, c.status, rec.Body) |
| + } |
| + jsonObject(t, rec) |
| + } |
| + if assets := deckAssets(t, a, token, sqid); len(assets) != 0 { |
| + t.Errorf("a refused picture was registered: %+v", assets) |
| + } |
| +} |
| + |
| +// TestWithoutAStoreAPictureHasNowhereToGo: 503 no_store. |
| +func TestWithoutAStoreAPictureHasNowhereToGo(t *testing.T) { |
| + a := newApp(t) |
| + token := mintAgent(t, a, signedIn(t, a, allowedAddress), "pictures") |
| + sqid := apiDeck(t, a, token, "Bare") |
| + rec := postPicture(t, a, sqid, token, "", onePixelPNG) |
| + if rec.Code != http.StatusServiceUnavailable { |
| + t.Fatalf("status %d, want 503\n%s", rec.Code, rec.Body) |
| + } |
| + if out := jsonObject(t, rec); out["error"] != "no_store" { |
| + t.Errorf("answered %v, want no_store", out) |
| + } |
| +} |