garage44.eu/jeroen/cartopolis

logclone: git clone https://garage44.eu/jeroen/cartopolis.git

.. /crates/simulator/src/assets.rs

raw

//! The model asset store: files named by their own bytes, and the rules about
//! what may become one.
//!
//! # Why the file is named after its content
//!
//! Two people upload the same bench and the server keeps one copy. That is the
//! obvious half. The half that matters more is that the name can never point at
//! different bytes than it did yesterday, so `/api/assets/{hash}.glb` is
//! immutable and everything downstream — the client's disk cache, the browser,
//! any proxy in between — can hold it forever without a revalidation. A model
//! that could be edited in place would need an expiry, and a stale model is a
//! building that changed shape while somebody was standing in it.
//!
//! The consequence to keep in mind is elsewhere, in `V16__model_assets.sql`: with
//! one file behind two uploaders, ownership and naming cannot live on the file.
//!
//! # Why the checks happen here and not on the client
//!
//! An upload is checked once, by the server, for everyone who will ever load it.
//! Doing it on the client instead means every viewer pays the check, a client
//! that skips it cannot be detected, and the first anyone hears about a model
//! nothing can draw is a phone dying in the street.
//!
//! What that costs is that the checks must be *decidable from the file*, which is
//! why they are counts and dimensions rather than judgements. Whether a model
//! looks good is a curator's question, in the atlas web UI.
//!
//! # The refusals are on parsed facts, never on an estimate
//!
//! [`docs/notes/mvt-capacity-guard.md`] is the standing warning here: a guard
//! that predicted a cost from the shape of a file before parsing it refused real
//! content and was reverted the same day. So this module parses the glTF once and
//! counts what is actually in it. The only pre-parse limit is a byte ceiling,
//! which is not an estimate of anything — it is the size of the read.

use blake2::{Blake2s256, Digest};
use std::fs;
use std::path::{Path, PathBuf};

/// The ceilings an upload is measured against. Defined in `cartopolis_core`
/// (with the argument for each number) because the client's Models panel says
/// them too, and the atlas web UI's copy is pinned to them by a test there;
/// enforced here, for everyone.
pub use cartopolis_core::model_limits::{
    MAX_ASSET_BYTES, MAX_ASSET_MB, MAX_NODES, MAX_TEXTURE_EDGE, MAX_TRIANGLES,
};

/// What an accepted upload turned out to be. Stored on the row, because these are
/// the numbers the refusal was decided on and re-deriving them means re-reading
/// every file to list the library.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub struct AssetFacts {
    pub hash: String,
    pub byte_size: u64,
    pub triangles: u64,
    pub nodes: u64,
    pub textures: u64,
    /// The longest edge of the largest image in the file, in pixels; 0 when the
    /// model carries no textures at all.
    pub largest_texture: u32,
}

/// The name a file is stored under: 32 bytes of BLAKE2s over its content, hex.
///
/// BLAKE2s because `auth::token_hash` already uses it, so this costs the
/// dependency graph nothing. The choice is not cryptographically load-bearing in
/// the way a signature would be — nothing here trusts a hash somebody supplied,
/// every route recomputes it from the bytes it received — but a collision would
/// silently serve one person's model in place of another's, so a real hash it is.
#[must_use]
pub fn content_hash(bytes: &[u8]) -> String {
    let mut hasher = Blake2s256::new();
    hasher.update(bytes);
    let digest = hasher.finalize();
    let mut out = String::with_capacity(digest.len() * 2);
    for byte in digest {
        use std::fmt::Write as _;
        let _ = write!(out, "{byte:02x}");
    }
    out
}

/// Whether a string could be a name this module produced.
///
/// Every route that takes a hash from a URL runs this first. It is the path
/// traversal guard as much as a format check: a hash is 64 lowercase hex digits
/// and therefore contains no separator, no dot and no `..`, so a value that
/// passes can be joined to a directory without further thought.
#[must_use]
pub fn is_hash(s: &str) -> bool {
    s.len() == 64
        && s.bytes()
            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
}

/// Where a hash lives on disk.
///
/// Flat, not sharded into `ab/cdef…` subdirectories. That fan-out exists to keep
/// a directory small enough for a filesystem to list quickly, and the number of
/// models in one world is thousands at the very most — ext4 has indexed
/// directories and does not care. It can be added later without touching a single
/// stored name, since the name is not the path.
fn asset_path(dir: &str, hash: &str) -> PathBuf {
    Path::new(dir).join(format!("{hash}.glb"))
}

/// Read the model back, or `None` if this server has never held it.
///
/// The hash is checked rather than sanitised. Filtering the odd characters out of
/// an id and carrying on — which is what `textures::load_texture` does — is right
/// for a name an operator typed into a directory and wrong for one that arrives
/// in a URL, where a value that needed cleaning is a value somebody chose.
#[must_use]
pub fn load(dir: &str, hash: &str) -> Option<Vec<u8>> {
    if !is_hash(hash) {
        return None;
    }
    fs::read(asset_path(dir, hash)).ok()
}

/// Write the model, creating the store directory if this is the first one.
///
/// Writing to a temporary file and renaming, rather than writing in place: a
/// download route running concurrently with an upload of the same hash must see
/// either nothing or the whole file, never a prefix. `rename` within one
/// directory is atomic on every filesystem this runs on.
///
/// A file that is already there is left alone. It cannot differ — the name is a
/// hash of the content — so rewriting it would be pure risk.
pub fn store(dir: &str, hash: &str, bytes: &[u8]) -> std::io::Result<()> {
    let final_path = asset_path(dir, hash);
    if final_path.exists() {
        return Ok(());
    }
    fs::create_dir_all(dir)?;
    let temp_path = Path::new(dir).join(format!(".{hash}.part"));
    fs::write(&temp_path, bytes)?;
    fs::rename(&temp_path, &final_path)
}

/// Parse an uploaded file and answer what it is, or why it will not do.
///
/// The error strings are what a person sees in the upload dialog, so they say
/// what was measured and what the ceiling is. "Rejected" with no number is a
/// message that sends someone to a maintainer.
/// Turn a self-contained `.gltf` into the `.glb` everything downstream expects,
/// or leave a `.glb` alone.
///
/// # Why accept the JSON form at all
///
/// It is the same format. What made `.glb` the only accepted spelling is that a
/// `.gltf` normally *names* its buffers and textures as separate files, and an
/// upload that makes the server fetch a URL of the uploader's choosing is not an
/// upload — it is a request generator sitting inside a private network. That
/// argument is about external references and says nothing about the case where
/// everything is already in the file as a data URI, which Blender writes when
/// asked for "glTF Embedded" and which a person has no way of knowing is the
/// wrong one of the three menu entries.
///
/// So: external references are refused exactly as before, and a self-contained
/// one is **repacked** here rather than stored as it arrived. Repacking rather
/// than accepting two formats is what keeps this one decision: the store, the
/// download route, the client's `sim://` reader and Bevy's loader all continue to
/// see one kind of file, and the hash names what was stored.
///
/// # Two consequences worth knowing
///
/// The output is always **smaller** than the input — base64 is a third larger
/// than the bytes it encodes — so the byte ceiling applied to the upload still
/// bounds what is stored.
///
/// And the same model uploaded both ways is **two files**: the hash is of the
/// bytes stored, and a repack is not byte-identical to whatever a different
/// exporter would have produced. Deduplication is a property of identical bytes
/// and has never been more than that.
pub fn repack_gltf(bytes: &[u8]) -> Result<Option<Vec<u8>>, String> {
    if bytes.starts_with(b"glTF") {
        return Ok(None);
    }
    // A glTF JSON document, or nothing this understands. Checked on the first
    // non-whitespace byte rather than on the file extension, which the upload
    // route never sees.
    if !bytes
        .iter()
        .find(|b| !b.is_ascii_whitespace())
        .is_some_and(|b| *b == b'{')
    {
        return Err("that is neither a .glb nor a .gltf — export as glTF".to_string());
    }
    let mut doc: serde_json::Value =
        serde_json::from_slice(bytes).map_err(|e| format!("that .gltf will not parse: {e}"))?;
    if doc["asset"]["version"].as_str().is_none() {
        return Err("that JSON file is not a glTF document".to_string());
    }

    let mut blob: Vec<u8> = Vec::new();
    // Where each of the document's buffers ended up in the single blob.
    let mut buffer_starts: Vec<usize> = Vec::new();
    let buffers = doc["buffers"].as_array().cloned().unwrap_or_default();
    for buffer in &buffers {
        let uri = buffer["uri"].as_str().ok_or_else(|| {
            // A buffer with no `uri` means "the GLB's own binary chunk", which a
            // .gltf does not have. Nothing can supply those bytes.
            "that .gltf expects a binary chunk it does not carry — export it as .glb".to_string()
        })?;
        let data = decode_data_uri(uri)?;
        align(&mut blob);
        buffer_starts.push(blob.len());
        blob.extend_from_slice(&data);
    }

    // Every view moves onto the one buffer, keeping its index so accessors do not
    // have to be touched at all.
    let mut views = doc["bufferViews"].as_array().cloned().unwrap_or_default();
    for view in &mut views {
        let index = view["buffer"].as_u64().unwrap_or(0) as usize;
        let start = *buffer_starts
            .get(index)
            .ok_or_else(|| "that .gltf refers to a buffer it does not have".to_string())?;
        let offset = view["byteOffset"].as_u64().unwrap_or(0) as usize;
        view["buffer"] = serde_json::json!(0);
        view["byteOffset"] = serde_json::json!(start + offset);
    }

    // Images named by a data URI become views of their own; images that already
    // ride a view are left exactly as they are.
    let mut images = doc["images"].as_array().cloned().unwrap_or_default();
    for image in &mut images {
        let Some(uri) = image["uri"].as_str().map(str::to_string) else {
            continue;
        };
        let mime = data_uri_mime(&uri).ok_or_else(|| {
            "that .gltf has a texture with no type on it — export the textures embedded".to_string()
        })?;
        let data = decode_data_uri(&uri)?;
        align(&mut blob);
        let start = blob.len();
        blob.extend_from_slice(&data);
        views.push(serde_json::json!({
            "buffer": 0,
            "byteOffset": start,
            "byteLength": data.len(),
        }));
        let object = image
            .as_object_mut()
            .ok_or_else(|| "that .gltf has an image that is not an object".to_string())?;
        object.remove("uri");
        object.insert("bufferView".into(), serde_json::json!(views.len() - 1));
        object.insert("mimeType".into(), serde_json::json!(mime));
    }

    doc["buffers"] = serde_json::json!([{ "byteLength": blob.len() }]);
    doc["bufferViews"] = serde_json::Value::Array(views);
    if !images.is_empty() {
        doc["images"] = serde_json::Value::Array(images);
    }
    Ok(Some(write_glb(&doc, &blob)?))
}

/// The bytes behind a `data:` URI, or a refusal naming what was pointed at.
///
/// Base64 only. The percent-encoded form of a data URI is legal and is not what
/// any exporter writes, and accepting it would mean a second decoder for a case
/// nobody produces.
fn decode_data_uri(uri: &str) -> Result<Vec<u8>, String> {
    use base64::Engine;
    let Some(rest) = uri.strip_prefix("data:") else {
        // The external-reference refusal, which is the whole reason the JSON form
        // was not accepted before. It names what it saw, truncated: a URI can be
        // any length and this sentence is shown to a person.
        let shown: String = uri.chars().take(40).collect();
        return Err(format!(
            "that model refers to a file outside itself ({shown}) — export it with the buffers              and textures embedded, or as .glb"
        ));
    };
    let Some((_mime, payload)) = rest.split_once(";base64,") else {
        return Err("that model has a data URI this server cannot read — export it as .glb".into());
    };
    base64::engine::general_purpose::STANDARD
        .decode(payload.trim())
        .map_err(|e| format!("that model has a data URI that will not decode: {e}"))
}

/// The media type in a `data:` URI, for an image that is about to become a view.
///
/// glTF requires `mimeType` beside a `bufferView` image — the loader has no file
/// name to guess from — so a data URI with no type on it cannot be repacked.
fn data_uri_mime(uri: &str) -> Option<String> {
    let rest = uri.strip_prefix("data:")?;
    let (mime, _) = rest.split_once(";base64,")?;
    let mime = mime.trim();
    (!mime.is_empty()).then(|| mime.to_string())
}

/// Pad to the four-byte alignment glTF requires of a buffer view's offset.
fn align(blob: &mut Vec<u8>) {
    while blob.len() % 4 != 0 {
        blob.push(0);
    }
}

/// The container: a header, the JSON chunk, and the binary chunk.
///
/// Both chunks are padded to four bytes, and with what the specification asks
/// for: spaces after the JSON (so it stays parseable as text) and zeros after the
/// binary.
fn write_glb(doc: &serde_json::Value, blob: &[u8]) -> Result<Vec<u8>, String> {
    let mut json = serde_json::to_vec(doc).map_err(|e| format!("could not rewrite it: {e}"))?;
    while json.len() % 4 != 0 {
        json.push(b' ');
    }
    let mut bin = blob.to_vec();
    while bin.len() % 4 != 0 {
        bin.push(0);
    }
    let total = 12 + 8 + json.len() + if bin.is_empty() { 0 } else { 8 + bin.len() };
    let mut out = Vec::with_capacity(total);
    out.extend_from_slice(b"glTF");
    out.extend_from_slice(&2u32.to_le_bytes());
    out.extend_from_slice(
        &(u32::try_from(total).map_err(|_| "that model is too large")?).to_le_bytes(),
    );
    out.extend_from_slice(
        &(u32::try_from(json.len()).map_err(|_| "that model is too large")?).to_le_bytes(),
    );
    out.extend_from_slice(b"JSON");
    out.extend_from_slice(&json);
    if !bin.is_empty() {
        out.extend_from_slice(
            &(u32::try_from(bin.len()).map_err(|_| "that model is too large")?).to_le_bytes(),
        );
        out.extend_from_slice(b"BIN\0");
        out.extend_from_slice(&bin);
    }
    Ok(out)
}

pub fn inspect(bytes: &[u8]) -> Result<AssetFacts, String> {
    if bytes.len() > MAX_ASSET_BYTES {
        return Err(format!(
            "that file is {:.1} MB and the limit is {MAX_ASSET_MB} MB",
            bytes.len() as f64 / (1024.0 * 1024.0),
        ));
    }
    if bytes.is_empty() {
        return Err("that file is empty".to_string());
    }
    // Binary glTF only by the time anything gets here, and the magic is the
    // test. A `.gltf` that named its buffers and images as separate files would
    // mean either fetching whatever it names — an upload that makes the server
    // issue requests of the uploader's choosing — or storing a model that cannot
    // be drawn; a self-contained one has already been repacked into this form by
    // `repack_gltf`. One file carrying everything is the property the whole store
    // is built on.
    if !bytes.starts_with(b"glTF") {
        // Reached only when something bypassed `repack_gltf`, which is where an
        // upload's format is decided and which hands this a GLB or an error.
        return Err("that is not a .glb file — export as glTF Binary (.glb)".to_string());
    }

    let gltf =
        gltf::Gltf::from_slice(bytes).map_err(|e| format!("that .glb will not parse: {e}"))?;

    // Every buffer must be the GLB's own binary chunk. A `Uri` here is either an
    // external file (which did not come with the upload) or a data URI (which is
    // base64 in the JSON, a third larger than it needs to be, and a way to smuggle
    // past a byte limit measured on the file). Both are refusals.
    for buffer in gltf.buffers() {
        if let gltf::buffer::Source::Uri(uri) = buffer.source() {
            let shown: String = uri.chars().take(40).collect();
            return Err(format!(
                "that model refers to a file outside itself ({shown}) — export it with the buffers embedded"
            ));
        }
    }

    let mut triangles: u64 = 0;
    for mesh in gltf.meshes() {
        for primitive in mesh.primitives() {
            // A count of *vertices*, turned into triangles by the topology. A
            // strip or a fan of n vertices is n-2 triangles, not n/3, and reading
            // every mode as a list would over-count a strip threefold and let a
            // fan through a limit it should have hit.
            let vertices = match primitive.indices() {
                Some(accessor) => accessor.count() as u64,
                None => primitive
                    .get(&gltf::Semantic::Positions)
                    .map_or(0, |a| a.count() as u64),
            };
            triangles += match primitive.mode() {
                gltf::mesh::Mode::Triangles => vertices / 3,
                gltf::mesh::Mode::TriangleStrip | gltf::mesh::Mode::TriangleFan => {
                    vertices.saturating_sub(2)
                }
                // Points and lines draw no triangles. They are not refused: a
                // model may legitimately carry a line for an edge highlight.
                _ => 0,
            };
        }
    }
    if triangles > MAX_TRIANGLES {
        return Err(format!(
            "that model has {triangles} triangles and the limit is {MAX_TRIANGLES}"
        ));
    }

    let nodes = gltf.nodes().count();
    if nodes > MAX_NODES {
        return Err(format!(
            "that model has {nodes} nodes and the limit is {MAX_NODES}"
        ));
    }

    let blob = gltf.blob.as_deref().unwrap_or_default();
    let mut textures: u64 = 0;
    let mut largest_texture: u32 = 0;
    for image in gltf.images() {
        let gltf::image::Source::View { view, .. } = image.source() else {
            return Err(
                "that model refers to a texture file outside itself — export it with the textures embedded"
                    .to_string(),
            );
        };
        textures += 1;
        let start = view.offset();
        let end = start.saturating_add(view.length());
        let Some(encoded) = blob.get(start..end) else {
            return Err("that model's texture data is truncated".to_string());
        };
        // Header only. `into_dimensions` reads far enough to answer and stops,
        // which is the point: decoding a 16384-square image to find out it is
        // 16384 square is the attack, not the check.
        let edge = image_edge(encoded)?;
        largest_texture = largest_texture.max(edge);
    }
    if largest_texture > MAX_TEXTURE_EDGE {
        return Err(format!(
            "that model has a {largest_texture}-pixel texture and the limit is {MAX_TEXTURE_EDGE}"
        ));
    }

    // A document with no geometry in it parses, hashes and stores perfectly well
    // and draws nothing, which is the one outcome an uploader cannot debug from
    // the other side. It became reachable when the JSON form was accepted —
    // `{"asset":{"version":"2.0"}}` is a *valid* glTF document — so the rule that
    // used to fall out of "binary only" is now stated.
    if triangles == 0 {
        return Err(
            "that file has no geometry in it — a model needs at least one mesh to draw".to_string(),
        );
    }

    Ok(AssetFacts {
        hash: content_hash(bytes),
        byte_size: bytes.len() as u64,
        triangles,
        nodes: nodes as u64,
        textures,
        largest_texture,
    })
}

/// The longer edge of an encoded image, read from its header.
fn image_edge(encoded: &[u8]) -> Result<u32, String> {
    let reader = image::ImageReader::new(std::io::Cursor::new(encoded))
        .with_guessed_format()
        .map_err(|e| format!("that model has a texture that will not read: {e}"))?;
    let (w, h) = reader
        .into_dimensions()
        .map_err(|e| format!("that model has a texture that will not read: {e}"))?;
    Ok(w.max(h))
}

#[cfg(test)]
mod tests {
    use super::*;

    /// A minimal binary glTF: one triangle, no textures, no external references.
    ///
    /// Built here rather than checked in, for the reason `tools/ifc_demo_building.py`
    /// exists — a fixture that describes exactly what the test is about beats a
    /// binary nobody can read the diff of, and this one is small enough to write.
    fn glb(json: &str, bin: &[u8]) -> Vec<u8> {
        let mut json_chunk = json.as_bytes().to_vec();
        while json_chunk.len() % 4 != 0 {
            json_chunk.push(b' ');
        }
        let mut bin_chunk = bin.to_vec();
        while bin_chunk.len() % 4 != 0 {
            bin_chunk.push(0);
        }
        let total = 12
            + 8
            + json_chunk.len()
            + if bin_chunk.is_empty() {
                0
            } else {
                8 + bin_chunk.len()
            };
        let mut out = Vec::with_capacity(total);
        out.extend_from_slice(b"glTF");
        out.extend_from_slice(&2u32.to_le_bytes());
        out.extend_from_slice(&(total as u32).to_le_bytes());
        out.extend_from_slice(&(json_chunk.len() as u32).to_le_bytes());
        out.extend_from_slice(b"JSON");
        out.extend_from_slice(&json_chunk);
        if !bin_chunk.is_empty() {
            out.extend_from_slice(&(bin_chunk.len() as u32).to_le_bytes());
            out.extend_from_slice(b"BIN\0");
            out.extend_from_slice(&bin_chunk);
        }
        out
    }

    /// Three positions and nothing else — the smallest thing that is a model.
    fn one_triangle() -> Vec<u8> {
        let positions: [f32; 9] = [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0];
        let mut bin = Vec::new();
        for v in positions {
            bin.extend_from_slice(&v.to_le_bytes());
        }
        let json = r#"{
            "asset": {"version": "2.0"},
            "scene": 0,
            "scenes": [{"nodes": [0]}],
            "nodes": [{"mesh": 0}],
            "meshes": [{"primitives": [{"attributes": {"POSITION": 0}}]}],
            "accessors": [{"bufferView": 0, "componentType": 5126, "count": 3, "type": "VEC3",
                           "min": [0,0,0], "max": [1,1,0]}],
            "bufferViews": [{"buffer": 0, "byteOffset": 0, "byteLength": 36}],
            "buffers": [{"byteLength": 36}]
        }"#;
        glb(json, &bin)
    }

    #[test]
    fn accepts_a_minimal_binary_gltf() {
        let facts = inspect(&one_triangle()).expect("a one-triangle glb is a model");
        assert_eq!(facts.triangles, 1);
        assert_eq!(facts.nodes, 1);
        assert_eq!(facts.textures, 0);
        assert_eq!(facts.largest_texture, 0);
        assert_eq!(facts.hash.len(), 64);
    }

    /// The name is the content, so two uploads of the same bytes are one file —
    /// and a byte's difference is a different file.
    #[test]
    fn the_hash_is_the_content() {
        let a = one_triangle();
        assert_eq!(content_hash(&a), content_hash(&a.clone()));
        let mut b = a.clone();
        *b.last_mut().unwrap() ^= 0x01;
        assert_ne!(content_hash(&a), content_hash(&b));
    }

    /// A JSON `.gltf` names its buffers as separate files. Accepting one would
    /// mean either fetching what it names or storing something undrawable.
    #[test]
    fn refuses_json_gltf() {
        // `inspect` itself still takes binary glTF only. The JSON form is decided
        // one step earlier, in `repack_gltf`, which either hands this a GLB or
        // refuses — see the round trip below.
        let err = inspect(br#"{"asset":{"version":"2.0"}}"#).unwrap_err();
        assert!(err.contains(".glb"), "{err}");
    }

    /// A self-contained `.gltf` — Blender's "glTF Embedded" — is repacked and
    /// then reads as exactly the model it describes.
    #[test]
    fn repacks_an_embedded_gltf() {
        use base64::Engine;
        let positions: [f32; 9] = [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0];
        let mut bin = Vec::new();
        for v in positions {
            bin.extend_from_slice(&v.to_le_bytes());
        }
        let encoded = base64::engine::general_purpose::STANDARD.encode(&bin);
        let doc = format!(
            r#"{{
                "asset": {{"version": "2.0"}},
                "scene": 0,
                "scenes": [{{"nodes": [0]}}],
                "nodes": [{{"mesh": 0}}],
                "meshes": [{{"primitives": [{{"attributes": {{"POSITION": 0}}}}]}}],
                "accessors": [{{"bufferView": 0, "componentType": 5126, "count": 3,
                                "type": "VEC3", "min": [0,0,0], "max": [1,1,0]}}],
                "bufferViews": [{{"buffer": 0, "byteOffset": 0, "byteLength": 36}}],
                "buffers": [{{"byteLength": 36, "uri": "data:application/octet-stream;base64,{encoded}"}}]
            }}"#
        );
        let repacked = repack_gltf(doc.as_bytes())
            .expect("an embedded gltf is acceptable")
            .expect("and it is repacked");
        assert!(repacked.starts_with(b"glTF"));
        // Base64 is a third larger than what it carries, so a repack can only
        // shrink — which is what keeps the byte ceiling applied to the upload a
        // bound on what is stored.
        assert!(repacked.len() < doc.len());
        let facts = inspect(&repacked).expect("and it is a model");
        assert_eq!(facts.triangles, 1);
        assert_eq!(facts.nodes, 1);
    }

    /// A `.glb` is not touched: the repack step has to be invisible to the format
    /// that was already right.
    #[test]
    fn leaves_a_glb_alone() {
        assert!(repack_gltf(&one_triangle())
            .expect("a glb is acceptable")
            .is_none());
    }

    /// The refusal the whole restriction exists for. A `.gltf` naming a file
    /// beside it must not send the server looking for it.
    #[test]
    fn refuses_a_gltf_that_names_a_file_beside_it() {
        let doc = br#"{
            "asset": {"version": "2.0"},
            "buffers": [{"byteLength": 36, "uri": "model.bin"}]
        }"#;
        let err = repack_gltf(doc).unwrap_err();
        assert!(err.contains("model.bin"), "{err}");
    }

    /// …including when the file it names is a URL, which is the case that would
    /// make the simulator fetch something for a stranger.
    #[test]
    fn refuses_a_gltf_that_names_a_url() {
        let doc = br#"{
            "asset": {"version": "2.0"},
            "buffers": [{"byteLength": 4, "uri": "http://169.254.169.254/latest/meta-data/"}]
        }"#;
        let err = repack_gltf(doc).unwrap_err();
        assert!(err.contains("outside itself"), "{err}");
    }

    /// A texture in a data URI becomes a view of its own, and keeps the media
    /// type the loader needs — a `bufferView` image with no `mimeType` is a
    /// texture nothing can decode.
    #[test]
    fn an_embedded_texture_becomes_a_view() {
        use base64::Engine;
        // A 1×1 PNG, which is enough for the repack; `inspect` reads its header.
        let png: &[u8] = &[
            0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48,
            0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, 0x00, 0x00,
            0x00, 0x1F, 0x15, 0xC4, 0x89, 0x00, 0x00, 0x00, 0x0A, 0x49, 0x44, 0x41, 0x54, 0x78,
            0x9C, 0x63, 0x00, 0x01, 0x00, 0x00, 0x05, 0x00, 0x01, 0x0D, 0x0A, 0x2D, 0xB4, 0x00,
            0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82,
        ];
        let encoded = base64::engine::general_purpose::STANDARD.encode(png);
        // Geometry as well as the texture: a file with no mesh in it is refused
        // on its own terms now, and this test is about the texture.
        let positions: [f32; 9] = [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0];
        let mut bin = Vec::new();
        for v in positions {
            bin.extend_from_slice(&v.to_le_bytes());
        }
        let mesh = base64::engine::general_purpose::STANDARD.encode(&bin);
        let doc = format!(
            r#"{{
                "asset": {{"version": "2.0"}},
                "images": [{{"uri": "data:image/png;base64,{encoded}"}}],
                "meshes": [{{"primitives": [{{"attributes": {{"POSITION": 0}}}}]}}],
                "accessors": [{{"bufferView": 0, "componentType": 5126, "count": 3,
                                "type": "VEC3", "min": [0,0,0], "max": [1,1,0]}}],
                "bufferViews": [{{"buffer": 0, "byteOffset": 0, "byteLength": 36}}],
                "buffers": [{{"byteLength": 36, "uri": "data:application/octet-stream;base64,{mesh}"}}]
            }}"#
        );
        let repacked = repack_gltf(doc.as_bytes())
            .expect("acceptable")
            .expect("repacked");
        let gltf = gltf::Gltf::from_slice(&repacked).expect("a readable glb");
        let image = gltf.images().next().expect("the image survived");
        assert!(matches!(image.source(), gltf::image::Source::View { .. }));
        let facts = inspect(&repacked).expect("a model");
        assert_eq!(facts.textures, 1);
        assert_eq!(facts.largest_texture, 1);
    }

    /// A valid glTF document with nothing in it is a file that would draw
    /// nothing. It only became reachable when the JSON form was accepted.
    #[test]
    fn refuses_a_document_with_no_geometry() {
        let repacked = repack_gltf(br#"{"asset":{"version":"2.0"}}"#)
            .expect("it is a glTF document")
            .expect("and it repacks");
        let err = inspect(&repacked).unwrap_err();
        assert!(err.contains("no geometry"), "{err}");
    }

    /// Anything that is neither is refused before a parser sees it.
    #[test]
    fn refuses_something_that_is_neither() {
        let err = repack_gltf(b"FBX binary  \x1a\x00").unwrap_err();
        assert!(err.contains(".glb"), "{err}");
    }

    /// The same refusal from the other direction: a GLB whose buffer points
    /// outside itself.
    #[test]
    fn refuses_an_external_buffer() {
        let json = r#"{
            "asset": {"version": "2.0"},
            "buffers": [{"uri": "geometry.bin", "byteLength": 36}]
        }"#;
        let err = inspect(&glb(json, &[])).unwrap_err();
        assert!(err.contains("outside itself"), "{err}");
    }

    #[test]
    fn refuses_an_external_texture() {
        let json = r#"{
            "asset": {"version": "2.0"},
            "images": [{"uri": "colour.png"}]
        }"#;
        let err = inspect(&glb(json, &[])).unwrap_err();
        assert!(err.contains("outside itself"), "{err}");
    }

    #[test]
    fn refuses_an_oversized_file() {
        let err = inspect(&vec![b'x'; MAX_ASSET_BYTES + 1]).unwrap_err();
        assert!(err.contains("limit is"), "{err}");
    }

    /// A hash from a URL is joined to a directory, so anything that is not one
    /// has to be refused before it gets there.
    #[test]
    fn a_hash_cannot_be_a_path() {
        assert!(is_hash(&"a".repeat(64)));
        assert!(
            !is_hash(&"A".repeat(64)),
            "uppercase is not the output format"
        );
        assert!(!is_hash("../../etc/passwd"));
        assert!(!is_hash(&format!("{}/x", "a".repeat(62))));
        assert!(!is_hash(""));
        assert!(load("/tmp", "../../etc/passwd").is_none());
    }

    /// A strip of n vertices is n-2 triangles. Reading every mode as a list
    /// over-counts a strip threefold, which is a limit that refuses honest models.
    #[test]
    fn counts_a_triangle_strip_as_a_strip() {
        let positions: [f32; 15] = [
            0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 2.0, 0.0, 0.0,
        ];
        let mut bin = Vec::new();
        for v in positions {
            bin.extend_from_slice(&v.to_le_bytes());
        }
        let json = r#"{
            "asset": {"version": "2.0"},
            "nodes": [{"mesh": 0}],
            "meshes": [{"primitives": [{"attributes": {"POSITION": 0}, "mode": 5}]}],
            "accessors": [{"bufferView": 0, "componentType": 5126, "count": 5, "type": "VEC3",
                           "min": [0,0,0], "max": [2,1,0]}],
            "bufferViews": [{"buffer": 0, "byteOffset": 0, "byteLength": 60}],
            "buffers": [{"byteLength": 60}]
        }"#;
        let facts = inspect(&glb(json, &bin)).expect("a strip is a model");
        assert_eq!(
            facts.triangles, 3,
            "five vertices as a strip are three triangles"
        );
    }

    /// Storing is atomic and idempotent: the second write of a name that is
    /// already there is a no-op, because it cannot differ.
    #[test]
    fn stores_and_reads_back() {
        let dir = std::env::temp_dir().join(format!("carto-assets-{}", std::process::id()));
        let dir = dir.to_str().unwrap();
        let bytes = one_triangle();
        let hash = content_hash(&bytes);
        store(dir, &hash, &bytes).unwrap();
        store(dir, &hash, &bytes).unwrap();
        assert_eq!(load(dir, &hash).as_deref(), Some(&bytes[..]));
        assert!(load(dir, &content_hash(b"nothing")).is_none());
        let _ = fs::remove_dir_all(dir);
    }
}