mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-25 20:14:31 +01:00
Gate-sized cases for slow non-UI tests; full sizes and every case nightly
Boundary tests set by a production constant check a small limit through a private seam that takes it (b64 decode, drawingml table normalize, openpgp verify), with the real constant nightly; captions and jbig2 check their full-size boundaries nightly. Sweeps run every divisor-th case at the gate (develop balanced highlights and thin line, jpeg low-memory tokens, png streamed rows, mxf extreme fields, pdf crypt proptests), the fax bomb guard page is wider and shorter, the resample bound pulls a shorter block, the nef measured frames are read through probe_info, and local tone compares 64 and 256 pixels.
This commit is contained in:
1 parent
3656e8aaa4
commit
d402a1d71b
21 files changed
+205
-111
No files matched your search
Generated
+3
@@ -2375,6 +2375,7 @@ dependencies = [
|
||||
"craft-geom",
|
||||
"craft-raw",
|
||||
"craft-render-parity",
|
||||
"craft-testkit",
|
||||
"proptest",
|
||||
"rayon",
|
||||
"serde",
|
||||
@@ -2533,6 +2534,7 @@ name = "craft-drawingml"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"craft-testkit",
|
||||
"craft-xml",
|
||||
"kurbo",
|
||||
"log",
|
||||
@@ -3127,6 +3129,7 @@ dependencies = [
|
||||
name = "craft-jpeg"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"craft-testkit",
|
||||
"jpeg-decoder",
|
||||
"jpeg-encoder 0.6.1",
|
||||
"rayon",
|
||||
|
||||
@@ -418,21 +418,20 @@ mod tests {
|
||||
/// returns `MAX_RESAMPLE_BLOCK` frames.
|
||||
#[test]
|
||||
fn source_held_and_block_length_are_bounded() {
|
||||
let t0 = std::time::Instant::now();
|
||||
// At this ratio a pull holds about 42 output frames' worth of source, so 64 frames take two pulls; each output
|
||||
// frame pulls 1,536 source frames of 64 channels, so nightly runs a longer block.
|
||||
let frames = if craft_testkit::hostile::divisor() == 1 { 1_024 } else { 64 };
|
||||
let mut r = StreamResampler::new(1_536_000, 1_000);
|
||||
let mut widest = 0;
|
||||
let out = r.process(0, 1_024, |_, frames| {
|
||||
let out = r.process(0, frames, |_, frames| {
|
||||
widest = widest.max(frames);
|
||||
vec![vec![0.5; frames]; 64]
|
||||
});
|
||||
assert_eq!((out.len(), out[0].len()), (64, 1_024));
|
||||
assert_eq!((out.len(), out[0].len()), (64, frames));
|
||||
assert!(widest <= MAX_RESAMPLE_HELD / 64, "{widest}");
|
||||
assert!(r.held.iter().map(Vec::len).sum::<usize>() <= MAX_RESAMPLE_HELD);
|
||||
eprintln!("DIAG resample wide ratio {:?}", t0.elapsed());
|
||||
let t1 = std::time::Instant::now();
|
||||
let mut r = StreamResampler::new(48_000, 48_000);
|
||||
let out = r.process(0, usize::MAX, |_, frames| vec![vec![0.5; frames]]);
|
||||
eprintln!("DIAG resample oversized block {:?}", t1.elapsed());
|
||||
assert_eq!(out[0].len(), MAX_RESAMPLE_BLOCK);
|
||||
assert!(out[0].iter().all(|&x| x == 0.5));
|
||||
}
|
||||
|
||||
@@ -18,7 +18,10 @@ fn input_over_the_size_limit_is_refused() {
|
||||
for format in Format::ALL {
|
||||
assert_eq!(parse(&big, format), Err(Error::TooLarge(MAX_INPUT)), "{format:?}");
|
||||
}
|
||||
assert!(parse(big.get(..MAX_INPUT).unwrap(), Format::Srt).is_ok());
|
||||
// Reading 64 MiB at the limit takes seconds: nightly only.
|
||||
if craft_testkit::hostile::divisor() == 1 {
|
||||
assert!(parse(big.get(..MAX_INPUT).unwrap(), Format::Srt).is_ok());
|
||||
}
|
||||
}
|
||||
|
||||
/// TTML is read without entity expansion: a document type with entities defines nothing.
|
||||
|
||||
@@ -24,4 +24,5 @@ rayon = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
craft-render-parity = { workspace = true }
|
||||
craft-testkit = { workspace = true }
|
||||
proptest = { workspace = true }
|
||||
@@ -652,7 +652,7 @@ mod tests {
|
||||
apply(&mut px, n, n, 70.0, -60.0, SRGB);
|
||||
[px[(n / 8) * n + n / 8][0], px[(3 * n / 4) * n + 3 * n / 4][0]]
|
||||
};
|
||||
let (a, b) = (at(96), at(384));
|
||||
let (a, b) = (at(64), at(256));
|
||||
assert!((a[0] - b[0]).abs() < 0.02 && (a[1] - b[1]).abs() < 0.02, "{a:?} {b:?}");
|
||||
}
|
||||
}
|
||||
@@ -163,8 +163,13 @@ fn rebuilt_ramp_is_continuous_from_the_first_clip_to_the_last() {
|
||||
/// background surrounds it.
|
||||
#[test]
|
||||
fn thin_line_without_reliable_colour_is_continuous_where_it_clips() {
|
||||
for height in [32usize, 512, 1024] {
|
||||
for width in [1usize, 4, 16] {
|
||||
// The gate runs a one-row line in 32 rows and a four-row line in 512; nightly every pair, up to 1024 rows.
|
||||
let full = craft_testkit::hostile::divisor() == 1;
|
||||
for (h, height) in [32usize, 512, 1024].into_iter().enumerate() {
|
||||
for (w, width) in [1usize, 4, 16].into_iter().enumerate() {
|
||||
if !full && (w != h || h > 1) {
|
||||
continue;
|
||||
}
|
||||
let top = (height - width) / 2;
|
||||
let (row, first) = rebuilt_ramp(top..top + width, height);
|
||||
assert_continuous(&row, first, 0.002, &format!("{width} rows of {height}"));
|
||||
|
||||
@@ -552,7 +552,9 @@ fn coloured_highlights_keep_their_brightness_at_the_edges() {
|
||||
let tubes = [([1.0f32, 0.15, 0.1], 3.5f32), ([1.0, 0.85, 0.15], 2.6), ([0.25, 1.0, 0.4], 2.0)];
|
||||
let scenes = suns.map(|(tint, level)| (tint, level, true)).into_iter().chain(tubes.map(|(tint, level)| (tint, level, false)));
|
||||
let lum = |p: [f32; 3]| 0.2126 * p[0] + 0.7152 * p[1] + 0.0722 * p[2];
|
||||
for (tint, level, sun) in scenes {
|
||||
// The gate develops every divisor-th (scene, layout) pair, a different layout per scene; nightly all of them.
|
||||
let divisor = craft_testkit::hostile::divisor();
|
||||
for (scene_index, (tint, level, sun)) in scenes.enumerate() {
|
||||
let scene_name = if sun { "sun" } else { "tube" };
|
||||
let scene = |x: f32, y: f32| {
|
||||
if sun {
|
||||
@@ -572,7 +574,10 @@ fn coloured_highlights_keep_their_brightness_at_the_edges() {
|
||||
})
|
||||
});
|
||||
let truth = |x: usize, y: usize| -> [f32; 3] { std::array::from_fn(|c| lights[c][y * w + x]) };
|
||||
for (name, cfa, method) in layouts() {
|
||||
for (layout_index, (name, cfa, method)) in layouts().into_iter().enumerate() {
|
||||
if !(scene_index + layout_index).is_multiple_of(divisor) {
|
||||
continue;
|
||||
}
|
||||
let raw = raw_of(w, h, &cfa, DAYLIGHT, truth);
|
||||
let (mut img, mask) = raw.develop_balanced_masked(method, DAYLIGHT, CLIP).unwrap();
|
||||
let mut by_value = img.clone();
|
||||
|
||||
@@ -18,4 +18,5 @@ log = "0.4"
|
||||
serde = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
craft-testkit = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
@@ -342,30 +342,42 @@ impl Table {
|
||||
}
|
||||
/// Whether [`Table::normalize`] would drop rows or columns to fit [`MAX_CELLS`].
|
||||
pub fn over_cap(&self) -> bool {
|
||||
let n = self.cols.len();
|
||||
n > MAX_CELLS || self.rows.len() > (MAX_CELLS / n.max(1)).max(1)
|
||||
self.over(MAX_CELLS)
|
||||
}
|
||||
/// What [`Table::normalize`] would leave of this table, cloning only the rows and cells that
|
||||
/// survive (an oversized table is not copied whole first).
|
||||
pub fn normalized(&self) -> Table {
|
||||
let n = self.cols.len().min(MAX_CELLS);
|
||||
let keep = (MAX_CELLS / n.max(1)).max(1);
|
||||
let rows = self.rows.iter().take(keep).map(|r| Row { height: r.height, cells: r.cells.iter().take(n).cloned().collect() }).collect();
|
||||
let mut t = Table { cols: self.cols[..n].to_vec(), rows, background: self.background.clone(), style: self.style.clone(), ..*self };
|
||||
t.normalize();
|
||||
if self.over_cap() {
|
||||
t.clip_spans();
|
||||
}
|
||||
t
|
||||
self.normalized_within(MAX_CELLS)
|
||||
}
|
||||
/// Make every row have exactly `cols.len()` cells (repair after loading). A grid over
|
||||
/// [`MAX_CELLS`] loses its last rows (and columns) first, so a file naming many rows and many
|
||||
/// columns but few cells cannot make this allocate their product.
|
||||
pub fn normalize(&mut self) {
|
||||
let truncated = self.over_cap();
|
||||
self.cols.truncate(MAX_CELLS);
|
||||
self.normalize_within(MAX_CELLS);
|
||||
}
|
||||
/// [`Table::over_cap`] for a cap of `max` cells.
|
||||
fn over(&self, max: usize) -> bool {
|
||||
let n = self.cols.len();
|
||||
self.rows.truncate((MAX_CELLS / n.max(1)).max(1));
|
||||
n > max || self.rows.len() > (max / n.max(1)).max(1)
|
||||
}
|
||||
/// [`Table::normalized`] for a cap of `max` cells.
|
||||
fn normalized_within(&self, max: usize) -> Table {
|
||||
let n = self.cols.len().min(max);
|
||||
let keep = (max / n.max(1)).max(1);
|
||||
let rows = self.rows.iter().take(keep).map(|r| Row { height: r.height, cells: r.cells.iter().take(n).cloned().collect() }).collect();
|
||||
let mut t = Table { cols: self.cols[..n].to_vec(), rows, background: self.background.clone(), style: self.style.clone(), ..*self };
|
||||
t.normalize_within(max);
|
||||
if self.over(max) {
|
||||
t.clip_spans();
|
||||
}
|
||||
t
|
||||
}
|
||||
/// [`Table::normalize`] for a cap of `max` cells.
|
||||
fn normalize_within(&mut self, max: usize) {
|
||||
let truncated = self.over(max);
|
||||
self.cols.truncate(max);
|
||||
let n = self.cols.len();
|
||||
self.rows.truncate((max / n.max(1)).max(1));
|
||||
for r in &mut self.rows {
|
||||
r.cells.resize_with(n, || Cell::new(""));
|
||||
for c in &mut r.cells {
|
||||
@@ -741,22 +753,27 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn normalize_caps_a_sparse_grid_at_max_cells() {
|
||||
let mut t = Table { cols: vec![10.0; 1000], rows: vec![Row::default(); 1000], ..Default::default() };
|
||||
t.normalize();
|
||||
assert_eq!(t.cols.len(), 1000);
|
||||
assert_eq!(t.rows.len(), MAX_CELLS / 1000);
|
||||
assert!(t.rows.iter().all(|r| r.cells.len() == 1000));
|
||||
let mut t = Table { cols: vec![1.0; MAX_CELLS + 5], rows: vec![Row::default(); 3], ..Default::default() };
|
||||
t.normalize();
|
||||
assert_eq!((t.cols.len(), t.rows.len()), (MAX_CELLS, 1));
|
||||
let wide = Table {
|
||||
cols: vec![10.0; 1000],
|
||||
rows: vec![Row { height: 1.0, cells: vec![Cell::new("x"); 1100] }; MAX_CELLS / 1000 + 1],
|
||||
..Default::default()
|
||||
};
|
||||
let mut n = wide.clone();
|
||||
n.normalize();
|
||||
assert_eq!(wide.normalized(), n);
|
||||
// At a cap 100 times smaller; nightly also at MAX_CELLS.
|
||||
let full = craft_testkit::hostile::divisor() == 1;
|
||||
for max in [MAX_CELLS / 100].into_iter().chain(full.then_some(MAX_CELLS)) {
|
||||
let cols = max / 100;
|
||||
let mut t = Table { cols: vec![10.0; cols], rows: vec![Row::default(); 1000], ..Default::default() };
|
||||
t.normalize_within(max);
|
||||
assert_eq!(t.cols.len(), cols);
|
||||
assert_eq!(t.rows.len(), max / cols);
|
||||
assert!(t.rows.iter().all(|r| r.cells.len() == cols));
|
||||
let mut t = Table { cols: vec![1.0; max + 5], rows: vec![Row::default(); 3], ..Default::default() };
|
||||
t.normalize_within(max);
|
||||
assert_eq!((t.cols.len(), t.rows.len()), (max, 1));
|
||||
let wide = Table {
|
||||
cols: vec![10.0; cols],
|
||||
rows: vec![Row { height: 1.0, cells: vec![Cell::new("x"); cols + cols / 10] }; max / cols + 1],
|
||||
..Default::default()
|
||||
};
|
||||
let mut n = wide.clone();
|
||||
n.normalize_within(max);
|
||||
assert_eq!(wide.normalized_within(max), n);
|
||||
}
|
||||
let mut t = Table::new(4, 4, 400.0, 30.0);
|
||||
t.normalize();
|
||||
assert_eq!((t.n_rows(), t.n_cols()), (4, 4));
|
||||
|
||||
@@ -2324,6 +2324,9 @@ mod streamed_tests {
|
||||
/// gives, at 8 and 16 bits, with a profile, resolution, text and XMP.
|
||||
#[test]
|
||||
fn streamed_rows_match_the_whole_image_encoder() {
|
||||
// The gate runs every divisor-th (image, level, bands) case, nightly all twelve.
|
||||
let divisor = craft_media_testkit::hostile::divisor();
|
||||
let mut case = 0usize;
|
||||
for (layout, sample, ch, bytes, w, h) in
|
||||
[(ChannelLayout::Rgba, SampleType::U8, 4usize, 1usize, 1024u32, 1025u32), (ChannelLayout::Rgb, SampleType::U16, 3, 2, 1024, 700)]
|
||||
{
|
||||
@@ -2339,9 +2342,20 @@ mod streamed_tests {
|
||||
.with_meta(meta);
|
||||
for level in [PngCompression::Fast, PngCompression::Default] {
|
||||
let opts = EncodeOptions { png_compression: level, ..Default::default() };
|
||||
let one_band = [h];
|
||||
let cases: Vec<&[u32]> = [&[1u32, 77, 300][..], &[256, 256, 256], &one_band]
|
||||
.into_iter()
|
||||
.filter(|_| {
|
||||
case += 1;
|
||||
(case - 1).is_multiple_of(divisor)
|
||||
})
|
||||
.collect();
|
||||
if cases.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let whole = crate::encode(&img, Format::Png, &opts).unwrap();
|
||||
let (head, zlib, _) = split(&whole);
|
||||
for heights in [&[1u32, 77, 300][..], &[256, 256, 256], &[h]] {
|
||||
for heights in cases {
|
||||
let png = streamed(&img, heights, &opts);
|
||||
let (h2, z2, _) = split(&png);
|
||||
assert!(h2 == head, "{layout:?} {level:?} {heights:?}: header chunks differ");
|
||||
|
||||
@@ -340,24 +340,28 @@ fn blank_g4(h: u32) -> Vec<u8> {
|
||||
fn a_blank_fax_page_wider_than_4096_px_passes_the_bomb_guard() {
|
||||
// A blank page codes each row in one bit, so a row wider than 4096 pixels is past 4096:1: it
|
||||
// must open, with or without the metadata and other pages that used to raise the bound. The
|
||||
// page has enough rows to hold more than the guard's fixed 1 MiB of slack.
|
||||
for (w, h) in [(20_000u32, 800u32)] {
|
||||
let mut d = Dir { entries: base(w, h, 1, 1, 0), chunks: vec![blank_g4(h)], tiled: false }.tag(278, LONG, &[u64::from(h)]);
|
||||
d.entries.retain(|e| e.0 != 259);
|
||||
let d = d.tag(259, SHORT, &[4]);
|
||||
let pages: Vec<Dir> = (0..2).map(|_| d.clone()).collect();
|
||||
for (what, bytes) in
|
||||
[("one page", build(true, false, std::slice::from_ref(&d), &[0]).bytes), ("two pages", build(true, false, &pages, &[0, 1]).bytes)]
|
||||
{
|
||||
let img = decode(&bytes).unwrap_or_else(|e| panic!("{w}x{h} {what}: {e}"));
|
||||
assert_eq!(img.dimensions(), (w, h), "{what}");
|
||||
assert!(img.data().iter().all(|&v| v == 255), "{w}x{h} {what}: not white");
|
||||
}
|
||||
}
|
||||
let mut d = Dir { entries: base(20_000, 800, 1, 1, 0), chunks: vec![blank_g4(800)], tiled: false }.tag(278, LONG, &[800]);
|
||||
// page has enough rows to hold more than the guard's fixed 1 MiB of slack: (w - 4096) * h / 8
|
||||
// bytes past 4096:1, so a wider page needs fewer pixels. The gate decodes the one-page file;
|
||||
// nightly also the two-page file and the banded decode.
|
||||
let full = craft_media_testkit::hostile::divisor() == 1;
|
||||
let (w, h) = (60_000u32, 160u32);
|
||||
let mut d = Dir { entries: base(w, h, 1, 1, 0), chunks: vec![blank_g4(h)], tiled: false }.tag(278, LONG, &[u64::from(h)]);
|
||||
d.entries.retain(|e| e.0 != 259);
|
||||
let bytes = build(true, false, &[d.tag(259, SHORT, &[4])], &[0]).bytes;
|
||||
assert!(banded(&bytes, None, &Limits::banded(), true).unwrap().data() == decode(&bytes).unwrap().data());
|
||||
let d = d.tag(259, SHORT, &[4]);
|
||||
let one_page = build(true, false, std::slice::from_ref(&d), &[0]).bytes;
|
||||
let mut files = vec![("one page", one_page.clone())];
|
||||
if full {
|
||||
let pages: Vec<Dir> = (0..2).map(|_| d.clone()).collect();
|
||||
files.push(("two pages", build(true, false, &pages, &[0, 1]).bytes));
|
||||
}
|
||||
for (what, bytes) in files {
|
||||
let img = decode(&bytes).unwrap_or_else(|e| panic!("{w}x{h} {what}: {e}"));
|
||||
assert_eq!(img.dimensions(), (w, h), "{what}");
|
||||
assert!(img.data().iter().all(|&v| v == 255), "{w}x{h} {what}: not white");
|
||||
}
|
||||
if full {
|
||||
assert!(banded(&one_page, None, &Limits::banded(), true).unwrap().data() == decode(&one_page).unwrap().data());
|
||||
}
|
||||
// Still a bound: 100 bytes of Group 4 can't hold that page (4096:1 for Group 3, which is not decoded).
|
||||
for compression in [4, 3] {
|
||||
let mut d = Dir { entries: base(7016, 4961, 1, 1, 0), chunks: vec![vec![0x80; 100]], tiled: false }.tag(278, LONG, &[4961]);
|
||||
|
||||
@@ -16,6 +16,7 @@ thiserror = { workspace = true }
|
||||
rayon = { workspace = true, optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
craft-testkit = { workspace = true }
|
||||
# Reference encoder and baseline decoder for the comparison tests.
|
||||
jpeg-encoder = "0.6"
|
||||
zune-jpeg = "0.5"
|
||||
|
||||
@@ -42,12 +42,19 @@ fn compare(src: &[u8], w: usize, h: usize, ch: usize, q: u8, sub: ChromaSubsampl
|
||||
|
||||
#[test]
|
||||
fn all_sampling_and_channels_match_retained_tokens_byte_for_byte() {
|
||||
// The gate compares every divisor-th case, so every size, channel count, subsampling and quality still runs;
|
||||
// nightly compares them all.
|
||||
let divisor = craft_testkit::hostile::divisor();
|
||||
let mut case = 0usize;
|
||||
for (w, h) in [(1, 1), (7, 9), (17, 31), (33, 65), (17, 1025)] {
|
||||
for ch in [1, 3, 4] {
|
||||
let src = noise(w * h * ch);
|
||||
for sub in [ChromaSubsampling::S444, ChromaSubsampling::S422, ChromaSubsampling::S420] {
|
||||
for q in [0, 1, 25, 50, 90, 100, 255] {
|
||||
compare(&src, w, h, ch, q, sub, &[]);
|
||||
case += 1;
|
||||
if case.is_multiple_of(divisor) {
|
||||
compare(&src, w, h, ch, q, sub, &[]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -159,13 +159,15 @@ fn extreme(f: &mut [u8], at: usize, len: usize, r: &mut Rng) {
|
||||
fn extreme_metadata_index_and_partition_fields_never_panic() {
|
||||
let mut r = Rng(0x00C0_FFEE_1234_5678);
|
||||
let mut opened = 0;
|
||||
// The gate damages each base the hostile divisor's fraction of the rounds; nightly all 600.
|
||||
let rounds = 600 / craft_media_testkit::hostile::divisor();
|
||||
for base in bases() {
|
||||
assert!(exercise(&base), "the unchanged file opens");
|
||||
// local sets (header metadata, index table segments) and partition packs
|
||||
let sets: Vec<(usize, usize, usize)> =
|
||||
klvs(&base).into_iter().filter(|&(k, _, len)| len > 0 && base[k + 4] == 0x02 && matches!(base[k + 5], 0x53 | 0x05)).collect();
|
||||
assert!(sets.len() > 10, "{} packets to damage", sets.len());
|
||||
for round in 0..600 {
|
||||
for round in 0..rounds {
|
||||
let mut f = base.clone();
|
||||
for _ in 0..1 + round % 3 {
|
||||
let (k, v, len) = sets[r.below(sets.len())];
|
||||
@@ -184,7 +186,7 @@ fn extreme_metadata_index_and_partition_fields_never_panic() {
|
||||
opened += usize::from(exercise(&f));
|
||||
}
|
||||
}
|
||||
assert!(opened > 1200, "most damaged files still open and are read: {opened}");
|
||||
assert!(opened > 2 * rounds, "most damaged files still open and are read: {opened} of {rounds} rounds a base");
|
||||
}
|
||||
|
||||
/// KLV lengths that lie (longer than the file, the largest BER lengths, zero) and keys that stop
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
use pgp::crypto::hash::HashAlgorithm;
|
||||
|
||||
use crate::fixtures::*;
|
||||
use crate::{CantCheck, Checked, Coverage, Fingerprint, KeyRing, MAX_MESSAGE, NotVerified, Outcome, verify};
|
||||
use crate::{CantCheck, Checked, Coverage, Fingerprint, KeyRing, MAX_MESSAGE, NotVerified, Outcome, verify, verify_within};
|
||||
|
||||
const ALICE: &str = "Alice <alice@example.org>";
|
||||
|
||||
@@ -120,17 +120,21 @@ fn an_armour_header_other_than_hash_or_an_unescaped_dash_line_is_unreadable() {
|
||||
|
||||
#[test]
|
||||
fn a_signed_message_too_large_to_check_says_so() {
|
||||
let mut big = signed_message(&secret(ALICE, Make::default()), HashAlgorithm::Sha256);
|
||||
big.resize(MAX_MESSAGE + 1, b'a');
|
||||
let checked = verify(&big, ALICE, &KeyRing::new(), LATER, yes).unwrap();
|
||||
assert!(matches!(checked.outcome, Outcome::CantCheck { why: CantCheck::TooLarge, .. }));
|
||||
// Inline-signed, the block found anywhere in it.
|
||||
let mut big = plain(ALICE, "7bit", &"a".repeat(1 << 20));
|
||||
big.extend_from_slice(b"\r\n-----BEGIN PGP SIGNED MESSAGE-----\r\n");
|
||||
big.resize(MAX_MESSAGE + 1, b'a');
|
||||
assert!(verify(&big, ALICE, &KeyRing::new(), LATER, yes).is_some());
|
||||
// Not signed at all: nothing to say.
|
||||
let mut big = plain(ALICE, "7bit", "Just text.\r\n");
|
||||
big.resize(MAX_MESSAGE + 1, b'a');
|
||||
assert_eq!(verify(&big, ALICE, &KeyRing::new(), LATER, yes), None);
|
||||
// At a 64 KiB limit; nightly also at MAX_MESSAGE.
|
||||
let full = craft_testkit::hostile::divisor() == 1;
|
||||
for max in [64 << 10].into_iter().chain(full.then_some(MAX_MESSAGE)) {
|
||||
let mut big = signed_message(&secret(ALICE, Make::default()), HashAlgorithm::Sha256);
|
||||
big.resize(max + 1, b'a');
|
||||
let checked = verify_within(&big, max, ALICE, &KeyRing::new(), LATER, yes).unwrap();
|
||||
assert!(matches!(checked.outcome, Outcome::CantCheck { why: CantCheck::TooLarge, .. }));
|
||||
// Inline-signed, the block found anywhere in it.
|
||||
let mut big = plain(ALICE, "7bit", &"a".repeat(max / 2));
|
||||
big.extend_from_slice(b"\r\n-----BEGIN PGP SIGNED MESSAGE-----\r\n");
|
||||
big.resize(max + 1, b'a');
|
||||
assert!(verify_within(&big, max, ALICE, &KeyRing::new(), LATER, yes).is_some());
|
||||
// Not signed at all: nothing to say.
|
||||
let mut big = plain(ALICE, "7bit", "Just text.\r\n");
|
||||
big.resize(max + 1, b'a');
|
||||
assert_eq!(verify_within(&big, max, ALICE, &KeyRing::new(), LATER, yes), None);
|
||||
}
|
||||
}
|
||||
@@ -101,7 +101,19 @@ pub(crate) fn guard<T>(f: impl FnOnce() -> T) -> Option<T> {
|
||||
/// [`Outcome::Verified`] only when the signature covers all of it ([`Coverage::whole`]); one
|
||||
/// that covers part of it is at best [`Outcome::Valid`] with [`NotVerified::partly_signed`].
|
||||
pub fn verify(original: &[u8], from: &str, keys: &KeyRing, now: u64, verified: impl Fn(&Fingerprint, &str) -> bool) -> Option<Checked> {
|
||||
if original.len() > MAX_MESSAGE {
|
||||
verify_within(original, MAX_MESSAGE, from, keys, now, verified)
|
||||
}
|
||||
|
||||
/// [`verify`] for messages of at most `max` bytes.
|
||||
fn verify_within(
|
||||
original: &[u8],
|
||||
max: usize,
|
||||
from: &str,
|
||||
keys: &KeyRing,
|
||||
now: u64,
|
||||
verified: impl Fn(&Fingerprint, &str) -> bool,
|
||||
) -> Option<Checked> {
|
||||
if original.len() > max {
|
||||
return looks_signed(original).then(|| Checked { outcome: Outcome::cant(CantCheck::TooLarge), coverage: Coverage::default() });
|
||||
}
|
||||
let cx = check::Context {
|
||||
|
||||
@@ -120,10 +120,10 @@ fn open_aes256() -> &'static SecurityHandler {
|
||||
HANDLER.get_or_init(|| make(Algorithm::Aes256, "", "owner"))
|
||||
}
|
||||
|
||||
/// Cases for the expensive properties (each draws fresh AES-256 files): the gate's fraction of
|
||||
/// `full` (the hostile-input divisor), at least `floor`; nightly runs `full`.
|
||||
fn cases(full: u32, floor: u32) -> ProptestConfig {
|
||||
ProptestConfig::with_cases((full / craft_testkit::hostile::divisor() as u32).max(floor))
|
||||
/// Cases for the expensive properties (each case creates a file and runs a password hash per
|
||||
/// password it tries): `gate` cases at the gate, `full` nightly (hostile-input divisor 1).
|
||||
fn cases(full: u32, gate: u32) -> ProptestConfig {
|
||||
ProptestConfig::with_cases(if craft_testkit::hostile::divisor() == 1 { full } else { gate })
|
||||
}
|
||||
|
||||
proptest! {
|
||||
@@ -280,7 +280,7 @@ proptest! {
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#![proptest_config(cases(256, 12))]
|
||||
#![proptest_config(cases(256, 3))]
|
||||
/// A file created for `user` and `owner` opens for exactly the passwords whose effective bytes
|
||||
/// equal one of theirs, and reports the role that match earned — owner first, since viewers try
|
||||
/// `/O` before `/U`. Everything else is `WrongPassword`: never an opening, and no panic on odd
|
||||
@@ -414,7 +414,7 @@ proptest! {
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#![proptest_config(cases(256, 12))]
|
||||
#![proptest_config(cases(256, 5))]
|
||||
/// `/Perms` certifies the permission bits and `/EncryptMetadata`: decrypted with the file key it
|
||||
/// must hold `/P` little-endian, four set bytes, 'T' or 'F', and the `adb` sentinel (Algorithm 10).
|
||||
/// Nothing else in this crate reads it — `cos` writes it out and no code takes it back apart — so
|
||||
|
||||
+17
-11
@@ -987,10 +987,12 @@ mod tests {
|
||||
/// D70 and D70s get best-guess frames (the D40 shares the D50 / D70 / D70s data size but not their frame).
|
||||
#[test]
|
||||
fn measured_older_dx_bodies_image_area() {
|
||||
let decode_as = |model: &str, (w, h): (usize, usize)| {
|
||||
let nef = nef_model_in(ByteOrder::Big, model, 1, 12, vec![vec![0x10; w * h * 2]], w as u32, h as u32, h as u32, None);
|
||||
crate::decode(&nef).unwrap()
|
||||
let nef_as = |model: &str, (w, h): (usize, usize)| {
|
||||
nef_model_in(ByteOrder::Big, model, 1, 12, vec![vec![0x10; w * h * 2]], w as u32, h as u32, h as u32, None)
|
||||
};
|
||||
// The headers decide the frame (`probe_info` equals the decoded image's info); one body decodes in full.
|
||||
let crop_of = |model: &str, size: (usize, usize)| crate::probe_info(&nef_as(model, size)).unwrap().crop;
|
||||
assert_eq!(crate::decode(&nef_as("NIKON D200", (3904, 2616))).unwrap().crop, Rect::new(16, 12, 3872, 2592));
|
||||
for (model, size, crop) in [
|
||||
("NIKON D200", (3904, 2616), Rect::new(16, 12, 3872, 2592)),
|
||||
("NIKON D80", (3904, 2616), Rect::new(14, 9, 3872, 2592)),
|
||||
@@ -1003,10 +1005,10 @@ mod tests {
|
||||
("NIKON D70", (3040, 2014), Rect::new(15, 7, 3008, 2000)),
|
||||
("NIKON D70s", (3040, 2014), Rect::new(15, 7, 3008, 2000)),
|
||||
] {
|
||||
assert_eq!(decode_as(model, size).crop, crop, "{model}");
|
||||
assert_eq!(crop_of(model, size), crop, "{model}");
|
||||
}
|
||||
// the V1's area on the V2's data size: no entry, the whole data
|
||||
assert_eq!(decode_as("NIKON 1 V1", (4620, 3084)).crop, Rect::new(0, 0, 4620, 3084));
|
||||
assert_eq!(crop_of("NIKON 1 V1", (4620, 3084)), Rect::new(0, 0, 4620, 3084));
|
||||
}
|
||||
|
||||
/// Every measured entry is a crop inside its data, once per model, data size and depth, with a white level (if
|
||||
@@ -1028,21 +1030,25 @@ mod tests {
|
||||
/// image areas (full frame and 1.3x crop), so renders came out larger and Lightroom crops landed off.
|
||||
#[test]
|
||||
fn measured_d7100_image_area() {
|
||||
let decode_as = |model: &str, (w, h): (usize, usize)| {
|
||||
let nef_as = |model: &str, (w, h): (usize, usize)| {
|
||||
let mut nef = nef(1, 14, vec![vec![0x10; w * h * 2]], w as u32, h as u32, h as u32);
|
||||
// the fixture's model is "NIKON TEST" plus its NUL: 11 bytes to overwrite
|
||||
let at = nef.windows(11).position(|b| b == b"NIKON TEST\0").unwrap();
|
||||
let name = format!("{model:\0<11}");
|
||||
nef[at..at + 11].copy_from_slice(name.as_bytes());
|
||||
crate::decode(&nef).unwrap()
|
||||
nef
|
||||
};
|
||||
// The headers decide the frame (`probe_info` equals the decoded image's info); the white level needs the
|
||||
// samples, so the full-frame area decodes in full.
|
||||
let d7100 = crate::decode(&nef_as("NIKON D7100", (6036, 4020))).unwrap();
|
||||
assert_eq!(d7100.crop, Rect::new(18, 10, 6000, 4000));
|
||||
assert_ne!(d7100.white, vec![15520.0]);
|
||||
for (size, crop) in [((6036, 4020), Rect::new(18, 10, 6000, 4000)), ((4812, 3212), Rect::new(6, 6, 4800, 3200))] {
|
||||
let d7100 = decode_as("NIKON D7100", size);
|
||||
let d7100 = crate::probe_info(&nef_as("NIKON D7100", size)).unwrap();
|
||||
assert_eq!(d7100.crop, crop);
|
||||
assert_eq!((d7100.crop.width, d7100.crop.height), (crop.width, crop.height));
|
||||
assert_ne!(d7100.white, vec![15520.0]);
|
||||
assert_eq!(d7100.info().developed_size(), (crop.width, crop.height));
|
||||
assert_eq!(decode_as("NIKON D7200", size).crop, Rect::new(0, 0, size.0, size.1));
|
||||
assert_eq!(d7100.developed_size(), (crop.width, crop.height));
|
||||
assert_eq!(crate::probe_info(&nef_as("NIKON D7200", size)).unwrap().crop, Rect::new(0, 0, size.0, size.1));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -37,7 +37,12 @@ fn value(c: u8) -> Option<u32> {
|
||||
/// Decodes padded (or unpadded) standard base64. `None` for malformed input or a result larger
|
||||
/// than [`MAX_DECODED_BYTES`].
|
||||
pub fn decode(text: &str) -> Option<Vec<u8>> {
|
||||
if text.bytes().filter(|c| !c.is_ascii_whitespace()).count() > MAX_DECODED_BYTES.div_ceil(3).saturating_mul(4) {
|
||||
decode_capped(text, MAX_DECODED_BYTES)
|
||||
}
|
||||
|
||||
/// [`decode`] with the output capped at `max` bytes.
|
||||
fn decode_capped(text: &str, max: usize) -> Option<Vec<u8>> {
|
||||
if text.bytes().filter(|c| !c.is_ascii_whitespace()).count() > max.div_ceil(3).saturating_mul(4) {
|
||||
return None;
|
||||
}
|
||||
let syms: Vec<u8> = text.bytes().filter(|c| !c.is_ascii_whitespace()).collect();
|
||||
@@ -46,7 +51,7 @@ pub fn decode(text: &str) -> Option<Vec<u8>> {
|
||||
return None;
|
||||
}
|
||||
let decoded_len = body.len() / 4 * 3 + body.len() % 4 * 3 / 4;
|
||||
if decoded_len > MAX_DECODED_BYTES {
|
||||
if decoded_len > max {
|
||||
return None;
|
||||
}
|
||||
let mut out = Vec::with_capacity(decoded_len);
|
||||
@@ -99,19 +104,17 @@ mod tests {
|
||||
encoded
|
||||
}
|
||||
|
||||
// Build valid base64 directly instead of encoding a 64 MiB allocation on every case.
|
||||
// This keeps the same decoded-size boundary checks while making the workspace gate much
|
||||
// faster and using less temporary memory.
|
||||
let exact = encoded_zero_bytes(MAX_DECODED_BYTES);
|
||||
assert_eq!(decode(&exact).map(|bytes| bytes.len()), Some(MAX_DECODED_BYTES), "padded boundary");
|
||||
let too_large = encoded_zero_bytes(MAX_DECODED_BYTES + 1);
|
||||
assert!(decode(&too_large).is_none(), "padded over boundary");
|
||||
// Each case decodes tens of MiB: the gate runs the two above, nightly the rest.
|
||||
if craft_testkit::hostile::divisor() > 1 {
|
||||
return;
|
||||
// The boundary at a cap of every remainder mod 3; nightly also at the real 64 MiB cap.
|
||||
let full = craft_testkit::hostile::divisor() == 1;
|
||||
let caps = [97, 98, 99].into_iter().chain(full.then_some(MAX_DECODED_BYTES));
|
||||
for max in caps {
|
||||
let exact = encoded_zero_bytes(max);
|
||||
assert_eq!(decode_capped(&exact, max).map(|bytes| bytes.len()), Some(max), "padded boundary at {max}");
|
||||
let too_large = encoded_zero_bytes(max + 1);
|
||||
assert!(decode_capped(&too_large, max).is_none(), "padded over boundary at {max}");
|
||||
assert_eq!(decode_capped(exact.trim_end_matches('='), max).map(|bytes| bytes.len()), Some(max), "unpadded boundary at {max}");
|
||||
let spaced = format!("{}\n {}", &too_large[..8], &too_large[8..]);
|
||||
assert!(decode_capped(&spaced, max).is_none(), "whitespace over boundary at {max}");
|
||||
}
|
||||
assert_eq!(decode(exact.trim_end_matches('=')).map(|bytes| bytes.len()), Some(MAX_DECODED_BYTES), "unpadded boundary");
|
||||
let spaced = format!("{}\n {}", &too_large[..8], &too_large[8..]);
|
||||
assert!(decode(&spaced).is_none(), "whitespace over boundary");
|
||||
}
|
||||
}
|
||||
@@ -434,6 +434,10 @@ mod tests {
|
||||
self.0 += 1;
|
||||
}
|
||||
}
|
||||
// The largest page, 2^28 pixels, takes seconds to encode and decode: nightly only.
|
||||
if craft_testkit::hostile::divisor() > 1 {
|
||||
return;
|
||||
}
|
||||
// One black pixel, so a page that came back blank wouldn't pass.
|
||||
let mut largest = vec![0xFF; 2_048 * 16_384];
|
||||
largest[0] = 0x7F;
|
||||
|
||||
@@ -518,7 +518,10 @@ mod tests {
|
||||
// decoder, which has the same one and can refuse it first.
|
||||
let large = |rows| decode_jbig2(&page_of(&data, 16_384, rows), None, 16_384, rows, usize::MAX);
|
||||
assert!(matches!(large(16_385), Err(CodecError::Unsupported(_) | CodecError::Corrupt { .. })), "{:?}", large(16_385));
|
||||
assert!(large(16_384).is_ok(), "{:?}", large(16_384).map(|page| page.len()));
|
||||
// Decoding the 2^28-pixel page takes seconds: nightly only.
|
||||
if craft_testkit::hostile::divisor() == 1 {
|
||||
assert!(large(16_384).is_ok(), "{:?}", large(16_384).map(|page| page.len()));
|
||||
}
|
||||
|
||||
// An extension segment (ISO/IEC 14492 7.4.14), which a decoder skips: its 11-byte header
|
||||
// gives the length of the data after it.
|
||||
|
||||
Reference in new issue
Block a user