Files
faunosteo/crates/worker/src/fixtures.rs
T
bchanot e967ce6736 test(worker): verify child at the input caps, brk bounded by the limits
Max frame (document and base 2 MiB, drawings 6 MiB) passes through the full
sandbox; refusals just beyond give caps verdicts; RLIMIT_AS and the argument
filters still stop the verify child; seccomp traced on the max input; the two
tracked misclassifications asserted as current behaviour.
2026-11-01 21:07:23 +01:00

463 lines
19 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! Synthetic images and framed sheet inputs for the sandbox tests and the seccomp
//! derivation (`test-hooks` only): nothing binary lives in the repository.
use std::io::Cursor;
use faunosteo_core::domain::sheet::verdict::{
VerdictBinding, VerdictDrawing, VerdictInput, sha256_hex,
};
use image::{DynamicImage, ImageBuffer, ImageFormat, Rgba};
use serde_json::{Value, json};
use crate::verify_frame;
fn gradient(width: u32, height: u32) -> DynamicImage {
let buffer = ImageBuffer::from_fn(width, height, |x, y| {
let r = u8::try_from(x * 255 / width.max(1)).unwrap_or(255);
let g = u8::try_from(y * 255 / height.max(1)).unwrap_or(255);
let b = u8::try_from((x / 8 + y / 8) % 256).unwrap_or(0);
Rgba([r, g, b, 255])
});
DynamicImage::ImageRgba8(buffer)
}
fn encode(image: &DynamicImage, format: ImageFormat) -> Vec<u8> {
let mut out = Cursor::new(Vec::new());
if image.write_to(&mut out, format).is_err() {
return Vec::new();
}
out.into_inner()
}
/// A PNG gradient.
pub fn png(width: u32, height: u32) -> Vec<u8> {
encode(&gradient(width, height), ImageFormat::Png)
}
/// A baseline JPEG gradient (no alpha channel).
pub fn jpeg(width: u32, height: u32) -> Vec<u8> {
let rgb = DynamicImage::ImageRgb8(gradient(width, height).into_rgb8());
encode(&rgb, ImageFormat::Jpeg)
}
/// A lossless WebP gradient (the only WebP encoder of the `image` crate).
pub fn webp(width: u32, height: u32) -> Vec<u8> {
encode(&gradient(width, height), ImageFormat::WebP)
}
/// A PNG whose header declares `width` × `height` with no pixel data: the decoder must
/// refuse it on dimensions before allocating anything.
pub fn png_header_only(width: u32, height: u32) -> Vec<u8> {
let mut out = vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a];
let mut ihdr = Vec::new();
ihdr.extend_from_slice(&width.to_be_bytes());
ihdr.extend_from_slice(&height.to_be_bytes());
ihdr.extend_from_slice(&[8, 6, 0, 0, 0]);
push_chunk(&mut out, b"IHDR", &ihdr);
push_chunk(&mut out, b"IEND", &[]);
out
}
fn push_chunk(out: &mut Vec<u8>, kind: &[u8; 4], payload: &[u8]) {
out.extend_from_slice(&(payload.len() as u32).to_be_bytes());
let mut hasher = crc32fast::Hasher::new();
hasher.update(kind);
hasher.update(payload);
out.extend_from_slice(kind);
out.extend_from_slice(payload);
out.extend_from_slice(&hasher.finalize().to_be_bytes());
}
/// A small PNG header whose `iCCP` profile inflates to `inflated_bytes` (hundreds of
/// kilobytes of compressed zeros) and that carries no image data: the decoder refuses it as
/// content (`decode_failed` or `resource_limit`, depending on which check fires first),
/// never as a broken environment. R1 adds a variant with image data so the budget itself
/// is seen firing.
pub fn png_iccp_bomb(inflated_bytes: usize) -> Vec<u8> {
use std::io::Write;
let mut out = vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a];
let mut ihdr = Vec::new();
ihdr.extend_from_slice(&64u32.to_be_bytes());
ihdr.extend_from_slice(&64u32.to_be_bytes());
ihdr.extend_from_slice(&[8, 6, 0, 0, 0]);
push_chunk(&mut out, b"IHDR", &ihdr);
let mut iccp = b"p\0\0".to_vec();
let mut encoder = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::best());
let zeros = vec![0u8; 1 << 20];
let mut written = 0;
while written < inflated_bytes {
let chunk = (inflated_bytes - written).min(zeros.len());
if encoder.write_all(&zeros[..chunk]).is_err() {
break;
}
written += chunk;
}
iccp.extend_from_slice(&encoder.finish().unwrap_or_default());
push_chunk(&mut out, b"iCCP", &iccp);
push_chunk(&mut out, b"IEND", &[]);
out
}
/// The first bytes of a GIF: a format the avatar pipeline never accepts.
pub fn gif() -> Vec<u8> {
let mut out = b"GIF89a".to_vec();
out.extend_from_slice(&[64, 0, 64, 0, 0xf7, 0, 0]);
out.extend(std::iter::repeat_n(0u8, 800));
out
}
/// A valid PNG cut in half.
pub fn truncated_png() -> Vec<u8> {
let mut bytes = png(200, 200);
bytes.truncate(bytes.len() / 2);
bytes
}
/// The asset id the verification fixtures draw on.
pub const SHEET_ASSET: &str = "11111111-2222-4333-8444-555555555555";
/// A drawing in its stored form, as the page's cleaning uploads it
/// (`crates/core/tests/sheet_verdict.rs`).
pub const SHEET_DRAWING: &str = concat!(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n",
r#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10"><path d="M0 0L5 5"/></svg>"#
);
/// The round of the verification fixtures.
pub fn sheet_binding() -> VerdictBinding {
VerdictBinding {
sheet_id: "aaaaaaaa-0000-4000-8000-000000000001".to_owned(),
version_id: "aaaaaaaa-0000-4000-8000-000000000002".to_owned(),
revision: 3,
review_id: "aaaaaaaa-0000-4000-8000-000000000003".to_owned(),
}
}
fn name(text: &str) -> Value {
json!({ "fr": text, "en": text })
}
/// A small valid document drawn on `SHEET_ASSET` (the core's `sheet_verdict::document`).
pub fn sheet_document() -> Value {
json!({
"schema_version": 2, "species_id": "canine", "name": name("Chien"),
"description": {}, "scope_disclaimer": { "fr": "Outil", "en": "Tool" },
"attribution": { "authors": ["A"], "license": null, "notes": null },
"vertebral_config": { "regions": [] }, "references": [],
"categories": [{ "id": "c", "name": name("C"), "color": null }],
"views": [{ "id": "main", "kind": "main", "name": name("Vue"), "svg_asset_id": SHEET_ASSET, "view_box": null }],
"annotations": [{ "id": "a1", "kind": "point", "view_id": "main", "category_id": "c",
"laterality": "unpaired", "geometry": { "type": "circle", "cx": 1, "cy": 1, "r": 1 },
"review_status": "to_confirm", "name": name("P"), "finding_zone_id": "z1", "vertebral_region_code": null }],
"finding_zones": [{ "id": "z1", "name": name("Z"), "categories": [{ "id": "cat", "kind": "dysfunction",
"name": name("D"), "review_status": "to_confirm",
"children": [{ "id": "n1", "name": name("N"), "review_status": "to_confirm" }] }] }]
})
}
/// A document at every cap (the core's `sheet_verdict::at_caps`): 64 views, 1024
/// annotations, 8192 finding nodes, depth 8.
pub fn sheet_document_at_caps() -> Value {
let mut doc = sheet_document();
let mut views = vec![
json!({ "id": "main", "kind": "main", "name": name("V"), "svg_asset_id": SHEET_ASSET, "view_box": null }),
];
let mut annotations = Vec::new();
for i in 1..64 {
views.push(json!({ "id": format!("d{i}"), "kind": "detail", "name": name("D"), "svg_asset_id": null,
"view_box": { "min_x": 0, "min_y": 0, "width": 5, "height": 5 }, "parent_view_id": "main" }));
annotations.push(json!({ "id": format!("t{i}"), "kind": "detail_trigger", "view_id": "main", "category_id": "c",
"laterality": "unpaired", "geometry": { "type": "polygon", "points": [[0, 0], [1, 0], [1, 1]] },
"review_status": "reviewed", "name": null, "opens_view_id": format!("d{i}") }));
}
let zones: Vec<Value> = (0..64)
.map(|z| {
let mut children = vec![chain_reviewed(7)];
children.extend((0..120).map(|n| json!({ "id": format!("l{n}"), "name": name("Nœud de lésion"), "review_status": "reviewed" })));
json!({ "id": format!("z{z}"), "name": name("Zone"), "categories": [{ "id": "cat", "kind": "dysfunction",
"name": name("Catégorie"), "review_status": "reviewed", "children": children }] })
})
.collect();
for i in 0..(1024 - 63) {
annotations.push(json!({ "id": format!("p{i}"), "kind": "point", "view_id": format!("d{}", 1 + i % 63),
"category_id": "c", "laterality": "left", "geometry": { "type": "circle", "cx": 1.25, "cy": 2.5, "r": 0.5 },
"review_status": "reviewed", "name": name("Point"), "finding_zone_id": format!("z{}", i % 64),
"vertebral_region_code": null }));
}
doc["views"] = Value::Array(views);
doc["annotations"] = Value::Array(annotations);
doc["finding_zones"] = Value::Array(zones);
doc
}
fn chain_reviewed(levels: usize) -> Value {
let mut node =
json!({ "id": format!("c{levels}"), "name": name("N"), "review_status": "reviewed" });
for level in (1..levels).rev() {
node = json!({ "id": format!("c{level}"), "name": name("N"), "review_status": "reviewed", "children": [node] });
}
node
}
/// The framed input of `document` drawn on `SHEET_DRAWING`, the document also as its base
/// (the base path is traced too); empty on a framing error.
pub fn sheet_frame(document: &Value) -> Vec<u8> {
sheet_frame_on(document, SHEET_DRAWING.as_bytes())
}
/// The same framed input with `drawing` as the main view's drawing, its row matching its
/// bytes (size and sha256), so the core reads it.
pub fn sheet_frame_on(document: &Value, drawing: &[u8]) -> Vec<u8> {
let text = document.to_string();
let sha256 = sha256_hex(drawing);
let input = VerdictInput {
binding: sheet_binding(),
document: &text,
base_document: Some(&text),
drawings: vec![VerdictDrawing {
asset_id: SHEET_ASSET,
sha256: &sha256,
byte_size: drawing.len() as u64,
bytes: Some(drawing),
}],
};
verify_frame::encode(&input).unwrap_or_default()
}
/// The server cap on a document text and on one drawing (2 MiB each, contract §12.2).
pub const DOCUMENT_CAP_BYTES: usize = 2 * 1024 * 1024;
const MIB: usize = 1024 * 1024;
/// Elements of the filler of a large drawing (the root and the closing path come on top,
/// well under the reader's 20 000).
const FILLER_PATHS: usize = 10_000;
/// `octet_length(value::jsonb::text)`'s spelling of `value`: `": "` after a key, `", "`
/// between members and elements (`core::domain::sheet::size`). Exact for the fixtures, whose
/// strings carry no control character.
pub fn pg_text(value: &Value) -> String {
match value {
Value::Array(items) => {
let parts: Vec<String> = items.iter().map(pg_text).collect();
format!("[{}]", parts.join(", "))
}
Value::Object(map) => {
let parts: Vec<String> = map
.iter()
.map(|(key, item)| format!("{}: {}", Value::from(key.as_str()), pg_text(item)))
.collect();
format!("{{{}}}", parts.join(", "))
}
other => other.to_string(),
}
}
/// The asset id of the `index`-th drawing of the large fixtures.
pub fn sheet_asset_id(index: usize) -> String {
format!("11111111-2222-4333-8444-{index:012}")
}
/// A document whose main view and `assets - 1` detail views each draw on their own asset
/// (`sheet_asset_id(0..assets)`), as the `pg_text` of exactly `target_bytes` bytes: the
/// attribution notes are the filler. A target below the unpadded size (0 for none) gives the
/// unpadded document.
pub fn sheet_document_text(assets: usize, target_bytes: usize) -> String {
let mut doc = sheet_document();
let mut views = vec![
json!({ "id": "main", "kind": "main", "name": name("V"), "svg_asset_id": sheet_asset_id(0), "view_box": null }),
];
let mut annotations = Vec::new();
for i in 1..assets {
views.push(
json!({ "id": format!("d{i}"), "kind": "detail", "name": name("D"),
"svg_asset_id": sheet_asset_id(i), "view_box": null, "parent_view_id": "main" }),
);
annotations.push(json!({ "id": format!("t{i}"), "kind": "detail_trigger", "view_id": "main", "category_id": "c",
"laterality": "unpaired", "geometry": { "type": "polygon", "points": [[0, 0], [1, 0], [1, 1]] },
"review_status": "reviewed", "name": null, "opens_view_id": format!("d{i}") }));
}
if let Some(list) = doc["annotations"].as_array_mut() {
list.extend(annotations);
}
doc["views"] = Value::Array(views);
doc["attribution"]["notes"] = Value::from("n");
let unpadded = pg_text(&doc).len();
let pad = target_bytes.saturating_sub(unpadded);
doc["attribution"]["notes"] = Value::from("n".repeat(1 + pad));
pg_text(&doc)
}
/// A drawing of exactly `size` bytes in its stored form: the prolog, a 10 × 10 root, 10 000
/// `<path d="M0 0L5 5"/>` and a last path whose `d` ends in as many spaces as `size` needs.
/// Below its fixed part (about 210 KB) it returns the unpadded drawing.
pub fn drawing_of_size(size: usize) -> Vec<u8> {
let head = concat!(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n",
r#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10">"#
);
let path = r#"<path d="M0 0L5 5"/>"#;
let tail = "</svg>";
let fixed = head.len() + (FILLER_PATHS + 1) * path.len() + tail.len();
let mut out = String::with_capacity(size.max(fixed));
out.push_str(head);
out.push_str(&path.repeat(FILLER_PATHS));
out.push_str(&format!(
r#"<path d="M0 0L5 5{}"/>"#,
" ".repeat(size.saturating_sub(fixed))
));
out.push_str(tail);
out.into_bytes()
}
/// A framed input on the large fixtures: `document` (and `base`) as given, the drawings on
/// `sheet_asset_id(0..)` in order, each row matching its bytes.
pub fn large_frame(document: &str, base: Option<&str>, drawings: &[Vec<u8>]) -> Vec<u8> {
let ids: Vec<String> = (0..drawings.len()).map(sheet_asset_id).collect();
let hashes: Vec<String> = drawings.iter().map(|d| sha256_hex(d)).collect();
let rows = drawings
.iter()
.enumerate()
.map(|(i, bytes)| VerdictDrawing {
asset_id: &ids[i],
sha256: &hashes[i],
byte_size: bytes.len() as u64,
bytes: Some(bytes),
})
.collect();
let input = VerdictInput {
binding: sheet_binding(),
document,
base_document: base,
drawings: rows,
};
verify_frame::encode(&input).unwrap_or_default()
}
/// The input at the maximum the policy allows: document and base of 2 097 152 bytes, four
/// drawings of 2 MiB, 2 MiB, 1 MiB and 1 MiB (6 291 456 in all).
pub fn verify_max_frame() -> Vec<u8> {
let document = sheet_document_text(4, DOCUMENT_CAP_BYTES);
let sizes = [2 * MIB, 2 * MIB, MIB, MIB];
let drawings: Vec<Vec<u8>> = sizes.into_iter().map(drawing_of_size).collect();
large_frame(&document, Some(&document), &drawings)
}
/// Four drawings of 2 MiB (8 MiB, over the 6 MiB total), no base: the frame stays under the
/// child's input cap.
pub fn beyond_total_frame() -> Vec<u8> {
let drawings: Vec<Vec<u8>> = (0..4).map(|_| drawing_of_size(2 * MIB)).collect();
large_frame(&sheet_document_text(4, 0), None, &drawings)
}
/// Five small drawings, one over the count cap.
pub fn beyond_count_frame() -> Vec<u8> {
let drawings: Vec<Vec<u8>> = (0..5).map(|_| SHEET_DRAWING.as_bytes().to_vec()).collect();
large_frame(&sheet_document_text(5, 0), None, &drawings)
}
/// One drawing of 2 097 153 bytes.
pub fn beyond_drawing_frame() -> Vec<u8> {
let drawings = [drawing_of_size(2 * MIB + 1)];
large_frame(&sheet_document_text(1, 0), None, &drawings)
}
/// A document of 2 097 153 bytes.
pub fn beyond_document_frame() -> Vec<u8> {
let document = sheet_document_text(1, DOCUMENT_CAP_BYTES + 1);
large_frame(&document, None, &[SHEET_DRAWING.as_bytes().to_vec()])
}
/// Writes one named fixture on stdout (`faunosteo-worker fixture <name>`).
pub fn by_name(name: &str) -> Option<Vec<u8>> {
Some(match name {
"png" => png(800, 600),
"jpeg" => jpeg(640, 480),
"webp" => webp(300, 700),
"big-jpeg" => jpeg(4096, 4096),
// Same pixel budget as the JPEG but compressible (4096 × 2048 of this gradient
// weighed more than the 5 MiB input cap).
"big-png" => png(3000, 3000),
"tiny" => png(32, 32),
"huge-header" => png_header_only(20_000, 20_000),
"iccp-bomb" => png_iccp_bomb(300 << 20),
"gif" => gif(),
"truncated" => truncated_png(),
"verify-clean" => sheet_frame(&sheet_document()),
"verify-caps" => sheet_frame(&sheet_document_at_caps()),
"verify-max" => verify_max_frame(),
_ => return None,
})
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
use super::*;
use crate::verify;
use faunosteo_core::domain::js::parse_json;
use faunosteo_core::domain::sheet::size::document_text_bytes;
fn verdict_of(frame: &[u8]) -> Value {
serde_json::from_slice(&verify::process(frame).unwrap()).unwrap()
}
fn assert_caps_failure(frame: &[u8], cap: &str) {
let verdict = verdict_of(frame);
assert_eq!(verdict["outcome"], "failed", "{}", verdict["failures"]);
assert_eq!(verdict["failure_code"], "verification.validation.caps");
let exceeded = verdict["caps"]["exceeded"].to_string();
assert!(exceeded.contains(cap), "{exceeded}");
}
#[test]
fn the_padded_document_measures_as_the_server_does() {
let text = sheet_document_text(4, DOCUMENT_CAP_BYTES);
assert_eq!(text.len(), DOCUMENT_CAP_BYTES);
let value = parse_json(&text).unwrap();
assert_eq!(document_text_bytes(&value), DOCUMENT_CAP_BYTES as u64);
}
#[test]
fn the_large_drawings_have_their_exact_size() {
for size in [2 * MIB, 2 * MIB + 1, MIB] {
assert_eq!(drawing_of_size(size).len(), size);
}
}
#[test]
fn the_maximum_input_passes_with_its_exact_sizes() {
let frame = verify_max_frame();
let decoded = verify_frame::decode(&frame).unwrap();
assert_eq!(decoded.document.len(), 2_097_152);
assert_eq!(decoded.base.map(str::len), Some(2_097_152));
let sizes: Vec<usize> = decoded
.drawing_bytes
.iter()
.map(|b| b.unwrap().len())
.collect();
assert_eq!(sizes, [2_097_152, 2_097_152, 1_048_576, 1_048_576]);
assert_eq!(sizes.iter().sum::<usize>(), 6_291_456);
let verdict = verdict_of(&frame);
assert_eq!(verdict["outcome"], "passed", "{}", verdict["failures"]);
assert_eq!(verdict["document_bytes"], 2_097_152);
}
#[test]
fn four_drawings_over_the_total_fail_as_caps() {
assert_caps_failure(&beyond_total_frame(), "drawings_total_bytes");
}
#[test]
fn five_drawings_fail_as_caps() {
assert_caps_failure(&beyond_count_frame(), "drawings");
}
#[test]
fn a_drawing_one_byte_over_fails_as_caps() {
assert_caps_failure(&beyond_drawing_frame(), "drawing_bytes");
}
#[test]
fn a_document_one_byte_over_fails_as_caps() {
assert_caps_failure(&beyond_document_frame(), "document_bytes");
}
}