feat(domain): R4.5a PNG gate (pngIssue port) and UPNG-rule decoder (O6 108/108)
The branding gate in pngIssue's order; the decoder reproduces UPNG's decode and toRGBA8 (typed-array semantics, first-row filter rewrite, the Average first-row pre-pass at absolute offsets, the 16-bit grey tRNS key at off + x, 16-bit high byte, palette tRNS by declared length), pdf-lib's alpha drop; caps checked before any allocation; crafted files refused (animated, text chunks without NUL, broken streams) where UPNG spun or threw. 108 O6 rows equal; 50 hostile files return in under 20 ms.
This commit is contained in:
1 parent
d420f67352
commit
d7984449ed
2 files changed
+1439
-2
No files matched your search
File diff suppressed because it is too large.
Load diff
@@ -1 +1,258 @@
|
||||
//! R4.5 placeholder, written by its track.
|
||||
//! O6: the branding gate `png_issue` against `pngIssue` and the decoder `decode_png` against
|
||||
//! pdf-lib 1.17.1 `embedPng` (UPNG decode, `toRGBA8`, alpha split), frozen in
|
||||
//! `tests/oracles/r4/png.json`.
|
||||
#![allow(clippy::disallowed_methods, clippy::unwrap_used, clippy::expect_used)]
|
||||
|
||||
mod common;
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use common::r4::{r4_oracle, repo_root, sha256_hex};
|
||||
use faunosteo_core::pdf::write::png::{
|
||||
PNG_MAX_PIXELS, PNG_MAX_RAW_BYTES, PNG_MAX_SIDE, PngDecodeError, decode_png, png_issue,
|
||||
};
|
||||
use serde_json::Value;
|
||||
|
||||
/// The 108 rows of O6.
|
||||
fn cases() -> Vec<Value> {
|
||||
let oracle = r4_oracle("png.json");
|
||||
let cases = oracle["cases"].as_array().unwrap().clone();
|
||||
assert_eq!(cases.len(), 108, "O6 row count");
|
||||
cases
|
||||
}
|
||||
|
||||
/// The bytes of a row, checked against the length and digest the oracle recorded.
|
||||
fn case_bytes(case: &Value) -> Vec<u8> {
|
||||
let file = case["file"].as_str().unwrap();
|
||||
let bytes = std::fs::read(repo_root().join(file)).unwrap_or_else(|e| panic!("{file}: {e}"));
|
||||
assert_eq!(
|
||||
bytes.len() as u64,
|
||||
case["bytes"].as_u64().unwrap(),
|
||||
"{file}: length"
|
||||
);
|
||||
assert_eq!(
|
||||
sha256_hex(&bytes),
|
||||
case["sha256"].as_str().unwrap(),
|
||||
"{file}: digest"
|
||||
);
|
||||
bytes
|
||||
}
|
||||
|
||||
fn name(case: &Value) -> &str {
|
||||
case["name"].as_str().unwrap()
|
||||
}
|
||||
|
||||
/// The pdf-lib `PngType` of the colour type in the first IHDR.
|
||||
fn png_type(bytes: &[u8]) -> &'static str {
|
||||
match bytes[25] {
|
||||
0 => "Greyscale",
|
||||
2 => "Truecolour",
|
||||
3 => "IndexedColour",
|
||||
4 => "GreyscaleWithAlpha",
|
||||
6 => "TruecolourWithAlpha",
|
||||
_ => "unknown",
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_caps_are_the_oracle_caps() {
|
||||
let oracle = r4_oracle("png.json");
|
||||
assert_eq!(oracle["caps"]["side"].as_u64(), Some(PNG_MAX_SIDE));
|
||||
assert_eq!(oracle["caps"]["pixels"].as_u64(), Some(PNG_MAX_PIXELS));
|
||||
assert_eq!(oracle["caps"]["rawBytes"].as_u64(), Some(PNG_MAX_RAW_BYTES));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_o6_gate_verdict_matches_png_issue() {
|
||||
let mut failures = Vec::new();
|
||||
for case in cases() {
|
||||
let got = png_issue(&case_bytes(&case)).map(|issue| issue.as_str());
|
||||
if got != case["gate"].as_str() {
|
||||
failures.push(format!(
|
||||
"{}: node {}, rust {got:?}",
|
||||
name(&case),
|
||||
case["gate"]
|
||||
));
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
failures.is_empty(),
|
||||
"O6 gate rows differ:\n{}",
|
||||
failures.join("\n")
|
||||
);
|
||||
}
|
||||
|
||||
/// One decoded row against the oracle: sizes, plane lengths and digests, alpha kept or not.
|
||||
fn decode_mismatch(case: &Value, bytes: &[u8]) -> Option<String> {
|
||||
let expected = &case["decode"];
|
||||
let got = match decode_png(bytes) {
|
||||
Ok(got) => got,
|
||||
Err(error) => return Some(format!("{}: rust error {error:?}", name(case))),
|
||||
};
|
||||
assert_eq!(expected["bitsPerComponent"], 8, "{}", name(case));
|
||||
assert_eq!(expected["colorSpace"], "DeviceRGB", "{}", name(case));
|
||||
assert_eq!(expected["pngType"], png_type(bytes), "{}", name(case));
|
||||
let alpha = got.alpha.as_deref().map(sha256_hex);
|
||||
let facts = [
|
||||
(u64::from(got.width), expected["width"].as_u64().unwrap()),
|
||||
(u64::from(got.height), expected["height"].as_u64().unwrap()),
|
||||
(got.rgb.len() as u64, expected["rgbBytes"].as_u64().unwrap()),
|
||||
];
|
||||
let sizes_equal = facts.iter().all(|(rust, node)| rust == node);
|
||||
let rgb_equal = sha256_hex(&got.rgb) == expected["rgbSha256"].as_str().unwrap();
|
||||
let alpha_equal = alpha.as_deref() == expected["alphaSha256"].as_str();
|
||||
let pixels = u64::from(got.width) * u64::from(got.height);
|
||||
let alpha_length = got
|
||||
.alpha
|
||||
.as_ref()
|
||||
.is_none_or(|plane| plane.len() as u64 == pixels);
|
||||
(!(sizes_equal && rgb_equal && alpha_equal && alpha_length)).then(|| {
|
||||
format!(
|
||||
"{}: node {expected}, rust {}x{} rgb {} alpha {alpha:?}",
|
||||
name(case),
|
||||
got.width,
|
||||
got.height,
|
||||
sha256_hex(&got.rgb)
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Default, Debug)]
|
||||
struct GroupCount {
|
||||
rows: u32,
|
||||
decoded: u32,
|
||||
errors: u32,
|
||||
not_run: u32,
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_o6_decode_matches_pdf_lib() {
|
||||
let mut failures = Vec::new();
|
||||
let mut groups: BTreeMap<String, GroupCount> = BTreeMap::new();
|
||||
for case in cases() {
|
||||
let bytes = case_bytes(&case);
|
||||
let count = groups
|
||||
.entry(case["group"].as_str().unwrap().to_owned())
|
||||
.or_default();
|
||||
count.rows += 1;
|
||||
let expected = &case["decode"];
|
||||
if expected.is_null() {
|
||||
count.not_run += 1;
|
||||
} else if expected.get("error").is_some() {
|
||||
count.errors += 1;
|
||||
if let Ok(got) = decode_png(&bytes) {
|
||||
failures.push(format!(
|
||||
"{}: node {expected}, rust {}x{}",
|
||||
name(&case),
|
||||
got.width,
|
||||
got.height
|
||||
));
|
||||
}
|
||||
} else {
|
||||
count.decoded += 1;
|
||||
failures.extend(decode_mismatch(&case, &bytes));
|
||||
}
|
||||
}
|
||||
for (group, count) in &groups {
|
||||
println!("O6 {group}: {count:?}");
|
||||
}
|
||||
assert!(
|
||||
failures.is_empty(),
|
||||
"O6 decode rows differ:\n{}",
|
||||
failures.join("\n")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_error_rows_fail_in_rust_with_their_reason() {
|
||||
for case in cases()
|
||||
.iter()
|
||||
.filter(|case| case["decode"].get("error").is_some())
|
||||
{
|
||||
let outcome = decode_png(&case_bytes(case));
|
||||
println!(
|
||||
"O6 error {}: node {}, rust {outcome:?}",
|
||||
name(case),
|
||||
case["decode"]["error"]
|
||||
);
|
||||
assert_eq!(
|
||||
outcome.err(),
|
||||
Some(PngDecodeError::Palette),
|
||||
"{}",
|
||||
name(case)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The hostile rows UPNG was never run on (the gate refuses them; UPNG may never return):
|
||||
/// the Rust decoder returns, Ok or Err, within a second and never panics.
|
||||
#[test]
|
||||
fn the_rows_upng_never_ran_return_within_a_second() {
|
||||
let mut slow = Vec::new();
|
||||
for case in cases().iter().filter(|case| case["decode"].is_null()) {
|
||||
let bytes = case_bytes(case);
|
||||
let started = Instant::now();
|
||||
let outcome = decode_png(&bytes).map(|got| (got.width, got.height));
|
||||
let elapsed = started.elapsed();
|
||||
println!("O6 not run {}: rust {outcome:?} in {elapsed:?}", name(case));
|
||||
if elapsed > Duration::from_secs(1) {
|
||||
slow.push(format!("{}: {elapsed:?}", name(case)));
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
slow.is_empty(),
|
||||
"slow hostile decodes:\n{}",
|
||||
slow.join("\n")
|
||||
);
|
||||
}
|
||||
|
||||
/// A PNG of one IHDR (zero CRCs, as the security suite writes them), an IDAT holding an
|
||||
/// empty stored zlib stream, and IEND.
|
||||
fn header_only_png(width: u32, height: u32, depth: u8, colour_type: u8) -> Vec<u8> {
|
||||
let mut bytes = vec![0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
|
||||
let chunk = |bytes: &mut Vec<u8>, kind: &[u8; 4], data: &[u8]| {
|
||||
bytes.extend_from_slice(&(data.len() as u32).to_be_bytes());
|
||||
bytes.extend_from_slice(kind);
|
||||
bytes.extend_from_slice(data);
|
||||
bytes.extend_from_slice(&[0; 4]);
|
||||
};
|
||||
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(&[depth, colour_type, 0, 0, 0]);
|
||||
chunk(&mut bytes, b"IHDR", &ihdr);
|
||||
chunk(
|
||||
&mut bytes,
|
||||
b"IDAT",
|
||||
&[0x78, 0x01, 0x01, 0x00, 0x00, 0xff, 0xff, 0, 0, 0, 1],
|
||||
);
|
||||
chunk(&mut bytes, b"IEND", &[]);
|
||||
bytes
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_decoder_refuses_over_the_caps_before_allocating() {
|
||||
let refused = [
|
||||
(4097, 4096, 8, 0),
|
||||
(8193, 1, 8, 0),
|
||||
(1, 8193, 8, 0),
|
||||
(4096, 4096, 8, 6),
|
||||
(4096, 4096, 8, 0),
|
||||
(0, 1, 8, 0),
|
||||
];
|
||||
for (width, height, depth, colour_type) in refused {
|
||||
let started = Instant::now();
|
||||
let outcome = decode_png(&header_only_png(width, height, depth, colour_type));
|
||||
assert_eq!(outcome, Err(PngDecodeError::Dimensions), "{width}x{height}");
|
||||
assert!(
|
||||
started.elapsed() < Duration::from_millis(50),
|
||||
"{width}x{height}"
|
||||
);
|
||||
}
|
||||
// At the side cap the size check passes; the empty stream leaves UPNG's buffer short, and
|
||||
// every sample read past it is `undefined`: an opaque black row.
|
||||
let at_the_cap = decode_png(&header_only_png(8192, 1, 8, 0)).unwrap();
|
||||
assert_eq!((at_the_cap.width, at_the_cap.alpha), (8192, None));
|
||||
assert!(at_the_cap.rgb.iter().all(|&byte| byte == 0));
|
||||
}
|
||||
Reference in new issue
Block a user