246 lines
10 KiB
Rust
246 lines
10 KiB
Rust
//! 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()
|
||
}
|
||
|
||
/// 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()),
|
||
_ => return None,
|
||
})
|
||
}
|