oficina / docs Public

core: images in the read view and JSON export (ABI 8), and imagefile

The read view draws a document's own image, /d/{sqid}/images/{id}, under
the view's base (/d/{sqid} or /p/{token}); every other source is the
missing box, and node_json emits only the checked id, escaped alt and
clamped sizes (Docs images spec §4.1, §4.2). docs_core_set_view carries
the view; Store.HTML takes one, and the public page uses /p/{token} so
its markup never names the sqid.

internal/imagefile is Mapa's, copied with its tests and fuzz seeds, at
40 MP (§3.2). golang.org/x/image bumped to Mapa's v0.45.0.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev ab164d9a806d2a0ad2b3d1c6ba5be62b04210fba parent a656d20
42 files changed, +1,977 −51
  • core/src/abi.rs +56 −4
  • core/src/fragment.rs +195 −9
  • core/src/lib.rs +7 −2
  • core/tests/images.rs +232 −0
  • fixtures/generate-fragment.mjs +22 −1
  • fixtures/vectors/fragment/images.bin binary
  • go.mod +1 −1
  • go.sum +2 −0
  • internal/core/core.go +79 −6
  • internal/core/core_test.go +63 −0
  • internal/core/testdata/docs_core.wasm binary
  • internal/core/testdata/docs_core.wasm.stamp +2 −2
  • internal/docs/agent_store.go +1 −1
  • internal/docs/export_test.go +1 −1
  • internal/docs/publish.go +3 −2
  • internal/docs/sample_documents_test.go +1 −1
  • internal/docs/seed_test.go +4 −4
  • internal/docs/snapshots_test.go +10 −10
  • internal/docs/store.go +23 −5
  • internal/docs/updates_test.go +2 −2
  • internal/imagefile/exif.go +60 −0
  • internal/imagefile/fuzz_test.go +61 −0
  • internal/imagefile/gif.go +135 −0
  • internal/imagefile/imagefile.go +134 −0
  • internal/imagefile/imagefile_test.go +244 −0
  • internal/imagefile/jpeg.go +205 −0
  • internal/imagefile/png.go +70 −0
  • internal/imagefile/review_test.go +101 −0
  • internal/imagefile/testdata/anim.gif binary
  • internal/imagefile/testdata/anim.png binary
  • internal/imagefile/testdata/anim.webp binary
  • internal/imagefile/testdata/baseline.jpg binary
  • internal/imagefile/testdata/cmyk.jpg binary
  • internal/imagefile/testdata/lossless.webp binary
  • internal/imagefile/testdata/lossy.webp binary
  • internal/imagefile/testdata/make.py +145 −0
  • internal/imagefile/testdata/meta.png binary
  • internal/imagefile/testdata/motion.jpg binary
  • internal/imagefile/testdata/progressive.jpg binary
  • internal/imagefile/testdata/restart.jpg binary
  • internal/imagefile/testdata/thumbnail.jpg binary
  • internal/imagefile/webp.go +118 −0
diff --git a/core/src/abi.rs b/core/src/abi.rs
index 364539b..b1cad73 100644
--- a/core/src/abi.rs
+++ b/core/src/abi.rs
@@ -47,8 +47,8 @@
//! exists to avoid.
use crate::{
- apply_update, fragment_html, fragment_json, fragment_text, snapshot_bytes, verify_snapshot,
- CoreError,
+ apply_update, fragment_html_in, fragment_json_in, fragment_text, snapshot_bytes,
+ verify_snapshot, CoreError, View,
};
use std::cell::RefCell;
use std::collections::HashMap;
@@ -57,6 +57,10 @@ use yrs::{Doc, Options};
thread_local! {
static DOCS: RefCell<HashMap<u32, Doc>> = RefCell::new(HashMap::new());
+ /// Each handle's view (Docs images spec §4.1): what its HTML and JSON
+ /// draw images under. Absent means the default view, every image
+ /// missing. Set by `docs_core_set_view` before every view-aware read.
+ static VIEWS: RefCell<HashMap<u32, View>> = RefCell::new(HashMap::new());
static NEXT: RefCell<u32> = const { RefCell::new(1) };
}
@@ -98,6 +102,29 @@ pub fn doc_new(guid: &str, client_id: u64) -> u32 {
pub fn doc_free(handle: u32) {
DOCS.with(|d| d.borrow_mut().remove(&handle));
+ VIEWS.with(|v| v.borrow_mut().remove(&handle));
+}
+
+fn view_of(handle: u32) -> View {
+ VIEWS.with(|v| v.borrow().get(&handle).cloned().unwrap_or_default())
+}
+
+/// Sets `handle`'s view from `"{sqid}\n{base}"`, or the default view from
+/// the empty string. `ERR_NO_DOC` for an unknown handle, `ERR_DECODE` for
+/// a view that fails its grammar (the previous view is cleared either
+/// way, so a refused set never leaves a stale one behind).
+pub fn set_view(handle: u32, raw: &str) -> i32 {
+ VIEWS.with(|v| v.borrow_mut().remove(&handle));
+ if get_doc(handle).is_none() {
+ return ERR_NO_DOC;
+ }
+ match View::parse(raw) {
+ Some(view) => {
+ VIEWS.with(|v| v.borrow_mut().insert(handle, view));
+ 0
+ }
+ None => ERR_DECODE,
+ }
}
pub fn apply_slice(handle: u32, update: &[u8]) -> i32 {
@@ -149,7 +176,7 @@ pub fn text_string(handle: u32) -> Option<String> {
/// real empty document. Callers must not collapse the two (Finding 3),
/// exactly as `text_string` above.
pub fn html_string(handle: u32) -> Option<String> {
- get_doc(handle).map(|doc| fragment_html(&doc))
+ get_doc(handle).map(|doc| fragment_html_in(&doc, &view_of(handle)))
}
/// `None` for an unknown handle — distinct from `Some(String::new())`, a
@@ -160,7 +187,7 @@ pub fn html_string(handle: u32) -> Option<String> {
/// `docs_core_json_len` is unreachable for a live handle and the host
/// need not treat it as a special case the way the other two do.
pub fn json_string(handle: u32) -> Option<String> {
- get_doc(handle).map(|doc| fragment_json(&doc))
+ get_doc(handle).map(|doc| fragment_json_in(&doc, &view_of(handle)))
}
/// The whole document as one update. Bytes, not a string — the host
@@ -290,6 +317,31 @@ pub extern "C" fn docs_core_doc_free(handle: u32) {
doc_free(handle)
}
+/// Sets the view `handle`'s HTML and JSON are drawn for (Docs images spec
+/// §4.1; `set_view`). Added at ABI 8.
+///
+/// # Safety
+///
+/// `ptr` and `len` must describe a byte range that lies entirely within
+/// this module's linear memory and is not mutated for the duration of
+/// this call. (Checked by `in_bounds` before any slice is constructed.)
+#[no_mangle]
+pub unsafe extern "C" fn docs_core_set_view(handle: u32, ptr: u32, len: u32) -> i32 {
+ // The default view arrives as (0, 0): no slice is built from a null
+ // pointer, even an empty one.
+ if len == 0 {
+ return set_view(handle, "");
+ }
+ if !in_bounds(ptr, len) {
+ return ERR_INVALID_LENGTH;
+ }
+ let bytes = std::slice::from_raw_parts(ptr as *const u8, len as usize);
+ match std::str::from_utf8(bytes) {
+ Ok(raw) => set_view(handle, raw),
+ Err(_) => ERR_DECODE,
+ }
+}
+
/// # Safety
///
/// `ptr` and `len` must describe a byte range that lies entirely within
diff --git a/core/src/fragment.rs b/core/src/fragment.rs
index 2d365c1..2894a09 100644
--- a/core/src/fragment.rs
+++ b/core/src/fragment.rs
@@ -53,6 +53,13 @@ fn escape(s: &str, out: &mut String) {
/// attribute escaping and (for `href`) a scheme allowlist, not a row in
/// this table.
///
+/// Images (Docs images spec §4.1) are the one place that decision was
+/// made, and they are not a mark: `image_html` writes an image's id into
+/// attribute position only after it has matched a fixed grammar exactly
+/// (16 of `[0-9a-z]`, needing no escaping), under a base `View::parse`
+/// has checked, and writes the alt text escaped. No other byte of an
+/// image's attributes is written anywhere.
+///
/// Paragraph alignment (ALIGNMENTS below) is that same discipline
/// applied to a property that genuinely cannot be a mark: it belongs to
/// the block, so it arrives as an attribute WITH a value — and that
@@ -357,11 +364,150 @@ fn text_html<T: ReadTxn>(txn: &T, t: &XmlTextRef, out: &mut String) {
}
}
-fn node_html<T: ReadTxn>(txn: &T, node: &XmlOut, out: &mut String) {
+/// Where a rendering will be read (Docs images spec §4.1): the document's
+/// own sqid, and the base an image's address is drawn under — `/d/{sqid}`
+/// for a signed-in reader, `/p/{token}` for a link holder. The default
+/// view has neither, and draws every image as missing: a rendering with
+/// no document to answer for cannot name one of its images.
+///
+/// Both halves are checked against their grammars here, whatever the host
+/// already checked, because what this module writes into attribute
+/// position is `base` itself.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct View {
+ sqid: String,
+ base: String,
+}
+
+/// store.go's sqidAlphabet.
+const SQID_ALPHABET: &[u8] = b"23456789abcdefghjkmnpqrstuvwxyz";
+/// An image's public id: exactly this many of `[0-9a-z]` (spec §1
+/// decision 2). Go's `imagePublicID` and the editor's `IMAGE_ID` agree.
+pub const IMAGE_ID_LEN: usize = 16;
+
+fn is_sqid(s: &str) -> bool {
+ !s.is_empty() && s.len() <= 32 && s.bytes().all(|b| SQID_ALPHABET.contains(&b))
+}
+
+/// links.go's tokens: base64url, no padding. 16 bytes is 22 characters;
+/// the bound leaves room without admitting anything but the alphabet.
+fn is_token(s: &str) -> bool {
+ !s.is_empty() && s.len() <= 64 && s.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
+}
+
+fn is_image_id(s: &str) -> bool {
+ s.len() == IMAGE_ID_LEN && s.bytes().all(|b| b.is_ascii_digit() || b.is_ascii_lowercase())
+}
+
+impl View {
+ /// `"{sqid}\n{base}"`, or the empty string for the default view. Any
+ /// other shape is `None`, and the host's read refuses.
+ pub fn parse(raw: &str) -> Option<View> {
+ if raw.is_empty() {
+ return Some(View::default());
+ }
+ let (sqid, base) = raw.split_once('\n')?;
+ if !is_sqid(sqid) {
+ return None;
+ }
+ let ok = match base.strip_prefix("/d/") {
+ Some(own) => own == sqid,
+ None => base.strip_prefix("/p/").is_some_and(is_token),
+ };
+ ok.then(|| View { sqid: sqid.to_string(), base: base.to_string() })
+ }
+
+ /// The image id `src` names, when `src` is exactly this document's own
+ /// address, `/d/{own sqid}/images/{id}`. Everything else — another
+ /// document's address, the absolute form, `data:`, a remote URL, a
+ /// trailing path, a look-alike — is `None`, and draws as missing.
+ fn image_id<'a>(&self, src: &'a str) -> Option<&'a str> {
+ if self.sqid.is_empty() {
+ return None;
+ }
+ let rest = src.strip_prefix("/d/")?.strip_prefix(self.sqid.as_str())?;
+ let id = rest.strip_prefix("/images/")?;
+ is_image_id(id).then_some(id)
+ }
+}
+
+/// An image's `width` or `height` (spec §1 decision 5): 1 to 5 digits,
+/// clamped to 10,000; 0, junk, and a missing value are `None`. y-prosemirror
+/// never runs the schema's `validate` on what it reads, so a value can
+/// arrive as a number (yrs prints an integral number as its digits) or as
+/// anything at all.
+fn dimension<T: ReadTxn>(txn: &T, e: &XmlElementRef, name: &str) -> Option<u32> {
+ let raw = e.get_attribute(txn, name)?;
+ if raw.is_empty() || raw.len() > 5 || !raw.bytes().all(|b| b.is_ascii_digit()) {
+ return None;
+ }
+ match raw.parse::<u32>().ok()? {
+ 0 => None,
+ n => Some(n.min(10_000)),
+ }
+}
+
+/// An image node's parts, checked: its id (when it is this document's
+/// own), its alt text, and its size when both sides are present.
+struct ImageParts {
+ id: Option<String>,
+ alt: String,
+ size: Option<(u32, u32)>,
+}
+
+fn image_parts<T: ReadTxn>(txn: &T, e: &XmlElementRef, view: &View) -> ImageParts {
+ let src = e.get_attribute(txn, "src").unwrap_or_default();
+ let id = view.image_id(&src).map(str::to_string);
+ let alt = e.get_attribute(txn, "alt").unwrap_or_default();
+ let size = match (dimension(txn, e, "width"), dimension(txn, e, "height")) {
+ (Some(w), Some(h)) => Some((w, h)),
+ _ => None,
+ };
+ ImageParts { id, alt, size }
+}
+
+/// An image in the read view. This is the one place a byte from a
+/// document reaches attribute position, and only these do: the `id`,
+/// after it has matched the grammar exactly (so it is 16 of `[0-9a-z]`
+/// and needs no escaping), and the alt text, escaped. `base` is the
+/// view's, checked by `View::parse`; the sizes are numbers this function
+/// formats. Anything that is not this document's own image is a fixed
+/// box holding its alt text: no request, no URL from the document.
+fn image_html<T: ReadTxn>(txn: &T, e: &XmlElementRef, view: &View, out: &mut String) {
+ let parts = image_parts(txn, e, view);
+ match parts.id {
+ Some(id) => {
+ let _ = write!(out, "<img src=\"{}/images/{}\" alt=\"", view.base, id);
+ escape(&parts.alt, out);
+ out.push('"');
+ if let Some((w, h)) = parts.size {
+ let _ = write!(out, " width=\"{w}\" height=\"{h}\"");
+ }
+ out.push_str(" loading=\"lazy\" decoding=\"async\">");
+ }
+ None => {
+ out.push_str("<span class=\"docs-image-missing\">");
+ escape(&parts.alt, out);
+ out.push_str("</span>");
+ }
+ }
+}
+
+fn node_html<T: ReadTxn>(txn: &T, node: &XmlOut, view: &View, out: &mut String) {
match node {
XmlOut::Text(t) => text_html(txn, t, out),
XmlOut::Element(e) => {
let name = e.tag().to_string();
+ if name == "image" {
+ image_html(txn, e, view, out);
+ // An image has no children; a client posting raw Yjs
+ // bytes could give it some, and they render after it
+ // rather than vanishing (the module comment).
+ for child in e.children(txn) {
+ node_html(txn, &child, view, out);
+ }
+ return;
+ }
let (open, close) = match name.as_str() {
// A paragraph can be aligned, indented, both, or
// neither. Both classes are literals this binary builds
@@ -420,26 +566,31 @@ fn node_html<T: ReadTxn>(txn: &T, node: &XmlOut, out: &mut String) {
};
out.push_str(&open);
for child in e.children(txn) {
- node_html(txn, &child, out);
+ node_html(txn, &child, view, out);
}
out.push_str(&close);
}
XmlOut::Fragment(f) => {
for child in f.children(txn) {
- node_html(txn, &child, out);
+ node_html(txn, &child, view, out);
}
}
}
}
/// The document rendered as HTML, escaped and ready to place inside the
-/// page container.
+/// page container, with every image drawn as missing (the default view).
pub fn fragment_html(doc: &Doc) -> String {
+ fragment_html_in(doc, &View::default())
+}
+
+/// The document rendered as HTML for one view (Docs images spec §4.1).
+pub fn fragment_html_in(doc: &Doc, view: &View) -> String {
let f = root(doc);
let txn = doc.transact();
let mut out = String::new();
for child in f.children(&txn) {
- node_html(&txn, &child, &mut out);
+ node_html(&txn, &child, view, &mut out);
}
out
}
@@ -672,7 +823,32 @@ fn text_json<T: ReadTxn>(txn: &T, t: &XmlTextRef, out: &mut String, first: &mut
// what internal/export reads. The empty `content` is how this renderer
// spells every childless element (an empty paragraph included), so a
// leaf is not a special shape here.
-fn node_json<T: ReadTxn>(txn: &T, node: &XmlOut, out: &mut String, first: &mut bool) {
+/// An image's JSON (Docs images spec §4.2), after `{"type":"image"`. The
+/// rule above holds — no unchecked document byte reaches JSON: the id has
+/// matched its grammar, the sizes are numbers, and the alt text goes
+/// through `escape_json`. Anything not this document's own image is the
+/// missing form, so a 12 MB `data:` source or a remote URL never reaches
+/// an export, a preview, an import read or an agent. Children are not
+/// written: an image has none, and the exporters draw it as a unit.
+fn image_json<T: ReadTxn>(txn: &T, e: &XmlElementRef, view: &View, out: &mut String) {
+ let parts = image_parts(txn, e, view);
+ out.push_str(",\"attrs\":{");
+ match &parts.id {
+ Some(id) => {
+ let _ = write!(out, "\"id\":\"{id}\"");
+ }
+ None => out.push_str("\"missing\":true"),
+ }
+ out.push_str(",\"alt\":\"");
+ escape_json(&parts.alt, out);
+ out.push('"');
+ if let (Some(_), Some((w, h))) = (&parts.id, parts.size) {
+ let _ = write!(out, ",\"width\":{w},\"height\":{h}");
+ }
+ out.push_str("},\"content\":[]}");
+}
+
+fn node_json<T: ReadTxn>(txn: &T, node: &XmlOut, view: &View, out: &mut String, first: &mut bool) {
match node {
XmlOut::Text(t) => text_json(txn, t, out, first),
XmlOut::Element(e) => {
@@ -684,6 +860,10 @@ fn node_json<T: ReadTxn>(txn: &T, node: &XmlOut, out: &mut String, first: &mut b
out.push_str("{\"type\":\"");
escape_json(&name, out);
out.push('"');
+ if name == "image" {
+ image_json(txn, e, view, out);
+ return;
+ }
// Attributes are collected and written ONCE, as a single
// object.
//
@@ -739,7 +919,7 @@ fn node_json<T: ReadTxn>(txn: &T, node: &XmlOut, out: &mut String, first: &mut b
out.push_str(",\"content\":[");
let mut inner = true;
for child in e.children(txn) {
- node_json(txn, &child, out, &mut inner);
+ node_json(txn, &child, view, out, &mut inner);
}
out.push_str("]}");
}
@@ -748,7 +928,7 @@ fn node_json<T: ReadTxn>(txn: &T, node: &XmlOut, out: &mut String, first: &mut b
// `node_html` renders a nested fragment's children with no
// wrapper of its own.
for child in f.children(txn) {
- node_json(txn, &child, out, first);
+ node_json(txn, &child, view, out, first);
}
}
}
@@ -760,12 +940,18 @@ fn node_json<T: ReadTxn>(txn: &T, node: &XmlOut, out: &mut String, first: &mut b
/// one place that took work — so a Go consumer's golden files are
/// stable.
pub fn fragment_json(doc: &Doc) -> String {
+ fragment_json_in(doc, &View::default())
+}
+
+/// `fragment_json` for one view (Docs images spec §4.2): an image is its
+/// checked parts or the missing form, never its raw `src`.
+pub fn fragment_json_in(doc: &Doc, view: &View) -> String {
let f = root(doc);
let txn = doc.transact();
let mut out = String::from("{\"type\":\"doc\",\"content\":[");
let mut first = true;
for child in f.children(&txn) {
- node_json(&txn, &child, &mut out, &mut first);
+ node_json(&txn, &child, view, &mut out, &mut first);
}
out.push_str("]}");
out
diff --git a/core/src/lib.rs b/core/src/lib.rs
index 218b821..dc5fdd1 100644
--- a/core/src/lib.rs
+++ b/core/src/lib.rs
@@ -59,7 +59,10 @@ pub mod edit;
mod fragment;
pub mod initial;
mod snapshot;
-pub use fragment::{fragment_html, fragment_json, fragment_text, ROOT as FRAGMENT_ROOT};
+pub use fragment::{
+ fragment_html, fragment_html_in, fragment_json, fragment_json_in, fragment_text, View,
+ IMAGE_ID_LEN, ROOT as FRAGMENT_ROOT,
+};
pub use snapshot::{snapshot_bytes, verify_snapshot};
#[cfg(target_arch = "wasm32")]
@@ -92,6 +95,8 @@ extern "Rust" fn __getrandom_v03_custom(
/// Version 5 adds bounded initial paragraph/heading construction.
/// Version 6 adds bounded semantic splices on a disposable replay handle.
/// Version 7 adds rich document imports through `docs_core_build`.
+/// Version 8 adds `docs_core_set_view`, the view a handle's HTML and JSON
+/// draw images for (Docs images spec §4.1).
///
/// Adding an export is, strictly, backwards compatible — a host that
/// never calls the new function cannot tell 3 from 2 — so the bump is
@@ -105,7 +110,7 @@ extern "Rust" fn __getrandom_v03_custom(
/// here.
#[no_mangle]
pub extern "C" fn docs_core_abi_version() -> u32 {
- 7
+ 8
}
use yrs::updates::decoder::Decode;
diff --git a/core/tests/images.rs b/core/tests/images.rs
new file mode 100644
index 0000000..73436d5
--- /dev/null
+++ b/core/tests/images.rs
@@ -0,0 +1,232 @@
+//! Images in the read view and the JSON export (Docs images spec §4.1,
+//! §4.2): only this document's own address draws, under the view's base;
+//! every other source is the missing box, and no byte of it reaches
+//! attribute position or JSON.
+
+use docs_core::{fragment_html_in, fragment_json_in, fragment_text, View};
+use yrs::{Doc, Options, Transact, Xml, XmlElementPrelim, XmlFragment, XmlTextPrelim};
+
+const OWN: &str = "k3m9";
+const ID: &str = "0123456789abcdef";
+
+/// A document with one paragraph holding `text` and one image carrying
+/// `attrs`.
+fn with_image(attrs: &[(&str, &str)]) -> Doc {
+ let doc = Doc::with_options(Options::with_guid_and_client_id("images".into(), 1));
+ {
+ let f = doc.get_or_insert_xml_fragment("prosemirror");
+ let mut txn = doc.transact_mut();
+ let p = f.push_back(&mut txn, XmlElementPrelim::empty("paragraph"));
+ p.push_back(&mut txn, XmlTextPrelim::new("Before "));
+ let img = p.push_back(&mut txn, XmlElementPrelim::empty("image"));
+ for (k, v) in attrs {
+ img.insert_attribute(&mut txn, *k, *v);
+ }
+ p.push_back(&mut txn, XmlTextPrelim::new(" after"));
+ }
+ doc
+}
+
+fn signed_in() -> View {
+ View::parse(&format!("{OWN}\n/d/{OWN}")).expect("view")
+}
+
+fn own_src() -> String {
+ format!("/d/{OWN}/images/{ID}")
+}
+
+#[test]
+fn own_image_draws_under_the_signed_in_base() {
+ let src = own_src();
+ let doc = with_image(&[("src", &src), ("alt", "A cat"), ("width", "640"), ("height", "480")]);
+ assert_eq!(
+ fragment_html_in(&doc, &signed_in()),
+ format!(
+ "<p>Before <img src=\"/d/{OWN}/images/{ID}\" alt=\"A cat\" width=\"640\" height=\"480\" loading=\"lazy\" decoding=\"async\"> after</p>"
+ )
+ );
+}
+
+#[test]
+fn own_image_draws_under_a_public_base_without_the_sqid() {
+ let src = own_src();
+ let doc = with_image(&[("src", &src), ("alt", "")]);
+ let view = View::parse(&format!("{OWN}\n/p/AbC-_9xyzAbC-_9xyzAb")).expect("view");
+ let html = fragment_html_in(&doc, &view);
+ assert!(
+ html.contains(&format!("<img src=\"/p/AbC-_9xyzAbC-_9xyzAb/images/{ID}\" alt=\"\"")),
+ "got {html}"
+ );
+ assert!(!html.contains(OWN), "the public markup named the sqid: {html}");
+}
+
+#[test]
+fn the_default_view_draws_every_image_as_missing() {
+ let src = own_src();
+ let doc = with_image(&[("src", &src), ("alt", "A cat")]);
+ let html = docs_core::fragment_html(&doc);
+ assert_eq!(html, "<p>Before <span class=\"docs-image-missing\">A cat</span> after</p>");
+ assert!(docs_core::fragment_json(&doc).contains("\"missing\":true"));
+}
+
+#[test]
+fn anything_but_this_documents_own_address_is_missing() {
+ let hostile = [
+ format!("https://example.com/d/{OWN}/images/{ID}"),
+ format!("/d/other/images/{ID}"),
+ format!("/d/{OWN}/images/{ID}/x"),
+ format!("/d/{OWN}/images/{ID}?x=1"),
+ format!("/d/{OWN}/images/{}", &ID[..15]),
+ format!("/d/{OWN}/images/{ID}0"),
+ format!("/d/{OWN}/images/0123456789ABCDEF"),
+ format!("/d/{OWN}%2fimages/{ID}"),
+ format!("/d/{OWN}/images/0123456789abcde\u{0435}"),
+ format!("/d/{OWN}/images/\"onerror=\"x"),
+ "javascript:alert(1)".to_string(),
+ "data:image/png;base64,iVBORw0KGgo=".to_string(),
+ String::new(),
+ ];
+ for src in hostile {
+ let doc = with_image(&[("src", &src), ("alt", "x")]);
+ let html = fragment_html_in(&doc, &signed_in());
+ assert!(!html.contains("<img"), "{src:?} drew an image: {html}");
+ assert!(html.contains("<span class=\"docs-image-missing\">x</span>"), "{src:?}: {html}");
+ let json = fragment_json_in(&doc, &signed_in());
+ assert!(json.contains("\"missing\":true"), "{src:?}: {json}");
+ assert!(!json.contains("src"), "{src:?} reached JSON: {json}");
+ }
+}
+
+#[test]
+fn alt_text_is_escaped_in_html_and_json() {
+ let src = own_src();
+ let alt = "\"><script>alert('x')</script>&\\\n";
+ let doc = with_image(&[("src", &src), ("alt", alt)]);
+ let html = fragment_html_in(&doc, &signed_in());
+ assert!(
+ html.contains("alt=\"&quot;&gt;&lt;script&gt;alert(&#39;x&#39;)&lt;/script&gt;&amp;\\\n\""),
+ "got {html}"
+ );
+ let json = fragment_json_in(&doc, &signed_in());
+ let parsed: serde_json_lite::Value = serde_json_lite::parse(&json);
+ assert_eq!(parsed.image_alt(), alt, "json {json}");
+}
+
+#[test]
+fn sizes_are_digits_clamped_and_both_or_neither() {
+ let src = own_src();
+ let cases: &[(&str, &str, Option<&str>)] = &[
+ ("640", "480", Some(" width=\"640\" height=\"480\"")),
+ ("99999", "20", Some(" width=\"10000\" height=\"20\"")),
+ ("0", "20", None),
+ ("640", "", None),
+ ("6.5", "20", None),
+ ("640px", "20", None),
+ (" 640", "20", None),
+ ("123456", "20", None),
+ ("-1", "20", None),
+ ];
+ for (w, h, want) in cases {
+ let doc = with_image(&[("src", &src), ("alt", ""), ("width", w), ("height", h)]);
+ let html = fragment_html_in(&doc, &signed_in());
+ match want {
+ Some(dims) => assert!(html.contains(dims), "{w:?}x{h:?}: {html}"),
+ None => assert!(!html.contains("width="), "{w:?}x{h:?}: {html}"),
+ }
+ }
+ let doc = with_image(&[("src", &src), ("alt", "")]);
+ assert!(!fragment_html_in(&doc, &signed_in()).contains("width="));
+}
+
+#[test]
+fn json_carries_only_the_checked_parts() {
+ let src = own_src();
+ let doc = with_image(&[("src", &src), ("alt", "A cat"), ("width", "640"), ("height", "480"), ("title", "t")]);
+ let json = fragment_json_in(&doc, &signed_in());
+ assert!(
+ json.contains(&format!(
+ "{{\"type\":\"image\",\"attrs\":{{\"id\":\"{ID}\",\"alt\":\"A cat\",\"width\":640,\"height\":480}},\"content\":[]}}"
+ )),
+ "got {json}"
+ );
+ assert!(!json.contains("/d/"), "the address reached JSON: {json}");
+}
+
+#[test]
+fn views_are_checked_against_their_grammars() {
+ for bad in [
+ "k3m9",
+ "k3m9\n/d/other",
+ "k3m9\n/d/k3m9/",
+ "k3m9\n/x/k3m9",
+ "k3m9\n/p/",
+ "k3m9\n/p/a\"b",
+ "k3m9\n/p/a/b",
+ "K3M9\n/d/K3M9",
+ "k3m0\n/d/k3m0",
+ "\n/d/",
+ ] {
+ assert!(View::parse(bad).is_none(), "{bad:?} parsed");
+ }
+ assert!(View::parse("").is_some());
+ assert!(View::parse("k3m9\n/d/k3m9").is_some());
+}
+
+#[test]
+fn text_is_unchanged_around_an_image() {
+ let src = own_src();
+ let doc = with_image(&[("src", &src), ("alt", "A cat")]);
+ assert_eq!(fragment_text(&doc), "Before after");
+}
+
+/// Just enough JSON reading to check one escaped string round-trips, so
+/// the test needs no new dependency.
+mod serde_json_lite {
+ pub struct Value(String);
+ pub fn parse(json: &str) -> Value {
+ Value(json.to_string())
+ }
+ impl Value {
+ /// The alt string of the first image, unescaped.
+ pub fn image_alt(&self) -> String {
+ let at = self.0.find("\"alt\":\"").expect("alt") + 7;
+ let mut out = String::new();
+ let mut chars = self.0[at..].chars();
+ while let Some(c) = chars.next() {
+ match c {
+ '"' => return out,
+ '\\' => match chars.next().expect("escape") {
+ 'n' => out.push('\n'),
+ 'r' => out.push('\r'),
+ 't' => out.push('\t'),
+ other => out.push(other),
+ },
+ c => out.push(c),
+ }
+ }
+ panic!("unterminated alt in {}", self.0)
+ }
+ }
+}
+
+/// The wire vector (fixtures/generate-fragment.mjs's images.bin), as Yjs
+/// itself writes it: string sizes, a NUMBER width y-prosemirror never
+/// validated, a `data:` image with no size, and another document's
+/// address.
+#[test]
+fn reads_the_wire_vector() {
+ use yrs::updates::decoder::Decode;
+ let doc = Doc::with_options(Options::with_guid_and_client_id("fixture".into(), 1));
+ let update = yrs::Update::decode_v1(include_bytes!("../../fixtures/vectors/fragment/images.bin"))
+ .expect("decode");
+ doc.transact_mut().apply_update(update).expect("apply");
+ let html = fragment_html_in(&doc, &signed_in());
+ assert_eq!(
+ html,
+ "<p>A <img src=\"/d/k3m9/images/0123456789abcdef\" alt=\"A cat\" width=\"640\" height=\"480\" loading=\"lazy\" decoding=\"async\"> and <img src=\"/d/k3m9/images/fedcba9876543210\" alt=\"\" width=\"320\" height=\"200\" loading=\"lazy\" decoding=\"async\"></p>\
+<p><span class=\"docs-image-missing\">Pasted</span><span class=\"docs-image-missing\">Elsewhere</span></p>"
+ );
+ let json = fragment_json_in(&doc, &signed_in());
+ assert!(json.contains("\"id\":\"fedcba9876543210\",\"alt\":\"\",\"width\":320,\"height\":200"), "{json}");
+ assert!(!json.contains("data:"), "{json}");
+}
diff --git a/fixtures/generate-fragment.mjs b/fixtures/generate-fragment.mjs
index 06e1246..4889ad5 100644
--- a/fixtures/generate-fragment.mjs
+++ b/fixtures/generate-fragment.mjs
@@ -250,6 +250,27 @@ writeFileSync('vectors/fragment/inline.bin', docWith(f => {
// to one written before alignment existed. The last one says "left" out
// loud, which a paste or a future build can produce and which must
// render as no class rather than as a class of its own.
+// images.bin (Docs images spec §4.1): an image of this document's own
+// (sqid k3m9) with its size as y-prosemirror writes it from the upload's
+// reply, strings; a second whose width arrived as a NUMBER, which
+// y-prosemirror never validates and the core must still read; one with
+// no size at all (a native paste's data: image today); and another
+// document's address, which must draw as missing.
+writeFileSync('vectors/fragment/images.bin', docWith(f => {
+ f.insert(0, [
+ el('paragraph', null,
+ text('A '),
+ el('image', { src: '/d/k3m9/images/0123456789abcdef', alt: 'A cat', width: '640', height: '480' }),
+ text(' and '),
+ el('image', { src: '/d/k3m9/images/fedcba9876543210', alt: '', width: 320, height: 200 }),
+ ),
+ el('paragraph', null,
+ el('image', { src: 'data:image/png;base64,iVBORw0KGgo=', alt: 'Pasted' }),
+ el('image', { src: '/d/other/images/0123456789abcdef', alt: 'Elsewhere' }),
+ ),
+ ])
+}))
+
writeFileSync('vectors/fragment/aligned.bin', docWith(f => {
f.insert(0, [
el('paragraph', null, text('Left by default.')),
@@ -458,4 +479,4 @@ emitTrap('concurrent', (doc) => {
Y.applyUpdate(doc, Y.encodeStateAsUpdate(a))
})
-console.log('wrote 15 fragment vectors + 4 trap-containment vectors')
+console.log('wrote 16 fragment vectors + 4 trap-containment vectors')
diff --git a/fixtures/vectors/fragment/images.bin b/fixtures/vectors/fragment/images.bin
new file mode 100644
index 0000000..40ada88
Binary files /dev/null and b/fixtures/vectors/fragment/images.bin differ
diff --git a/go.mod b/go.mod
index fc3788f..148db54 100644
--- a/go.mod
+++ b/go.mod
@@ -23,7 +23,7 @@ require (
github.com/google/uuid v1.6.0
github.com/modelcontextprotocol/go-sdk v1.8.0
github.com/tetratelabs/wazero v1.12.0
- golang.org/x/image v0.23.0
+ golang.org/x/image v0.45.0
golang.org/x/oauth2 v0.35.0
golang.org/x/text v0.41.0
gorm.io/gorm v1.31.2
diff --git a/go.sum b/go.sum
index 6cefe51..e19d6a2 100644
--- a/go.sum
+++ b/go.sum
@@ -116,6 +116,8 @@ golang.org/x/crypto v0.55.0 h1:+KWHjbgOaAQ66dh/YlkZKHlz9ZUlq61AFirAR9ntP8M=
golang.org/x/crypto v0.55.0/go.mod h1:uq0V9dE/fzQuJtbnL+2EhWOE63vo164FY8xqEnV9xis=
golang.org/x/image v0.23.0 h1:HseQ7c2OpPKTPVzNjG5fwJsOTCiiwS4QdsYi5XU6H68=
golang.org/x/image v0.23.0/go.mod h1:wJJBTdLfCCf3tiHa1fNxpZmUI4mmoZvwMCPP0ddoNKY=
+golang.org/x/image v0.45.0 h1:FMb1nTbH5H9vF55SriQHgFw5GnNL9Jg6L25BwXKzhB0=
+golang.org/x/image v0.45.0/go.mod h1:n62x/7RqlwXDvGsSU4u6IUTUf6KghUZ9Bt7cG/T9Fx4=
golang.org/x/mod v0.38.0 h1:MECBjubtXD7yj4HrhIUcywNaGeNVUdfVnxmPajOk4yk=
golang.org/x/mod v0.38.0/go.mod h1:V6Xz0pq8TQ3dGqVQ1FVHuelZpAL0uNhSkk9ogYP3c40=
golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To=
diff --git a/internal/core/core.go b/internal/core/core.go
index 4c64eb1..480042a 100644
--- a/internal/core/core.go
+++ b/internal/core/core.go
@@ -79,7 +79,9 @@ var moduleWASM []byte
// version skew to tolerate, so the bump exists to catch a stale .wasm
// at load time instead of "unknown export" deep inside a request.
// Version 7 adds rich imports alongside initialization and semantic editing.
-const abiVersion = 7
+// Version 8 adds docs_core_set_view, the view HTML and JSON draw images
+// for (Docs images spec §4.1).
+const abiVersion = 8
// ABIVersion is abiVersion, exported for callers outside this package
// (snapshot storage and its tests) that need to know which ABI contract
@@ -615,9 +617,16 @@ func (h *Handle) Text(ctx context.Context) (string, error) {
}
// HTML returns the document's current content rendered as HTML (spec
-// §6.2: the read view is server-rendered, no script required).
+// §6.2: the read view is server-rendered, no script required), drawn for
+// no view: every image is the missing box. A page shows HTMLIn.
func (h *Handle) HTML(ctx context.Context) (string, error) {
- return h.read(ctx, "html")
+ return h.readIn(ctx, "html", View{})
+}
+
+// HTMLIn is HTML drawn for one view (Docs images spec §4.1): this
+// document's own images are drawn under v.Base.
+func (h *Handle) HTMLIn(ctx context.Context, v View) (string, error) {
+ return h.readIn(ctx, "html", v)
}
// JSON returns the document's structure as ProseMirror-shaped JSON —
@@ -629,8 +638,33 @@ func (h *Handle) HTML(ctx context.Context) (string, error) {
// The bytes are always a complete JSON document for a live handle,
// never "" — an empty document is {"type":"doc","content":[]} — so a
// caller may unmarshal the result without a special case for empty.
+//
+// Drawn for no view, so every image is {"missing":true}; JSONIn names
+// this document's own.
func (h *Handle) JSON(ctx context.Context) (string, error) {
- return h.read(ctx, "json")
+ return h.readIn(ctx, "json", View{})
+}
+
+// JSONIn is JSON for one view (Docs images spec §4.2).
+func (h *Handle) JSONIn(ctx context.Context, v View) (string, error) {
+ return h.readIn(ctx, "json", v)
+}
+
+// View is where a rendering will be read (Docs images spec §4.1): the
+// document's own sqid, and the base its images are drawn under —
+// "/d/{sqid}" for a signed-in reader, "/p/{token}" for a link holder. The
+// zero View draws every image as missing. The core checks both against
+// their grammars and refuses the read otherwise.
+type View struct {
+ Sqid string
+ Base string
+}
+
+func (v View) wire() []byte {
+ if v == (View{}) {
+ return nil
+ }
+ return []byte(v.Sqid + "\n" + v.Base)
}
// Snapshot returns the document's entire state as one Yjs update — what
@@ -733,7 +767,23 @@ func (h *Handle) VerifySnapshot(ctx context.Context, candidate []byte) (bool, er
// fix like fix-round-1's finding 3 (read the written count, not the
// buffer size) to be applied to two of.
func (h *Handle) read(ctx context.Context, renderer string) (string, error) {
- s, err := readOn(ctx, h.rt.callTimeout, h.mod, h.handle, renderer)
+ return h.readIn(ctx, renderer, View{})
+}
+
+// readIn is read with a view set first, for the two renderers that draw
+// images ("html" and "json"). The view is set before every attempt, the
+// retry included: a rebuilt instance holds none, and a warm handle may
+// hold the last caller's.
+func (h *Handle) readIn(ctx context.Context, renderer string, v View) (string, error) {
+ attempt := func() (string, error) {
+ if renderer == "html" || renderer == "json" {
+ if err := setViewOn(ctx, h.rt.callTimeout, h.mod, h.handle, v.wire()); err != nil {
+ return "", err
+ }
+ }
+ return readOn(ctx, h.rt.callTimeout, h.mod, h.handle, renderer)
+ }
+ s, err := attempt()
if err == nil {
return s, nil
}
@@ -743,13 +793,36 @@ func (h *Handle) read(ctx context.Context, renderer string) (string, error) {
if rebuildErr := h.rebuild(ctx); rebuildErr != nil {
return "", errors.Join(err, rebuildErr)
}
- s, err = readOn(ctx, h.rt.callTimeout, h.mod, h.handle, renderer)
+ s, err = attempt()
if err != nil {
return "", fmt.Errorf("reading %s from the rebuilt instance: %w", renderer, err)
}
return s, nil
}
+// setViewOn calls docs_core_set_view. An empty view sets the default.
+func setViewOn(ctx context.Context, timeout time.Duration, mod api.Module, docHandle uint64, view []byte) error {
+ ptr, n := uint64(0), uint64(len(view))
+ if n > 0 {
+ var err error
+ if ptr, err = allocIn(ctx, timeout, mod, n); err != nil {
+ return fmt.Errorf("alloc: %w", err)
+ }
+ defer freeIn(ctx, timeout, mod, ptr, n)
+ if !mod.Memory().Write(uint32(ptr), view) {
+ return fmt.Errorf("writing %d bytes at %d: out of range", n, ptr)
+ }
+ }
+ rc, err := callGuest(ctx, timeout, mod.ExportedFunction("docs_core_set_view"), docHandle, ptr, n)
+ if err != nil {
+ return fmt.Errorf("set_view trapped or timed out: %w", err)
+ }
+ if code := int32(rc[0]); code != 0 {
+ return fmt.Errorf("set_view refused the view: code %d", code)
+ }
+ return nil
+}
+
// readOn performs one renderer's len-then-read dance against
// docs_core_<renderer>_len and docs_core_<renderer>_read. renderer is
// always one of this package's own four literals ("text", "html",
diff --git a/internal/core/core_test.go b/internal/core/core_test.go
index c8cd2be..78c4aff 100644
--- a/internal/core/core_test.go
+++ b/internal/core/core_test.go
@@ -5,6 +5,7 @@ import (
"encoding/json"
"os"
"path/filepath"
+ "strings"
"testing"
"github.com/carlosframework/docs/internal/core"
@@ -295,3 +296,65 @@ func TestVerifySnapshotAcceptsItsOwnAndRejectsGarbage(t *testing.T) {
t.Errorf("garbage verified: ok=%v err=%v", ok, err)
}
}
+
+// TestViewDrawsImages covers the ABI 8 view (Docs images spec §4.1): the
+// document's own images draw under the view's base; the plain HTML and
+// JSON draw them missing; a refused view is an error, not a rendering;
+// and a handle read with a view and then without keeps nothing of the
+// first — a warm handle is read by many callers in turn.
+func TestViewDrawsImages(t *testing.T) {
+ ctx := context.Background()
+ rt, err := core.New(ctx)
+ if err != nil {
+ t.Fatalf("core.New: %v", err)
+ }
+ t.Cleanup(func() { rt.Close(ctx) })
+ update, err := os.ReadFile(filepath.Join("..", "..", "fixtures", "vectors", "fragment", "images.bin"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ doc, err := rt.NewDoc(ctx, "view-test-guid", 9002)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer doc.Close(ctx)
+ if err := doc.Apply(ctx, update); err != nil {
+ t.Fatal(err)
+ }
+
+ public := core.View{Sqid: "k3m9", Base: "/p/AbCdEfGhIjKlMnOpQrStUv"}
+ html, err := doc.HTMLIn(ctx, public)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if want := `<img src="/p/AbCdEfGhIjKlMnOpQrStUv/images/0123456789abcdef"`; !strings.Contains(html, want) {
+ t.Errorf("public view: %s", html)
+ }
+ if strings.Contains(html, "k3m9") {
+ t.Errorf("the public view named the sqid: %s", html)
+ }
+ plain, err := doc.HTML(ctx)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if strings.Contains(plain, "<img") {
+ t.Errorf("HTML after HTMLIn kept the view: %s", plain)
+ }
+ structure, err := doc.JSONIn(ctx, core.View{Sqid: "k3m9", Base: "/d/k3m9"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !strings.Contains(structure, `"id":"0123456789abcdef"`) {
+ t.Errorf("JSONIn: %s", structure)
+ }
+ for _, bad := range []core.View{
+ {Sqid: "k3m9", Base: "/d/other"},
+ {Sqid: "k3m9", Base: `/p/a"b`},
+ {Sqid: "K3M9", Base: "/d/K3M9"},
+ {Sqid: "k3m9"},
+ } {
+ if got, err := doc.HTMLIn(ctx, bad); err == nil {
+ t.Errorf("%+v was accepted: %s", bad, got)
+ }
+ }
+}
diff --git a/internal/core/testdata/docs_core.wasm b/internal/core/testdata/docs_core.wasm
index a592a10..ec895fb 100755
Binary files a/internal/core/testdata/docs_core.wasm and b/internal/core/testdata/docs_core.wasm differ
diff --git a/internal/core/testdata/docs_core.wasm.stamp b/internal/core/testdata/docs_core.wasm.stamp
index fd44ad3..881eddd 100644
--- a/internal/core/testdata/docs_core.wasm.stamp
+++ b/internal/core/testdata/docs_core.wasm.stamp
@@ -1,3 +1,3 @@
# Written by scripts/build-wasm.sh; checked by scripts/wasm-stamp.sh check docs_core.
-inputs b73d4d4a823f8c44f8aa5a9f794383d6340826eb03f7a8df9b576e79223f5c2d
-wasm efc55a06e62779c1863a3887dcb7789adb2615015ab2c65bf1ff964c1ec9cecd
+inputs 4c95fb10efe7cb22bedde5c07e6786270e48f6fd4112b74775022434d6d4fd70
+wasm 52067962aae6db56ad0fd6f913867403b75dcc80180467f2d005d834edf45047
diff --git a/internal/docs/agent_store.go b/internal/docs/agent_store.go
index 3860169..e6422ad 100644
--- a/internal/docs/agent_store.go
+++ b/internal/docs/agent_store.go
@@ -188,7 +188,7 @@ func (a *documentAgent) body(ctx context.Context, actor Actor, sqid string) (any
if err != nil {
return nil, agentFailure(err)
}
- content, err := h.JSON(ctx)
+ content, err := h.JSONIn(ctx, DocView(doc))
if err != nil {
return nil, agentFailure(err)
}
diff --git a/internal/docs/export_test.go b/internal/docs/export_test.go
index fbe3f18..cd95884 100644
--- a/internal/docs/export_test.go
+++ b/internal/docs/export_test.go
@@ -438,7 +438,7 @@ func TestEveryClassTheRendererEmitsIsStyled(t *testing.T) {
if _, err := app.Store().ApplyUpdate(ctx, doc, app.TestActorFor(t, doc), readFixture(t, "../../fixtures/vectors/fragment/"+name)); err != nil {
t.Fatalf("ApplyUpdate %s: %v", name, err)
}
- html, err := app.Store().HTML(ctx, doc)
+ html, err := app.Store().HTML(ctx, doc, DocView(doc))
if err != nil {
t.Fatalf("HTML %s: %v", name, err)
}
diff --git a/internal/docs/publish.go b/internal/docs/publish.go
index f5d1513..4f7ab9a 100644
--- a/internal/docs/publish.go
+++ b/internal/docs/publish.go
@@ -44,7 +44,8 @@ type publicPage struct {
// the differences between them tell a stranger which documents exist and
// which were published and then withdrawn.
func (h *handlers) publicShow(w http.ResponseWriter, r *http.Request) {
- doc, err := h.store.ByToken(r.Context(), r.PathValue("token"))
+ token := r.PathValue("token")
+ doc, err := h.store.ByToken(r.Context(), token)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
h.fail(w, r, http.StatusNotFound, failDocument)
@@ -55,7 +56,7 @@ func (h *handlers) publicShow(w http.ResponseWriter, r *http.Request) {
return
}
- html, err := h.store.HTML(r.Context(), doc)
+ html, err := h.store.HTML(r.Context(), doc, publicView(doc, token))
if err != nil {
h.logger.Error("docs: public document html", "err", err)
h.fail(w, r, h.internalFailureStatus(), failStatus)
diff --git a/internal/docs/sample_documents_test.go b/internal/docs/sample_documents_test.go
index e0e2bea..f108ca6 100644
--- a/internal/docs/sample_documents_test.go
+++ b/internal/docs/sample_documents_test.go
@@ -63,7 +63,7 @@ func TestNewPersonWithSampleDocumentsOnGetsExactlySix(t *testing.T) {
}
for _, d := range list {
- html, err := app.Store().HTML(ctx, d)
+ html, err := app.Store().HTML(ctx, d, docs.DocView(d))
if err != nil {
t.Fatalf("HTML(%q): %v", d.Title, err)
}
diff --git a/internal/docs/seed_test.go b/internal/docs/seed_test.go
index 600c458..48be840 100644
--- a/internal/docs/seed_test.go
+++ b/internal/docs/seed_test.go
@@ -43,7 +43,7 @@ func TestSeedProducesReadableDocuments(t *testing.T) {
// Every seeded document must have real content, through the CRDT.
for _, d := range list {
- html, err := app.Store().HTML(ctx, d)
+ html, err := app.Store().HTML(ctx, d, docs.DocView(d))
if err != nil {
t.Fatalf("HTML(%q): %v", d.Title, err)
}
@@ -134,7 +134,7 @@ func TestSeedContentMatchesItsSource(t *testing.T) {
}
for _, d := range list {
- html, err := app.Store().HTML(ctx, d)
+ html, err := app.Store().HTML(ctx, d, docs.DocView(d))
if err != nil {
t.Fatalf("HTML(%q): %v", d.Title, err)
}
@@ -178,7 +178,7 @@ func TestSeededDocumentsRenderAsHTML(t *testing.T) {
t.Fatalf("List: %v", err)
}
for _, d := range docList {
- html, err := app.Store().HTML(ctx, d)
+ html, err := app.Store().HTML(ctx, d, docs.DocView(d))
if err != nil {
t.Fatalf("HTML(%q): %v", d.Title, err)
}
@@ -210,7 +210,7 @@ func TestWaterworksHistoryHasHeadings(t *testing.T) {
if !strings.Contains(d.Title, "Millbrook") {
continue
}
- html, err := app.Store().HTML(ctx, d)
+ html, err := app.Store().HTML(ctx, d, docs.DocView(d))
if err != nil {
t.Fatalf("HTML: %v", err)
}
diff --git a/internal/docs/snapshots_test.go b/internal/docs/snapshots_test.go
index 4aac115..591a1ae 100644
--- a/internal/docs/snapshots_test.go
+++ b/internal/docs/snapshots_test.go
@@ -200,7 +200,7 @@ func TestSnapshotThenTailRendersIdenticallyToAFullReplay(t *testing.T) {
t.Fatalf("newest snapshot is at seq %d, below the distinct row at seq %d — the tail would carry that content on its own and this test would prove nothing", snap.Seq, want)
}
- withSnapshot, err := app.Store().HTML(ctx, doc)
+ withSnapshot, err := app.Store().HTML(ctx, doc, DocView(doc))
if err != nil {
t.Fatalf("HTML: %v", err)
}
@@ -210,7 +210,7 @@ func TestSnapshotThenTailRendersIdenticallyToAFullReplay(t *testing.T) {
Where("doc_id = ?", doc.ID).Delete(&DocSnapshot{}).Error; err != nil {
t.Fatalf("delete snapshots: %v", err)
}
- fullReplay, err := app.Store().HTML(ctx, doc)
+ fullReplay, err := app.Store().HTML(ctx, doc, DocView(doc))
if err != nil {
t.Fatalf("HTML after deleting snapshots: %v", err)
}
@@ -273,7 +273,7 @@ func TestConcurrentPostsAtTheCadenceBoundaryDoNotStrandContent(t *testing.T) {
t.Fatalf("newestSnapshot = (%v, %v), want a snapshot written at the boundary", snap, err)
}
- withSnapshot, err := app.Store().HTML(ctx, doc)
+ withSnapshot, err := app.Store().HTML(ctx, doc, DocView(doc))
if err != nil {
t.Fatalf("HTML: %v", err)
}
@@ -281,7 +281,7 @@ func TestConcurrentPostsAtTheCadenceBoundaryDoNotStrandContent(t *testing.T) {
Where("doc_id = ?", doc.ID).Delete(&DocSnapshot{}).Error; err != nil {
t.Fatalf("delete snapshots: %v", err)
}
- fullReplay, err := app.Store().HTML(ctx, doc)
+ fullReplay, err := app.Store().HTML(ctx, doc, DocView(doc))
if err != nil {
t.Fatalf("HTML: %v", err)
}
@@ -596,7 +596,7 @@ func TestACorruptSnapshotFallsBackToTheLog(t *testing.T) {
t.Fatalf("ApplyUpdate %d: %v", i, err)
}
}
- want, err := app.Store().HTML(ctx, doc)
+ want, err := app.Store().HTML(ctx, doc, DocView(doc))
if err != nil {
t.Fatalf("HTML: %v", err)
}
@@ -612,7 +612,7 @@ func TestACorruptSnapshotFallsBackToTheLog(t *testing.T) {
t.Fatalf("corrupt the snapshot: %v", err)
}
- got, err := app.Store().HTML(ctx, doc)
+ got, err := app.Store().HTML(ctx, doc, DocView(doc))
if err != nil {
t.Fatalf("HTML with a corrupt snapshot: %v", err)
}
@@ -774,7 +774,7 @@ func TestALongLogWithNoUsableSnapshotStillReads(t *testing.T) {
t.Fatalf("newestSnapshot = (%v, %v), want no snapshot at all — that is the whole premise of this test", snap, err)
}
- html, err := app.Store().HTML(ctx, doc)
+ html, err := app.Store().HTML(ctx, doc, DocView(doc))
if err != nil {
t.Fatalf("HTML of a %d-row log with no snapshot: %v", total, err)
}
@@ -817,7 +817,7 @@ func TestALongLogWithNoUsableSnapshotStillAcceptsWrites(t *testing.T) {
// refused would persist that loss into the snapshot ApplyUpdate
// takes above. So read the document back and require the whole log
// to still be in it.
- html, err := app.Store().HTML(ctx, doc)
+ html, err := app.Store().HTML(ctx, doc, DocView(doc))
if err != nil {
t.Fatalf("HTML after the write: %v", err)
}
@@ -875,7 +875,7 @@ func TestALongLogWhoseOnlySnapshotIsFromAnotherABIStillReadsAndWrites(t *testing
t.Fatalf("newestSnapshot = (%v, %v), want nil — an older ABI's row must be unusable, or this test proves nothing", snap, err)
}
- html, err := app.Store().HTML(ctx, doc)
+ html, err := app.Store().HTML(ctx, doc, DocView(doc))
if err != nil {
t.Fatalf("HTML after an ABI bump invalidated the snapshot: %v", err)
}
@@ -918,7 +918,7 @@ func TestReSeedingMidReplayRendersTheSameDocument(t *testing.T) {
t.Fatalf("the comparison replay is %d updates long, which crosses the cap itself", len(unique))
}
- reSeeded, err := app.Store().HTML(ctx, doc)
+ reSeeded, err := app.Store().HTML(ctx, doc, DocView(doc))
if err != nil {
t.Fatalf("HTML of a %d-row log: %v", total, err)
}
diff --git a/internal/docs/store.go b/internal/docs/store.go
index 005d65d..d2223fa 100644
--- a/internal/docs/store.go
+++ b/internal/docs/store.go
@@ -689,14 +689,19 @@ func (s *Store) Text(ctx context.Context, doc *Document) (string, error) {
// "this is trusted markup" decision is made, once, next to the
// escaping that earns it, rather than left for views/show.html to
// assert with a {{ ... | html }} pipeline of its own.
-func (s *Store) HTML(ctx context.Context, doc *Document) (template.HTML, error) {
+//
+// view is where it will be read (Docs images spec §4.1): DocView for a
+// signed-in reader, publicView for a link holder. Images are the one
+// place a document byte reaches attribute position, and only as an id
+// the core has matched against its grammar.
+func (s *Store) HTML(ctx context.Context, doc *Document, view core.View) (template.HTML, error) {
h, _, _, err := s.replay(ctx, doc)
if err != nil {
return "", err
}
defer h.Close(ctx)
- html, err := h.HTML(ctx)
+ html, err := h.HTMLIn(ctx, view)
if err != nil {
return "", fmt.Errorf("docs: read html for document %d: %w", doc.ID, err)
}
@@ -714,11 +719,11 @@ func (s *Store) Page(ctx context.Context, doc *Document) (template.HTML, string,
}
defer h.Close(ctx)
- html, err := h.HTML(ctx)
+ html, err := h.HTMLIn(ctx, DocView(doc))
if err != nil {
return "", "", fmt.Errorf("docs: read html for document %d: %w", doc.ID, err)
}
- structure, err := h.JSON(ctx)
+ structure, err := h.JSONIn(ctx, DocView(doc))
if err != nil {
return "", "", fmt.Errorf("docs: read structure for document %d: %w", doc.ID, err)
}
@@ -741,13 +746,26 @@ func (s *Store) JSON(ctx context.Context, doc *Document) (string, error) {
}
defer h.Close(ctx)
- structure, err := h.JSON(ctx)
+ structure, err := h.JSONIn(ctx, DocView(doc))
if err != nil {
return "", fmt.Errorf("docs: read structure for document %d: %w", doc.ID, err)
}
return structure, nil
}
+// DocView is the view a signed-in reader of doc sees it in: its images
+// under /d/{sqid} (Docs images spec §4.1).
+func DocView(doc *Document) core.View {
+ return core.View{Sqid: doc.Sqid, Base: "/d/" + doc.Sqid}
+}
+
+// publicView is the view a holder of doc's link sees it in: its images
+// under /p/{token}, so the public markup never names the sqid
+// (publish.go).
+func publicView(doc *Document, token string) core.View {
+ return core.View{Sqid: doc.Sqid, Base: "/p/" + token}
+}
+
// updateRejection wraps whatever error Handle.Apply(update) itself
// returned for the update just submitted to ApplyUpdate below — never
// for a failure while replay (above) rebuilds this document's
diff --git a/internal/docs/updates_test.go b/internal/docs/updates_test.go
index cd3024b..fc5af75 100644
--- a/internal/docs/updates_test.go
+++ b/internal/docs/updates_test.go
@@ -94,7 +94,7 @@ func TestPostedUpdateSurvivesRoundTrip(t *testing.T) {
t.Fatalf("POST = %d, want 204: %s", rec.Code, rec.Body)
}
- html, err := app.Store().HTML(ctx, doc)
+ html, err := app.Store().HTML(ctx, doc, DocView(doc))
if err != nil {
t.Fatalf("HTML: %v", err)
}
@@ -305,7 +305,7 @@ func TestConcurrentUpdatesDoNotCollideOnSeq(t *testing.T) {
// The document must still replay — not just "no duplicate rows",
// but every one of those rows a real, applyable update the core
// accepts in sequence.
- html, err := app.Store().HTML(ctx, doc)
+ html, err := app.Store().HTML(ctx, doc, DocView(doc))
if err != nil {
t.Fatalf("HTML after %d concurrent updates: %v", n, err)
}
diff --git a/internal/imagefile/exif.go b/internal/imagefile/exif.go
new file mode 100644
index 0000000..aa0f8b2
--- /dev/null
+++ b/internal/imagefile/exif.go
@@ -0,0 +1,60 @@
+package imagefile
+
+import "encoding/binary"
+
+// EXIF's Orientation tag, read from an APP1 that is then dropped, and
+// written back alone (§5). An EXIF block Mapa cannot read gives 1: it
+// is dropped whole either way, so nothing in it is passed through.
+
+const tagOrientation = 0x0112
+
+// orientation is the Orientation tag of a TIFF structure, or 1.
+func orientation(tiff []byte) int {
+ if len(tiff) < 8 {
+ return 1
+ }
+ var order binary.ByteOrder
+ switch string(tiff[:2]) {
+ case "II":
+ order = binary.LittleEndian
+ case "MM":
+ order = binary.BigEndian
+ default:
+ return 1
+ }
+ if order.Uint16(tiff[2:]) != 42 {
+ return 1
+ }
+ return ifdOrientation(tiff, order, int(order.Uint32(tiff[4:])))
+}
+
+func ifdOrientation(tiff []byte, order binary.ByteOrder, ifd int) int {
+ if ifd < 8 || ifd+2 > len(tiff) {
+ return 1
+ }
+ count := int(order.Uint16(tiff[ifd:]))
+ for entry := range count {
+ at := ifd + 2 + 12*entry
+ if at+12 > len(tiff) {
+ return 1
+ }
+ if order.Uint16(tiff[at:]) != tagOrientation {
+ continue
+ }
+ value := int(order.Uint16(tiff[at+8:]))
+ if order.Uint16(tiff[at+2:]) != 3 || value < 1 || value > 8 {
+ return 1
+ }
+ return value
+ }
+ return 1
+}
+
+// orientationExif is a minimal APP1 payload: one IFD, one tag.
+func orientationExif(value int) []byte {
+ out := []byte("Exif\x00\x00MM\x00\x2a\x00\x00\x00\x08" +
+ "\x00\x01\x01\x12\x00\x03\x00\x00\x00\x01\x00\x00\x00\x00" +
+ "\x00\x00\x00\x00")
+ binary.BigEndian.PutUint16(out[6+8+2+8:], uint16(value))
+ return out
+}
diff --git a/internal/imagefile/fuzz_test.go b/internal/imagefile/fuzz_test.go
new file mode 100644
index 0000000..6040343
--- /dev/null
+++ b/internal/imagefile/fuzz_test.go
@@ -0,0 +1,61 @@
+package imagefile
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+)
+
+// One fuzz target per walker (IMG5). `go test` runs each seed corpus
+// (the fixtures) in CI; `go test -fuzz` explores. A walker must never
+// panic, and what it keeps must be readable by its own walk again.
+
+func seed(f *testing.F, names ...string) {
+ for _, name := range names {
+ raw, err := os.ReadFile(filepath.Join("testdata", name))
+ if err != nil {
+ f.Fatal(err)
+ }
+ f.Add(raw)
+ }
+}
+
+func fuzzWalker(f *testing.F, walk func([]byte) ([]byte, int, error)) {
+ f.Fuzz(func(t *testing.T, raw []byte) {
+ cleaned, _, err := walk(raw)
+ if err != nil {
+ return
+ }
+ if _, _, err := walk(cleaned); err != nil {
+ t.Errorf("a cleaned file did not walk again: %v", err)
+ }
+ })
+}
+
+func FuzzJPEG(f *testing.F) {
+ seed(f, "baseline.jpg", "progressive.jpg", "restart.jpg", "cmyk.jpg",
+ "thumbnail.jpg", "motion.jpg")
+ fuzzWalker(f, cleanJPEG)
+}
+
+func FuzzPNG(f *testing.F) {
+ seed(f, "meta.png", "anim.png")
+ fuzzWalker(f, cleanPNG)
+}
+
+func FuzzWebP(f *testing.F) {
+ seed(f, "lossy.webp", "lossless.webp", "anim.webp")
+ fuzzWalker(f, cleanWebP)
+}
+
+func FuzzGIF(f *testing.F) {
+ seed(f, "anim.gif")
+ fuzzWalker(f, cleanGIF)
+}
+
+func FuzzClean(f *testing.F) {
+ seed(f, "baseline.jpg", "meta.png", "lossy.webp", "anim.gif")
+ f.Fuzz(func(t *testing.T, raw []byte) {
+ _, _, _ = Clean(raw)
+ })
+}
diff --git a/internal/imagefile/gif.go b/internal/imagefile/gif.go
new file mode 100644
index 0000000..dc748e6
--- /dev/null
+++ b/internal/imagefile/gif.go
@@ -0,0 +1,135 @@
+package imagefile
+
+import "encoding/binary"
+
+// The GIF walker (§5). It keeps the image data, the graphic control
+// extensions and the NETSCAPE2.0 loop extension; it drops comments,
+// plain-text extensions and every other application extension (XMP
+// rides in one), and ends the file at the trailer.
+
+const (
+ gifImage = 0x2c
+ gifExtension = 0x21
+ gifTrailer = 0x3b
+ gifControl = 0xf9
+ gifApp = 0xff
+)
+
+func cleanGIF(raw []byte) ([]byte, int, error) {
+ if len(raw) < 13 {
+ return nil, 0, ErrMalformed
+ }
+ at := 13 + colourTable(raw[10])
+ if at > len(raw) {
+ return nil, 0, ErrMalformed
+ }
+ screen := [2]int{int(binary.LittleEndian.Uint16(raw[6:])),
+ int(binary.LittleEndian.Uint16(raw[8:]))}
+ out := append(make([]byte, 0, len(raw)), raw[:at]...)
+ for {
+ if at >= len(raw) {
+ return nil, 0, ErrMalformed
+ }
+ var next int
+ var keep bool
+ var err error
+ switch raw[at] {
+ case gifTrailer:
+ return append(out, gifTrailer), 1, nil
+ case gifImage:
+ next, err = gifPicture(raw, at, screen)
+ keep = true
+ case gifExtension:
+ var loop []byte
+ next, loop, keep, err = gifExtensionBlock(raw, at)
+ if loop != nil {
+ out, keep = append(out, loop...), false
+ }
+ default:
+ return nil, 0, ErrMalformed
+ }
+ if err != nil {
+ return nil, 0, err
+ }
+ if keep {
+ out = append(out, raw[at:next]...)
+ }
+ at = next
+ }
+}
+
+// colourTable is the size of the colour table a packed field announces.
+func colourTable(packed byte) int {
+ if packed&0x80 == 0 {
+ return 0
+ }
+ return 3 * (1 << (int(packed&0x07) + 1))
+}
+
+// gifPicture is an image descriptor, its local colour table, its LZW
+// code size and its data sub-blocks. A frame must lie inside the
+// logical screen, which is all the limits read (Fable M2): a GIF that
+// says 1×1 may not carry a 60,000×60,000 frame.
+func gifPicture(raw []byte, at int, screen [2]int) (int, error) {
+ if at+11 > len(raw) {
+ return 0, ErrMalformed
+ }
+ left := int(binary.LittleEndian.Uint16(raw[at+1:]))
+ top := int(binary.LittleEndian.Uint16(raw[at+3:]))
+ width := int(binary.LittleEndian.Uint16(raw[at+5:]))
+ height := int(binary.LittleEndian.Uint16(raw[at+7:]))
+ if left+width > screen[0] || top+height > screen[1] {
+ return 0, ErrMalformed
+ }
+ at += 10 + colourTable(raw[at+9]) + 1
+ return subBlocks(raw, at)
+}
+
+// gifExtensionBlock is one extension and whether it is kept as it is;
+// for NETSCAPE2.0's loop, the extension written again with its loop
+// count alone, any further sub-block dropped (Fable L10).
+func gifExtensionBlock(raw []byte, at int) (int, []byte, bool, error) {
+ if at+2 > len(raw) {
+ return 0, nil, false, ErrMalformed
+ }
+ label := raw[at+1]
+ next, err := subBlocks(raw, at+2)
+ if err != nil {
+ return 0, nil, false, err
+ }
+ switch label {
+ case gifControl:
+ return next, nil, true, nil
+ case gifApp:
+ return next, netscapeLoop(raw[at:next]), false, nil
+ }
+ return next, nil, false, nil
+}
+
+// netscapeLoop is a NETSCAPE2.0 extension's header and its 3-byte loop
+// sub-block, then the terminator, or nil for any other extension.
+func netscapeLoop(block []byte) []byte {
+ head := block[2:]
+ if len(head) < 17 || head[0] != 11 ||
+ string(head[1:12]) != "NETSCAPE2.0" || head[12] != 3 ||
+ head[13] != 1 {
+ return nil
+ }
+ return append(append([]byte{}, block[:2+16]...), 0)
+}
+
+// subBlocks is where a run of data sub-blocks ends, after its
+// terminator.
+func subBlocks(raw []byte, at int) (int, error) {
+ for {
+ if at >= len(raw) {
+ return 0, ErrMalformed
+ }
+ size := int(raw[at])
+ at++
+ if size == 0 {
+ return at, nil
+ }
+ at += size
+ }
+}
diff --git a/internal/imagefile/imagefile.go b/internal/imagefile/imagefile.go
new file mode 100644
index 0000000..39b57d3
--- /dev/null
+++ b/internal/imagefile/imagefile.go
@@ -0,0 +1,134 @@
+// Package imagefile reads an uploaded image: its type
+// from its bytes, its size from the format's own decoder, and a copy
+// with its metadata taken out by a container walker that never decodes
+// a pixel. The claimed Content-Type and the file name are never read.
+//
+// Each walker drops named kinds of metadata and keeps the image's own
+// structure, so a segment it does not list is never lost when the
+// picture needs it, and ends the file where the format ends it. A file
+// a walker cannot parse is refused, never passed through: location,
+// camera serials, authors, edit history, thumbnails and trailers never
+// reach the bucket.
+//
+// Copied from Mapa's internal/mapa/imagefile (Mapa's images spec §5,
+// live since 2026-11-17), with one change: MaxPixels is 40 megapixels,
+// not 50, because a picture uploaded to Docs must show in the shipped
+// Mac and iPhone apps, which decode at most 40 MP (Docs images spec
+// §3.2). "§5" below is Mapa's spec. Lift both copies into rastrillo when
+// a third app needs them (Docs images spec §9).
+package imagefile
+
+import (
+ "bytes"
+ "errors"
+ "image"
+ _ "image/gif" // DecodeConfig for GIF
+ _ "image/jpeg" // DecodeConfig for JPEG
+ _ "image/png" // DecodeConfig for PNG
+
+ _ "golang.org/x/image/webp" // DecodeConfig for WebP
+)
+
+// The limits (§5; Docs images spec §3.2): at most 10,000 px on a side
+// and 40 megapixels in all, read from the header before any further
+// work. Docs never decodes
+// pixels, so a decompression bomb costs it nothing.
+const (
+ MaxSide = 10000
+ MaxPixels = 40_000_000
+)
+
+// The four types Docs takes.
+const (
+ PNG = "image/png"
+ JPEG = "image/jpeg"
+ GIF = "image/gif"
+ WebP = "image/webp"
+)
+
+// Refusals. ErrType is anything but the four formats, SVG, HEIC and
+// HTML included; ErrDimensions is a picture past the limits;
+// ErrMalformed is a file of one of the four that its walker or decoder
+// cannot read.
+var (
+ ErrType = errors.New("imagefile: not a PNG, JPEG, GIF or WebP")
+ ErrDimensions = errors.New("imagefile: the picture is too large")
+ ErrMalformed = errors.New("imagefile: the file cannot be read")
+)
+
+// Info is what Docs keeps of a picture, sealed: its type, and its width
+// and height as shown, after a JPEG's orientation.
+type Info struct {
+ Type string `json:"type"`
+ Width, Height int
+}
+
+// Sniff is the type the bytes say, or "" for anything else.
+func Sniff(raw []byte) string {
+ switch {
+ case bytes.HasPrefix(raw, []byte("\x89PNG\r\n\x1a\n")):
+ return PNG
+ case bytes.HasPrefix(raw, []byte{0xff, 0xd8, 0xff}):
+ return JPEG
+ case bytes.HasPrefix(raw, []byte("GIF87a")),
+ bytes.HasPrefix(raw, []byte("GIF89a")):
+ return GIF
+ case len(raw) >= 12 && bytes.HasPrefix(raw, []byte("RIFF")) &&
+ string(raw[8:12]) == "WEBP":
+ return WebP
+ }
+ return ""
+}
+
+// walkers strip each format. Each returns the cleaned file and, for a
+// JPEG, its EXIF orientation (1 for upright or unknown).
+var walkers = map[string]func([]byte) ([]byte, int, error){
+ PNG: cleanPNG, JPEG: cleanJPEG, GIF: cleanGIF, WebP: cleanWebP,
+}
+
+// formats is image.DecodeConfig's name for each type.
+var formats = map[string]string{
+ PNG: "png", JPEG: "jpeg", GIF: "gif", WebP: "webp",
+}
+
+// Clean checks raw and returns it with its metadata taken out.
+func Clean(raw []byte) ([]byte, Info, error) {
+ kind := Sniff(raw)
+ if kind == "" {
+ return nil, Info{}, ErrType
+ }
+ config, err := checkConfig(raw, kind)
+ if err != nil {
+ return nil, Info{}, err
+ }
+ cleaned, orientation, err := walkers[kind](raw)
+ if err != nil {
+ return nil, Info{}, err
+ }
+ after, err := checkConfig(cleaned, kind)
+ if err != nil || after != config {
+ return nil, Info{}, ErrMalformed
+ }
+ info := Info{Type: kind, Width: config.Width, Height: config.Height}
+ if orientation >= 5 {
+ info.Width, info.Height = info.Height, info.Width
+ }
+ return cleaned, info, nil
+}
+
+// checkConfig reads the header with the format's own decoder, which
+// must agree on the type, and holds it to the limits.
+func checkConfig(raw []byte, kind string) (image.Config, error) {
+ config, format, err := image.DecodeConfig(bytes.NewReader(raw))
+ if err != nil || format != formats[kind] {
+ return config, ErrMalformed
+ }
+ if config.Width <= 0 || config.Height <= 0 {
+ return config, ErrMalformed
+ }
+ if config.Width > MaxSide || config.Height > MaxSide ||
+ int64(config.Width)*int64(config.Height) > MaxPixels {
+ return config, ErrDimensions
+ }
+ return image.Config{Width: config.Width, Height: config.Height}, nil
+}
diff --git a/internal/imagefile/imagefile_test.go b/internal/imagefile/imagefile_test.go
new file mode 100644
index 0000000..18c6588
--- /dev/null
+++ b/internal/imagefile/imagefile_test.go
@@ -0,0 +1,244 @@
+package imagefile
+
+import (
+ "bytes"
+ "image"
+ "image/color"
+ "image/png"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+// IMG5 (images spec §6): every fixture loses its canaries, keeps its
+// ICC profile and (JPEG) its orientation, and decodes to the same
+// pixels. Mapa itself never decodes; the test does, before and after.
+
+type fixture struct {
+ name, kind string
+ icc bool
+ orientation int
+ width, height int
+}
+
+var fixtures = []fixture{
+ {name: "meta.png", kind: PNG, icc: true, width: 64, height: 48},
+ {name: "anim.png", kind: PNG, width: 64, height: 48},
+ {name: "baseline.jpg", kind: JPEG, icc: true, orientation: 6,
+ width: 48, height: 64},
+ {name: "progressive.jpg", kind: JPEG, icc: true, orientation: 6,
+ width: 48, height: 64},
+ {name: "restart.jpg", kind: JPEG, icc: true, orientation: 6,
+ width: 48, height: 64},
+ {name: "cmyk.jpg", kind: JPEG, icc: true, orientation: 6, width: 48,
+ height: 64},
+ {name: "thumbnail.jpg", kind: JPEG, width: 64, height: 48},
+ {name: "motion.jpg", kind: JPEG, icc: true, orientation: 6, width: 48,
+ height: 64},
+ {name: "lossy.webp", kind: WebP, icc: true, width: 64, height: 48},
+ {name: "lossless.webp", kind: WebP, icc: true, width: 64, height: 48},
+ {name: "anim.webp", kind: WebP, icc: true, width: 64, height: 48},
+ {name: "anim.gif", kind: GIF, width: 64, height: 48},
+}
+
+func read(t *testing.T, name string) []byte {
+ t.Helper()
+ raw, err := os.ReadFile(filepath.Join("testdata", name))
+ if err != nil {
+ t.Fatal(err)
+ }
+ return raw
+}
+
+func TestCleanStripsEveryCanary(t *testing.T) {
+ for _, each := range fixtures {
+ t.Run(each.name, func(t *testing.T) {
+ raw := read(t, each.name)
+ if !bytes.Contains(raw, []byte("CANARY-")) {
+ t.Fatal("the fixture carries no canary")
+ }
+ cleaned, info, err := Clean(raw)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if at := bytes.Index(cleaned, []byte("CANARY")); at >= 0 {
+ t.Errorf("a canary survived: %q",
+ cleaned[at:min(at+24, len(cleaned))])
+ }
+ want := Info{Type: each.kind, Width: each.width,
+ Height: each.height}
+ if info != want {
+ t.Errorf("info %+v, want %+v", info, want)
+ }
+ checkKept(t, each, cleaned)
+ if each.name == "anim.webp" {
+ sameFrames(t, raw, cleaned)
+ return
+ }
+ samePixels(t, raw, cleaned)
+ })
+ }
+}
+
+// checkKept: the ICC profile stays, and a JPEG's orientation is the
+// only EXIF left.
+func checkKept(t *testing.T, each fixture, cleaned []byte) {
+ t.Helper()
+ profile := map[string]string{PNG: "iCCP", JPEG: "ICC_PROFILE",
+ WebP: "ICCP"}[each.kind]
+ if profile != "" &&
+ each.icc != bytes.Contains(cleaned, []byte(profile)) {
+ t.Errorf("ICC profile kept: %v, want %v", !each.icc, each.icc)
+ }
+ if each.kind != JPEG {
+ return
+ }
+ at := bytes.Index(cleaned, []byte("Exif\x00\x00"))
+ switch {
+ case each.orientation == 0 && at >= 0:
+ t.Error("an upright JPEG kept an EXIF segment")
+ case each.orientation != 0 && at < 0:
+ t.Error("the orientation was lost")
+ case each.orientation != 0 &&
+ orientation(cleaned[at+6:]) != each.orientation:
+ t.Errorf("orientation %d", orientation(cleaned[at+6:]))
+ }
+}
+
+func samePixels(t *testing.T, before, after []byte) {
+ t.Helper()
+ old, _, err := image.Decode(bytes.NewReader(before))
+ if err != nil {
+ t.Fatalf("decoding the original: %v", err)
+ }
+ fresh, _, err := image.Decode(bytes.NewReader(after))
+ if err != nil {
+ t.Fatalf("decoding the cleaned file: %v", err)
+ }
+ if old.Bounds() != fresh.Bounds() {
+ t.Fatalf("bounds %v became %v", old.Bounds(), fresh.Bounds())
+ }
+ bounds := old.Bounds()
+ for row := bounds.Min.Y; row < bounds.Max.Y; row++ {
+ for column := bounds.Min.X; column < bounds.Max.X; column++ {
+ if !sameColour(old.At(column, row), fresh.At(column, row)) {
+ t.Fatalf("pixel (%d, %d) changed", column, row)
+ }
+ }
+ }
+}
+
+// sameFrames is samePixels for an animated WebP, which Go's decoder
+// does not draw: every frame chunk is kept byte for byte.
+func sameFrames(t *testing.T, before, after []byte) {
+ t.Helper()
+ frames := 0
+ for at := 12; at < len(before); {
+ kind, next, err := webpChunk(before, at, len(before))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if kind == "ANMF" {
+ frames++
+ if !bytes.Contains(after, before[at:next]) {
+ t.Errorf("frame %d changed", frames)
+ }
+ }
+ at = next
+ }
+ if frames < 2 {
+ t.Errorf("%d frames", frames)
+ }
+}
+
+func sameColour(left, right color.Color) bool {
+ red, green, blue, alpha := left.RGBA()
+ red2, green2, blue2, alpha2 := right.RGBA()
+ return red == red2 && green == green2 && blue == blue2 &&
+ alpha == alpha2
+}
+
+func TestRefusals(t *testing.T) {
+ jpeg := read(t, "baseline.jpg")
+ pngFile := read(t, "meta.png")
+ webp := read(t, "lossy.webp")
+ cases := map[string]struct {
+ raw []byte
+ want error
+ }{
+ "svg": {[]byte(`<svg xmlns="http://www.w3.org/2000/svg">` +
+ `<script>alert(1)</script></svg>`), ErrType},
+ "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},
+ // Docs' own limit (Docs images spec §3.2): just over 40 MP.
+ "over 40 MP": {encodePNG(t, 6400, 6251), ErrDimensions},
+ "png then nothing": {[]byte(pngSignature), ErrMalformed},
+ }
+ for name, each := range cases {
+ if _, _, err := Clean(each.raw); err != each.want {
+ t.Errorf("%s: %v, want %v", name, err, each.want)
+ }
+ }
+}
+
+// TestFortyMegapixelsIsAllowed pins Docs' limit from the other side: a
+// picture of exactly 40 MP is taken, so every picture Docs keeps decodes
+// in the shipped Mac and iPhone apps (width × height ≤ 40,000,000 there).
+func TestFortyMegapixelsIsAllowed(t *testing.T) {
+ if MaxPixels != 40_000_000 {
+ t.Fatalf("MaxPixels is %d; the native apps decode at most 40,000,000", MaxPixels)
+ }
+ if _, info, err := Clean(encodePNG(t, 8000, 5000)); err != nil ||
+ info.Width != 8000 || info.Height != 5000 {
+ t.Fatalf("8000x5000: %+v, %v", info, err)
+ }
+}
+
+func flip(raw []byte, at int) []byte {
+ out := append([]byte{}, raw...)
+ out[at] ^= 0xff
+ return out
+}
+
+// oversized gives the JPEG's first segment a length past the file.
+func oversized(raw []byte) []byte {
+ out := append([]byte{}, raw...)
+ out[4], out[5] = 0xff, 0xff
+ return out
+}
+
+func riffSize(raw []byte, size uint32) []byte {
+ out := append([]byte{}, raw...)
+ out[4], out[5], out[6], out[7] = byte(size), byte(size>>8),
+ byte(size>>16), byte(size>>24)
+ return out
+}
+
+func encodePNG(t *testing.T, width, height int) []byte {
+ t.Helper()
+ var out bytes.Buffer
+ picture := image.NewGray(image.Rect(0, 0, width, height))
+ if err := png.Encode(&out, picture); err != nil {
+ t.Fatal(err)
+ }
+ return out.Bytes()
+}
+
+func TestSniffIgnoresWhatIsClaimed(t *testing.T) {
+ if Sniff([]byte("GIF89a")) != GIF || Sniff([]byte("hello")) != "" {
+ t.Error("Sniff reads the bytes")
+ }
+ if !strings.HasPrefix(string(read(t, "lossy.webp")[8:12]), "WEBP") {
+ t.Error("fixture")
+ }
+}
diff --git a/internal/imagefile/jpeg.go b/internal/imagefile/jpeg.go
new file mode 100644
index 0000000..551dacc
--- /dev/null
+++ b/internal/imagefile/jpeg.go
@@ -0,0 +1,205 @@
+package imagefile
+
+import (
+ "bytes"
+ "encoding/binary"
+)
+
+// The JPEG walker (§5). It keeps every marker segment but two kinds:
+// APPn segments other than JFIF's APP0, an ICC profile's APP2 and
+// Adobe's APP14; and comments. So every SOFn, DQT, DHT, DRI, DNL, DAC
+// and SOS stays, with its scan data and restart markers. The JFIF
+// thumbnail goes, as does JFXX. The file ends at EOI, which drops Motion
+// Photo video, MPF's second images, gain maps and vendor trailers.
+// EXIF goes too; its orientation, when not 1, is written back as a
+// minimal APP1 holding that one tag, so a phone's photo stays upright.
+
+const (
+ markerSOI = 0xd8
+ markerEOI = 0xd9
+ markerSOS = 0xda
+ markerAPP0 = 0xe0
+ markerAPP1 = 0xe1
+ markerAPP2 = 0xe2
+ markerAPPE = 0xee
+ markerAPPF = 0xef
+ markerCOM = 0xfe
+
+ // adobeHeader is APP14's whole meaning: "Adobe", version, flags0,
+ // flags1, transform.
+ adobeHeader = 12
+)
+
+// jpegWalk is one walk's state.
+type jpegWalk struct {
+ raw []byte
+ segments [][]byte
+ orientation int
+ frame, scan bool
+}
+
+func cleanJPEG(raw []byte) ([]byte, int, error) {
+ if len(raw) < 4 || raw[0] != 0xff || raw[1] != markerSOI {
+ return nil, 0, ErrMalformed
+ }
+ walk := &jpegWalk{raw: raw, orientation: 1}
+ for at := 2; ; {
+ marker, start, err := walk.marker(at)
+ if err != nil {
+ return nil, 0, err
+ }
+ if marker == markerEOI {
+ return walk.finish()
+ }
+ if at, err = walk.segment(marker, start); err != nil {
+ return nil, 0, err
+ }
+ }
+}
+
+// marker reads the marker at raw[at], after any fill bytes.
+func (walk *jpegWalk) marker(at int) (byte, int, error) {
+ raw := walk.raw
+ if at >= len(raw) || raw[at] != 0xff {
+ return 0, 0, ErrMalformed
+ }
+ start := at
+ for at < len(raw) && raw[at] == 0xff {
+ at++
+ }
+ if at >= len(raw) || raw[at] == 0 {
+ return 0, 0, ErrMalformed
+ }
+ return raw[at], start, nil
+}
+
+// segment reads the segment starting at raw[start] and keeps it or not.
+// It returns where the next marker starts.
+func (walk *jpegWalk) segment(marker byte, start int) (int, error) {
+ raw := walk.raw
+ at := start
+ for raw[at] == 0xff {
+ at++
+ }
+ at++ // past the marker byte
+ if standalone(marker) {
+ walk.segments = append(walk.segments, []byte{0xff, marker})
+ return at, nil
+ }
+ if at+2 > len(raw) {
+ return 0, ErrMalformed
+ }
+ length := int(binary.BigEndian.Uint16(raw[at:]))
+ end := at + length
+ if length < 2 || end > len(raw) {
+ return 0, ErrMalformed
+ }
+ payload := raw[at+2 : end]
+ if marker == markerSOS {
+ walk.scan = true
+ scanned, err := scanEnd(raw, end)
+ if err != nil {
+ return 0, err
+ }
+ walk.keep(marker, raw[at-2:scanned], payload)
+ return scanned, nil
+ }
+ walk.keep(marker, raw[at-2:end], payload)
+ return end, nil
+}
+
+// standalone markers have no length: RSTn and TEM.
+func standalone(marker byte) bool {
+ return marker >= 0xd0 && marker <= 0xd7 || marker == 0x01
+}
+
+// keep decides one segment: dropped, kept as it is, or (JFIF) kept
+// without its thumbnail. whole is the segment as read, from its marker
+// to its end (a scan's entropy-coded bytes included), never copied.
+func (walk *jpegWalk) keep(marker byte, whole, payload []byte) {
+ isFrame := marker >= 0xc0 && marker <= 0xcf && marker != 0xc4 &&
+ marker != 0xc8 && marker != 0xcc
+ walk.frame = walk.frame || isFrame
+ switch {
+ case marker == markerCOM:
+ return
+ case marker == markerAPP1 && bytes.HasPrefix(payload,
+ []byte("Exif\x00\x00")):
+ walk.orientation = orientation(payload[6:])
+ return
+ case marker == markerAPP0 && bytes.HasPrefix(payload,
+ []byte("JFIF\x00")) && len(payload) >= 14:
+ whole = segmentBytes(marker,
+ append(append([]byte{}, payload[:12]...), 0, 0))
+ case marker == markerAPPE && keptApp(marker, payload) &&
+ len(payload) > adobeHeader:
+ // "Adobe", its version, two flag words and the transform: what
+ // a CMYK picture needs, and nothing after it (Fable L10).
+ whole = segmentBytes(marker, payload[:adobeHeader])
+ case marker >= markerAPP0 && marker <= markerAPPF &&
+ !keptApp(marker, payload):
+ return
+ }
+ walk.segments = append(walk.segments, whole)
+}
+
+// keptApp is the two APPn segments kept as they are: an ICC profile and
+// Adobe's colour transform, which a CMYK JPEG needs.
+func keptApp(marker byte, payload []byte) bool {
+ return marker == markerAPP2 && bytes.HasPrefix(payload,
+ []byte("ICC_PROFILE\x00")) ||
+ marker == markerAPPE && bytes.HasPrefix(payload, []byte("Adobe"))
+}
+
+func segmentBytes(marker byte, payload []byte) []byte {
+ out := []byte{0xff, marker, 0, 0}
+ binary.BigEndian.PutUint16(out[2:], uint16(len(payload)+2))
+ return append(out, payload...)
+}
+
+// scanEnd is where a scan's entropy-coded data ends: the first marker
+// that is not a stuffed zero, a restart marker or a fill byte.
+func scanEnd(raw []byte, at int) (int, error) {
+ for at < len(raw) {
+ if raw[at] != 0xff {
+ at++
+ continue
+ }
+ if at+1 >= len(raw) {
+ return 0, ErrMalformed
+ }
+ next := raw[at+1]
+ switch {
+ case next == 0 || next >= 0xd0 && next <= 0xd7:
+ at += 2
+ case next == 0xff:
+ at++
+ default:
+ return at, nil
+ }
+ }
+ return 0, ErrMalformed
+}
+
+// finish assembles the kept segments, the orientation APP1 after
+// JFIF's APP0 when there is one, and EOI.
+func (walk *jpegWalk) finish() ([]byte, int, error) {
+ if !walk.frame || !walk.scan {
+ return nil, 0, ErrMalformed
+ }
+ segments := walk.segments
+ if walk.orientation != 1 {
+ at := 0
+ if len(segments) > 0 && segments[0][1] == markerAPP0 {
+ at = 1
+ }
+ app1 := segmentBytes(markerAPP1, orientationExif(walk.orientation))
+ segments = append(segments[:at:at],
+ append([][]byte{app1}, segments[at:]...)...)
+ }
+ out := append(make([]byte, 0, len(walk.raw)+64), 0xff, markerSOI)
+ for _, segment := range segments {
+ out = append(out, segment...)
+ }
+ return append(out, 0xff, markerEOI), walk.orientation, nil
+}
diff --git a/internal/imagefile/png.go b/internal/imagefile/png.go
new file mode 100644
index 0000000..c7d5c91
--- /dev/null
+++ b/internal/imagefile/png.go
@@ -0,0 +1,70 @@
+package imagefile
+
+import (
+ "encoding/binary"
+ "hash/crc32"
+)
+
+// The PNG walker (§5). It keeps the critical chunks, the colour and
+// layout chunks a picture needs (iCCP, sRGB, gAMA, cHRM, cICP, mDCV,
+// cLLI, sBIT, pHYs, tRNS, bKGD) and APNG's (acTL, fcTL, fdAT). It drops
+// eXIf, tEXt, zTXt, iTXt, tIME and every unknown ancillary chunk, and
+// ends the file at IEND. A chunk whose CRC is wrong, or a critical
+// chunk it does not know, is refused.
+
+var pngKept = map[string]bool{
+ "IHDR": true, "PLTE": true, "IDAT": true, "IEND": true,
+ "iCCP": true, "sRGB": true, "gAMA": true, "cHRM": true, "cICP": true,
+ "mDCV": true, "cLLI": true, "sBIT": true, "pHYs": true, "tRNS": true,
+ "bKGD": true, "acTL": true, "fcTL": true, "fdAT": true,
+}
+
+const pngSignature = "\x89PNG\r\n\x1a\n"
+
+func cleanPNG(raw []byte) ([]byte, int, error) {
+ out := append(make([]byte, 0, len(raw)), pngSignature...)
+ for at := len(pngSignature); ; {
+ kind, end, err := pngChunk(raw, at)
+ if err != nil {
+ return nil, 0, err
+ }
+ if at == len(pngSignature) && kind != "IHDR" {
+ return nil, 0, ErrMalformed
+ }
+ critical := kind[0] >= 'A' && kind[0] <= 'Z'
+ switch {
+ case pngKept[kind]:
+ out = append(out, raw[at:end]...)
+ case critical:
+ return nil, 0, ErrMalformed
+ }
+ if kind == "IEND" {
+ return out, 1, nil
+ }
+ at = end
+ }
+}
+
+// pngChunk reads the chunk at raw[at]: its type and where it ends.
+func pngChunk(raw []byte, at int) (string, int, error) {
+ if at+12 > len(raw) {
+ return "", 0, ErrMalformed
+ }
+ length := binary.BigEndian.Uint32(raw[at:])
+ if uint64(length) > uint64(len(raw)-at-12) {
+ return "", 0, ErrMalformed
+ }
+ end := at + 12 + int(length)
+ kind := string(raw[at+4 : at+8])
+ for _, letter := range []byte(kind) {
+ if !(letter >= 'A' && letter <= 'Z' || letter >= 'a' &&
+ letter <= 'z') {
+ return "", 0, ErrMalformed
+ }
+ }
+ sum := binary.BigEndian.Uint32(raw[end-4:])
+ if crc32.ChecksumIEEE(raw[at+4:end-4]) != sum {
+ return "", 0, ErrMalformed
+ }
+ return kind, end, nil
+}
diff --git a/internal/imagefile/review_test.go b/internal/imagefile/review_test.go
new file mode 100644
index 0000000..ce4723f
--- /dev/null
+++ b/internal/imagefile/review_test.go
@@ -0,0 +1,101 @@
+package imagefile
+
+import (
+ "bytes"
+ "encoding/binary"
+ "testing"
+)
+
+// Fable's round on 49d8df3: M2 (a GIF frame past its logical screen)
+// and L10 (data the walkers kept that names nothing a picture needs).
+
+// TestAGIFFrameStaysInsideItsScreen: a 35-byte GIF that says 1×1 but
+// carries a 60,000×60,000 frame is refused; the limits read only the
+// logical screen.
+func TestAGIFFrameStaysInsideItsScreen(t *testing.T) {
+ gif := []byte("GIF89a\x01\x00\x01\x00\x00\x00\x00" +
+ "\x2c\x00\x00\x00\x00\x60\xea\x60\xea\x00" +
+ "\x02\x01\x00\x00\x3b")
+ if _, _, err := Clean(gif); err != ErrMalformed {
+ t.Fatalf("a frame past the screen: %v", err)
+ }
+}
+
+// replaceSegment puts payload in place of the first segment marker
+// holds, in a JPEG.
+func withSegment(t *testing.T, raw []byte, marker byte,
+ change func([]byte) []byte) []byte {
+ t.Helper()
+ for at := 2; at+4 < len(raw); {
+ length := int(binary.BigEndian.Uint16(raw[at+2:]))
+ if raw[at+1] == marker {
+ payload := change(append([]byte{}, raw[at+4:at+2+length]...))
+ head := []byte{0xff, marker, 0, 0}
+ binary.BigEndian.PutUint16(head[2:], uint16(len(payload)+2))
+ out := append(append([]byte{}, raw[:at]...), head...)
+ out = append(out, payload...)
+ return append(out, raw[at+2+length:]...)
+ }
+ at += 2 + length
+ }
+ t.Fatalf("no segment %x", marker)
+ return nil
+}
+
+func TestAdobesSegmentKeepsOnlyItsHeader(t *testing.T) {
+ raw := withSegment(t, read(t, "cmyk.jpg"), markerAPPE,
+ func(payload []byte) []byte {
+ return append(payload, []byte("CANARY-ADOBE-TAIL")...)
+ })
+ cleaned, _, err := Clean(raw)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if bytes.Contains(cleaned, []byte("CANARY")) {
+ t.Error("data after Adobe's header was kept")
+ }
+ samePixels(t, raw, cleaned)
+}
+
+func TestNetscapesLoopKeepsOnlyItsCount(t *testing.T) {
+ raw := read(t, "anim.gif")
+ at := bytes.Index(raw, []byte("NETSCAPE2.0"))
+ // The loop sub-block, then one more sub-block with a canary in it.
+ loop := at + 11
+ extra := append([]byte{byte(len("CANARY-LOOP"))}, "CANARY-LOOP"...)
+ end := loop + 1 + int(raw[loop])
+ grown := append(append(append([]byte{}, raw[:end]...), extra...),
+ raw[end:]...)
+ cleaned, _, err := Clean(grown)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if bytes.Contains(cleaned, []byte("CANARY")) {
+ t.Error("an extra NETSCAPE2.0 sub-block was kept")
+ }
+ if !bytes.Contains(cleaned, []byte("NETSCAPE2.0")) {
+ t.Error("the loop count was lost")
+ }
+}
+
+func TestAWebPFrameKeepsOnlyItsPicture(t *testing.T) {
+ raw := read(t, "anim.webp")
+ at := bytes.Index(raw, []byte("ANMF"))
+ size := int(binary.LittleEndian.Uint32(raw[at+4:]))
+ inner := append([]byte("XTRA"), 0, 0, 0, 0)
+ binary.LittleEndian.PutUint32(inner[4:], uint32(len("CANARY-FRAME!!")))
+ inner = append(inner, "CANARY-FRAME!!"...)
+ end := at + 8 + size
+ grown := append(append(append([]byte{}, raw[:end]...), inner...),
+ raw[end:]...)
+ binary.LittleEndian.PutUint32(grown[at+4:], uint32(size+len(inner)))
+ binary.LittleEndian.PutUint32(grown[4:], uint32(len(grown)-8))
+ cleaned, _, err := Clean(grown)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if bytes.Contains(cleaned, []byte("CANARY")) {
+ t.Error("an unknown chunk inside a frame was kept")
+ }
+ sameFrames(t, raw, cleaned)
+}
diff --git a/internal/imagefile/testdata/anim.gif b/internal/imagefile/testdata/anim.gif
new file mode 100644
index 0000000..3406a35
Binary files /dev/null and b/internal/imagefile/testdata/anim.gif differ
diff --git a/internal/imagefile/testdata/anim.png b/internal/imagefile/testdata/anim.png
new file mode 100644
index 0000000..57bbc3c
Binary files /dev/null and b/internal/imagefile/testdata/anim.png differ
diff --git a/internal/imagefile/testdata/anim.webp b/internal/imagefile/testdata/anim.webp
new file mode 100644
index 0000000..ef2638d
Binary files /dev/null and b/internal/imagefile/testdata/anim.webp differ
diff --git a/internal/imagefile/testdata/baseline.jpg b/internal/imagefile/testdata/baseline.jpg
new file mode 100644
index 0000000..aa1c0e1
Binary files /dev/null and b/internal/imagefile/testdata/baseline.jpg differ
diff --git a/internal/imagefile/testdata/cmyk.jpg b/internal/imagefile/testdata/cmyk.jpg
new file mode 100644
index 0000000..48b3ebc
Binary files /dev/null and b/internal/imagefile/testdata/cmyk.jpg differ
diff --git a/internal/imagefile/testdata/lossless.webp b/internal/imagefile/testdata/lossless.webp
new file mode 100644
index 0000000..4f91c44
Binary files /dev/null and b/internal/imagefile/testdata/lossless.webp differ
diff --git a/internal/imagefile/testdata/lossy.webp b/internal/imagefile/testdata/lossy.webp
new file mode 100644
index 0000000..2a3e3ee
Binary files /dev/null and b/internal/imagefile/testdata/lossy.webp differ
diff --git a/internal/imagefile/testdata/make.py b/internal/imagefile/testdata/make.py
new file mode 100644
index 0000000..73cf7fe
--- /dev/null
+++ b/internal/imagefile/testdata/make.py
@@ -0,0 +1,145 @@
+"""Writes imagefile's fixtures (IMG5): each format, carrying canaries in
+every kind of metadata the walkers must drop. Run from anywhere:
+
+ python3 -I internal/mapa/imagefile/testdata/make.py
+
+It needs Pillow with WebP. The outputs are committed; this script is
+their provenance. Every canary starts CANARY- so a test can find any.
+"""
+import io
+import os
+import struct
+import sys
+import zlib
+
+from PIL import Image, ImageCms, PngImagePlugin
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+ICC = ImageCms.ImageCmsProfile(ImageCms.createProfile("sRGB")).tobytes()
+XMP = (b'<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF><rdf:Description '
+ b'author="CANARY-XMP-AUTHOR" GCamera:MotionPhoto="1"/></rdf:RDF>'
+ b'</x:xmpmeta>')
+
+
+def picture(mode="RGB", size=(64, 48)):
+ """A picture with structure, so a lost segment shows in pixels."""
+ image = Image.new(mode, size)
+ pixels = image.load()
+ for x in range(size[0]):
+ for y in range(size[1]):
+ value = ((x * 7) % 256, (y * 11) % 256, ((x + y) * 5) % 256)
+ if mode == "RGBA":
+ value += ((x * y) % 256,)
+ if mode == "CMYK":
+ value += ((x * 3) % 256,)
+ pixels[x, y] = value
+ return image
+
+
+def exif(orientation=6):
+ data = Image.Exif()
+ data[0x0112] = orientation
+ data[0x010F] = "CANARY-EXIF-MAKE"
+ data[0x013B] = "CANARY-EXIF-ARTIST"
+ data[0x8825] = {1: "N", 2: (53.0, 20.0, 0.0), 3: "W",
+ 4: (6.0, 15.0, 0.0), 0x1B: "CANARY-GPS"}
+ return data.tobytes()
+
+
+def save(name, data):
+ with open(os.path.join(HERE, name), "wb") as out:
+ out.write(data)
+
+
+def encoded(image, fmt, **options):
+ buffer = io.BytesIO()
+ image.save(buffer, fmt, **options)
+ return buffer.getvalue()
+
+
+def png_chunk(kind, data):
+ body = kind + data
+ return struct.pack(">I", len(data)) + body + struct.pack(
+ ">I", zlib.crc32(body) & 0xFFFFFFFF)
+
+
+def png_fixtures():
+ info = PngImagePlugin.PngInfo()
+ info.add_text("Comment", "CANARY-PNG-TEXT")
+ info.add_text("Author", "CANARY-PNG-ZTXT", zip=True)
+ info.add_itxt("XML:com.adobe.xmp", XMP.decode())
+ raw = encoded(picture("RGBA"), "PNG", pnginfo=info, icc_profile=ICC,
+ exif=exif(1))
+ iend = raw.rindex(b"IEND") - 4
+ extra = png_chunk(b"tIME", b"\x07\xea\x0b\x11\x0c\x00\x00") + \
+ png_chunk(b"prVt", b"CANARY-PNG-PRIVATE")
+ save("meta.png", raw[:iend] + extra + raw[iend:] + b"CANARY-PNG-TRAILER")
+ frames = [picture("RGBA"), picture("RGBA").rotate(90)]
+ save("anim.png", encoded(frames[0], "PNG", save_all=True,
+ append_images=frames[1:], pnginfo=info))
+
+
+def jpeg_segment(marker, payload):
+ return b"\xff" + bytes([marker]) + struct.pack(">H", len(payload) + 2) \
+ + payload
+
+
+def after_soi(raw, *segments):
+ return raw[:2] + b"".join(segments) + raw[2:]
+
+
+def jpeg_fixtures():
+ meta = dict(exif=exif(6), icc_profile=ICC, comment=b"CANARY-JPEG-COM")
+ xmp = jpeg_segment(0xE1, b"http://ns.adobe.com/xap/1.0/\x00" + XMP)
+ base = encoded(picture(), "JPEG", quality=90, **meta)
+ save("baseline.jpg", after_soi(base, xmp) + b"CANARY-JPEG-TRAILER")
+ save("progressive.jpg", encoded(picture(), "JPEG", progressive=True,
+ **meta))
+ save("restart.jpg", encoded(picture(), "JPEG", restart_marker_blocks=2,
+ **meta))
+ save("cmyk.jpg", encoded(picture("CMYK"), "JPEG", **meta))
+ # A JFIF thumbnail of 3x1 pixels whose bytes are the canary, and a
+ # JFXX extension segment.
+ thumb = jpeg_segment(0xE0, b"JFIF\x00\x01\x02\x00\x00\x01\x00\x01"
+ b"\x03\x01CANARY-TH")
+ jfxx = jpeg_segment(0xE0, b"JFXX\x00\x13CANARY-JFXX")
+ plain = encoded(picture(), "JPEG", quality=90)
+ assert plain[2:4] == b"\xff\xe0"
+ app0_end = 4 + struct.unpack(">H", plain[4:6])[0]
+ save("thumbnail.jpg", plain[:2] + thumb + jfxx + plain[app0_end:])
+ # A Motion Photo: an MPF APP2 naming a second picture, and a video
+ # after EOI.
+ mpf = jpeg_segment(0xE2, b"MPF\x00CANARY-MPF")
+ save("motion.jpg", after_soi(base, xmp, mpf) + plain +
+ b"\x00\x00\x00\x18ftypmp42CANARY-VIDEO")
+
+
+def webp_fixtures():
+ meta = dict(exif=exif(1), xmp=XMP, icc_profile=ICC)
+ save("lossy.webp", encoded(picture("RGB"), "WEBP", quality=80, **meta))
+ save("lossless.webp", encoded(picture("RGBA"), "WEBP", lossless=True,
+ **meta))
+ frames = [picture("RGBA"), picture("RGBA").rotate(90)]
+ save("anim.webp", encoded(frames[0], "WEBP", save_all=True,
+ append_images=frames[1:], loop=0, **meta))
+
+
+def gif_fixtures():
+ frames = [picture().convert("P"), picture().rotate(90).convert("P")]
+ raw = encoded(frames[0], "GIF", save_all=True, append_images=frames[1:],
+ loop=0, comment=b"CANARY-GIF-COMMENT")
+ xmp = b"\x21\xff\x0bXMP DataXMP" + bytes([len(b"CANARY-GIF-XMP")]) + \
+ b"CANARY-GIF-XMP\x00"
+ text = b"\x21\x01\x0c" + b"\x00" * 12 + bytes([16]) + \
+ b"CANARY-GIF-TEXT!" + b"\x00"
+ trailer = raw.rindex(b"\x3b")
+ save("anim.gif", raw[:trailer] + xmp + text + raw[trailer:] +
+ b"CANARY-GIF-TRAILER")
+
+
+if __name__ == "__main__":
+ png_fixtures()
+ jpeg_fixtures()
+ webp_fixtures()
+ gif_fixtures()
+ sys.exit(0)
diff --git a/internal/imagefile/testdata/meta.png b/internal/imagefile/testdata/meta.png
new file mode 100644
index 0000000..9df2710
Binary files /dev/null and b/internal/imagefile/testdata/meta.png differ
diff --git a/internal/imagefile/testdata/motion.jpg b/internal/imagefile/testdata/motion.jpg
new file mode 100644
index 0000000..e5590bb
Binary files /dev/null and b/internal/imagefile/testdata/motion.jpg differ
diff --git a/internal/imagefile/testdata/progressive.jpg b/internal/imagefile/testdata/progressive.jpg
new file mode 100644
index 0000000..453a75c
Binary files /dev/null and b/internal/imagefile/testdata/progressive.jpg differ
diff --git a/internal/imagefile/testdata/restart.jpg b/internal/imagefile/testdata/restart.jpg
new file mode 100644
index 0000000..ef3fc12
Binary files /dev/null and b/internal/imagefile/testdata/restart.jpg differ
diff --git a/internal/imagefile/testdata/thumbnail.jpg b/internal/imagefile/testdata/thumbnail.jpg
new file mode 100644
index 0000000..49e1897
Binary files /dev/null and b/internal/imagefile/testdata/thumbnail.jpg differ
diff --git a/internal/imagefile/webp.go b/internal/imagefile/webp.go
new file mode 100644
index 0000000..5994a12
--- /dev/null
+++ b/internal/imagefile/webp.go
@@ -0,0 +1,118 @@
+package imagefile
+
+import (
+ "encoding/binary"
+)
+
+// The WebP walker (§5). It keeps VP8, VP8L, VP8X, ALPH, ANIM, ANMF and
+// ICCP, drops EXIF, XMP and unknown chunks, rewrites VP8X's flags and
+// RIFF's size to match, and ends the file at the RIFF length.
+
+var webpKept = map[string]bool{
+ "VP8 ": true, "VP8L": true, "VP8X": true, "ALPH": true, "ANIM": true,
+ "ANMF": true, "ICCP": true,
+}
+
+// VP8X's flags for the two chunks the walker drops.
+const (
+ webpFlagExif = 0x08
+ webpFlagXMP = 0x04
+)
+
+func cleanWebP(raw []byte) ([]byte, int, error) {
+ if len(raw) < 12 {
+ return nil, 0, ErrMalformed
+ }
+ size := binary.LittleEndian.Uint32(raw[4:])
+ if size < 4 || uint64(size) > uint64(len(raw)-8) {
+ return nil, 0, ErrMalformed
+ }
+ end := 8 + int(size)
+ // One buffer, the header first (Fable L9).
+ out := append(make([]byte, 0, end), "RIFF\x00\x00\x00\x00WEBP"...)
+ for at := 12; at < end; {
+ kind, next, err := webpChunk(raw, at, end)
+ if err != nil {
+ return nil, 0, err
+ }
+ if out, err = keepWebP(out, raw, kind, at, next); err != nil {
+ return nil, 0, err
+ }
+ at = next
+ }
+ binary.LittleEndian.PutUint32(out[4:], uint32(len(out)-8))
+ return out, 1, nil
+}
+
+// keepWebP appends one top-level chunk to out, if it is kept: VP8X with
+// the dropped chunks' flags cleared, and ANMF with only its picture.
+func keepWebP(out, raw []byte, kind string, at, next int) ([]byte,
+ error) {
+ if !webpKept[kind] {
+ return out, nil
+ }
+ start := len(out)
+ switch kind {
+ case "ANMF":
+ return keepFrame(out, raw[at:next])
+ case "VP8X":
+ out = append(out, raw[at:next]...)
+ out[start+8] &^= webpFlagExif | webpFlagXMP
+ return out, nil
+ }
+ return append(out, raw[at:next]...), nil
+}
+
+// frameKept is what an ANMF frame may hold after its 16-byte header:
+// its picture, and nothing else (Fable L10).
+var frameKept = map[string]bool{"ALPH": true, "VP8 ": true, "VP8L": true}
+
+// keepFrame appends an ANMF chunk holding only its header and picture
+// chunks, its size written again.
+func keepFrame(out, chunk []byte) ([]byte, error) {
+ if len(chunk) < 8+16 {
+ return nil, ErrMalformed
+ }
+ start := len(out)
+ out = append(out, chunk[:8+16]...)
+ end := 8 + int(binary.LittleEndian.Uint32(chunk[4:]))
+ if end < 8+16 || end > len(chunk) {
+ return nil, ErrMalformed
+ }
+ for at := 8 + 16; at < end; {
+ kind, next, err := webpChunk(chunk, at, end)
+ if err != nil {
+ return nil, err
+ }
+ if frameKept[kind] {
+ out = append(out, chunk[at:next]...)
+ }
+ at = next
+ }
+ binary.LittleEndian.PutUint32(out[start+4:], uint32(len(out)-start-8))
+ return out, nil
+}
+
+// webpChunk reads the chunk at raw[at], inside the RIFF's end: its
+// FourCC and where the next chunk starts, after any padding byte.
+func webpChunk(raw []byte, at, end int) (string, int, error) {
+ if at+8 > end {
+ return "", 0, ErrMalformed
+ }
+ kind := string(raw[at : at+4])
+ length := binary.LittleEndian.Uint32(raw[at+4:])
+ if uint64(length) > uint64(end-at-8) {
+ return "", 0, ErrMalformed
+ }
+ next := at + 8 + int(length)
+ if length%2 == 1 {
+ if next >= end {
+ return "", 0, ErrMalformed
+ }
+ next++
+ }
+ if kind == "VP8X" && length < 10 {
+ return "", 0, ErrMalformed
+ }
+ return kind, next, nil
+}