oficina / docs Public

server: picture upload, copy and serving, sealed in object storage

Docs images spec §3 and §4.2. A document's pictures are stripped of
metadata (imagefile), sealed under content keys 5 and 6 with a random
seal id, padded to 64 KiB and put in the CARLOS object store under the
ciphertext's hash. document_images holds the sealed record; image_trash
queues objects a failed delete leaves behind.

- POST /d/{sqid}/images and /images/copy for writers; GET
  /d/{sqid}/images/{id} for readers (private, immutable, ETag) and
  /p/{token}/images/{id} for link holders (no-store). Every not-found is
  the document's one no-store 404.
- 8 MB and 40 MP per picture; 1 GiB per person and 100 MiB per guest of
  stored bytes, counted over documents not deleted.
- Images are off, every way in hidden, until both an object store is
  bound and content sealing is active. Development stores beside the
  database.
- Markdown names each image by its absolute address; the PDF sets
  "[Image: alt]" in its place until slice 3.
- golang.org/x/image v0.45.0: v0.23.0 cannot decode lossless WebP.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 7ebc7e8711f7b1be9d20b9d2d0701a313bde1820 parent ab164d9
19 files changed, +1,763 −12
  • cmd/docs/main.go +9 −0
  • internal/docs/app.go +17 −0
  • internal/docs/colophon.json +1 −1
  • internal/docs/errors_test.go +5 −1
  • internal/docs/export.go +9 −0
  • internal/docs/handlers_images.go +349 −0
  • internal/docs/images.go +558 −0
  • internal/docs/images_bucket.go +84 −0
  • internal/docs/images_config.go +138 −0
  • internal/docs/images_test.go +372 −0
  • internal/docs/migrations/0014_document_images.sql +34 −0
  • internal/docs/render.go +17 −0
  • internal/docs/store.go +3 −0
  • internal/docs/team_emission.go +19 −0
  • internal/export/document.go +23 −0
  • internal/export/images_test.go +57 −0
  • internal/export/markdown.go +38 −1
  • internal/export/pdf.go +21 −0
  • internal/imagefile/imagefile_test.go +9 −9
diff --git a/cmd/docs/main.go b/cmd/docs/main.go
index 7488c1b..4e8784b 100644
--- a/cmd/docs/main.go
+++ b/cmd/docs/main.go
@@ -336,6 +336,15 @@ func main() {
// is a refusal in docs.New.
SuiteConsumers: os.Getenv("DOCS" + server.EnvSuffix),
}
+ // Images (Docs images spec §1 decision 4): CARLOS's store, delivered
+ // as CARLOS_STORE_*, and the allowances. A missing or partial store is
+ // not a refusal; a malformed allowance is.
+ images, err := docs.LoadImages(os.Getenv)
+ if err != nil {
+ logger.Error(err.Error())
+ os.Exit(1)
+ }
+ cfg.Images = images
home := docs.HomeConfig{Issuer: os.Getenv("DOCS_HOME_ISSUER"), ConsumerID: os.Getenv("DOCS_HOME_CONSUMER_ID"), KeysBase64: os.Getenv("DOCS_HOME_KEYS_BASE64"), DEKBase64: os.Getenv("DOCS_HOME_DEK_BASE64")}
if home.Issuer != "" || home.ConsumerID != "" || home.KeysBase64 != "" || home.DEKBase64 != "" {
cfg.Home = &home
diff --git a/internal/docs/app.go b/internal/docs/app.go
index 571531f..3a0ede5 100644
--- a/internal/docs/app.go
+++ b/internal/docs/app.go
@@ -76,6 +76,11 @@ type Config struct {
// DBPath is the SQLite file New opens via rastrillo's db package.
DBPath string
ContentKey string
+ // Images is the object store and the allowances images use (Docs
+ // images spec §1 decision 4, §3.4; LoadImages). The zero value is no
+ // store: every way in is hidden and uploads answer 503, except in
+ // development, where images go in a directory beside the database.
+ Images ImagesConfig
// Env is "development" or "production" ("" defaults to
// "production"). It gates two fail-closed defaults below — Origin
@@ -501,6 +506,11 @@ func New(cfg Config) (*App, error) {
if state != nil {
store.content = cipher
}
+ if err := bindImages(store, cfg, logger); err != nil {
+ rt.Close(context.Background())
+ d.Close()
+ return nil, err
+ }
// A grant admits its holder. Wired here rather than inside
// resolveAllowlist because the allowlist is resolved before the store
@@ -731,6 +741,8 @@ func New(cfg Config) (*App, error) {
// sits above the RequireSession group rather than inside it with an
// exception carved into the middleware.
r.Get("/p/{token}", h.publicShow)
+ // Its images (Docs images spec §3.3), authorized the same way.
+ r.Get("/p/{token}/images/{id}", h.imagePublic)
// Alta's readiness probe (team_probe.go): unauthenticated, no account
// data, and {"team_mode":false} on an instance not in team mode.
r.Method(http.MethodGet, teamProbePath, teamProbe(store.team))
@@ -847,6 +859,11 @@ func New(cfg Config) (*App, error) {
// operating system both already understand.
r.Get("/d/{sqid}/export.md", h.exportMarkdown)
r.Get("/d/{sqid}/export.pdf", h.exportPDF)
+ // Images (Docs images spec §3.3): upload and copy for writers,
+ // serving for readers.
+ r.Post("/d/{sqid}/images", h.imageUpload)
+ r.Post("/d/{sqid}/images/copy", h.imageCopy)
+ r.Get("/d/{sqid}/images/{id}", h.imageServe)
// Plan 5: the live-update stream (stream.go). A GET, so
// csrf.Protect passes it through untouched, and reader-scoped
// through the same getDocumentForUpdates helper as the two
diff --git a/internal/docs/colophon.json b/internal/docs/colophon.json
index f8e2679..9d87aa0 100644
--- a/internal/docs/colophon.json
+++ b/internal/docs/colophon.json
@@ -283,7 +283,7 @@
{
"ecosystem": "go",
"name": "golang.org/x/image",
- "version": "v0.23.0",
+ "version": "v0.45.0",
"notices": [
{
"Name": "LICENSE",
diff --git a/internal/docs/errors_test.go b/internal/docs/errors_test.go
index 4bf35fa..ca8d38e 100644
--- a/internal/docs/errors_test.go
+++ b/internal/docs/errors_test.go
@@ -259,7 +259,11 @@ func TestEveryPlainTextErrorIsClassified(t *testing.T) {
"search.go:handlers.searchJSON": {3, "jump-to palette JSON"},
"stream.go:handlers.stream": {9, "live update stream (its 400 for a bad push cursor, its 503 for a team lease it cannot read)"},
"team_access.go:teamRuntime.admission": {1, "shared guard, identity missing: a wiring failure, not a page state"},
- "team_emission.go:writeGuardedBody": {1, "response already guarded"},
+ "team_emission.go:writeGuardedBodyThen": {1, "response already guarded"},
+ "handlers_images.go:handlers.imageUpload": {1, "image upload, fetched by the editor"},
+ "handlers_images.go:handlers.imageCopy": {2, "image copy, fetched by the editor"},
+ "handlers_images.go:handlers.refuseImage": {2, "image upload and copy refusals, fetched by the editor"},
+ "handlers_images.go:handlers.refuseServe": {3, "an image's bytes, read by an <img>, never a page"},
}
got := httpErrorSites(t)
var problems []string
diff --git a/internal/docs/export.go b/internal/docs/export.go
index 627521c..b923c43 100644
--- a/internal/docs/export.go
+++ b/internal/docs/export.go
@@ -324,6 +324,15 @@ func (h *handlers) documentForExport(w http.ResponseWriter, r *http.Request) (*D
h.fail(w, r, h.internalFailureStatus(), failStatus)
return nil, export.Document{}, false
}
+ // Images (Docs images spec §4.2): Markdown names each by its absolute
+ // address; the PDF sets a line in its place, in the reader's language.
+ structure.ImageBase = h.origin + "/d/" + doc.Sqid
+ structure.ImageLine = func(alt string) string {
+ if strings.TrimSpace(alt) == "" {
+ return rastrillo.T(r, "docs.export.image.noalt")
+ }
+ return rastrillo.Tf(r, "docs.export.image", "alt", alt)
+ }
return doc, structure, true
}
diff --git a/internal/docs/handlers_images.go b/internal/docs/handlers_images.go
new file mode 100644
index 0000000..7628928
--- /dev/null
+++ b/internal/docs/handlers_images.go
@@ -0,0 +1,349 @@
+package docs
+
+import (
+ "encoding/json"
+ "errors"
+ "io"
+ "net/http"
+ "strconv"
+ "strings"
+ "time"
+
+ "amadan.net/rastrillo/rastrillo"
+ "amadan.net/rastrillo/rastrillo/number"
+ "gorm.io/gorm"
+
+ "github.com/carlosframework/docs/internal/imagefile"
+)
+
+// The images' routes (Docs images spec §3.3): upload and copy in the
+// signed-in group, serving there and beside /p/{token}. Every refusal
+// about a document — one the person may not read, may not write, one
+// that does not exist, an image not in it — is the app's ordinary 404.
+
+// uploadSlack is a multipart request's room beyond its file: the
+// boundaries and headers.
+const uploadSlack = 64 << 10
+
+// maxCopyBody bounds a copy request: one address as JSON.
+const maxCopyBody = 4 << 10
+
+// imageServeDeadline bounds writing an image's body, in lone mode as in
+// team mode, so a slow reader cannot hold the connection open forever
+// (§3.3). The blob slot is already given back by then.
+const imageServeDeadline = 30 * time.Second
+
+// imageUpload is POST /d/{sqid}/images: one file, multipart field "file",
+// answered as JSON {src, width, height}.
+func (h *handlers) imageUpload(w http.ResponseWriter, r *http.Request) {
+ doc, ok := h.getDocumentForUpdates(w, r)
+ if !ok {
+ return
+ }
+ actor, err := h.actor(r)
+ if err != nil {
+ h.logger.Error("docs: resolve signed-in person", "err", err)
+ h.fail(w, r, h.internalFailureStatus(), failStatus)
+ return
+ }
+ if !h.store.CanWrite(r.Context(), actor, doc.ID) {
+ http.Error(w, rastrillo.T(r, "docs.error.notfound"), http.StatusNotFound)
+ return
+ }
+ if !h.store.ImagesReady() {
+ h.refuseImage(w, r, ErrImagesOff)
+ return
+ }
+ r.Body = http.MaxBytesReader(w, r.Body, MaxImageBytes+uploadSlack)
+ raw, err := readImageFile(r)
+ if err != nil {
+ h.refuseImage(w, r, err)
+ return
+ }
+ reply, err := h.store.AddImage(r.Context(), actor, doc, raw, !h.member(r))
+ if err != nil {
+ h.refuseImage(w, r, err)
+ return
+ }
+ writeImageJSON(w, http.StatusOK, reply)
+}
+
+// errNoImageFile is a form with no file part, or an empty one.
+var errNoImageFile = errors.New("docs: no image file in the form")
+
+// readImageFile reads the "file" part without spilling to disk
+// (MultipartReader, as import does), at most MaxImageBytes+1 of it, so a
+// file over the limit is told apart from one at it.
+func readImageFile(r *http.Request) ([]byte, error) {
+ mr, err := r.MultipartReader()
+ if err != nil {
+ return nil, errNoImageFile
+ }
+ for {
+ part, err := mr.NextPart()
+ if err == io.EOF {
+ return nil, errNoImageFile
+ }
+ if err != nil {
+ var tooLarge *http.MaxBytesError
+ if errors.As(err, &tooLarge) {
+ return nil, ErrImageTooLarge
+ }
+ return nil, errNoImageFile
+ }
+ if part.FormName() != "file" {
+ _ = part.Close()
+ continue
+ }
+ raw, err := io.ReadAll(io.LimitReader(part, MaxImageBytes+1))
+ _ = part.Close()
+ var tooLarge *http.MaxBytesError
+ switch {
+ case errors.As(err, &tooLarge), len(raw) > MaxImageBytes:
+ return nil, ErrImageTooLarge
+ case err != nil, len(raw) == 0:
+ return nil, errNoImageFile
+ }
+ return raw, nil
+ }
+}
+
+// imageCopy is POST /d/{sqid}/images/copy: {"src": address} naming an
+// image of another document, stored again as one of this document's
+// (§2.2, §3.3). The address may be relative or absolute on this origin.
+func (h *handlers) imageCopy(w http.ResponseWriter, r *http.Request) {
+ doc, ok := h.getDocumentForUpdates(w, r)
+ if !ok {
+ return
+ }
+ actor, err := h.actor(r)
+ if err != nil {
+ h.logger.Error("docs: resolve signed-in person", "err", err)
+ h.fail(w, r, h.internalFailureStatus(), failStatus)
+ return
+ }
+ if !h.store.CanWrite(r.Context(), actor, doc.ID) {
+ http.Error(w, rastrillo.T(r, "docs.error.notfound"), http.StatusNotFound)
+ return
+ }
+ if !h.store.ImagesReady() {
+ h.refuseImage(w, r, ErrImagesOff)
+ return
+ }
+ var body struct {
+ Src string `json:"src"`
+ }
+ if err := json.NewDecoder(io.LimitReader(r.Body, maxCopyBody)).Decode(&body); err != nil {
+ http.Error(w, rastrillo.T(r, "docs.error.notfound"), http.StatusNotFound)
+ return
+ }
+ src := strings.TrimPrefix(body.Src, h.origin)
+ reply, err := h.store.CopyImage(r.Context(), actor, doc, src, !h.member(r))
+ if err != nil {
+ h.refuseImage(w, r, err)
+ return
+ }
+ writeImageJSON(w, http.StatusOK, reply)
+}
+
+// imageServe is GET /d/{sqid}/images/{id}, for a reader of the document.
+func (h *handlers) imageServe(w http.ResponseWriter, r *http.Request) {
+ // Every answer but the image itself is no-store, the document
+ // lookup's 404 included, so all four not-founds are one (§3.3).
+ w.Header().Set("Cache-Control", "no-store")
+ doc, ok := h.getDocumentForUpdates(w, r)
+ if !ok {
+ return
+ }
+ id := r.PathValue("id")
+ // An id the document holds never changes its bytes, so a match is
+ // answered without reading the store. Only an id that is the
+ // document's own can match: the row is checked first, cheaply.
+ if match := r.Header.Get("If-None-Match"); match != "" && match == imageETag(id) && h.store.HasImage(r.Context(), doc, id) {
+ h.writeImage(w, r, ServedImage{PublicID: id}, false, true)
+ return
+ }
+ served, err := h.store.ReadImage(r.Context(), doc, id, false)
+ if err != nil {
+ h.refuseServe(w, r, err)
+ return
+ }
+ h.writeImage(w, r, served, false, false)
+}
+
+// imagePublic is GET /p/{token}/images/{id}, for a holder of the link:
+// the same image, no-store, so a revoked link stops working at once
+// (§3.3). It sits above the session group, beside /p/{token}.
+func (h *handlers) imagePublic(w http.ResponseWriter, r *http.Request) {
+ doc, err := h.store.ByToken(r.Context(), r.PathValue("token"))
+ if err != nil {
+ if !errors.Is(err, gorm.ErrRecordNotFound) {
+ h.logger.Error("docs: resolve public link", "err", err)
+ }
+ h.notFoundNoStore(w, r)
+ return
+ }
+ served, err := h.store.ReadImage(r.Context(), doc, r.PathValue("id"), true)
+ if err != nil {
+ h.refuseServe(w, r, err)
+ return
+ }
+ h.writeImage(w, r, served, true, false)
+}
+
+func imageETag(publicID string) string { return `"` + publicID + `"` }
+
+// writeImage writes an image with §3.3's headers. They are set only once
+// the response is allowed (writeGuardedBodyThen), so a failure never
+// carries them.
+func (h *handlers) writeImage(w http.ResponseWriter, r *http.Request, served ServedImage, public, notModified bool) {
+ headers := func(header http.Header) {
+ header.Set("X-Content-Type-Options", "nosniff")
+ header.Set("Content-Security-Policy", "default-src 'none'; sandbox")
+ header.Set("Cross-Origin-Resource-Policy", "same-origin")
+ if public {
+ header.Set("Cache-Control", "no-store")
+ header.Set("X-Robots-Tag", "noindex, nofollow")
+ } else {
+ header.Set("Cache-Control", "private, max-age=3600, immutable")
+ header.Set("ETag", imageETag(served.PublicID))
+ }
+ if !notModified {
+ header.Set("Content-Type", served.Type)
+ header.Set("Content-Disposition", "inline")
+ }
+ }
+ controller := http.NewResponseController(w)
+ _ = controller.SetWriteDeadline(time.Now().Add(imageServeDeadline))
+ defer controller.SetWriteDeadline(time.Time{})
+ status := 0
+ var body [][]byte
+ if notModified {
+ status = http.StatusNotModified
+ } else {
+ body = [][]byte{served.Body}
+ }
+ if err := writeGuardedBodyThen(w, r, status, headers, body...); err != nil {
+ h.logger.Warn("docs: write image", "err", err)
+ }
+}
+
+// refuseServe answers a read that cannot be served. Every not-found —
+// and a row whose object is missing, which is also logged — is the
+// ordinary 404 with no-store; a wait that ran out is 503 with
+// Retry-After.
+func (h *handlers) refuseServe(w http.ResponseWriter, r *http.Request, err error) {
+ switch {
+ case errors.Is(err, gorm.ErrRecordNotFound):
+ h.notFoundNoStore(w, r)
+ case errors.Is(err, errImageObjectMissing):
+ h.logger.Error("docs: an image row's object is missing")
+ h.notFoundNoStore(w, r)
+ case errors.Is(err, ErrImageBusy):
+ w.Header().Set("Cache-Control", "no-store")
+ w.Header().Set("Retry-After", "5")
+ http.Error(w, rastrillo.T(r, "docs.images.error.busy"), http.StatusServiceUnavailable)
+ case errors.Is(err, errTeamUnavailable):
+ w.Header().Set("Cache-Control", "no-store")
+ http.Error(w, rastrillo.T(r, "docs.error.generic"), http.StatusServiceUnavailable)
+ default:
+ h.logger.Error("docs: serve image", "err", err)
+ w.Header().Set("Cache-Control", "no-store")
+ http.Error(w, rastrillo.T(r, "docs.error.generic"), h.internalFailureStatus())
+ }
+}
+
+// notFoundNoStore is the app's ordinary 404, said not to be stored.
+func (h *handlers) notFoundNoStore(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Cache-Control", "no-store")
+ h.fail(w, r, http.StatusNotFound, failDocument)
+}
+
+// imageRefusalKeys is each upload or copy refusal's status and catalog
+// key (§3.2–§3.4).
+var imageRefusalKeys = []struct {
+ err error
+ status int
+ key string
+}{
+ {ErrImageType, http.StatusUnsupportedMediaType, "docs.images.error.type"},
+ {ErrImageTooLarge, http.StatusRequestEntityTooLarge, "docs.images.error.toolarge"},
+ {ErrImageDimensions, http.StatusUnprocessableEntity, "docs.images.error.dimensions"},
+ {ErrImagesOff, http.StatusServiceUnavailable, "docs.images.error.off"},
+ {ErrImageBusy, http.StatusServiceUnavailable, "docs.images.error.busy"},
+ {ErrStorageFull, http.StatusInsufficientStorage, "docs.images.error.full"},
+ {errNoImageFile, http.StatusUnprocessableEntity, "docs.images.error.nofile"},
+}
+
+// refuseImage answers a refused upload or copy as JSON {"error": sentence}.
+// Not being allowed to write, a source that cannot be read, and a lapsed
+// team standing are the same answers updatesPost gives.
+func (h *handlers) refuseImage(w http.ResponseWriter, r *http.Request, err error) {
+ w.Header().Set("Cache-Control", "no-store")
+ switch {
+ case errors.Is(err, ErrNotWritable), errors.Is(err, gorm.ErrRecordNotFound):
+ http.Error(w, rastrillo.T(r, "docs.error.notfound"), http.StatusNotFound)
+ return
+ case errors.Is(err, errTeamUnavailable):
+ http.Error(w, rastrillo.T(r, "docs.error.generic"), http.StatusServiceUnavailable)
+ return
+ case errors.Is(err, ErrImageQuota):
+ writeImageJSON(w, http.StatusInsufficientStorage, map[string]string{
+ "error": rastrillo.Tf(r, "docs.images.error.quota", "size", h.imageAllowance(r)),
+ })
+ return
+ }
+ if errors.Is(err, ErrImageBusy) {
+ w.Header().Set("Retry-After", "5")
+ }
+ for _, refusal := range imageRefusalKeys {
+ if errors.Is(err, refusal.err) {
+ say := rastrillo.T(r, refusal.key)
+ if refusal.err == ErrImageTooLarge || refusal.err == ErrImageDimensions {
+ say = rastrillo.Tf(r, refusal.key,
+ "size", formatImageMB(r, MaxImageBytes),
+ "side", formatImageNumber(r, imagefile.MaxSide),
+ "megapixels", formatImageNumber(r, imagefile.MaxPixels/1_000_000))
+ }
+ writeImageJSON(w, refusal.status, map[string]string{"error": say})
+ return
+ }
+ }
+ h.logger.Error("docs: image failed", "path", r.URL.Path, "err", err)
+ writeImageJSON(w, http.StatusInternalServerError, map[string]string{
+ "error": rastrillo.T(r, "docs.images.error.failed"),
+ })
+}
+
+// imageAllowance is the person's allowance, written in their locale.
+func (h *handlers) imageAllowance(r *http.Request) string {
+ limit := h.store.images.quotaPerson
+ if !h.member(r) {
+ limit = h.store.images.quotaGuest
+ }
+ if limit >= 1<<30 && limit%(1<<30) == 0 {
+ return rastrillo.Tf(r, "docs.images.size.gb", "n", formatImageNumber(r, int(limit>>30)))
+ }
+ return formatImageMB(r, limit)
+}
+
+func formatImageMB(r *http.Request, bytes int64) string {
+ return rastrillo.Tf(r, "docs.images.size.mb", "n", formatImageNumber(r, int(bytes>>20)))
+}
+
+// formatImageNumber writes n in the request's locale, through
+// rastrillo's number formatting, never by hand (§2.5).
+func formatImageNumber(r *http.Request, n int) string {
+ out, err := number.Format(rastrillo.LocaleFrom(r), number.Decimal(strconv.Itoa(n)), number.Options{})
+ if err != nil {
+ return strconv.Itoa(n)
+ }
+ return out
+}
+
+func writeImageJSON(w http.ResponseWriter, status int, body any) {
+ w.Header().Set("Content-Type", "application/json; charset=utf-8")
+ w.Header().Set("Cache-Control", "no-store")
+ w.WriteHeader(status)
+ _ = json.NewEncoder(w).Encode(body)
+}
diff --git a/internal/docs/images.go b/internal/docs/images.go
new file mode 100644
index 0000000..960eba0
--- /dev/null
+++ b/internal/docs/images.go
@@ -0,0 +1,558 @@
+package docs
+
+import (
+ "bytes"
+ "context"
+ "crypto/rand"
+ "crypto/sha256"
+ "encoding/binary"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "strings"
+ "time"
+
+ "amadan.net/rastrillo/rastrillo/blobs"
+ "gorm.io/gorm"
+
+ "github.com/carlosframework/docs/internal/imagefile"
+)
+
+// Images (Docs images spec). An image belongs to exactly one document and
+// is addressed as /d/{sqid}/images/{public id} (decision 2). Its bytes
+// are checked and stripped (imagefile), padded to 64 KiB, sealed under the
+// content key and Put before any transaction; then one transaction checks
+// write permission and the uploader's allowance again and writes the row
+// (§3.3). Reading checks the object's hash, opens it, and trims the
+// padding.
+
+// The two content kinds images seal under (decision 1). Their own kind
+// bytes, so an image's ciphertext can never open as an update, a snapshot
+// or a report of the same document, nor one of those as an image.
+const (
+ contentImageKind byte = 5
+ contentImageRecordKind byte = 6
+)
+
+// The limits (§3.2): 8 MiB per image, so the shipped native apps, which
+// fetch at most 8 MB, show every one.
+const MaxImageBytes = 8 << 20
+
+// imagePad is the step a sealed image's plaintext is padded to, so its
+// stored size says it only to within 64 KiB (decision 1).
+const imagePad = 64 << 10
+
+// ImagePublicIDLen is an image's public id: exactly this many of
+// [0-9a-z] (decision 2). The core's IMAGE_ID_LEN and the editor agree.
+const ImagePublicIDLen = 16
+
+// How long a request waits for a blob slot (§3.3, Mapa §1.4): an upload
+// or copy answers 503 after uploadWait; a read, whose 503 is a broken
+// image, waits readWait.
+const (
+ uploadWait = 10 * time.Second
+ readWait = 30 * time.Second
+)
+
+// The blob slots (§3.3): four operations at a time hold about 30 MiB each
+// at most. Reads through a public link may hold at most two of them, so a
+// link holder reloading a published page can never push uploads to their
+// 503.
+const (
+ imageSlots = 4
+ publicImageSlots = 2
+)
+
+// The refusals. Each is a status and a sentence in handlers_images.go.
+var (
+ ErrImagesOff = errors.New("docs: images are not set up on this instance")
+ ErrImageType = errors.New("docs: not a PNG, JPEG, GIF or WebP image")
+ ErrImageTooLarge = errors.New("docs: the image is larger than 8 MiB")
+ ErrImageDimensions = errors.New("docs: the image has too many pixels")
+ ErrImageQuota = errors.New("docs: over the image allowance")
+ ErrStorageFull = errors.New("docs: the object store refused the image")
+ ErrImageBusy = errors.New("docs: every image slot is busy")
+ // errImageObjectMissing is a row whose object the store does not
+ // have: served as the ordinary 404, and logged (§3.3).
+ errImageObjectMissing = errors.New("docs: an image's object is missing")
+)
+
+// DocumentImage is one row of document_images (0014_document_images.sql).
+type DocumentImage struct {
+ ID int64 `gorm:"primaryKey"`
+ PublicID string `gorm:"column:public_id"`
+ SealID int64 `gorm:"column:seal_id"`
+ DocumentID int64 `gorm:"column:document_id"`
+ UploaderID int64 `gorm:"column:uploader_id"`
+ CreatedAt time.Time `gorm:"column:created_at"`
+ StoredBytes int64 `gorm:"column:stored_bytes"`
+ ObjectKey string `gorm:"column:object_key"`
+ SealedRecord []byte `gorm:"column:sealed_record"`
+}
+
+func (DocumentImage) TableName() string { return "document_images" }
+
+type imageTrash struct {
+ ObjectKey string `gorm:"column:object_key;primaryKey"`
+ QueuedAt time.Time `gorm:"column:queued_at"`
+}
+
+func (imageTrash) TableName() string { return "image_trash" }
+
+// imageRecord is what an image's sealed record holds (§3.1).
+type imageRecord struct {
+ Type string `json:"type"`
+ Width int `json:"width"`
+ Height int `json:"height"`
+ // Size is the true length, before padding.
+ Size int `json:"size"`
+}
+
+// ImageReply is what an upload or a copy answers: the address the editor
+// inserts, and the size the page reserves before a byte arrives.
+type ImageReply struct {
+ Src string `json:"src"`
+ Width int `json:"width"`
+ Height int `json:"height"`
+}
+
+// ServedImage is an image's bytes and their sniffed type.
+type ServedImage struct {
+ Type string
+ PublicID string
+ Body []byte
+}
+
+// imageStore is the store's images half; nil when images are off.
+type imageStore struct {
+ objects blobs.Store
+ slots chan struct{}
+ publicSlots chan struct{}
+ quotaPerson int64
+ quotaGuest int64
+}
+
+func newImageStore(objects blobs.Store, config ImagesConfig) *imageStore {
+ images := &imageStore{
+ objects: objects,
+ slots: make(chan struct{}, imageSlots),
+ publicSlots: make(chan struct{}, publicImageSlots),
+ quotaPerson: config.QuotaPerson,
+ quotaGuest: config.QuotaGuest,
+ }
+ if images.quotaPerson <= 0 {
+ images.quotaPerson = DefaultImageQuotaPerson
+ }
+ if images.quotaGuest <= 0 {
+ images.quotaGuest = DefaultImageQuotaGuest
+ }
+ return images
+}
+
+// ImagesReady reports whether this instance takes images: a store is
+// bound and content sealing is active (decision 4). When it is false,
+// every way in is hidden and upload answers 503.
+func (s *Store) ImagesReady() bool {
+ return s.images != nil && s.images.objects != nil && s.content != nil
+}
+
+// acquire takes a slot from each of chans in turn, waiting at most wait
+// in all. release gives back every slot taken.
+func acquire(ctx context.Context, wait time.Duration, chans ...chan struct{}) (release func(), err error) {
+ timer := time.NewTimer(wait)
+ defer timer.Stop()
+ var held []chan struct{}
+ release = func() {
+ for _, ch := range held {
+ <-ch
+ }
+ }
+ for _, ch := range chans {
+ select {
+ case ch <- struct{}{}:
+ held = append(held, ch)
+ case <-timer.C:
+ release()
+ return nil, ErrImageBusy
+ case <-ctx.Done():
+ release()
+ return nil, ctx.Err()
+ }
+ }
+ return release, nil
+}
+
+// AddImage checks, strips, seals and stores raw as a new image of doc,
+// uploaded by actor (§3.3's upload). guest says actor was admitted only
+// by a grant, so the guest allowance applies (§3.4). The caller has
+// resolved doc with GetFor; write permission is checked here, inside the
+// row's transaction.
+func (s *Store) AddImage(ctx context.Context, actor Actor, doc *Document, raw []byte, guest bool) (ImageReply, error) {
+ if !s.ImagesReady() {
+ return ImageReply{}, ErrImagesOff
+ }
+ if len(raw) > MaxImageBytes {
+ return ImageReply{}, ErrImageTooLarge
+ }
+ release, err := acquire(ctx, uploadWait, s.images.slots)
+ if err != nil {
+ return ImageReply{}, err
+ }
+ defer release()
+ cleaned, info, err := imagefile.Clean(raw)
+ if err != nil {
+ return ImageReply{}, imageRefusal(err)
+ }
+ return s.keepImage(ctx, actor, doc, cleaned, info, guest)
+}
+
+// imageRefusal is a walker's refusal as the store's own.
+func imageRefusal(err error) error {
+ switch {
+ case errors.Is(err, imagefile.ErrDimensions):
+ return ErrImageDimensions
+ case errors.Is(err, imagefile.ErrType), errors.Is(err, imagefile.ErrMalformed):
+ return ErrImageType
+ }
+ return err
+}
+
+// CopyImage stores the image src names again as a new image of target,
+// for actor (§3.3's copy): a picture pasted from document A into document
+// B, whose readers may not be able to read A. src is the relative form,
+// /d/{sqid}/images/{id}; the handler has taken any same-origin prefix
+// off. Every refusal about the source — an address that does not parse,
+// a document actor may not read, a deleted one, an id not in it — is
+// gorm.ErrRecordNotFound, one answer (§3.3).
+func (s *Store) CopyImage(ctx context.Context, actor Actor, target *Document, src string, guest bool) (ImageReply, error) {
+ if !s.ImagesReady() {
+ return ImageReply{}, ErrImagesOff
+ }
+ sqid, publicID, ok := ParseImageSrc(src)
+ if !ok {
+ return ImageReply{}, gorm.ErrRecordNotFound
+ }
+ source, err := s.GetFor(ctx, actor, sqid)
+ if err != nil {
+ return ImageReply{}, err
+ }
+ release, err := acquire(ctx, uploadWait, s.images.slots)
+ if err != nil {
+ return ImageReply{}, err
+ }
+ defer release()
+ served, record, err := s.openImage(ctx, source, publicID)
+ if err != nil {
+ return ImageReply{}, err
+ }
+ info := imagefile.Info{Type: record.Type, Width: record.Width, Height: record.Height}
+ return s.keepImage(ctx, actor, target, served.Body, info, guest)
+}
+
+// keepImage seals plain under doc, Puts it, and writes its row in one
+// transaction that checks write permission and the allowance again. The
+// caller holds a blob slot. An object whose row is not written is
+// deleted, or queued when that fails.
+func (s *Store) keepImage(ctx context.Context, actor Actor, doc *Document, plain []byte, info imagefile.Info, guest bool) (ImageReply, error) {
+ limit := s.images.quotaPerson
+ if guest {
+ limit = s.images.quotaGuest
+ }
+ sealID, err := newSealID()
+ if err != nil {
+ return ImageReply{}, err
+ }
+ padded := make([]byte, (len(plain)+imagePad-1)/imagePad*imagePad)
+ copy(padded, plain)
+ blob, err := s.content.seal(contentImageKind, doc.GUID, sealID, 0, padded)
+ if err != nil {
+ return ImageReply{}, err
+ }
+ record, err := json.Marshal(imageRecord{Type: info.Type, Width: info.Width, Height: info.Height, Size: len(plain)})
+ if err != nil {
+ return ImageReply{}, err
+ }
+ sealedRecord, err := s.content.seal(contentImageRecordKind, doc.GUID, sealID, 0, record)
+ if err != nil {
+ return ImageReply{}, err
+ }
+ size := int64(len(blob))
+ // A quick look first, so an upload over the allowance costs no Put;
+ // the one that counts is inside the transaction.
+ if used, err := s.imageBytesUsed(s.db.WithContext(ctx), actor); err != nil {
+ return ImageReply{}, err
+ } else if used+size > limit {
+ return ImageReply{}, ErrImageQuota
+ }
+ key := imageObjectKey(blob)
+ if err := s.putImageObject(ctx, key, blob); err != nil {
+ return ImageReply{}, err
+ }
+ publicID, err := newImagePublicID()
+ if err != nil {
+ s.dropImageObject(ctx, key)
+ return ImageReply{}, err
+ }
+ err = s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
+ if err := s.checkPermission(ctx, tx, actor, doc.ID, permissionWrite); err != nil {
+ return err
+ }
+ used, err := s.imageBytesUsed(tx, actor)
+ if err != nil {
+ return err
+ }
+ if used+size > limit {
+ return ErrImageQuota
+ }
+ return tx.Create(&DocumentImage{
+ PublicID: publicID,
+ SealID: sealID,
+ DocumentID: doc.ID,
+ UploaderID: actor.PersonID,
+ CreatedAt: time.Now().UTC(),
+ StoredBytes: size,
+ ObjectKey: key,
+ SealedRecord: sealedRecord,
+ }).Error
+ })
+ if err != nil {
+ s.dropImageObject(ctx, key)
+ return ImageReply{}, err
+ }
+ return ImageReply{
+ Src: ImageSrc(doc.Sqid, publicID),
+ Width: info.Width,
+ Height: info.Height,
+ }, nil
+}
+
+// imageBytesUsed is what actor's images hold in documents that are not
+// deleted (§3.4): the allowance counts by uploader, whatever document.
+func (s *Store) imageBytesUsed(db *gorm.DB, actor Actor) (int64, error) {
+ var used int64
+ err := db.Raw(`SELECT COALESCE(SUM(document_images.stored_bytes), 0)
+ FROM document_images JOIN documents ON documents.id = document_images.document_id
+ WHERE document_images.uploader_id = ? AND documents.deleted_at IS NULL`, actor.PersonID).
+ Scan(&used).Error
+ return used, err
+}
+
+// ReadImage is the image publicID names in doc, opened (§3.3's serve).
+// The caller has resolved doc — with GetFor, or ByToken for a link holder
+// (public). An id that is not in doc is gorm.ErrRecordNotFound. The slot
+// is given back before this returns, so it is never held while the body
+// is written.
+func (s *Store) ReadImage(ctx context.Context, doc *Document, publicID string, public bool) (ServedImage, error) {
+ if s.images == nil || s.images.objects == nil || s.content == nil {
+ return ServedImage{}, gorm.ErrRecordNotFound
+ }
+ if !IsImagePublicID(publicID) {
+ return ServedImage{}, gorm.ErrRecordNotFound
+ }
+ chans := []chan struct{}{s.images.slots}
+ if public {
+ chans = []chan struct{}{s.images.publicSlots, s.images.slots}
+ }
+ release, err := acquire(ctx, readWait, chans...)
+ if err != nil {
+ return ServedImage{}, err
+ }
+ defer release()
+ served, _, err := s.openImage(ctx, doc, publicID)
+ return served, err
+}
+
+// HasImage reports whether publicID names one of doc's images: what a
+// conditional GET checks before answering 304 without reading the store.
+func (s *Store) HasImage(ctx context.Context, doc *Document, publicID string) bool {
+ if !IsImagePublicID(publicID) {
+ return false
+ }
+ var count int64
+ err := s.db.WithContext(ctx).Model(&DocumentImage{}).
+ Where("public_id = ? AND document_id = ?", publicID, doc.ID).
+ Count(&count).Error
+ return err == nil && count > 0
+}
+
+// openImage reads, checks and opens one of doc's images. The caller holds
+// a blob slot.
+func (s *Store) openImage(ctx context.Context, doc *Document, publicID string) (ServedImage, imageRecord, error) {
+ var row DocumentImage
+ if err := s.db.WithContext(ctx).
+ Where("public_id = ? AND document_id = ?", publicID, doc.ID).
+ First(&row).Error; err != nil {
+ return ServedImage{}, imageRecord{}, err
+ }
+ rawRecord, err := s.content.open(contentImageRecordKind, doc.GUID, row.SealID, 0, row.SealedRecord)
+ if err != nil {
+ return ServedImage{}, imageRecord{}, err
+ }
+ var record imageRecord
+ if err := json.Unmarshal(rawRecord, &record); err != nil {
+ return ServedImage{}, imageRecord{}, err
+ }
+ object, err := s.images.objects.Get(ctx, row.ObjectKey)
+ if errors.Is(err, blobs.ErrNotFound) {
+ return ServedImage{}, imageRecord{}, errImageObjectMissing
+ }
+ if err != nil {
+ return ServedImage{}, imageRecord{}, fmt.Errorf("docs: reading an image object: %w", err)
+ }
+ defer object.Close()
+ blob, err := io.ReadAll(io.LimitReader(object, row.StoredBytes+1))
+ if err != nil {
+ return ServedImage{}, imageRecord{}, fmt.Errorf("docs: reading an image object: %w", err)
+ }
+ // A swapped or truncated object is refused, not served (decision 1).
+ if int64(len(blob)) != row.StoredBytes || imageObjectKey(blob) != row.ObjectKey {
+ return ServedImage{}, imageRecord{}, errContentAuthentication
+ }
+ padded, err := s.content.open(contentImageKind, doc.GUID, row.SealID, 0, blob)
+ if err != nil {
+ return ServedImage{}, imageRecord{}, err
+ }
+ if record.Size < 0 || record.Size > len(padded) {
+ return ServedImage{}, imageRecord{}, errContentAuthentication
+ }
+ return ServedImage{Type: record.Type, PublicID: row.PublicID, Body: padded[:record.Size]}, record, nil
+}
+
+// putImageObject stores sealed bytes as application/octet-stream. A
+// refusal from the platform (403 past the plan's grace) is
+// ErrStorageFull.
+func (s *Store) putImageObject(ctx context.Context, key string, blob []byte) error {
+ // A Buffer, so a store that can take its bytes as they are does
+ // (bucket.Put).
+ ref, err := s.images.objects.Put(ctx, bytes.NewBuffer(blob), "application/octet-stream")
+ if err != nil {
+ if errors.Is(err, errPutDenied) {
+ return fmt.Errorf("%w: %v", ErrStorageFull, err)
+ }
+ return fmt.Errorf("docs: storing an image: %w", err)
+ }
+ if ref.Hash != key {
+ s.dropImageObject(ctx, ref.Hash)
+ return errors.New("docs: the object store keyed an image by another hash")
+ }
+ return nil
+}
+
+// dropImageObject deletes an object no row names. If that fails, the key
+// is queued in image_trash for the next boot to delete, and the failure
+// is logged, never returned: the row's absence is what matters.
+func (s *Store) dropImageObject(ctx context.Context, key string) {
+ ctx = context.WithoutCancel(ctx)
+ err := s.images.objects.Delete(ctx, key)
+ if err == nil || errors.Is(err, blobs.ErrNotFound) {
+ return
+ }
+ s.logger.Error("docs: deleting an image object; queued", "err", err)
+ queued := imageTrash{ObjectKey: key, QueuedAt: time.Now().UTC()}
+ if e := s.db.WithContext(ctx).Where("object_key = ?", key).FirstOrCreate(&queued).Error; e != nil {
+ s.logger.Error("docs: queueing an image object for deletion", "err", e)
+ }
+}
+
+// EmptyImageTrash deletes every queued object and its queue row (§3.5).
+// It runs in a goroutine after boot and never fails it: a store outage
+// delays deletion and nothing else.
+func (s *Store) EmptyImageTrash(ctx context.Context) {
+ if s.images == nil || s.images.objects == nil {
+ return
+ }
+ var queued []imageTrash
+ if err := s.db.WithContext(ctx).Find(&queued).Error; err != nil {
+ s.logger.Error("docs: reading the image trash", "err", err)
+ return
+ }
+ for _, each := range queued {
+ err := s.images.objects.Delete(ctx, each.ObjectKey)
+ if err != nil && !errors.Is(err, blobs.ErrNotFound) {
+ s.logger.Error("docs: emptying the image trash", "err", err)
+ continue
+ }
+ if err := s.db.WithContext(ctx).Delete(&imageTrash{}, "object_key = ?", each.ObjectKey).Error; err != nil {
+ s.logger.Error("docs: emptying the image trash", "err", err)
+ }
+ }
+}
+
+func imageObjectKey(blob []byte) string {
+ sum := sha256.Sum256(blob)
+ return hex.EncodeToString(sum[:])
+}
+
+// newSealID is a random positive 63-bit number (decision 1).
+func newSealID() (int64, error) {
+ var buf [8]byte
+ for {
+ if _, err := rand.Read(buf[:]); err != nil {
+ return 0, err
+ }
+ if id := int64(binary.BigEndian.Uint64(buf[:]) >> 1); id > 0 {
+ return id, nil
+ }
+ }
+}
+
+const imageIDAlphabet = "0123456789abcdefghijklmnopqrstuvwxyz"
+
+// newImagePublicID is ImagePublicIDLen random characters of [0-9a-z],
+// about 82 bits, drawn without bias (252 is the largest multiple of 36
+// that fits a byte).
+func newImagePublicID() (string, error) {
+ out := make([]byte, 0, ImagePublicIDLen)
+ var buf [32]byte
+ for len(out) < ImagePublicIDLen {
+ if _, err := rand.Read(buf[:]); err != nil {
+ return "", err
+ }
+ for _, b := range buf {
+ if b < 252 && len(out) < ImagePublicIDLen {
+ out = append(out, imageIDAlphabet[b%36])
+ }
+ }
+ }
+ return string(out), nil
+}
+
+// IsImagePublicID reports whether id is exactly ImagePublicIDLen of
+// [0-9a-z].
+func IsImagePublicID(id string) bool {
+ if len(id) != ImagePublicIDLen {
+ return false
+ }
+ for i := 0; i < len(id); i++ {
+ if !strings.ContainsRune(imageIDAlphabet, rune(id[i])) {
+ return false
+ }
+ }
+ return true
+}
+
+// ImageSrc is an image's address in a document: /d/{sqid}/images/{id}.
+func ImageSrc(sqid, publicID string) string {
+ return "/d/" + sqid + "/images/" + publicID
+}
+
+// ParseImageSrc is the sqid and id of an address in exactly
+// ImageSrc's form, the sqid in store.go's alphabet.
+func ParseImageSrc(src string) (sqid, publicID string, ok bool) {
+ rest, found := strings.CutPrefix(src, "/d/")
+ if !found {
+ return "", "", false
+ }
+ sqid, publicID, found = strings.Cut(rest, "/images/")
+ if !found || sqid == "" || len(sqid) > 32 || !IsImagePublicID(publicID) {
+ return "", "", false
+ }
+ for i := 0; i < len(sqid); i++ {
+ if !strings.ContainsRune(sqidAlphabet, rune(sqid[i])) {
+ return "", "", false
+ }
+ }
+ return sqid, publicID, true
+}
diff --git a/internal/docs/images_bucket.go b/internal/docs/images_bucket.go
new file mode 100644
index 0000000..5f93c8a
--- /dev/null
+++ b/internal/docs/images_bucket.go
@@ -0,0 +1,84 @@
+package docs
+
+import (
+ "bytes"
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "net/url"
+ "time"
+
+ "amadan.net/rastrillo/rastrillo/blobs"
+)
+
+// bucket is CARLOS's bucket as Docs writes to it (copied from Mapa's images_bucket.go, Docs images spec §3.3): blobs.S3 for reading
+// and deleting, and a Put of Docs' own over a presigned URL, so that a
+// refusal is read from the response's status (Mapa images spec, Fable L8). blobs.S3's own
+// Put reports a status only as text.
+type bucket struct {
+ *blobs.S3
+ client *http.Client
+}
+
+// errPutDenied is the bucket refusing a Put: past the plan's grace,
+// CARLOS denies PutObject (Mapa images spec §3.4).
+var errPutDenied = errors.New("docs: the bucket refused the object")
+
+// presignFor is how long a Put's presigned URL lives: only for the Put
+// (Mapa images spec, Fable N5).
+const presignFor = 60 * time.Second
+
+func (store bucket) Put(ctx context.Context, data io.Reader,
+ kind string) (blobs.Ref, error) {
+ raw, err := heldBytes(data)
+ if err != nil {
+ return blobs.Ref{}, err
+ }
+ sum := sha256.Sum256(raw)
+ ref := blobs.Ref{Hash: hex.EncodeToString(sum[:]),
+ Size: int64(len(raw)), ContentType: kind}
+ address, err := store.PresignPut(ref.Hash, presignFor)
+ if err != nil {
+ return blobs.Ref{}, err
+ }
+ request, err := http.NewRequestWithContext(ctx, http.MethodPut,
+ address, bytes.NewReader(raw))
+ if err != nil {
+ return blobs.Ref{}, err
+ }
+ request.Header.Set("Content-Type", kind)
+ response, err := store.client.Do(request)
+ if err != nil {
+ // *url.Error's text holds the presigned address, signature and
+ // all, and this error is logged: only its cause goes on (Fable
+ // N5).
+ var failed *url.Error
+ if errors.As(err, &failed) {
+ err = failed.Err
+ }
+ return blobs.Ref{}, fmt.Errorf("docs: putting an image: %w", err)
+ }
+ defer response.Body.Close()
+ _, _ = io.Copy(io.Discard, io.LimitReader(response.Body, 4096))
+ switch {
+ case response.StatusCode == http.StatusForbidden:
+ return blobs.Ref{}, errPutDenied
+ case response.StatusCode/100 != 2:
+ return blobs.Ref{}, fmt.Errorf("docs: putting an image: %s",
+ response.Status)
+ }
+ return ref, nil
+}
+
+// heldBytes is data's bytes, without a copy when it holds them already
+// (Mapa images spec, Fable N7).
+func heldBytes(data io.Reader) ([]byte, error) {
+ if held, ok := data.(interface{ Bytes() []byte }); ok {
+ return held.Bytes(), nil
+ }
+ return io.ReadAll(data)
+}
diff --git a/internal/docs/images_config.go b/internal/docs/images_config.go
new file mode 100644
index 0000000..52babec
--- /dev/null
+++ b/internal/docs/images_config.go
@@ -0,0 +1,138 @@
+package docs
+
+import (
+ "context"
+ "fmt"
+ "log/slog"
+ "net/http"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "time"
+
+ "amadan.net/rastrillo/rastrillo/blobs"
+)
+
+// ImagesConfig is the images' config (Docs images spec §1 decision 4,
+// §3.4). CARLOS delivers a store as CARLOS_STORE_BUCKET and _REGION, with
+// _ACCESS_KEY and _SECRET_KEY as secrets (and _ENDPOINT only where there
+// is one). No store boots with every way in hidden and uploads at 503; so
+// does a partly delivered one, which New names loudly. An images fault
+// never takes documents down.
+type ImagesConfig struct {
+ // Objects is the object store. nil means images are not set up here,
+ // unless the instance runs in development, where New puts them in a
+ // directory beside the database.
+ Objects blobs.Store
+ // Missing names the variables a partly delivered store lacks.
+ Missing []string
+ // QuotaPerson and QuotaGuest are the allowances in stored bytes:
+ // $DOCS_IMAGE_QUOTA_PERSON for a member, $DOCS_IMAGE_QUOTA_GUEST for
+ // someone admitted only by a grant (§3.4). Zero means the default.
+ QuotaPerson int64
+ QuotaGuest int64
+}
+
+// The default allowances (§3.4, Paul's ruling 3).
+const (
+ DefaultImageQuotaPerson int64 = 1 << 30
+ DefaultImageQuotaGuest int64 = 100 << 20
+)
+
+// storeVars are the variables a store needs, in the order named.
+var storeVars = []string{"CARLOS_STORE_BUCKET", "CARLOS_STORE_REGION",
+ "CARLOS_STORE_ACCESS_KEY", "CARLOS_STORE_SECRET_KEY"}
+
+// LoadImages reads the images' config from the environment. A malformed
+// allowance is a refusal, like every other malformed setting; a missing
+// or partial store is not.
+func LoadImages(getenv func(string) string) (ImagesConfig, error) {
+ var config ImagesConfig
+ var err error
+ if config.QuotaPerson, err = imageQuota(getenv, "DOCS_IMAGE_QUOTA_PERSON", DefaultImageQuotaPerson); err != nil {
+ return config, err
+ }
+ if config.QuotaGuest, err = imageQuota(getenv, "DOCS_IMAGE_QUOTA_GUEST", DefaultImageQuotaGuest); err != nil {
+ return config, err
+ }
+ present := 0
+ for _, name := range storeVars {
+ if getenv(name) == "" {
+ config.Missing = append(config.Missing, name)
+ } else {
+ present++
+ }
+ }
+ switch {
+ case present == 0:
+ config.Missing = nil
+ case len(config.Missing) == 0:
+ config.Objects, err = bucketFrom(getenv)
+ }
+ return config, err
+}
+
+// imageQuota reads an allowance in bytes, or with a KiB, MiB or GiB
+// suffix.
+func imageQuota(getenv func(string) string, name string, fallback int64) (int64, error) {
+ raw := strings.TrimSpace(getenv(name))
+ if raw == "" {
+ return fallback, nil
+ }
+ scale := int64(1)
+ for suffix, size := range map[string]int64{"KiB": 1 << 10, "MiB": 1 << 20, "GiB": 1 << 30} {
+ if trimmed, ok := strings.CutSuffix(raw, suffix); ok {
+ raw, scale = strings.TrimSpace(trimmed), size
+ }
+ }
+ value, err := strconv.ParseInt(raw, 10, 64)
+ if err != nil || value <= 0 || value > (1<<62)/scale {
+ return 0, fmt.Errorf("docs: $%s is %q; it is a size in bytes, or a number of KiB, MiB or GiB", name, getenv(name))
+ }
+ return value * scale, nil
+}
+
+// bucketFrom is the delivered bucket, its Puts Docs' own (bucket).
+func bucketFrom(getenv func(string) string) (blobs.Store, error) {
+ s3, err := blobs.NewS3(blobs.S3Config{
+ Bucket: getenv("CARLOS_STORE_BUCKET"),
+ Region: getenv("CARLOS_STORE_REGION"),
+ Endpoint: getenv("CARLOS_STORE_ENDPOINT"),
+ AccessKey: getenv("CARLOS_STORE_ACCESS_KEY"),
+ SecretKey: getenv("CARLOS_STORE_SECRET_KEY")})
+ if err != nil {
+ return nil, err
+ }
+ return bucket{S3: s3, client: &http.Client{Timeout: 60 * time.Second}}, nil
+}
+
+// bindImages gives store its object store (§1 decision 4), says which
+// state images are in, and empties the image trash off the boot path.
+// A partly delivered store, or a store with content sealing off, boots
+// with images off and an Error line naming why.
+func bindImages(store *Store, cfg Config, logger *slog.Logger) error {
+ objects := cfg.Images.Objects
+ switch {
+ case len(cfg.Images.Missing) > 0:
+ logger.Error("docs: object store partly delivered; images are off",
+ "missing", strings.Join(cfg.Images.Missing, ", "))
+ return nil
+ case objects == nil && cfg.Env == "development" && cfg.DBPath != "" && cfg.DBPath != ":memory:":
+ dir, err := blobs.Dir(filepath.Join(filepath.Dir(cfg.DBPath), "images"))
+ if err != nil {
+ return fmt.Errorf("docs: development image store: %w", err)
+ }
+ objects = dir
+ case objects == nil:
+ logger.Info("docs: no object store; images are off")
+ return nil
+ }
+ store.images = newImageStore(objects, cfg.Images)
+ if store.content == nil {
+ logger.Error("docs: object store bound, but content sealing is not active; images are off")
+ } else {
+ logger.Info("docs: object store bound")
+ }
+ go store.EmptyImageTrash(context.Background())
+ return nil
+}
diff --git a/internal/docs/images_test.go b/internal/docs/images_test.go
new file mode 100644
index 0000000..5592d09
--- /dev/null
+++ b/internal/docs/images_test.go
@@ -0,0 +1,372 @@
+package docs
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "image"
+ "image/png"
+ "io"
+ "mime/multipart"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+// Images, server side (Docs images spec §3, §4.1, §7): upload, copy and
+// serving, their one 404, sealing at rest, the refusals, and the read
+// view drawing a document's own images.
+
+func smallPNG(t *testing.T, w, h int) []byte {
+ t.Helper()
+ var out bytes.Buffer
+ if err := png.Encode(&out, image.NewRGBA(image.Rect(0, 0, w, h))); err != nil {
+ t.Fatal(err)
+ }
+ return out.Bytes()
+}
+
+// metaPNG is imagefile's fixture with a canary in every place a PNG can
+// carry one: tEXt, zTXt, a private chunk and a trailer after IEND.
+func metaPNG(t *testing.T) []byte {
+ t.Helper()
+ raw, err := os.ReadFile(filepath.Join("..", "imagefile", "testdata", "meta.png"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ return raw
+}
+
+func uploadRequest(t *testing.T, app *App, who, sqid, name string, file []byte) *http.Request {
+ t.Helper()
+ var body bytes.Buffer
+ mw := multipart.NewWriter(&body)
+ if file != nil {
+ w, err := mw.CreateFormFile("file", name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ w.Write(file)
+ }
+ mw.Close()
+ req := asSignedIn(t, app, who, http.MethodPost, "/d/"+sqid+"/images", &body)
+ req.Header.Set("Content-Type", mw.FormDataContentType())
+ return req
+}
+
+func upload(t *testing.T, app *App, who, sqid string, file []byte) ImageReply {
+ t.Helper()
+ rec := serve(app, uploadRequest(t, app, who, sqid, "photo.png", file))
+ if rec.Code != http.StatusOK {
+ t.Fatalf("upload: %d %s", rec.Code, rec.Body.String())
+ }
+ var reply ImageReply
+ if err := json.Unmarshal(rec.Body.Bytes(), &reply); err != nil {
+ t.Fatal(err)
+ }
+ return reply
+}
+
+// teamDocument is a document created the way the app creates one: on the
+// team rung, which every member may read and only its owner may write.
+func teamDocument(t *testing.T, app *App, owner string) *Document {
+ t.Helper()
+ person := app.TestPerson(t, owner)
+ doc, err := app.store.createDocument(context.Background(), person, "Pictures", "", VisibilityTeam)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return doc
+}
+
+func privateDocument(t *testing.T, app *App, owner string) *Document {
+ t.Helper()
+ return app.TestCreatePrivate(t, app.TestPerson(t, owner), "Private pictures")
+}
+
+func TestImageUploadServesTheStrippedPictureSealedAtRest(t *testing.T) {
+ app, dbPath := sealedApp(t, Config{})
+ doc := teamDocument(t, app, "ana@example.com")
+ raw := metaPNG(t)
+
+ reply := upload(t, app, "ana@example.com", doc.Sqid, raw)
+ sqid, id, ok := ParseImageSrc(reply.Src)
+ if !ok || sqid != doc.Sqid {
+ t.Fatalf("src %q", reply.Src)
+ }
+ if reply.Width == 0 || reply.Height == 0 {
+ t.Fatalf("no size: %+v", reply)
+ }
+
+ rec := serve(app, asSignedIn(t, app, "ana@example.com", http.MethodGet, reply.Src, nil))
+ if rec.Code != http.StatusOK {
+ t.Fatalf("serve: %d", rec.Code)
+ }
+ for header, want := range map[string]string{
+ "Content-Type": "image/png",
+ "X-Content-Type-Options": "nosniff",
+ "Content-Security-Policy": "default-src 'none'; sandbox",
+ "Cross-Origin-Resource-Policy": "same-origin",
+ "Cache-Control": "private, max-age=3600, immutable",
+ "ETag": `"` + id + `"`,
+ "Content-Disposition": "inline",
+ } {
+ if got := rec.Header().Get(header); got != want {
+ t.Errorf("%s: %q, want %q", header, got, want)
+ }
+ }
+ if bytes.Contains(rec.Body.Bytes(), []byte("CANARY-")) {
+ t.Error("a metadata canary was served")
+ }
+ if !bytes.HasPrefix(rec.Body.Bytes(), []byte("\x89PNG")) {
+ t.Error("what was served is not the PNG")
+ }
+
+ // A match is answered without the body.
+ conditional := asSignedIn(t, app, "ana@example.com", http.MethodGet, reply.Src, nil)
+ conditional.Header.Set("If-None-Match", `"`+id+`"`)
+ if rec := serve(app, conditional); rec.Code != http.StatusNotModified || rec.Body.Len() != 0 {
+ t.Errorf("If-None-Match: %d, %d bytes", rec.Code, rec.Body.Len())
+ }
+
+ // At rest: no canary, no file name, no PNG magic, sizes in 64 KiB steps.
+ if app.TestRowContains(t, "document_images", "CANARY-") || app.TestRowContains(t, "document_images", "photo.png") {
+ t.Error("the database holds plaintext from the upload")
+ }
+ blobs, err := filepath.Glob(filepath.Join(filepath.Dir(dbPath), "images", "*"))
+ if err != nil || len(blobs) != 1 {
+ t.Fatalf("blobs: %v %v", blobs, err)
+ }
+ stored, err := os.ReadFile(blobs[0])
+ if err != nil {
+ t.Fatal(err)
+ }
+ if bytes.Contains(stored, []byte("CANARY-")) || bytes.HasPrefix(stored, []byte("\x89PNG")) {
+ t.Error("the stored object is not sealed")
+ }
+ if overhead := len(stored) % imagePad; overhead != 28 {
+ t.Errorf("stored %d bytes: not a 64 KiB step plus the seal's 28", len(stored))
+ }
+ for _, file := range []string{dbPath, dbPath + "-wal"} {
+ if raw, err := os.ReadFile(file); err == nil && bytes.Contains(raw, []byte("CANARY-")) {
+ t.Errorf("%s holds a canary", filepath.Base(file))
+ }
+ }
+}
+
+func TestImageRoutesGiveOneNotFound(t *testing.T) {
+ app, _ := sealedApp(t, Config{})
+ private := privateDocument(t, app, "ana@example.com")
+ team := teamDocument(t, app, "ana@example.com")
+ other := teamDocument(t, app, "ana@example.com")
+ reply := upload(t, app, "ana@example.com", private.Sqid, smallPNG(t, 4, 3))
+ _, id, _ := ParseImageSrc(reply.Src)
+
+ missing := serve(app, asSignedIn(t, app, "bo@example.com", http.MethodGet, "/d/zzzzzz/images/"+id, nil))
+ if missing.Code != http.StatusNotFound {
+ t.Fatalf("a document that does not exist: %d", missing.Code)
+ }
+ same := func(name string, rec *httptest.ResponseRecorder) {
+ t.Helper()
+ if rec.Code != missing.Code || rec.Body.String() != missing.Body.String() ||
+ rec.Header().Get("Cache-Control") != missing.Header().Get("Cache-Control") ||
+ rec.Header().Get("Content-Type") != missing.Header().Get("Content-Type") ||
+ rec.Header().Get("ETag") != "" {
+ t.Errorf("%s: %d %q %v, want the ordinary 404", name, rec.Code, rec.Body.String(), rec.Header())
+ }
+ }
+ // Bo may not read Ana's private document.
+ same("a stranger's GET", serve(app, asSignedIn(t, app, "bo@example.com", http.MethodGet, reply.Src, nil)))
+ // Ana reads both, but the image is not the other document's.
+ same("another document's address", serve(app, asSignedIn(t, app, "ana@example.com", http.MethodGet, "/d/"+other.Sqid+"/images/"+id, nil)))
+ same("an id that does not exist", serve(app, asSignedIn(t, app, "ana@example.com", http.MethodGet, "/d/"+private.Sqid+"/images/0000000000000000", nil)))
+ same("a malformed id", serve(app, asSignedIn(t, app, "ana@example.com", http.MethodGet, "/d/"+private.Sqid+"/images/x", nil)))
+
+ // Upload: a stranger gets the document's 404, a team reader the
+ // updates route's (ErrNotWritable).
+ stranger := serve(app, uploadRequest(t, app, "bo@example.com", private.Sqid, "a.png", smallPNG(t, 2, 2)))
+ if stranger.Code != http.StatusNotFound {
+ t.Errorf("a stranger's upload: %d", stranger.Code)
+ }
+ reader := serve(app, uploadRequest(t, app, "bo@example.com", team.Sqid, "a.png", smallPNG(t, 2, 2)))
+ if reader.Code != http.StatusNotFound {
+ t.Errorf("a team reader's upload: %d %s", reader.Code, reader.Body.String())
+ }
+ if n := countRows(t, app, "document_images"); n != 1 {
+ t.Errorf("%d rows after refused uploads, want 1", n)
+ }
+ // A team reader may read a team document's images.
+ teamImage := upload(t, app, "ana@example.com", team.Sqid, smallPNG(t, 2, 2))
+ if rec := serve(app, asSignedIn(t, app, "bo@example.com", http.MethodGet, teamImage.Src, nil)); rec.Code != http.StatusOK {
+ t.Errorf("a team reader's GET: %d", rec.Code)
+ }
+}
+
+func copyRequest(t *testing.T, app *App, who, sqid, src string) *http.Request {
+ t.Helper()
+ body, _ := json.Marshal(map[string]string{"src": src})
+ req := asSignedIn(t, app, who, http.MethodPost, "/d/"+sqid+"/images/copy", bytes.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ return req
+}
+
+func TestImageCopyStoresAgainUnderTheTarget(t *testing.T) {
+ app, _ := sealedApp(t, Config{})
+ source := privateDocument(t, app, "ana@example.com")
+ target := teamDocument(t, app, "ana@example.com")
+ original := upload(t, app, "ana@example.com", source.Sqid, smallPNG(t, 5, 4))
+
+ rec := serve(app, copyRequest(t, app, "ana@example.com", target.Sqid, "https://docs.example.test"+original.Src))
+ if rec.Code != http.StatusOK {
+ // The absolute form is only stripped for this instance's own
+ // origin; fall back to the relative form the editor also sends.
+ rec = serve(app, copyRequest(t, app, "ana@example.com", target.Sqid, original.Src))
+ }
+ if rec.Code != http.StatusOK {
+ t.Fatalf("copy: %d %s", rec.Code, rec.Body.String())
+ }
+ var copied ImageReply
+ json.Unmarshal(rec.Body.Bytes(), &copied)
+ sqid, _, ok := ParseImageSrc(copied.Src)
+ if !ok || sqid != target.Sqid || copied.Src == original.Src || copied.Width != 5 || copied.Height != 4 {
+ t.Fatalf("copied %+v from %+v", copied, original)
+ }
+ first := serve(app, asSignedIn(t, app, "ana@example.com", http.MethodGet, original.Src, nil))
+ second := serve(app, asSignedIn(t, app, "ana@example.com", http.MethodGet, copied.Src, nil))
+ if second.Code != http.StatusOK || !bytes.Equal(first.Body.Bytes(), second.Body.Bytes()) {
+ t.Errorf("the copy serves %d, %d bytes", second.Code, second.Body.Len())
+ }
+ // Bo reads the target but not the source: every refusal about the
+ // source is one answer, the same as a source that does not exist.
+ bosOwn := teamDocument(t, app, "bo@example.com")
+ unreadable := serve(app, copyRequest(t, app, "bo@example.com", bosOwn.Sqid, original.Src))
+ nowhere := serve(app, copyRequest(t, app, "bo@example.com", bosOwn.Sqid, "/d/zzzzzz/images/0000000000000000"))
+ malformed := serve(app, copyRequest(t, app, "bo@example.com", bosOwn.Sqid, "https://evil.example/x.png"))
+ for name, rec := range map[string]*httptest.ResponseRecorder{"unreadable": unreadable, "malformed": malformed} {
+ if rec.Code != nowhere.Code || rec.Body.String() != nowhere.Body.String() || rec.Code != http.StatusNotFound {
+ t.Errorf("%s source: %d %q, want %d %q", name, rec.Code, rec.Body.String(), nowhere.Code, nowhere.Body.String())
+ }
+ }
+}
+
+func TestImageRefusals(t *testing.T) {
+ app, _ := sealedApp(t, Config{Images: ImagesConfig{QuotaPerson: 100 << 10}})
+ doc := teamDocument(t, app, "ana@example.com")
+ refused := func(name string, file []byte, status int, says string) {
+ t.Helper()
+ rec := serve(app, uploadRequest(t, app, "ana@example.com", doc.Sqid, "x", file))
+ if rec.Code != status || !strings.Contains(rec.Body.String(), says) {
+ t.Errorf("%s: %d %s, want %d %q", name, rec.Code, rec.Body.String(), status, says)
+ }
+ }
+ refused("svg", []byte(`<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>`),
+ http.StatusUnsupportedMediaType, "docs.images.error.type")
+ refused("html", []byte("<!doctype html><p>hi"), http.StatusUnsupportedMediaType, "docs.images.error.type")
+ refused("too large", append(smallPNG(t, 2, 2), make([]byte, MaxImageBytes)...),
+ http.StatusRequestEntityTooLarge, "docs.images.error.toolarge")
+ refused("no file", nil, http.StatusUnprocessableEntity, "docs.images.error.nofile")
+
+ upload(t, app, "ana@example.com", doc.Sqid, smallPNG(t, 2, 2))
+ refused("over the allowance", smallPNG(t, 2, 2), http.StatusInsufficientStorage, "docs.images.error.quota")
+ if n := countRows(t, app, "document_images"); n != 1 {
+ t.Errorf("%d rows, want 1", n)
+ }
+}
+
+func TestImagesAreOffUntilContentSealingIsActive(t *testing.T) {
+ app, err := NewForTest(t)
+ if err != nil {
+ t.Fatal(err)
+ }
+ doc := teamDocument(t, app, "ana@example.com")
+ if app.store.ImagesReady() {
+ t.Fatal("images are ready on an unsealed instance")
+ }
+ rec := serve(app, uploadRequest(t, app, "ana@example.com", doc.Sqid, "a.png", smallPNG(t, 2, 2)))
+ if rec.Code != http.StatusServiceUnavailable || !strings.Contains(rec.Body.String(), "docs.images.error.off") {
+ t.Errorf("upload: %d %s", rec.Code, rec.Body.String())
+ }
+}
+
+// withImageNode puts the images.bin wire vector into doc, its first
+// image's address made doc's own: the vector names sqid k3m9 and id
+// 0123456789abcdef, so the document and the upload take those.
+func withImageNode(t *testing.T, app *App, doc *Document, reply ImageReply) {
+ t.Helper()
+ _, id, _ := ParseImageSrc(reply.Src)
+ db := app.store.db
+ if err := db.Exec("UPDATE documents SET sqid = 'k3m9' WHERE id = ?", doc.ID).Error; err != nil {
+ t.Fatal(err)
+ }
+ if err := db.Exec("UPDATE document_images SET public_id = '0123456789abcdef' WHERE public_id = ?", id).Error; err != nil {
+ t.Fatal(err)
+ }
+ doc.Sqid = "k3m9"
+ actor := app.TestActorFor(t, doc)
+ if _, err := app.store.ApplyUpdate(context.Background(), doc, actor, imageVector(t)); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestReadViewsDrawTheDocumentsOwnImages(t *testing.T) {
+ app, _ := sealedApp(t, Config{})
+ doc := teamDocument(t, app, "ana@example.com")
+ reply := upload(t, app, "ana@example.com", doc.Sqid, smallPNG(t, 6, 4))
+ withImageNode(t, app, doc, reply)
+
+ page := serve(app, asSignedIn(t, app, "ana@example.com", http.MethodGet, "/d/k3m9", nil))
+ if !strings.Contains(page.Body.String(), `<img src="/d/k3m9/images/0123456789abcdef" alt="A cat" width="640" height="480"`) {
+ t.Errorf("the signed-in read view does not draw the image")
+ }
+ if strings.Contains(page.Body.String(), "data:image/png;base64") {
+ t.Errorf("a data: source reached the read view")
+ }
+
+ // The link holder's page draws it under /p/{token} and never names the
+ // sqid; its image is no-store and has no ETag.
+ token, err := app.store.Publish(context.Background(), doc.OwnerID, "k3m9")
+ if err != nil {
+ t.Fatal(err)
+ }
+ public := serve(app, httptest.NewRequest(http.MethodGet, "/p/"+token, nil))
+ body := public.Body.String()
+ if !strings.Contains(body, `<img src="/p/`+token+`/images/0123456789abcdef"`) {
+ t.Errorf("the public page does not draw the image under its token")
+ }
+ if strings.Contains(body, "k3m9") {
+ t.Errorf("the public page names the sqid")
+ }
+ image := serve(app, httptest.NewRequest(http.MethodGet, "/p/"+token+"/images/0123456789abcdef", nil))
+ if image.Code != http.StatusOK || image.Header().Get("Cache-Control") != "no-store" || image.Header().Get("ETag") != "" ||
+ image.Header().Get("X-Robots-Tag") == "" {
+ t.Errorf("public image: %d %v", image.Code, image.Header())
+ }
+ gone := serve(app, httptest.NewRequest(http.MethodGet, "/p/not-a-token/images/0123456789abcdef", nil))
+ if gone.Code != http.StatusNotFound {
+ t.Errorf("an unknown token's image: %d", gone.Code)
+ }
+
+ // The Markdown export names the image's absolute address.
+ md := serve(app, asSignedIn(t, app, "ana@example.com", http.MethodGet, "/d/k3m9/export.md", nil))
+ if !strings.Contains(md.Body.String(), "![A cat](") || !strings.Contains(md.Body.String(), "/d/k3m9/images/0123456789abcdef)") {
+ t.Errorf("markdown: %s", md.Body.String())
+ }
+ pdf := serve(app, asSignedIn(t, app, "ana@example.com", http.MethodGet, "/d/k3m9/export.pdf", nil))
+ if pdf.Code != http.StatusOK {
+ t.Errorf("pdf: %d", pdf.Code)
+ }
+ _ = io.Discard
+}
+
+// imageVector is the images.bin wire vector (fixtures/generate-fragment.mjs).
+func imageVector(t *testing.T) []byte {
+ t.Helper()
+ b, err := os.ReadFile(filepath.Join("..", "..", "fixtures", "vectors", "fragment", "images.bin"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ return b
+}
diff --git a/internal/docs/migrations/0014_document_images.sql b/internal/docs/migrations/0014_document_images.sql
new file mode 100644
index 0000000..99fad21
--- /dev/null
+++ b/internal/docs/migrations/0014_document_images.sql
@@ -0,0 +1,34 @@
+-- Images (Docs images spec §3.1). One row per image; an image belongs to
+-- exactly one document (decision 2). The bytes are sealed under the
+-- content key with kind 5 and live in the object store under object_key,
+-- the SHA-256 of their ciphertext; sealed_record (kind 6) holds the sniffed
+-- type, the width and height after orientation, and the true size. Both
+-- seals bind the document's GUID and seal_id, a random positive 63-bit
+-- number drawn before sealing, because the row's own id does not exist yet
+-- when the bytes are sealed (decision 1).
+--
+-- Plaintext here, and in the leak list (2026-08-30-docs-design.md §2.1,
+-- item 3): how many images each document holds, who uploaded each and
+-- when, and its size to within 64 KiB. No file name is kept, sealed or
+-- not; alt text lives in the document, sealed with it.
+CREATE TABLE IF NOT EXISTS document_images (
+ id INTEGER PRIMARY KEY,
+ public_id TEXT NOT NULL UNIQUE,
+ seal_id INTEGER NOT NULL UNIQUE CHECK (seal_id > 0),
+ document_id INTEGER NOT NULL REFERENCES documents(id),
+ uploader_id INTEGER NOT NULL,
+ created_at DATETIME NOT NULL,
+ stored_bytes INTEGER NOT NULL CHECK (stored_bytes > 0),
+ object_key TEXT NOT NULL,
+ sealed_record BLOB NOT NULL
+);
+CREATE INDEX IF NOT EXISTS document_images_document ON document_images (document_id);
+CREATE INDEX IF NOT EXISTS document_images_uploader ON document_images (uploader_id);
+
+-- Objects to delete (§3.3, §3.5): an object whose row was never written,
+-- or whose row a purge removed, when deleting it at once failed. Emptied
+-- off the boot path; plaintext, holding only keys.
+CREATE TABLE IF NOT EXISTS image_trash (
+ object_key TEXT PRIMARY KEY,
+ queued_at DATETIME NOT NULL
+);
diff --git a/internal/docs/render.go b/internal/docs/render.go
index 0e8b417..e94cc5f 100644
--- a/internal/docs/render.go
+++ b/internal/docs/render.go
@@ -356,6 +356,23 @@ var Catalog = rastrillo.Catalog{
// reasoning that leaves an untranslated literal in the codebase.
"docs.error.badsince": "That update cursor is not valid.",
+ // Images (handlers_images.go, Docs images spec §3.2–§3.4): what an
+ // upload or a copy says when it is refused. Figures are written in the
+ // reader's locale through rastrillo's number formatting.
+ "docs.images.error.type": "Docs takes PNG, JPEG, GIF and WebP images.",
+ "docs.images.error.toolarge": "An image can be at most {size}.",
+ "docs.images.error.dimensions": "That image is too large: at most {side} pixels on a side, and {megapixels} megapixels in all.",
+ "docs.images.error.off": "Images aren’t set up on this Docs yet.",
+ "docs.images.error.busy": "Docs is busy with other images. Try again in a moment.",
+ "docs.images.error.full": "Docs’ storage is full. Ask whoever runs your team’s Oficina.",
+ "docs.images.error.nofile": "Choose an image to upload.",
+ "docs.images.error.failed": "The image could not be stored. Try again.",
+ "docs.images.error.quota": "You’ve used {size} of images. Deleting documents you no longer need frees space.",
+ "docs.export.image": "[Image: {alt}]",
+ "docs.export.image.noalt": "[Image]",
+ "docs.images.size.gb": "{n} GB",
+ "docs.images.size.mb": "{n} MB",
+
// docs.document.untitled is POST /documents' fallback title when
// the submitted one is empty or all whitespace — boilerplate copy
// this app writes, not the caller's own input, so it is a catalog
diff --git a/internal/docs/store.go b/internal/docs/store.go
index d2223fa..d623e9c 100644
--- a/internal/docs/store.go
+++ b/internal/docs/store.go
@@ -41,6 +41,9 @@ type Store struct {
db *gorm.DB
core *core.Runtime
content *contentCipher
+ // images is the images' store and slots (images.go); nil when no
+ // object store is bound.
+ images *imageStore
// sampleDocuments mirrors Config.SampleDocuments, already parsed —
// see EnsurePerson's own doc comment for what it gates and why the
diff --git a/internal/docs/team_emission.go b/internal/docs/team_emission.go
index d56b952..a0935ab 100644
--- a/internal/docs/team_emission.go
+++ b/internal/docs/team_emission.go
@@ -54,8 +54,21 @@ func (a *requestAccess) checkResponse(ctx context.Context) error {
// Once headers are sent, refusal must abort the transport rather than produce
// a successful short body with a sequence number for bytes never received.
func writeGuardedBody(w http.ResponseWriter, r *http.Request, status int, parts ...[]byte) error {
+ return writeGuardedBodyThen(w, r, status, nil, parts...)
+}
+
+// writeGuardedBodyThen is writeGuardedBody with headers that belong only to
+// an allowed response (Docs images spec §3.3): headers runs once the first
+// check has passed, just before the status is written, so a refusal never
+// carries them. An image's cache, ETag and sandbox CSP are set this way:
+// before it, the response carries the app's own page CSP, as the ordinary
+// 404 does, and a failure is never cached.
+func writeGuardedBodyThen(w http.ResponseWriter, r *http.Request, status int, headers func(http.Header), parts ...[]byte) error {
a, team := r.Context().Value(accessContextKey{}).(*requestAccess)
if !team || a == nil {
+ if headers != nil {
+ headers(w.Header())
+ }
if status != 0 {
w.WriteHeader(status)
}
@@ -70,6 +83,9 @@ func writeGuardedBody(w http.ResponseWriter, r *http.Request, status int, parts
w.Header().Del("Docs-Seq")
w.Header().Del("Content-Disposition")
w.Header().Del("Content-Length")
+ // A refusal is never stored, as the ordinary error page is not
+ // (errors.go).
+ w.Header().Set("Cache-Control", "no-store")
code := http.StatusServiceUnavailable
key := "docs.error.generic"
if errors.Is(e, gorm.ErrRecordNotFound) {
@@ -114,6 +130,9 @@ func writeGuardedBody(w http.ResponseWriter, r *http.Request, status int, parts
for _, part := range parts {
total += len(part)
}
+ if headers != nil {
+ headers(w.Header())
+ }
w.Header().Set("Content-Length", strconv.Itoa(total))
if status == 0 {
status = http.StatusOK
diff --git a/internal/export/document.go b/internal/export/document.go
index 20c3b9e..90fe527 100644
--- a/internal/export/document.go
+++ b/internal/export/document.go
@@ -28,6 +28,10 @@ type Node struct {
Content []Node `json:"content"`
Text string `json:"text"`
Marks []Mark `json:"marks"`
+
+ // markdown is an image's Markdown, worked out once by Markdown
+ // (withImageMarkdown) before the writers run.
+ markdown string
}
// Attrs is the small, closed set of node attributes the core emits.
@@ -42,6 +46,16 @@ type Attrs struct {
Level int `json:"level"`
Align string `json:"align"`
Indent int `json:"indent"`
+
+ // An image's (Docs images spec §4.2): its id when it is this
+ // document's own, already checked by the core; Missing otherwise. The
+ // core never emits an image's src, so no address from the document
+ // reaches an export.
+ ID string `json:"id"`
+ Alt string `json:"alt"`
+ Missing bool `json:"missing"`
+ Width int `json:"width"`
+ Height int `json:"height"`
}
// Mark is one mark on a text run. Only the name matters — every mark
@@ -72,6 +86,15 @@ func (n Node) IsText() bool { return n.Type == "text" }
type Document struct {
Title string
Root Node
+
+ // ImageBase is where this document's images are addressed, absolute:
+ // "https://{origin}/d/{sqid}". The Markdown export writes each image
+ // as ![alt](ImageBase/images/{id}) (Docs images spec §4.2).
+ ImageBase string
+ // ImageLine is what the PDF sets in an image's place until it embeds
+ // images (slice 3): "[Image: alt]" in the reader's language, from the
+ // catalog. nil writes the alt text in brackets.
+ ImageLine func(alt string) string
}
// Parse decodes the core's JSON into a Document.
diff --git a/internal/export/images_test.go b/internal/export/images_test.go
new file mode 100644
index 0000000..87e03a6
--- /dev/null
+++ b/internal/export/images_test.go
@@ -0,0 +1,57 @@
+package export_test
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/carlosframework/docs/internal/export"
+)
+
+// imagesJSON is a document with three inline images: one of its own, one with
+// no alt, and one the core could not place (Docs images spec §4.2).
+const imagesJSON = `{"type":"doc","content":[
+ {"type":"paragraph","content":[{"type":"text","text":"Before"}]},
+ {"type":"paragraph","content":[
+ {"type":"image","attrs":{"id":"0123456789abcdef","alt":"A [cat]\non a mat","width":640,"height":480}},
+ {"type":"text","text":" and "},
+ {"type":"image","attrs":{"id":"fedcba9876543210","alt":""}}
+ ]},
+ {"type":"paragraph","content":[{"type":"image","attrs":{"missing":true,"alt":"Pasted"}}]},
+ {"type":"paragraph","content":[{"type":"text","text":"After"}]}
+]}`
+
+func TestMarkdownNamesEachImageByItsAddress(t *testing.T) {
+ doc := mustParse(t, "Notes", imagesJSON)
+ doc.ImageBase = "https://docs.example.test/d/k3m9"
+ got := export.Markdown(doc)
+ for _, want := range []string{
+ `![A \[cat\] on a mat](https://docs.example.test/d/k3m9/images/0123456789abcdef)`,
+ `![](https://docs.example.test/d/k3m9/images/fedcba9876543210)`,
+ `![Pasted]()`,
+ } {
+ if !strings.Contains(got, want) {
+ t.Errorf("markdown is missing %q; got\n%s", want, got)
+ }
+ }
+ if strings.Contains(got, "/images/\n") || strings.Contains(got, "missing") {
+ t.Errorf("a missing image leaked an address or attribute:\n%s", got)
+ }
+}
+
+func TestPDFSetsALineInEachImagesPlace(t *testing.T) {
+ doc := mustParse(t, "Notes", imagesJSON)
+ doc.ImageLine = func(alt string) string {
+ if alt == "" {
+ return "[Image]"
+ }
+ return "[Image: " + alt + "]"
+ }
+ data, _ := mustPDF(t, doc)
+ f := readPDF(t, data)
+ got := f.text(t, f.pages(t)[0])
+ for _, want := range []string{"Before", "[Image: A [cat]", "[Image]", "[Image: Pasted]", "After"} {
+ if !strings.Contains(got, want) {
+ t.Errorf("PDF text is missing %q; got %q", want, got)
+ }
+ }
+}
diff --git a/internal/export/markdown.go b/internal/export/markdown.go
index d89e7f8..db3e2e7 100644
--- a/internal/export/markdown.go
+++ b/internal/export/markdown.go
@@ -41,7 +41,7 @@ func Markdown(doc Document) string {
b.WriteString(escapeMarkdown(doc.Title))
b.WriteString("\n\n")
}
- writeBlocks(&b, doc.Root.Content, "")
+ writeBlocks(&b, withImageMarkdown(doc.Root.Content, doc.ImageBase), "")
// Exactly one trailing newline: blocks each end with a blank line,
// which leaves two.
return strings.TrimRight(b.String(), "\n") + "\n"
@@ -208,8 +208,45 @@ func inlineString(nodes []Node) string {
// that share one: "**bold**" followed by "**er**" reads identically to
// "**bolder**" once rendered, and merging would mean tracking mark
// state across a sequence for no visible gain.
+// imageMarkdown is an image as Markdown (Docs images spec §4.2): its
+// absolute address when it is this document's own, or an empty one,
+// never a URL the document carried. The address opens only for someone
+// signed in who may read the document; Help says so.
+func imageMarkdown(n Node, base string) string {
+ var b strings.Builder
+ alt := strings.NewReplacer("\r\n", " ", "\n", " ", "\r", " ").Replace(n.Attrs.Alt)
+ b.WriteString("![")
+ b.WriteString(escapeMarkdown(alt))
+ b.WriteString("](")
+ if n.Attrs.ID != "" && !n.Attrs.Missing && base != "" {
+ b.WriteString(base)
+ b.WriteString("/images/")
+ b.WriteString(n.Attrs.ID)
+ }
+ b.WriteString(")")
+ return b.String()
+}
+
+// withImageMarkdown is nodes with each image's Markdown worked out, so
+// the writers below need no base of their own.
+func withImageMarkdown(nodes []Node, base string) []Node {
+ out := make([]Node, len(nodes))
+ for i, n := range nodes {
+ if n.Type == "image" {
+ n.markdown = imageMarkdown(n, base)
+ }
+ n.Content = withImageMarkdown(n.Content, base)
+ out[i] = n
+ }
+ return out
+}
+
func writeInline(b *strings.Builder, nodes []Node) {
for _, n := range nodes {
+ if n.Type == "image" {
+ b.WriteString(n.markdown)
+ continue
+ }
if n.Type == "hard_break" {
b.WriteString(hardBreak)
// A break has no children through the editor's schema and
diff --git a/internal/export/pdf.go b/internal/export/pdf.go
index 6362ed9..42a39c3 100644
--- a/internal/export/pdf.go
+++ b/internal/export/pdf.go
@@ -505,6 +505,7 @@ func renderPDF(doc Document, maxPages int) ([]byte, Report, error) {
// empty Title, which is why this branches rather than always laying
// one.
func (l *layout) document(doc Document) {
+ doc.Root.Content = imagesAsLines(doc.Root.Content, doc.ImageLine)
if doc.Title != "" {
l.block(Node{
Type: "heading",
@@ -1235,3 +1236,23 @@ func halfLeading(st style, lineHeight float64) float64 {
a, d := ascentDescent(st)
return (lineHeight - (a + d)) / 2
}
+
+// imagesAsLines sets each image as an italic line of text, "[Image: alt]"
+// in the reader's language, until the PDF embeds images (Docs images
+// spec §4.2, slice 3). Nothing vanishes silently.
+func imagesAsLines(nodes []Node, line func(alt string) string) []Node {
+ out := make([]Node, len(nodes))
+ for i, n := range nodes {
+ if n.Type == "image" {
+ text := "[" + n.Attrs.Alt + "]"
+ if line != nil {
+ text = line(n.Attrs.Alt)
+ }
+ out[i] = Node{Type: "text", Text: text, Marks: []Mark{{Type: "em"}}}
+ continue
+ }
+ n.Content = imagesAsLines(n.Content, line)
+ out[i] = n
+ }
+ return out
+}
diff --git a/internal/imagefile/imagefile_test.go b/internal/imagefile/imagefile_test.go
index 18c6588..a05db69 100644
--- a/internal/imagefile/imagefile_test.go
+++ b/internal/imagefile/imagefile_test.go
@@ -172,16 +172,16 @@ func TestRefusals(t *testing.T) {
"html": {[]byte("<!doctype html><p>hi"), ErrType},
"heic": {append([]byte("\x00\x00\x00\x18ftypheic"),
make([]byte, 64)...), ErrType},
- "truncated jpeg": {jpeg[:len(jpeg)/2], ErrMalformed},
- "truncated png": {pngFile[:len(pngFile)/2], ErrMalformed},
- "truncated webp": {webp[:len(webp)/2], ErrMalformed},
- "png bad crc": {flip(pngFile, 40), ErrMalformed},
- "jpeg bad length": {oversized(jpeg), ErrMalformed},
- "webp bad size": {riffSize(webp, 1<<30), ErrMalformed},
- "too wide": {encodePNG(t, MaxSide+1, 1), ErrDimensions},
- "too many pixels": {encodePNG(t, 7100, 7100), ErrDimensions},
+ "truncated jpeg": {jpeg[:len(jpeg)/2], ErrMalformed},
+ "truncated png": {pngFile[:len(pngFile)/2], ErrMalformed},
+ "truncated webp": {webp[:len(webp)/2], ErrMalformed},
+ "png bad crc": {flip(pngFile, 40), ErrMalformed},
+ "jpeg bad length": {oversized(jpeg), ErrMalformed},
+ "webp bad size": {riffSize(webp, 1<<30), ErrMalformed},
+ "too wide": {encodePNG(t, MaxSide+1, 1), ErrDimensions},
+ "too many pixels": {encodePNG(t, 7100, 7100), ErrDimensions},
// Docs' own limit (Docs images spec §3.2): just over 40 MP.
- "over 40 MP": {encodePNG(t, 6400, 6251), ErrDimensions},
+ "over 40 MP": {encodePNG(t, 6400, 6251), ErrDimensions},
"png then nothing": {[]byte(pngSignature), ErrMalformed},
}
for name, each := range cases {