diff --git a/crates/android-res/Cargo.toml b/crates/android-res/Cargo.toml index cc54d2513..114c4ae42 100644 --- a/crates/android-res/Cargo.toml +++ b/crates/android-res/Cargo.toml @@ -13,3 +13,6 @@ workspace = true [dependencies] serde = { workspace = true } thiserror = { workspace = true } + +[dev-dependencies] +craft-testkit = { workspace = true } diff --git a/crates/android-res/src/axml.rs b/crates/android-res/src/axml.rs index 3aea1f7ff..ad2ac8d9d 100644 --- a/crates/android-res/src/axml.rs +++ b/crates/android-res/src/axml.rs @@ -568,9 +568,13 @@ mod tests { #[test] fn shared_offsets_spend_a_pool_byte_budget() { - for utf8 in [true, false] { + // Each parse keeps 64 MiB of strings: the gate runs the UTF-8 pool with the appended bytes + // (the budget and the appended bytes together), nightly all four. + let full = craft_testkit::hostile::divisor() == 1; + let (encodings, appends): (&[bool], &[bool]) = if full { (&[true, false], &[false, true]) } else { (&[true], &[true]) }; + for &utf8 in encodings { let mut data = shared_ascii_pool(utf8, 8192); - for appended in [false, true] { + for &appended in appends { if appended { // Unrelated bytes after the chunk cannot buy more retained copies. data.resize(24 << 20, 0); diff --git a/crates/captions/Cargo.toml b/crates/captions/Cargo.toml index 1136f55f9..4a4e27520 100644 --- a/crates/captions/Cargo.toml +++ b/crates/captions/Cargo.toml @@ -21,6 +21,7 @@ craft-xml = { workspace = true } thiserror = { workspace = true } [dev-dependencies] +craft-testkit = { workspace = true } proptest = { workspace = true } # A second XML reader for the tests: checks of written TTML, and the comparison in tests/it/ttml_xml_views.rs. roxmltree = "0.21" diff --git a/crates/captions/tests/it/limits.rs b/crates/captions/tests/it/limits.rs index 3b908fa06..0b010ed41 100644 --- a/crates/captions/tests/it/limits.rs +++ b/crates/captions/tests/it/limits.rs @@ -35,7 +35,8 @@ fn mutated_files_never_panic() { for format in Format::ALL { let bytes = write(&doc(), format, WriteOptions::default()); // every byte of a text file, and the header and first blocks of the (sparse) binary one - for i in 0..bytes.len().min(2048) { + // The gate runs every divisor-th byte; nightly runs every one. + for i in (0..bytes.len().min(2048)).step_by(craft_testkit::hostile::divisor()) { for v in [0u8, 0x20, 0x3c, 0x7f, 0xff] { let mut m = bytes.clone(); if let Some(b) = m.get_mut(i) { diff --git a/crates/cfb/Cargo.toml b/crates/cfb/Cargo.toml index e2684da0b..853038aae 100644 --- a/crates/cfb/Cargo.toml +++ b/crates/cfb/Cargo.toml @@ -13,4 +13,5 @@ workspace = true [dependencies] [dev-dependencies] +craft-testkit = { workspace = true } craft-media-testkit = { workspace = true } diff --git a/crates/cfb/src/tests/ported.rs b/crates/cfb/src/tests/ported.rs index f49f9f6c0..476daebe3 100644 --- a/crates/cfb/src/tests/ported.rs +++ b/crates/cfb/src/tests/ported.rs @@ -557,7 +557,8 @@ fn truncation_at_every_length_never_panics() { #[test] fn every_single_bit_flip_never_panics_or_hangs() { for (mut file, _) in small_samples() { - for bit in 0..file.len() * 8 { + // The gate flips every divisor-th bit; nightly flips each one. + for bit in (0..file.len() * 8).step_by(craft_testkit::hostile::divisor()) { file[bit / 8] ^= 1 << (bit % 8); exercise(&file, None); file[bit / 8] ^= 1 << (bit % 8); diff --git a/crates/cms/Cargo.toml b/crates/cms/Cargo.toml index 51fb2aab7..c876e4d42 100644 --- a/crates/cms/Cargo.toml +++ b/crates/cms/Cargo.toml @@ -20,4 +20,5 @@ md5 = { workspace = true } rayon = { workspace = true } [dev-dependencies] +craft-testkit = { workspace = true } moxcms = "0.8" diff --git a/crates/cms/src/black_tests.rs b/crates/cms/src/black_tests.rs index 8752cdaa2..2d4864a99 100644 --- a/crates/cms/src/black_tests.rs +++ b/crates/cms/src/black_tests.rs @@ -70,10 +70,12 @@ fn the_destination_black_matches_the_source_lightness() { for intent in [Intent::RelativeColorimetric, Intent::Perceptual] { for bpc in [true, false] { let o = TransformOptions { intent, bpc, ..opts() }; - for (src, dst) in [(coated(), fogra()), (fogra(), coated())] { + // Both directions for one setting; the other settings in the forward one. + let directions = if intent == Intent::RelativeColorimetric && bpc { 2 } else { 1 }; + for (src, dst) in [(coated(), fogra()), (fogra(), coated())].into_iter().take(directions) { let bp = BlackPreserving::new(src, dst, o).unwrap(); let dst_black = lightness(dst, o, [0.0, 0.0, 0.0, 1.0]); - for k in [0.1f32, 0.3, 0.5, 0.7, 0.9, 1.0] { + for k in [0.1f32, 0.5, 0.9, 1.0] { let want = lightness(src, o, [0.0, 0.0, 0.0, k]); if want <= dst_black { assert_eq!(bp.map_k(k), 1.0, "darker than the destination's black clamps to K = 1"); diff --git a/crates/cms/tests/cms.rs b/crates/cms/tests/cms.rs index bf6934d9a..00b9b3b7a 100644 --- a/crates/cms/tests/cms.rs +++ b/crates/cms/tests/cms.rs @@ -115,7 +115,9 @@ fn white_is_exact_on_every_path() { let none = [0.0f32; 4]; for cmyk in [Builtin::CoatedCmyk, Builtin::CoatedFogra39] { for intent in [Intent::Perceptual, Intent::RelativeColorimetric, Intent::Saturation] { - for bpc in [false, true] { + // The gate runs black point compensation on; nightly both. + let bpcs: &[bool] = if craft_testkit::hostile::divisor() > 1 { &[true] } else { &[false, true] }; + for &bpc in bpcs { for precise_float in [false, true] { let opts = TransformOptions { intent, bpc, precise_float }; let at = format!("{cmyk:?} {opts:?}"); diff --git a/crates/doc/Cargo.toml b/crates/doc/Cargo.toml index decaff8db..dd3d2459d 100644 --- a/crates/doc/Cargo.toml +++ b/crates/doc/Cargo.toml @@ -29,3 +29,6 @@ thiserror = { workspace = true } # `pcraft-pixels`: PhotoCraft's tiles are zstd frames named by the BLAKE3 hash of their samples. blake3 = { version = "1.8", default-features = false, features = ["pure"], optional = true } ruzstd = { version = "0.9", default-features = false, features = ["std"], optional = true } + +[dev-dependencies] +craft-testkit = { workspace = true } diff --git a/crates/doc/tests/hostile.rs b/crates/doc/tests/hostile.rs index 33f93d69f..4c8aa5797 100644 --- a/crates/doc/tests/hostile.rs +++ b/crates/doc/tests/hostile.rs @@ -82,7 +82,7 @@ impl Rng { fn seeded_mutations_never_panic() { let mut rng = Rng(0x5eed); for s in samples() { - for _ in 0..1500 { + for _ in 0..1500 / craft_testkit::hostile::divisor() { let mut d = s.clone(); for _ in 0..1 + rng.below(4) { let at = rng.below(d.len()); diff --git a/crates/doc/tests/pixels.rs b/crates/doc/tests/pixels.rs index aa2f02f21..de2687b45 100644 --- a/crates/doc/tests/pixels.rs +++ b/crates/doc/tests/pixels.rs @@ -120,7 +120,8 @@ fn every_truncation_and_flipped_byte_is_an_error_not_a_panic() { let m = surface("Grayscale", "U8", false, &[255], &[(0, 0, &hash(&mask_tile))]); let file = bundle(3, 2, "Rgb", &[layer(&raster(&s), Some(&m))], &[&tile, &mask_tile]); assert!(read(&file, &[0]).mask.is_some()); - for n in 0..file.len() { + // The gate runs every divisor-th truncation and flip; nightly runs every one. + for n in (0..file.len()).step_by(craft_testkit::hostile::divisor()) { let _ = pcraft_layer_rgba(&file[..n], &[0], &Limits::default()); let mut flipped = file.clone(); flipped[n] ^= 0xff; diff --git a/crates/docx/Cargo.toml b/crates/docx/Cargo.toml index ed84356e0..0ffedf2aa 100644 --- a/crates/docx/Cargo.toml +++ b/crates/docx/Cargo.toml @@ -28,6 +28,7 @@ zeroize = "1" [dev-dependencies] craft-cfb = { workspace = true } +craft-testkit = { workspace = true } craft-opc = { workspace = true, features = ["test-support"] } craft-wordmodel = { workspace = true, features = ["test-support"] } image = { version = "0.25", default-features = false, features = ["png"] } diff --git a/crates/docx/src/read/chart/tests.rs b/crates/docx/src/read/chart/tests.rs index 1aeab5235..ea338016e 100644 --- a/crates/docx/src/read/chart/tests.rs +++ b/crates/docx/src/read/chart/tests.rs @@ -230,11 +230,12 @@ fn hostile_radar_charts_never_panic() { let small = chart_items(&space(&format!("{}", ser(0, "S", None, &["a", "b", "c"], &["1", "2", "3"]))), &theme(), 20.0, 20.0); let _ = small; - // Caps: thousands of categories and series stay bounded. - let cats: Vec = (0..5000).map(|i| format!("c{i}")).collect(); + // Caps: three times as many categories and series as are drawn stay bounded. + let n = 3 * MAX_SPOKES; + let cats: Vec = (0..n).map(|i| format!("c{i}")).collect(); let refs: Vec<&str> = cats.iter().map(String::as_str).collect(); - let vals = vec!["1"; 5000]; - let many: Vec = (0..300).map(|i| ser(i, "S", None, &refs, &vals)).collect(); + let vals = vec!["1"; n]; + let many: Vec = (0..3 * MAX_RADAR_SERIES).map(|i| ser(i, "S", None, &refs, &vals)).collect(); let items = radar_chart("marker", &many); let polygons = items.iter().filter(|it| matches!(it, GraphicItem::Path { stroke: Some(c), .. } if *c != GRID)).count(); assert!(polygons <= MAX_RADAR_SERIES, "{polygons}"); diff --git a/crates/docx/tests/it/comment_save_cost.rs b/crates/docx/tests/it/comment_save_cost.rs index 2bcd5fb86..88902400b 100644 --- a/crates/docx/tests/it/comment_save_cost.rs +++ b/crates/docx/tests/it/comment_save_cost.rs @@ -29,8 +29,8 @@ fn cpu_cost(mut f: impl FnMut()) -> f64 { #[test] fn many_comments_save_without_quadratic_id_searches() { for imported in [true, false] { - let small = comments(4_000, imported); - let big = comments(32_000, imported); + let small = comments(1_000, imported); + let big = comments(8_000, imported); let save = |d: &Document| drop(std::hint::black_box(craft_docx::write(d).unwrap())); save(&small); save(&big); @@ -39,7 +39,7 @@ fn many_comments_save_without_quadratic_id_searches() { // use elapsed time; retry ratios far from linear before declaring a regression. for _ in 0..3 { let (mut s, mut b) = (f64::INFINITY, f64::INFINITY); - for _ in 0..3 { + for _ in 0..2 { s = s.min(cpu_cost(|| (0..8).for_each(|_| save(&small))) / 8.0); b = b.min(cpu_cost(|| save(&big))); } diff --git a/crates/docx/tests/it/content_control_save_cost.rs b/crates/docx/tests/it/content_control_save_cost.rs index 9b96aeb7b..768f00ede 100644 --- a/crates/docx/tests/it/content_control_save_cost.rs +++ b/crates/docx/tests/it/content_control_save_cost.rs @@ -59,7 +59,7 @@ fn cost_ratio(scale: usize, mut small: impl FnMut(), mut big: impl FnMut()) -> ( big(); let mut small_scaled = || (0..scale).for_each(|_| small()); let (mut t1, mut tk) = (f64::INFINITY, f64::INFINITY); - for _ in 0..5 { + for _ in 0..3 { let a = Instant::now(); small_scaled(); t1 = t1.min(a.elapsed().as_secs_f64() / scale as f64); @@ -76,8 +76,8 @@ fn cost_ratio(scale: usize, mut small: impl FnMut(), mut big: impl FnMut()) -> ( #[test] fn a_document_with_many_inline_content_controls_saves_in_linear_time() { let scale = 4; - let small = inline_controls(8_000); - let big = inline_controls(8_000 * scale); + let small = inline_controls(2_000); + let big = inline_controls(2_000 * scale); let (t1, tk, ratio) = cost_ratio( scale, || { @@ -96,8 +96,8 @@ fn a_document_with_many_inline_content_controls_saves_in_linear_time() { #[test] fn a_document_with_many_block_content_controls_saves_in_linear_time() { let scale = 4; - let small = block_controls(8_000); - let big = block_controls(8_000 * scale); + let small = block_controls(2_000); + let big = block_controls(2_000 * scale); let (t1, tk, ratio) = cost_ratio( scale, || { diff --git a/crates/docx/tests/it/element_budget.rs b/crates/docx/tests/it/element_budget.rs index 6b220ae7c..d18e2762a 100644 --- a/crates/docx/tests/it/element_budget.rs +++ b/crates/docx/tests/it/element_budget.rs @@ -9,6 +9,11 @@ const W_NS: &str = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingm #[test] fn a_file_of_element_budget_parts_still_reads() { + // 18M elements: nightly only. `the_xml_element_budget_is_package_wide` (in `package.rs`) proves + // the package-wide budget with a small one at the gate. + if craft_testkit::hostile::divisor() > 1 { + return; + } // Nine chart parts of 2M elements each: 18M over the package's 16M budget. The later // parts are skipped with a warning instead of built, and the file still reads. Before // the budget, every part's whole tree was parsed and the chart trees stayed cached for diff --git a/crates/docx/tests/it/malformed.rs b/crates/docx/tests/it/malformed.rs index b1c5b8f17..fc65b8e2d 100644 --- a/crates/docx/tests/it/malformed.rs +++ b/crates/docx/tests/it/malformed.rs @@ -179,7 +179,8 @@ fn many_fields_and_huge_attribute_values() { /// limit error, or the extras are dropped and the text survives (#3702, WC-06). #[test] fn millions_of_attributes_on_one_paragraph_are_capped() { - let attrs: String = (0..2_000_000).map(|i| format!(" a{i}=\"\"")).collect(); + // The gate reads a fraction of the attributes; nightly all of them. + let attrs: String = (0..2_000_000 / craft_testkit::hostile::divisor()).map(|i| format!(" a{i}=\"\"")).collect(); let x = format!("kept"); // Only the read is timed: deflating the test input in a debug build is not what is bounded. let z = doc_zip(x.as_bytes()); @@ -253,7 +254,7 @@ fn malformed_or_hostile_bibliography_never_panics() { fn hostile_bibliography_source_count_is_capped() { let doc = format!("body"); let mut sources = String::from(r#""#); - for i in 0..60_000 { + for i in 0..(60_000 / craft_testkit::hostile::divisor()).max(10_500) { sources.push_str(&format!("T{i}Title {i}")); // Untagged duplicates all collapse into one source. sources.push_str("Same"); @@ -313,11 +314,13 @@ fn compound(info: &[u8], package: &[u8]) -> Vec { proptest! { // Each case that parses runs the 50,000-spin key derivation, so fewer cases. - #![proptest_config(ProptestConfig { cases: 48, ..ProptestConfig::default() })] + #![proptest_config(ProptestConfig { cases: (48 / craft_testkit::hostile::divisor() as u32).max(6), ..ProptestConfig::default() })] #[test] fn mutated_standard_encryption_never_panics(ops in proptest::collection::vec((0u8..3, any::(), any::(), any::()), 1..8)) { - let (mut info, mut package) = standard_streams(); + // Encrypting runs the key derivation too: once for every case. + static STREAMS: std::sync::OnceLock<(Vec, Vec)> = std::sync::OnceLock::new(); + let (mut info, mut package) = STREAMS.get_or_init(standard_streams).clone(); for (k, idx, byte, in_package) in ops { let x = if in_package { &mut package } else { &mut info }; let at = idx.index(x.len() + 1); diff --git a/crates/docx/tests/it/word_xml.rs b/crates/docx/tests/it/word_xml.rs index 31c022aa0..2571facb2 100644 --- a/crates/docx/tests/it/word_xml.rs +++ b/crates/docx/tests/it/word_xml.rs @@ -268,6 +268,10 @@ fn flat_opc_limits_count_what_is_not_kept() { assert!(limited(&r#"AA=="#.repeat(20_000))); assert!(limited(&"".repeat(20_000))); // A part nothing reads, one element over what the XML tree reader takes in a part (8 000 000). + // Millions of elements: nightly only; the checks above prove the same counting at the gate. + if craft_testkit::hostile::divisor() > 1 { + return; + } assert!(limited(&format!(r#"{}"#, "".repeat(8_000_000)))); } diff --git a/crates/drawingml/src/chart.rs b/crates/drawingml/src/chart.rs index 1dd92177a..91321e351 100644 --- a/crates/drawingml/src/chart.rs +++ b/crates/drawingml/src/chart.rs @@ -1762,8 +1762,8 @@ mod chartex_tests { #[test] fn large_box_hierarchy_and_stacked_charts_take_linear_work() { - // 50,000 distinct categories in one series: grouped through a map, one pass. - let n = 50_000; + // 5,000 distinct categories in one series: grouped through a map, one pass. + let n = 5_000; let mut c = Chart::sample(ChartType::BoxWhisker); c.series.truncate(1); c.categories = (0..n).map(|i| format!("g{i}")).collect(); @@ -1771,12 +1771,13 @@ mod chartex_tests { let (groups, stats) = c.box_groups(); assert_eq!((groups.len(), stats[0].len()), (n, n)); assert!(stats[0].iter().all(Option::is_some)); - // 2,000 series cap the groups so the result stays within MAX_BOX_CELLS. - c.series = vec![c.series[0].clone(); 2000]; + // Enough series to cap the groups so the result stays within MAX_BOX_CELLS. + let series = MAX_BOX_CELLS / n * 2; + c.series = vec![c.series[0].clone(); series]; let (groups, stats) = c.box_groups(); - assert_eq!(groups.len(), MAX_BOX_CELLS / 2000); + assert_eq!(groups.len(), MAX_BOX_CELLS / series); assert!(stats.iter().all(|s| s.len() == groups.len())); - // One long outer label over 50,000 leaves is shared, not copied per leaf. + // One long outer label over 5,000 leaves is shared, not copied per leaf. let mut t = Chart::sample(ChartType::Treemap); t.series.truncate(1); t.categories = (0..n).map(|i| format!("c{i}")).collect(); diff --git a/crates/drawingml/src/table.rs b/crates/drawingml/src/table.rs index b5d83d530..cc71dac1d 100644 --- a/crates/drawingml/src/table.rs +++ b/crates/drawingml/src/table.rs @@ -749,7 +749,7 @@ mod tests { 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"); 1500] }; 150], ..Default::default() }; + 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); diff --git a/crates/exr/Cargo.toml b/crates/exr/Cargo.toml index 7221a6858..28a1649b8 100644 --- a/crates/exr/Cargo.toml +++ b/crates/exr/Cargo.toml @@ -24,3 +24,6 @@ half = { version = "2", optional = true } thiserror = { workspace = true, optional = true } # zlib for scanline payloads and deep ZIPS chunks, which the `exr` crate does not read. flate2 = { version = "1", default-features = false, features = ["rust_backend"], optional = true } + +[dev-dependencies] +craft-testkit = { workspace = true } diff --git a/crates/exr/src/decode_tests.rs b/crates/exr/src/decode_tests.rs index 61f207a16..32fefa029 100644 --- a/crates/exr/src/decode_tests.rs +++ b/crates/exr/src/decode_tests.rs @@ -243,11 +243,13 @@ fn hostile_files_never_panic() { (5, 3), ); let limits = Limits { max_bytes: 1 << 24, ..Limits::default() }; - for n in 0..good.len() { + // The gate runs every divisor-th truncation and byte; nightly runs every one. + let step = craft_testkit::hostile::divisor(); + for n in (0..good.len()).step_by(step) { let _ = parts(&good[..n], &limits); let _ = decode_part(&good[..n], 1, &all, &limits); } - for i in 0..good.len() { + for i in (0..good.len()).step_by(step) { for v in [0u8, 1, 0x7F, 0xFF] { let mut b = good.clone(); b[i] = v; diff --git a/crates/exr/src/seek_tests.rs b/crates/exr/src/seek_tests.rs index 010492235..0f48fdb38 100644 --- a/crates/exr/src/seek_tests.rs +++ b/crates/exr/src/seek_tests.rs @@ -354,12 +354,13 @@ fn hostile_files_are_refused_and_never_panic() { let channels: Vec<(usize, usize)> = (0..index.parts().len()).flat_map(|p| channels_of(&index, p)).collect(); let _ = read_planes(&mut Cursor::new(data), &index, &Request::new(&channels, 1 << 24), &never); }; - // Every truncation. - for n in 0..bytes.len() { + // Every truncation (at the gate every divisor-th one, as for the flipped bytes). + let step = craft_testkit::hostile::divisor(); + for n in (0..bytes.len()).step_by(step) { try_read(&bytes[..n]); } // A flipped byte at every position (headers, tables and chunks). - for at in 0..bytes.len() { + for at in (0..bytes.len()).step_by(step) { let mut broken = bytes.clone(); broken[at] ^= 0xFF; try_read(&broken); @@ -1413,11 +1414,11 @@ fn groups_must_be_slots_of_one_part_each_in_one_group() { #[test] fn the_estimate_covers_what_the_read_does() { // A flat colour in ZIP16 (decodes to far more than it reads), lines of a ramp, and tiles. - let (w, h) = (1024usize, 600usize); + let (w, h) = (256usize, 160usize); let list = vec![AnyChannel::new("R", FlatSamples::F32(vec![0.25; w * h])), AnyChannel::new("G", FlatSamples::F32(vec![0.5; w * h]))]; let encoding = Encoding { compression: Compression::ZIP16, blocks: Blocks::ScanLines, line_order: LineOrder::Increasing }; let flat = file(vec![Layer::new((w, h), LayerAttributes::default(), encoding, AnyChannels::sort(list.into()))], (w, h)); - let ramp = file(vec![layer(None, (0, 0), (1024, 600), &["R", "G"], false, Compression::Uncompressed)], (1024, 600)); + let ramp = file(vec![layer(None, (0, 0), (256, 160), &["R", "G"], false, Compression::Uncompressed)], (256, 160)); let tiled = file(vec![layer(None, (0, 0), (300, 200), &["R", "G", "B"], true, Compression::PIZ)], (300, 200)); for bytes in [&flat, &ramp, &tiled] { let index = indexed(bytes); diff --git a/crates/font-subset/Cargo.toml b/crates/font-subset/Cargo.toml index 645b24f61..7810620ef 100644 --- a/crates/font-subset/Cargo.toml +++ b/crates/font-subset/Cargo.toml @@ -16,6 +16,7 @@ unicode-normalization = "0.1.26" write-fonts = { version = "0.55", features = ["read"] } [dev-dependencies] +craft-testkit = { workspace = true } rustybuzz = "0.20.1" serde_json = "1" wuff = "0.2.9" diff --git a/crates/font-subset/src/woff2.rs b/crates/font-subset/src/woff2.rs index e6a3d3526..57f0d2d25 100644 --- a/crates/font-subset/src/woff2.rs +++ b/crates/font-subset/src/woff2.rs @@ -185,7 +185,9 @@ mod tests { #[test] fn round_trips_every_table_and_header_matches_spec() { - for path in FIXTURES { + // The gate runs a TrueType and a CFF font (the first and the last); nightly runs all of them. + let all = craft_testkit::hostile::divisor() == 1; + for path in FIXTURES.iter().enumerate().filter(|(i, _)| all || *i == 0 || *i == FIXTURES.len() - 1).map(|(_, p)| p) { let sfnt = fixture(path); let tables = parse_tables(&sfnt).unwrap(); for quality in [Quality::Static, Quality::OnDemand] { diff --git a/crates/latex/Cargo.toml b/crates/latex/Cargo.toml index 4367c0b02..bc0bc9e26 100644 --- a/crates/latex/Cargo.toml +++ b/crates/latex/Cargo.toml @@ -18,6 +18,7 @@ craft-mime = { workspace = true, features = ["detect"] } craft-wordmodel = { workspace = true } [dev-dependencies] +craft-testkit = { workspace = true } craft-markdown = { workspace = true } proptest = { workspace = true } diff --git a/crates/latex/tests/hostile.rs b/crates/latex/tests/hostile.rs index d8bf8df70..40755bc28 100644 --- a/crates/latex/tests/hostile.rs +++ b/crates/latex/tests/hostile.rs @@ -54,9 +54,9 @@ fn latex_export_carries_no_commands_from_the_document() { assert!(!out.contains("\\input") && !out.contains("^^"), "{out}"); } -/// The fastest of three reads of `src`. +/// The fastest of two reads of `src`. fn fastest(src: &str) -> Duration { - (0..3) + (0..2) .map(|_| { let started = Instant::now(); assert!(import(src.as_bytes()).body.len() <= 2); @@ -71,8 +71,10 @@ fn fastest(src: &str) -> Duration { #[test] fn latex_labels_in_a_row_are_read_in_linear_time() { let cases: [fn(usize) -> String; 3] = [|n| "\\label{a} ".repeat(n) + "x", |n| "\\label{a}".repeat(n) + "x", |n| "\\hypertarget{a}{} ".repeat(n)]; + // The gate reads half the labels; nightly the full counts. + let size = |n: usize| n / craft_testkit::hostile::divisor().min(2); for make in cases { - let (small, large) = (fastest(&make(25_000)), fastest(&make(100_000))); + let (small, large) = (fastest(&make(size(25_000))), fastest(&make(size(100_000)))); assert!(large < small * 8 + Duration::from_millis(50), "{small:?} for 25,000, {large:?} for 100,000"); } let d = import("\\label{one}First \\label{two}second \\label{three}third.".as_bytes()); @@ -98,7 +100,8 @@ fn latex_optional_arguments_in_a_row_are_read_in_linear_time() { ]; for make in cases { assert_eq!(text(&make(3)), "x"); - let (small, large) = (fastest(&make(50_000)), fastest(&make(200_000))); + let size = |n: usize| n / craft_testkit::hostile::divisor().min(2); + let (small, large) = (fastest(&make(size(50_000))), fastest(&make(size(200_000)))); assert!(large < small * 8 + Duration::from_millis(50), "{small:?} for 50,000, {large:?} for 200,000"); } } diff --git a/crates/mesh/Cargo.toml b/crates/mesh/Cargo.toml index 6ba794aae..17519cb07 100644 --- a/crates/mesh/Cargo.toml +++ b/crates/mesh/Cargo.toml @@ -29,3 +29,6 @@ craft-zip = { workspace = true, optional = true } # 3MF is an OPC package of XML parts. craft-opc = { workspace = true, optional = true } craft-xml = { workspace = true, optional = true } + +[dev-dependencies] +craft-testkit = { workspace = true } diff --git a/crates/mesh/src/tests.rs b/crates/mesh/src/tests.rs index f2eac7e9f..31b84d2ef 100644 --- a/crates/mesh/src/tests.rs +++ b/crates/mesh/src/tests.rs @@ -21,17 +21,19 @@ mod threemf; mod triangulate; /// Every truncation of `good` and two mutations of every byte go through `read`: it may refuse -/// them, it must not panic, and what it accepts must be a valid scene. +/// them, it must not panic, and what it accepts must be a valid scene. The gate runs every +/// divisor-th truncation and byte (`CRAFT_HOSTILE_DIVISOR`); nightly runs every one. pub(crate) fn hammer(good: &[u8], read: &dyn Fn(&[u8]) -> Result) { let check = |bytes: &[u8]| { if let Ok(scene) = read(bytes) { scene.validate().unwrap(); } }; - for len in 0..good.len() { + let step = craft_testkit::hostile::divisor(); + for len in (0..good.len()).step_by(step) { check(&good[..len]); } - for i in 0..good.len() { + for i in (0..good.len()).step_by(step) { let mut b = good.to_vec(); b[i] ^= 0xA5; check(&b); diff --git a/crates/ods/tests/read.rs b/crates/ods/tests/read.rs index 530177b4c..9c44e09ec 100644 --- a/crates/ods/tests/read.rs +++ b/crates/ods/tests/read.rs @@ -206,23 +206,25 @@ fn expansion_bounds_stop_small_repeat_bombs() { r#""#, ); assert!(matches!(open(&cells), Err(Error::TooLarge(_)))); + // Text limits are set small so the files stay small: 1 MiB of text over all sheets, 64 KiB a cell. + let tight = Options { max_text: 1 << 20, max_cell_text: 64 << 10, ..Options::default() }; let text = format!( - r#""#, + r#""#, "x".repeat(1024) ); - assert!(matches!(open(&ods(&text)), Err(Error::TooLarge(_)))); - // One row of cells each just under the 1 MiB cell limit, past 64 MiB in all: refused while + assert!(matches!(read(&ods(&text), &tight), Err(Error::TooLarge(_)))); + // One row of cells each just under the cell limit, past the text limit in all: refused while // the row is read. The row's end is never reached. - let long = format!(r#""#, "x".repeat(1024 * 1024 - 1)); - let cells = package(content(&format!(r#"{}"#, long.repeat(65))).as_bytes()).unwrap(); - assert!(matches!(open(&cells), Err(Error::TooLarge(_)))); + let long = format!(r#""#, "x".repeat(64 * 1024 - 1)); + let cells = package(content(&format!(r#"{}"#, long.repeat(17))).as_bytes()).unwrap(); + assert!(matches!(read(&cells, &tight), Err(Error::TooLarge(_)))); // A row repeated once more than its cells' text allows is refused, and one that fits reads. let cell = format!(r#""#, "y".repeat(1024)); let rows = |n: u32| { ods(&format!(r#"{cell}"#)) }; - assert!(open(&rows(65_536)).is_ok()); - assert!(matches!(open(&rows(65_537)), Err(Error::TooLarge(_)))); + assert!(read(&rows(1024), &tight).is_ok()); + assert!(matches!(read(&rows(1025), &tight), Err(Error::TooLarge(_)))); // An attribute over the cell text limit. let small = Options { max_cell_text: 10, ..Options::default() }; assert!(matches!( diff --git a/crates/openpgp/Cargo.toml b/crates/openpgp/Cargo.toml index 5630c3829..0bb9cbd16 100644 --- a/crates/openpgp/Cargo.toml +++ b/crates/openpgp/Cargo.toml @@ -24,6 +24,7 @@ sha3 = { version = "0.10", default-features = false } pgp = { version = "=0.21.0", default-features = false, features = ["wasm"] } [dev-dependencies] +craft-testkit = { workspace = true } proptest = { workspace = true } # Keys and signatures made in the tests, from a seed: the random numbers rPGP 0.21 takes. rand = { version = "0.8", default-features = false, features = ["std", "std_rng"] } diff --git a/crates/openpgp/src/keys_tests.rs b/crates/openpgp/src/keys_tests.rs index 3cc53b0bc..05db88fbe 100644 --- a/crates/openpgp/src/keys_tests.rs +++ b/crates/openpgp/src/keys_tests.rs @@ -253,6 +253,11 @@ fn a_copy_with_junk_subkey_bindings_from_the_future_never_pushes_out_the_real_on #[test] fn a_copy_that_costs_more_checks_than_a_key_may_is_refused_not_cut_short() { + // Forging and checking more signatures than the cap: nightly only. The revocation test below + // proves the same refusal with a smaller cap at the gate. + if craft_testkit::hostile::divisor() > 1 { + return; + } let alice = secret(ALICE, Make { subkey: true, ..Make::default() }); let mallory = secret("Mallory ", Make { seed: 6, ..Make::default() }); let mut copy = SignedPublicKey::from(alice.clone()); diff --git a/crates/pages/tests/it/views.rs b/crates/pages/tests/it/views.rs index e0aa1babf..fb02cdc9c 100644 --- a/crates/pages/tests/it/views.rs +++ b/crates/pages/tests/it/views.rs @@ -512,7 +512,7 @@ fn a_page_gap_change_keeps_the_scroll_offset() { #[trial] fn the_pictures_a_view_holds_stay_bounded_as_it_scrolls_through_many_pages() { let budget = TextureStoreOptions::pages().budget.max_entries; - let count = 4 * budget; + let count = 2 * budget; let state = Rc::new(RefCell::new(state_with(|s| { s.continuous = true; s.fit = Fit::None; diff --git a/crates/pdf/Cargo.toml b/crates/pdf/Cargo.toml index bb82c8497..e4d3f57c6 100644 --- a/crates/pdf/Cargo.toml +++ b/crates/pdf/Cargo.toml @@ -83,6 +83,7 @@ ttf-parser = "=0.25.1" [target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies] proptest = { workspace = true } +craft-testkit = { workspace = true } [target.'cfg(target_arch = "wasm32")'.dev-dependencies] wasm-bindgen-test = "0.3" diff --git a/crates/pdf/src/cos/object.rs b/crates/pdf/src/cos/object.rs index 05b64eee2..3a82f8229 100644 --- a/crates/pdf/src/cos/object.rs +++ b/crates/pdf/src/cos/object.rs @@ -810,8 +810,56 @@ mod tests { #[test] fn decoded_stops_at_renderer_cap_of_256_mib() { - let data = vec![0u8; (256 << 20) + 1]; - let stream = Stream::flate(Dict::new(), &data); + // A zlib stream of `len` zero bytes written directly (one literal, then matches of 258 + // bytes at distance 1 in a fixed-Huffman block): compressing 256 MiB would cost far more + // than decoding up to the cap. + fn zero_stream(len: usize) -> Stream { + struct Bits { + out: Vec, + acc: u64, + count: u32, + } + impl Bits { + fn put(&mut self, value: u64, count: u32) { + self.acc |= value << self.count; + self.count += count; + while self.count >= 8 { + self.out.push(self.acc as u8); + self.acc >>= 8; + self.count -= 8; + } + } + /// A Huffman code, packed most significant bit first. + fn code(&mut self, value: u64, count: u32) { + self.put(value.reverse_bits() >> (64 - count), count); + } + } + let mut w = Bits { out: vec![0x78, 0x9c], acc: 0, count: 0 }; + w.put(1, 1); + w.put(1, 2); + w.code(0x30, 8); + let mut left = len - 1; + while left >= 258 { + w.code(0xC5, 8); + w.put(0, 5); + left -= 258; + } + for _ in 0..left { + w.code(0x30, 8); + } + w.put(0, 7); + if w.count > 0 { + w.out.push(w.acc as u8); + } + let mut out = w.out; + out.extend_from_slice(&(((len % 65521) as u32) << 16 | 1).to_be_bytes()); + let mut dict = Dict::new(); + dict.set(b"Filter".to_vec(), Object::Name(b"FlateDecode".to_vec())); + Stream::from_raw(dict, out) + } + let small = zero_stream(1000); + assert_eq!(&small.decoded().unwrap()[..], &[0u8; 1000][..], "the hand-written stream is a valid one"); + let stream = zero_stream((256 << 20) + 1); assert!(matches!(stream.decoded(), Err(CosError::Filter(_)))); } diff --git a/crates/pdf/src/cos/parser.rs b/crates/pdf/src/cos/parser.rs index 5a0585ba3..899e86de8 100644 --- a/crates/pdf/src/cos/parser.rs +++ b/crates/pdf/src/cos/parser.rs @@ -977,7 +977,11 @@ mod tests { let at_cap = Lexer::new(wide(MAX_NODES - 1).as_bytes(), 0).object(); assert!(matches!(at_cap, Ok(Object::Array(ref items)) if items.len() == MAX_NODES - 1)); assert!(Lexer::new(wide(MAX_NODES).as_bytes(), 0).object().is_err()); - // The same inside a dictionary value and behind tolerated junk. + // The gate stops at the plain array (each case parses millions of operands); nightly adds the same budget inside a + // dictionary value, behind tolerated junk, and per top-level object. + if craft_testkit::hostile::divisor() > 1 { + return; + } assert!(Lexer::new(format!("<< /A {} >>", wide(MAX_NODES)).as_bytes(), 0).object().is_err()); assert!(Lexer::new(format!("[[{}] ]", "0 ".repeat(MAX_NODES)).as_bytes(), 0).object().is_err()); // The budget is per top-level object: a lexer reused for many operands keeps working. diff --git a/crates/pdf/tests/contracts.rs b/crates/pdf/tests/contracts.rs index 444f33d22..3d169a3c5 100644 --- a/crates/pdf/tests/contracts.rs +++ b/crates/pdf/tests/contracts.rs @@ -137,7 +137,7 @@ fn max_coverage_omits_excess_strokes_and_fast_rects() { let red = |px: &[u8]| px.as_chunks::<4>().0.iter().filter(|p| p[0] > 200 && p[2] < 50).count(); for (leaf, marker) in cases { - let bytes = doubling_forms_pdf(10, leaf, marker); + let bytes = doubling_forms_pdf(8, leaf, marker); let (whole, whole_warnings) = render_with_coverage_budget(bytes.clone(), None); assert!(!whole.diagnostics.content_truncated); assert_eq!(whole_warnings, 0); diff --git a/crates/pdf/tests/cos/encryption.rs b/crates/pdf/tests/cos/encryption.rs index 2f971214a..626d2d772 100644 --- a/crates/pdf/tests/cos/encryption.rs +++ b/crates/pdf/tests/cos/encryption.rs @@ -689,7 +689,7 @@ fn an_identity_crypt_filter_selected_by_reference_leaves_a_stream_alone() { fn protecting_drops_a_crypt_filter_selected_by_reference() { let protected = |doc: &mut Document| { doc.set_encryption(&NewEncryption { - algorithm: Algorithm::Aes256, + algorithm: Algorithm::Aes128, user_password: "", owner_password: "owner", permissions: -1, diff --git a/crates/pdf/tests/crypt/proptests.rs b/crates/pdf/tests/crypt/proptests.rs index 7b9ede4d3..9f642839d 100644 --- a/crates/pdf/tests/crypt/proptests.rs +++ b/crates/pdf/tests/crypt/proptests.rs @@ -100,6 +100,32 @@ fn make(algorithm: Algorithm, user: &str, owner: &str) -> SecurityHandler { .unwrap() } +/// The handler for `user` / `owner` per algorithm, derived once: AES-256's key derivation is +/// slow and these properties draw the same file for every case. +fn standard(algorithm: Algorithm) -> &'static SecurityHandler { + use std::sync::OnceLock; + static CACHE: [OnceLock; 4] = [OnceLock::new(), OnceLock::new(), OnceLock::new(), OnceLock::new()]; + let slot = match algorithm { + Algorithm::Rc4_40 => 0, + Algorithm::Rc4_128 => 1, + Algorithm::Aes128 => 2, + Algorithm::Aes256 => 3, + }; + CACHE[slot].get_or_init(|| make(algorithm, "user", "owner")) +} + +/// A file with no user password and the owner password `owner`, AES-256, derived once. +fn open_aes256() -> &'static SecurityHandler { + static HANDLER: std::sync::OnceLock = std::sync::OnceLock::new(); + 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)) +} + proptest! { /// Encrypting then decrypting returns the input at every length, as a string and as each kind /// of stream — and is byte-for-byte reproducible, because re-running a save must not silently @@ -107,7 +133,7 @@ proptest! { /// need an all-zero keystream to leave them alone, and CBC cannot shrink a padded block. #[test] fn content_survives_the_trip_at_every_length(alg in algorithms(), data in payloads()) { - let h = make(alg, "user", "owner"); + let h = standard(alg); // The key width each algorithm promises: 5 bytes for export-grade 40-bit RC4, 16 for // AES-128 and RC4-128, 32 for AES-256. `key_len` is the only place that decides this and @@ -116,7 +142,7 @@ proptest! { let want_len = match alg { Algorithm::Rc4_40 => 5, Algorithm::Aes128 | Algorithm::Rc4_128 => 16, Algorithm::Aes256 => 32 }; prop_assert_eq!(h.file_key().len(), want_len, "{:?} must use a {} byte file key", alg, want_len); - let h = make(alg, "user", "owner"); + let h = standard(alg); for num in [0u32, 1, 4096, u32::MAX] { let generation = (num % 65_535) as u16; @@ -143,7 +169,7 @@ proptest! { /// whatever the bytes are. An input shorter than the IV has nothing left to decode. #[test] fn damaged_ciphertext_never_panics(alg in algorithms(), enc in prop::collection::vec(any::(), 0..64)) { - let h = make(alg, "user", "owner"); + let h = standard(alg); for cut in 0..=enc.len() { let broken = &enc[..cut]; let out = h.decrypt_string(7, 3, broken); @@ -180,7 +206,7 @@ proptest! { name in prop::sample::select(vec!["Identity", "StdCF", "Nope"]), bogus_identity_in_cf in any::(), ) { - let mut d = make(Algorithm::Aes256, "", "owner").dict().clone(); + let mut d = open_aes256().dict().clone(); d.str_f = name.as_bytes().to_vec(); d.stm_f = b"Identity".to_vec(); d.ef_f = b"StdCF".to_vec(); @@ -223,7 +249,7 @@ proptest! { /// differs would prove less, because our initial vector already covers `/Num`. #[test] fn object_keys_are_scoped_to_their_object(alg in prop::sample::select(vec![Algorithm::Rc4_40, Algorithm::Rc4_128, Algorithm::Aes128]), data in prop::collection::vec(any::(), 8..40)) { - let h = make(alg, "user", "owner"); + let h = standard(alg); let enc = h.encrypt_string(100, 0, &data); prop_assert_eq!(h.decrypt_string(100, 0, &enc), &data[..], "{:?} reads its own object back", alg); @@ -240,7 +266,7 @@ proptest! { prop_assert_ne!(&h.decrypt_string(1 << 23, 0, &low)[..], &data[..], "{:?}: the third byte of /Num must still reach the key", alg); prop_assert_eq!(&h.decrypt_string(1 << 24, 0, &low)[..], &data[..], "{:?}: /Num is folded three bytes wide, so a difference above bit 23 shares the key by design", alg); - let r6 = make(Algorithm::Aes256, "user", "owner"); + let r6 = standard(Algorithm::Aes256); let enc6 = r6.encrypt_string(100, 0, &data); prop_assert_eq!(&r6.decrypt_string(101, 3, &enc6)[..], &data[..], "AES-256 uses the file key for every object (§7.6.3.3)"); // ...which is exactly why the initial vector has to vary: revisions 5 and 6 reuse one key @@ -251,6 +277,10 @@ proptest! { prop_assert_ne!(&r6.encrypt_string(100, 1, &data)[..], &enc6[..], "AES-256 reused the same initial vector across generations"); } +} + +proptest! { + #![proptest_config(cases(256, 12))] /// 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 @@ -308,6 +338,7 @@ proptest! { suspects.push(collision_partner.clone()); suspects.dedup(); + let user_session = SecurityHandler::open(d.clone(), ID, Some(&user)).ok(); for suspect in &suspects { let want = expected_auth(alg, &user_bytes, &owner_bytes, suspect); match (want, SecurityHandler::open(d.clone(), ID, Some(suspect))) { @@ -324,7 +355,7 @@ proptest! { // The owner password upgrades a user session; nothing else does. When the two share // bytes, `create` gave /O the user's own bytes (revisions 2–4) or left it empty // (AES-256, pdfcraft #1185's sharp edge), so the open password *is* an owner password here. - if let Ok(session) = SecurityHandler::open(d.clone(), ID, Some(&user)) { + if let Some(session) = &user_session { let is_owner_password = expected_auth(alg, &user_bytes, &owner_bytes, suspect) == Some(Auth::Owner); let upgrade = session.authenticate_owner(ID, suspect).map(|u| u.auth()); if is_owner_password { @@ -347,6 +378,9 @@ proptest! { } } +} + +proptest! { /// The AES-CBC and RC4 primitives taken directly: a damaged file's `/Length` and crypt filters /// hand them keys and data of shapes `create` would never build, so they must invert each other /// for any key length (`Cipher::new` takes AES-256 at 32 bytes and zero-padded AES-128 below @@ -377,6 +411,10 @@ proptest! { prop_assert_eq!(rc4(&[], &data), &data[..], "an empty RC4 key passes bytes through"); } +} + +proptest! { + #![proptest_config(cases(256, 12))] /// `/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 @@ -410,22 +448,15 @@ proptest! { prop_assert_eq!(as_user.permissions().copy(), normalised & 0b1_0000 != 0, "/P bit 5 decides copying"); prop_assert!(!as_user.permissions().owner, "the user password must not report owner rights"); - // Bytes 13-16 of /Perms are the non-repeating filler. Nothing reads them, so pinning that - // they move with the seed is the only way to notice a producer that freezes them at zero. - let other = create( - &NewEncryption { algorithm: Algorithm::Aes256, user_password: "user", owner_password: "owner", permissions, encrypt_metadata, seed: [0x11; 32] }, - ID, - ) - .unwrap(); - let open_other = aes_cbc_decrypt(other.file_key(), &[0u8; 16], &other.dict().perms, false); - prop_assert_ne!(&open[12..16], &open_other[12..16], "the four filler bytes of /Perms must follow the seed, not sit constant"); - // Revisions below 5 carry no /Perms; pinned so the boundary of what we emit is explicit. for older in [Algorithm::Rc4_40, Algorithm::Rc4_128, Algorithm::Aes128] { - let legacy = make(older, "user", "owner"); + let legacy = standard(older); prop_assert!(legacy.dict().perms.is_empty(), "{:?} must emit no /Perms", older); } } +} + +proptest! { /// Revisions 4 mix four set bytes into every file key when `/EncryptMetadata` is false (Algorithm /// 2, step f), so the same password over the same `/ID` must produce a *different* key than when /// metadata is encrypted. Every other test in this crate builds `encrypt_metadata: true` only, @@ -466,3 +497,18 @@ proptest! { } } + +/// Bytes 13-16 of `/Perms` are the non-repeating filler. Nothing reads them, so pinning that +/// they move with the seed is the only way to notice a producer that freezes them at zero. +#[test] +fn perms_filler_follows_the_seed() { + let perms = |seed: u8| { + let h = create( + &NewEncryption { algorithm: Algorithm::Aes256, user_password: "user", owner_password: "owner", permissions: -1, encrypt_metadata: true, seed: [seed; 32] }, + ID, + ) + .unwrap(); + aes_cbc_decrypt(h.file_key(), &[0u8; 16], &h.dict().perms, false) + }; + assert_ne!(&perms(0x5e)[12..16], &perms(0x11)[12..16], "the four filler bytes of /Perms must follow the seed, not sit constant"); +} diff --git a/crates/pkcs7/tests/it/crypto.rs b/crates/pkcs7/tests/it/crypto.rs index d92612a5e..e32a4f5b0 100644 --- a/crates/pkcs7/tests/it/crypto.rs +++ b/crates/pkcs7/tests/it/crypto.rs @@ -162,11 +162,16 @@ fn signatures_round_trip_for_every_key_type() { } } +/// New digital ids are self-signed, survive a `.p12` round trip, and are written with the stronger +/// round count for the key and the MAC. Key derivation takes the time here, so one file per key +/// type is written and opened once: the wrong password only for the P-256 file (it stops at the +/// MAC, which is the same code for both), and the round count read off the P-256 file. #[test] fn new_digital_ids_are_self_signed_and_survive_a_p12_round_trip() { let name = Name::build("Grace Hopper", "Compilers", "Navy", "grace@example.com", "us"); let now = Time { year: 2026, month: 10, day: 2, hour: 12, minute: 0, second: 0 }; for key in [craft_pkcs7::PrivateKey::generate_rsa(2048).unwrap(), craft_pkcs7::PrivateKey::generate_p256().unwrap()] { + let is_p256 = matches!(key.public_key(), PublicKey::P256(_)); let cert = Certificate::self_signed(&name, &key, now, 5, &[0x42, 0x01]).unwrap(); assert!(cert.is_self_signed()); assert_eq!(cert.subject.display(), "C=US, O=Navy, OU=Compilers, CN=Grace Hopper, E=grace@example.com"); @@ -177,7 +182,18 @@ fn new_digital_ids_are_self_signed_and_survive_a_p12_round_trip() { let back = pkcs12::open(&p12, "s3cret").unwrap(); assert_eq!(back.certificate, id.certificate); assert_eq!(back.friendly_name.as_deref(), Some("Grace Hopper")); - assert!(matches!(pkcs12::open(&p12, "wrong"), Err(Error::WrongPassword))); + if is_p256 { + assert!(matches!(pkcs12::open(&p12, "wrong"), Err(Error::WrongPassword))); + // OWASP's figure for PBKDF2-HMAC-SHA-256, spelled out so lowering the constant fails here. + const ROUNDS: u64 = 600_000; + // MacData's iteration count, the last field of the file. + let pfx = Tlv::parse_all(&p12).unwrap().children().unwrap(); + let mac = pfx[2].children().unwrap(); + assert_eq!(mac[2].u64().unwrap(), ROUNDS); + // The same INTEGER three times: the MAC and the PBKDF2 parameters of both encrypted parts. + let rounds = craft_pkcs7::der::int(ROUNDS); + assert_eq!(p12.windows(rounds.len()).filter(|w| *w == rounds.as_slice()).count(), 3); + } let d = DigestAlg::Sha256.digest(&[b"x"]); let sig = cms::sign_detached(&back.key, &back.certificate, &[], DigestAlg::Sha256, &d).unwrap(); let sd = cms::SignedData::parse(&sig).unwrap(); @@ -185,26 +201,6 @@ fn new_digital_ids_are_self_signed_and_survive_a_p12_round_trip() { } } -#[test] -fn new_digital_ids_use_the_stronger_round_count_for_the_key_and_the_mac() { - let name = Name::build("Grace Hopper", "", "", "", ""); - let now = Time { year: 2026, month: 10, day: 14, hour: 12, minute: 0, second: 0 }; - let key = craft_pkcs7::PrivateKey::generate_p256().unwrap(); - let certificate = Certificate::self_signed(&name, &key, now, 5, &[0x42]).unwrap(); - let id = pkcs12::DigitalId { key, certificate, chain: Vec::new(), friendly_name: None }; - let p12 = pkcs12::write(&id, "s3cret12").unwrap(); - // OWASP's figure for PBKDF2-HMAC-SHA-256, spelled out so lowering the constant fails here. - const ROUNDS: u64 = 600_000; - // MacData's iteration count, the last field of the file. - let pfx = Tlv::parse_all(&p12).unwrap().children().unwrap(); - let mac = pfx[2].children().unwrap(); - assert_eq!(mac[2].u64().unwrap(), ROUNDS); - // The same INTEGER three times: the MAC and the PBKDF2 parameters of both encrypted parts. - let rounds = craft_pkcs7::der::int(ROUNDS); - assert_eq!(p12.windows(rounds.len()).filter(|w| *w == rounds.as_slice()).count(), 3); - assert_eq!(pkcs12::open(&p12, "s3cret12").unwrap().certificate, id.certificate); -} - /// A `.p12` whose MAC asks for `rounds` iterations. Its content is empty: opening it must stop /// at the MAC, before the content is read. fn p12_with_mac_rounds(rounds: u64) -> Vec { diff --git a/crates/prepress/Cargo.toml b/crates/prepress/Cargo.toml index 1ef038436..8fd6c92f2 100644 --- a/crates/prepress/Cargo.toml +++ b/crates/prepress/Cargo.toml @@ -20,6 +20,7 @@ linesweeper = { version = "0.5", optional = true } ttf-parser = { version = "=0.25.1", optional = true } [dev-dependencies] +craft-testkit = { workspace = true } craft-plate-test = { workspace = true } ttf-parser = "=0.25.1" diff --git a/crates/prepress/src/plates.rs b/crates/prepress/src/plates.rs index 8344e78b0..0a5d1ed8f 100644 --- a/crates/prepress/src/plates.rs +++ b/crates/prepress/src/plates.rs @@ -532,7 +532,8 @@ endstream endobj fn bands_reach_resolutions_past_the_plate_cap_and_can_stop() { let pdf = disc_and_spot(); // 40 pt at 3700 dpi is 2055 pixels a side: 4.2 MP, past `MAX_PLATE_PIXELS`. - assert!(plates(&pdf, 0, 3700.0, &Options::default()).unwrap().dpi < 3700.0); + // (The whole-page entry point reduces by `plate_scale`; the bands below are not reduced.) + assert!(plate_scale(40.0, 40.0, 3700.0 / 72.0) < 3700.0 / 72.0); let mut bands = Vec::new(); plates_in_bands(&pdf, 0, 3700.0, &Options::default(), |band| { let p = &band.plates; diff --git a/crates/proof/Cargo.toml b/crates/proof/Cargo.toml index 60cea674d..632016f4f 100644 --- a/crates/proof/Cargo.toml +++ b/crates/proof/Cargo.toml @@ -18,4 +18,5 @@ toml = { version = "1", default-features = false, features = ["parse", "serde", unicode-normalization = "0.1" [dev-dependencies] +craft-testkit = { workspace = true } proptest = { workspace = true } diff --git a/crates/proof/src/affix_suggest.rs b/crates/proof/src/affix_suggest.rs index ba72d8ebd..0ad2e5be1 100644 --- a/crates/proof/src/affix_suggest.rs +++ b/crates/proof/src/affix_suggest.rs @@ -883,7 +883,9 @@ mod tests { aff.push_str("SFX 9000 Y 1\nSFX 9000 0 s .\n"); let d = AffixDict::from_hunspell(&aff, "3\nb/1,5000\nab/2\nkot/9000\n", &[]).unwrap(); assert!(!d.stems().any(|s| s == "kots") && d.can_suggest("kots")); - for word in [input.clone(), input.to_uppercase()] { + // The gate asks for the word as typed; nightly adds the upper-case spelling (the case fallback). + let words = if craft_testkit::hostile::divisor() == 1 { vec![input.clone(), input.to_uppercase()] } else { vec![input.clone()] }; + for word in words { let got = suggest_in(&d, &word, 1, &Tuning::DEFAULT); assert_eq!(got.len(), 1, "accepted affixed candidate lost: {word}: {got:?}"); assert!(got[0].eq_ignore_ascii_case("kots"), "{word}: {got:?}"); diff --git a/crates/proto/Cargo.toml b/crates/proto/Cargo.toml index 528e407a8..8657aa51e 100644 --- a/crates/proto/Cargo.toml +++ b/crates/proto/Cargo.toml @@ -17,4 +17,5 @@ zeroize = "1" log = { workspace = true } [dev-dependencies] +craft-testkit = { workspace = true } proptest = { workspace = true } diff --git a/crates/proto/src/imap/gmail_labels_tests.rs b/crates/proto/src/imap/gmail_labels_tests.rs index 441e3220b..1673af4e3 100644 --- a/crates/proto/src/imap/gmail_labels_tests.rs +++ b/crates/proto/src/imap/gmail_labels_tests.rs @@ -165,6 +165,10 @@ fn tiny_labels_count_against_the_budget_too() { #[test] fn a_big_folders_listing_is_not_cut_short_for_its_size() { + // Sized to a cap of tens of MiB: the gate runs the cheaper tests of the same caps, nightly runs this one. + if craft_testkit::hostile::divisor() > 1 { + return; + } // 300,000 messages with labels: more text than one command may otherwise bring (32 MiB). let count: u32 = 300_000; let mut server = String::with_capacity(count as usize * 200); @@ -185,6 +189,10 @@ fn a_big_folders_listing_is_not_cut_short_for_its_size() { #[test] fn a_mailbox_claimed_huge_cant_fill_memory_with_flags() { + // Sized to a cap of tens of MiB: the gate runs the cheaper tests of the same caps, nightly runs this one. + if craft_testkit::hostile::divisor() > 1 { + return; + } // Any server (no Gmail here): ten million messages claimed, then message after message with // every flag it may have. The text it may send is capped, and so are the flags kept: the // listing fails, and never hands back messages that seem to have lost their flags. diff --git a/crates/proto/src/imap/limits_tests.rs b/crates/proto/src/imap/limits_tests.rs index 9b802055c..5da103e39 100644 --- a/crates/proto/src/imap/limits_tests.rs +++ b/crates/proto/src/imap/limits_tests.rs @@ -26,13 +26,16 @@ fn padding() -> String { #[test] fn a_flood_of_long_lines_ends_the_command() { let pad = padding(); - // 600 lines of 60 KB are more than the 32 MB one command may bring. - let server = flood(600, |n| format!("* {n} FETCH (UID {} FLAGS ({pad}))\r\n", n + 1)) + "A0001 OK done\r\n"; + // 600 lines of 60 KB are more than the 32 MB one command may bring. The gate sends lines that + // are not parsed (the cap counts the text read); nightly sends the lines of a real listing. + let full = craft_testkit::hostile::divisor() == 1; + let server = flood(600, |n| if full { format!("* {n} FETCH (UID {} FLAGS ({pad}))\r\n", n + 1) } else { format!("* OK {pad}\r\n") }) + + "A0001 OK done\r\n"; let mut s = Script::new(server); let err = opened(&mut s, 1000, 2000).uid_fetch_flags("1:*").unwrap_err(); assert!(matches!(err, ProtoError::Protocol(ref m) if m.to_string().contains("too much")), "{err:?}"); // The same in a list. - let server = flood(600, |n| format!("* LIST () \"/\" \"{n}{pad}\"\r\n")) + "A0001 OK done\r\n"; + let server = flood(600, |n| if full { format!("* LIST () \"/\" \"{n}{pad}\"\r\n") } else { format!("* OK {pad}\r\n") }) + "A0001 OK done\r\n"; let mut s = Script::new(server); assert!(matches!(opened(&mut s, 0, 0).list(), Err(ProtoError::Protocol(_)))); } @@ -120,6 +123,9 @@ fn more_distinct_uids_than_the_mailbox_can_hold_fail_the_command() { assert_eq!(opened(&mut s, 3, u32::MAX).uid_fetch_flags("1:*").unwrap().len(), room); let mut s = Script::new(many(room + 1)); assert!(matches!(opened(&mut s, 3, u32::MAX).uid_fetch_flags("1:*"), Err(ProtoError::Protocol(_)))); + if !full { + return; + } let sizes = flood(room + 1, |i| format!("* {i} FETCH (UID {} RFC822.SIZE 1)\r\n", i + 1)) + "A0001 OK done\r\n"; let mut s = Script::new(sizes); assert!(matches!(opened(&mut s, 3, u32::MAX).uid_fetch_sizes("1:*"), Err(ProtoError::Protocol(_)))); @@ -177,7 +183,9 @@ proptest! { #[test] fn a_folder_with_more_messages_than_other_commands_may_answer_still_reads() { - let exists = 300_000u32; + // The gate reads one folder just past the usual cap; nightly adds the sizes and the noise. + let full = craft_testkit::hostile::divisor() == 1; + let exists = if full { 300_000u32 } else { MAX_RESPONSES as u32 + 1 }; let lines = |n: u32| flood(n as usize, |i| format!("* {i} FETCH (UID {} FLAGS ())\r\n", i + 1)) + "A0001 OK done\r\n"; let mut s = Script::new(lines(exists)); assert_eq!(opened(&mut s, exists, exists + 1).uid_fetch_flags("1:*").unwrap().len(), exists as usize); diff --git a/crates/psd/Cargo.toml b/crates/psd/Cargo.toml index 30bf3a471..b08ca6ae1 100644 --- a/crates/psd/Cargo.toml +++ b/crates/psd/Cargo.toml @@ -28,6 +28,7 @@ serde = { workspace = true, optional = true } rayon = { workspace = true } [dev-dependencies] +craft-testkit = { workspace = true } proptest = { workspace = true } craft-psd = { path = ".", features = ["test-support"] } diff --git a/crates/psd/src/lazy.rs b/crates/psd/src/lazy.rs index 271d22088..98f885768 100644 --- a/crates/psd/src/lazy.rs +++ b/crates/psd/src/lazy.rs @@ -525,7 +525,8 @@ mod tests { let clean = std::sync::Arc::new(FailOnce { bytes: bytes.clone(), fail_at: usize::MAX, reads: 0.into() }); PsdFile::from_source(Source::from_arc(clean.clone())).unwrap(); let reads = clean.reads.load(std::sync::atomic::Ordering::SeqCst); - for fail_at in 0..reads { + // The gate fails every divisor-th read; nightly fails each one. + for fail_at in (0..reads).step_by(craft_testkit::hostile::divisor()) { let src = FailOnce { bytes: bytes.clone(), fail_at, reads: 0.into() }; match PsdFile::from_source(Source::new(src)) { Err(PsdError::Read(_)) => {} diff --git a/crates/pst/Cargo.toml b/crates/pst/Cargo.toml index 60ead7d8f..9dff7fa17 100644 --- a/crates/pst/Cargo.toml +++ b/crates/pst/Cargo.toml @@ -20,5 +20,6 @@ workspace = true [dependencies] [dev-dependencies] +craft-testkit = { workspace = true } craft-pst = { path = ".", features = ["test-support"] } proptest = { workspace = true } diff --git a/crates/pst/src/tests/salvage.rs b/crates/pst/src/tests/salvage.rs index 7d5d391ea..b7f341b7a 100644 --- a/crates/pst/src/tests/salvage.rs +++ b/crates/pst/src/tests/salvage.rs @@ -248,7 +248,9 @@ fn a_reader_that_fails_or_runs_out_ends_the_call() { } }; let mut failed = 0; - for (fail, short) in (1..=reads).flat_map(|n| [(n, false), (n, true)]) { + // The gate fails every divisor-th read; nightly fails each one. + let step = craft_testkit::hostile::divisor(); + for (fail, short) in (1..=reads).step_by(step).flat_map(|n| [(n, false), (n, true)]) { let Ok(mut pst) = Pst::open(Flaky { inner: Cursor::new(&bytes[..]), reads: 0, fail, short }) else { continue }; let got = answers(&mut pst, &folders, &items); failed += got.iter().filter(|r| r.is_err()).count(); @@ -257,7 +259,7 @@ fn a_reader_that_fails_or_runs_out_ends_the_call() { } assert!(failed > 0); let mut capped = 0; - for floor in (0..bytes.len() as u64 * 4).step_by(256) { + for floor in (0..bytes.len() as u64 * 4).step_by(256 * step) { let limits = Limits { read_multiple: 0, read_floor: floor, ..Default::default() }; let Ok(mut pst) = Pst::open_with(Cursor::new(&bytes[..]), limits) else { continue }; let got = answers(&mut pst, &folders, &items); diff --git a/crates/raw/Cargo.toml b/crates/raw/Cargo.toml index ddb1dbf2e..a99d44747 100644 --- a/crates/raw/Cargo.toml +++ b/crates/raw/Cargo.toml @@ -70,6 +70,7 @@ zune-core = { version = "0.5", default-features = false, features = ["std"], opt jxl-oxide = { version = "0.12", default-features = false, optional = true } [dev-dependencies] +craft-testkit = { workspace = true } proptest = { workspace = true } # The SHA-256 of the SR2 keystream known answer. sha2 = { version = "0.10", default-features = false, features = ["std"] } diff --git a/crates/raw/src/arw_lens.rs b/crates/raw/src/arw_lens.rs index b42d3afe0..c023bf071 100644 --- a/crates/raw/src/arw_lens.rs +++ b/crates/raw/src/arw_lens.rs @@ -1377,10 +1377,12 @@ mod tests { assert_eq!((h.lens_metadata, h.opcodes), (f.lens_metadata, f.opcodes)); } }; - for len in 0..good.len() { + // The gate runs every divisor-th truncation and byte; nightly runs every one. + let step = craft_testkit::hostile::divisor(); + for len in (0..good.len()).step_by(step) { check(&good[..len]); } - for at in (0..good.len()).filter(|at| !image.contains(at)) { + for at in (0..good.len()).step_by(step).filter(|at| !image.contains(at)) { for v in [0, 0xff, good[at] ^ 0x80, good[at] ^ 0x01] { let mut file = good.clone(); file[at] = v; diff --git a/crates/raw/tests/it/dng_lines.rs b/crates/raw/tests/it/dng_lines.rs index dd10c763c..a1acdb9dd 100644 --- a/crates/raw/tests/it/dng_lines.rs +++ b/crates/raw/tests/it/dng_lines.rs @@ -260,6 +260,10 @@ fn a_lossless_jpeg_larger_than_its_tile_is_refused_before_decoding_it_all() { #[test] fn short_lossy_jpeg_strips_are_charged_their_own_rows() { + // A 33-megapixel image next to the aggregate decode budget: nightly only. + if craft_testkit::hostile::divisor() > 1 { + return; + } // 8192 x 4096 RGB (below MAX_SAMPLES) in 16-row lossy JPEG strips: each strip's JPEG is exactly // 16 rows, so the decode budget charges 16 rows, not the 32 of the MCU padding allowance (which // would put the image over the aggregate budget and refuse it) diff --git a/crates/scraft-format/Cargo.toml b/crates/scraft-format/Cargo.toml index 9ec17cf9f..e445ff119 100644 --- a/crates/scraft-format/Cargo.toml +++ b/crates/scraft-format/Cargo.toml @@ -20,5 +20,6 @@ serde_json.workspace = true thiserror.workspace = true [dev-dependencies] +craft-testkit = { workspace = true } craft-audio = { workspace = true, features = ["decode", "serde"] } proptest.workspace = true diff --git a/crates/scraft-format/src/b64.rs b/crates/scraft-format/src/b64.rs index 100a9a08f..b4421c00b 100644 --- a/crates/scraft-format/src/b64.rs +++ b/crates/scraft-format/src/b64.rs @@ -104,10 +104,13 @@ mod tests { // 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"); - assert_eq!(decode(exact.trim_end_matches('=')).map(|bytes| bytes.len()), Some(MAX_DECODED_BYTES), "unpadded 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; + } + 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"); } diff --git a/crates/stream-codecs/Cargo.toml b/crates/stream-codecs/Cargo.toml index 14ce68603..173925212 100644 --- a/crates/stream-codecs/Cargo.toml +++ b/crates/stream-codecs/Cargo.toml @@ -21,5 +21,6 @@ hayro-jbig2 = { path = "../../vendor/hayro-jbig2", version = "=0.3.0", default-f thiserror = { workspace = true } [dev-dependencies] +craft-testkit = { workspace = true } proptest = { workspace = true } weezl = "0.2" diff --git a/crates/stream-codecs/src/jbig2/symbols.rs b/crates/stream-codecs/src/jbig2/symbols.rs index f56503a84..56f5e26ff 100644 --- a/crates/stream-codecs/src/jbig2/symbols.rs +++ b/crates/stream-codecs/src/jbig2/symbols.rs @@ -942,6 +942,10 @@ mod tests { let past = page(&data, columns).unwrap(); assert!(plan(&past, columns, rows, 1, None, None).is_none() && plan(&past, columns, rows, 2, None, None).is_none()); assert_eq!(encode_jbig2(&data, columns, rows).unwrap(), encode_jbig2_generic(&data, columns, rows).unwrap()); + // Each picture below is another 65,536 marks coded and decoded: nightly only. + if craft_testkit::hostile::divisor() > 1 { + return; + } // With two of them repeated, the second plan codes those two. let (data, columns, rows) = codes(MAX_CODED_SYMBOLS + 1, 200); let past = page(&data, columns).unwrap(); diff --git a/crates/wordmodel/src/table.rs b/crates/wordmodel/src/table.rs index bb951aa67..48584925c 100644 --- a/crates/wordmodel/src/table.rs +++ b/crates/wordmodel/src/table.rs @@ -723,9 +723,9 @@ mod tests { assert_eq!(t.rows.len(), 3); assert_eq!(t.cols(), 4); assert_eq!(t.total_width(), 468.0); - let huge = Table::new(1_000_000, 1000, 100.0); - assert_eq!(huge.rows.len(), MAX_ROWS); - assert_eq!(huge.cols(), MAX_COLS); + // Each cap on its own: the grid of both at once would be millions of cells. + assert_eq!(Table::new(1_000_000, 1, 100.0).rows.len(), MAX_ROWS); + assert_eq!(Table::new(1, 1000, 100.0).cols(), MAX_COLS); } #[test] diff --git a/crates/xfl/Cargo.toml b/crates/xfl/Cargo.toml index 9c8a40e3c..0375ab09c 100644 --- a/crates/xfl/Cargo.toml +++ b/crates/xfl/Cargo.toml @@ -14,3 +14,6 @@ workspace = true craft-xml = { workspace = true } miniz_oxide = "0.8" thiserror = { workspace = true } + +[dev-dependencies] +craft-testkit = { workspace = true } diff --git a/crates/xfl/src/tests.rs b/crates/xfl/src/tests.rs index 6075e4e57..064f22431 100644 --- a/crates/xfl/src/tests.rs +++ b/crates/xfl/src/tests.rs @@ -206,8 +206,8 @@ fn lying_sizes_and_checksums_are_damaged() { #[test] fn compression_bombs_are_refused() { - // A real 64 MB of zeros deflates past the ratio cap: refused before inflating. - let zeros = vec![0u8; 64 << 20]; + // A real 16 MiB of zeros deflates past the ratio cap: refused before inflating. + let zeros = vec![0u8; 16 << 20]; let z = zip(&[("bomb.xml", &zeros, true)]); assert!(z.len() < 100_000, "{}", z.len()); assert_eq!(Archive::open(&z).err(), Some(ZipError::Bomb("bomb.xml".into()))); diff --git a/crates/xlsx/Cargo.toml b/crates/xlsx/Cargo.toml index 18be3abe7..2b0ef958a 100644 --- a/crates/xlsx/Cargo.toml +++ b/crates/xlsx/Cargo.toml @@ -22,4 +22,5 @@ craft-xml = { workspace = true } thiserror = { workspace = true } [dev-dependencies] +craft-testkit = { workspace = true } craft-xlsx = { path = ".", features = ["test-support"] } diff --git a/crates/xlsx/tests/it/xlsb.rs b/crates/xlsx/tests/it/xlsb.rs index e32489e45..a6a189510 100644 --- a/crates/xlsx/tests/it/xlsb.rs +++ b/crates/xlsx/tests/it/xlsb.rs @@ -312,11 +312,12 @@ fn declared_counts_and_decoded_text_are_bounded() { assert!(read(&package(&book(false), &worksheet(&[], &[]), &count_mismatch, ROOT, RELS, TYPES)).is_err()); let mut data = row(0); let text = wide(&"x".repeat(32767)); - for col in 0..2050 { + for col in 0..40 { data.extend(cell(6, col, &text)); } - // Just over 64 MiB of text, the allowance before storytold/gridcraft#2126. - assert_eq!(read(&file(&worksheet(&data, &[]))).unwrap().sheets[0].cells.len(), 2050); + // Many maximal strings fit an allowance sized to them (storytold/gridcraft#2126: a fixed 64 MiB allowance refused a real file). + let limits = Limits { binary_text: 40 * 32767 + 1000, ..Limits::default() }; + assert_eq!(read_with(&file(&worksheet(&data, &[])), &limits).unwrap().sheets[0].cells.len(), 40); } /// A row as Excel writes it: the row header, then `BrtRwDescent` (1024) in an alternate-content @@ -353,6 +354,11 @@ fn two_sheets(one: &[u8], two: &[u8]) -> Vec { #[test] fn more_than_a_million_cells_open() { // storytold/gridcraft#2126: a million cells over the workbook was a quarter of what `.xls` allows. + assert!(Limits::default().binary_cells > 1_000_000); + // Reading that many cells: nightly only. + if craft_testkit::hostile::divisor() > 1 { + return; + } let wb = read(&file(&worksheet(&bool_cells(1_000_001, 16), &[]))).unwrap(); assert_eq!(wb.sheets[0].cells.len(), 1_000_001); assert_eq!(wb.sheets[0].value(CellRef::new(62_500, 0)), Value::Bool(true)); @@ -360,39 +366,45 @@ fn more_than_a_million_cells_open() { #[test] fn a_full_height_column_opens() { - // 1,048,576 cells in Excel's rows are 5.2 million records in one part. - let wb = read(&file(&worksheet(&bool_cells(1_048_576, 1), &[]))).unwrap(); - assert_eq!(wb.sheets[0].cells.len(), 1_048_576); - assert_eq!(wb.sheets[0].value(CellRef::new(1_048_575, 0)), Value::Bool(true)); + // A column of n cells in Excel's rows is five records a cell in one part; limits sized for + // n cells (the defaults are sized for a full 1,048,576-row column) admit it. + let n = 20_000u32; + let limits = Limits { binary_cells: n as usize, binary_records: 5 * n as usize + 100, ..Limits::default() }; + let wb = read_with(&file(&worksheet(&bool_cells(n, 1), &[])), &limits).unwrap(); + assert_eq!(wb.sheets[0].cells.len(), n as usize); + assert_eq!(wb.sheets[0].value(CellRef::new(n - 1, 0)), Value::Bool(true)); } #[test] fn formatted_blank_cells_cost_records_not_cells() { - // Filling A1:Z200000 and typing 30 values: Excel writes a BrtCellBlank for every formatted - // empty cell, 6 million records in all, which an allowance of 5 million per part refused. + // Filling A1:Z2000 and typing 30 values: Excel writes a BrtCellBlank for every formatted + // empty cell, 60 thousand records in all, which a cell-sized allowance of 5 times the cells + // (here 30 * 5) would refuse; the record allowance is separate from the cell allowance. let mut data = vec![]; - for r in 0..200_000u32 { + for r in 0..2_000u32 { data.extend(excel_row(r)); for c in 0..26 { data.extend(if r < 10 && c < 3 { cell(4, c, &[1]) } else { cell(1, c, &[]) }); } } - let wb = read(&file(&worksheet(&data, &[]))).unwrap(); + let limits = Limits { binary_records: 70_000, binary_cells: 100, ..Limits::default() }; + let wb = read_with(&file(&worksheet(&data, &[])), &limits).unwrap(); assert_eq!(wb.sheets[0].cells.len(), 30); } #[test] fn cells_are_limited_to_four_million_over_the_workbook() { - // The `.xls` limit, counted across sheets: 2M + 2M opens, 2M + 2M + 1 does not. - let half = bool_cells(2_000_000, 40); + // The limit is counted across sheets: half + half opens, half + half + 1 does not. + let half = bool_cells(2_000, 40); let mut over = half.clone(); - over.extend(excel_row(50_000)); + over.extend(excel_row(50)); over.extend(cell(4, 0, &[1])); - let wb = read(&two_sheets(&worksheet(&half, &[]), &worksheet(&half, &[]))).unwrap(); - assert_eq!(wb.sheets.iter().map(|s| s.cells.len()).sum::(), 4_000_000); - let err = read(&two_sheets(&worksheet(&half, &[]), &worksheet(&over, &[]))).err().unwrap(); + let limits = Limits { binary_cells: 4_000, ..Limits::default() }; + let wb = read_with(&two_sheets(&worksheet(&half, &[]), &worksheet(&half, &[])), &limits).unwrap(); + assert_eq!(wb.sheets.iter().map(|s| s.cells.len()).sum::(), 4_000); + let err = read_with(&two_sheets(&worksheet(&half, &[]), &worksheet(&over, &[])), &limits).err().unwrap(); assert!(matches!(err, Error::TooLarge(_)), "{err}"); - assert!(err.to_string().contains("4000000"), "{err}"); + assert!(err.to_string().contains("4000"), "{err}"); } #[test] @@ -403,14 +415,15 @@ fn records_share_one_allowance_over_the_workbook() { let records = |n| Limits { binary_records: n, ..Limits::default() }; assert!(matches!(read_with(&bytes, &records(2_000)), Err(Error::TooLarge(_)))); assert!(read_with(&bytes, &records(4_000)).is_ok()); - // The default allowance: exactly 40 million records, then one more. The other parts hold 20 + // Exactly the allowance, then one more. The other parts hold 20 // (7 in the workbook, 3 shared-string records, 5 + 5 sheet framing records). let filler = record(30, &[]); // Not a cell record: skipped inside the sheet data. - let mut data = filler.repeat(40_000_000 - 20); - assert!(read(&file(&worksheet(&data, &[]))).is_ok()); + let exact = Limits { binary_records: 100_000, ..Limits::default() }; + let mut data = filler.repeat(100_000 - 20); + assert!(read_with(&file(&worksheet(&data, &[])), &exact).is_ok()); data.extend(filler.repeat(1)); - let err = read(&file(&worksheet(&data, &[]))).err().unwrap(); - assert!(matches!(err, Error::TooLarge(_)) && err.to_string().contains("too many records (more than 40000000)"), "{err}"); + let err = read_with(&file(&worksheet(&data, &[])), &exact).err().unwrap(); + assert!(matches!(err, Error::TooLarge(_)) && err.to_string().contains("too many records (more than 100000)"), "{err}"); } #[test] diff --git a/crates/xml/Cargo.toml b/crates/xml/Cargo.toml index 02d68985b..d7743f973 100644 --- a/crates/xml/Cargo.toml +++ b/crates/xml/Cargo.toml @@ -14,3 +14,6 @@ workspace = true quick-xml = { version = "0.41", default-features = false } thiserror = { workspace = true } serde = { workspace = true, features = ["derive"] } + +[dev-dependencies] +craft-testkit = { workspace = true } diff --git a/crates/xml/tests/it/hostile.rs b/crates/xml/tests/it/hostile.rs index 19efdd235..1065a2dff 100644 --- a/crates/xml/tests/it/hostile.rs +++ b/crates/xml/tests/it/hostile.rs @@ -308,19 +308,24 @@ fn mismatched_tags_are_repaired_or_refused() { /// 5 MB of input. #[test] fn attributes_are_bounded_over_the_whole_tree() { - let el = format!("", " a=\"\"".repeat(1024)); - let doc = format!("{}", el.repeat(1025)); - let limits = Limits { max_attrs_total: 1024 * 1024, ..Limits::DEFAULT }; + // `ATTRS` attributes on each of `ATTRS + 1` elements, against a limit of `ATTRS` elements' worth. + const ATTRS: usize = 64; + let el = format!("", " a=\"\"".repeat(ATTRS)); + let doc = format!("{}", el.repeat(ATTRS + 1)); + let limits = Limits { max_attrs_total: ATTRS * ATTRS, ..Limits::DEFAULT }; let opts = Options::default().with_limits(limits); let err = opts.parse(doc.as_bytes()).unwrap_err(); - assert_eq!(err, Error::TooManyAttrsTotal(1024 * 1024)); + assert_eq!(err, Error::TooManyAttrsTotal(ATTRS * ATTRS)); assert!(err.is_limit()); // exactly at the limit is accepted - let fits = format!("{}", el.repeat(1024)); - assert_eq!(opts.parse(fits.as_bytes()).map(|r| r.children.len()), Ok(1024)); - // the default stops a document that is nothing but attributes - let hostile = format!("{}", el.repeat(4000)); - assert_eq!(parse(hostile.as_bytes()), Err(Error::TooManyAttrsTotal(4_000_000))); + let fits = format!("{}", el.repeat(ATTRS)); + assert_eq!(opts.parse(fits.as_bytes()).map(|r| r.children.len()), Ok(ATTRS)); + // the default stops a document that is nothing but attributes (millions of them: nightly only) + if craft_testkit::hostile::divisor() == 1 { + let el = format!("", " a=\"\"".repeat(1024)); + let hostile = format!("{}", el.repeat(4000)); + assert_eq!(parse(hostile.as_bytes()), Err(Error::TooManyAttrsTotal(4_000_000))); + } // streamed elements take their attributes with them: any number of rows, as long as the // ones held at once fit let mut rows = 0; @@ -328,9 +333,9 @@ fn attributes_are_bounded_over_the_whole_tree() { rows += c.attrs.len(); Ok::<(), Error>(()) }); - assert_eq!((rows, root.map(|r| r.children.len())), (1025 * 1024, Ok(0))); - let tight = Options::default().with_limits(Limits { max_attrs_total: 1023, ..Limits::DEFAULT }); - assert_eq!(tight.parse_streaming(doc.as_bytes(), &["c"], |_| Ok::<(), Error>(())), Err(Error::TooManyAttrsTotal(1023))); + assert_eq!((rows, root.map(|r| r.children.len())), ((ATTRS + 1) * ATTRS, Ok(0))); + let tight = Options::default().with_limits(Limits { max_attrs_total: ATTRS * ATTRS - 1, ..Limits::DEFAULT }); + assert_eq!(tight.parse_streaming(doc.as_bytes(), &["c"], |_| Ok::<(), Error>(())), Err(Error::TooManyAttrsTotal(ATTRS * ATTRS - 1))); } /// An internal subset is found wherever it hides, and looking for it is linear in the input.