From 9730c888fba05ee9d477e0bd49017ea55ff0355f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 02:01:10 -0800 Subject: [PATCH] Tests: seed the PDF file key test through protect The test called Entropy::seeded directly, so it still passed if export stopped reading the OS random source. Entropy::new now reads the OS bytes and the time through seed_sources(), which a test can set for its thread, and the test runs protect with fixed OS bytes, other OS bytes and a failed OS read. The OS read in vectorcraft-js's os_random() is now one function for tests and builds alike. --- crates/js/src/interp.rs | 22 ++++++++++-------- crates/pdf/src/encrypt.rs | 40 ++++++++++++++++++++++++++++----- crates/pdf/src/tests/encrypt.rs | 25 ++++++++++++++------- 3 files changed, 64 insertions(+), 23 deletions(-) diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 05e704b08e..dac4a0c729 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -547,22 +547,26 @@ fn random_seed() -> u64 { random_seed_from(os_random()) } -/// The OS random source. -#[cfg(not(test))] -fn os_random() -> Result { - getrandom::u64() -} - #[cfg(test)] thread_local! { /// What the OS random source returns to realms made on this thread, when set. pub(crate) static TEST_OS_RANDOM: std::cell::Cell>> = const { std::cell::Cell::new(None) }; } -/// The OS random source, or what a test set in [`TEST_OS_RANDOM`]. -#[cfg(test)] +/// The OS random source (in tests, what `TEST_OS_RANDOM` holds when set). fn os_random() -> Result { - TEST_OS_RANDOM.with(std::cell::Cell::get).unwrap_or_else(getrandom::u64) + test_os_random().unwrap_or_else(getrandom::u64) +} + +/// What a test set in `TEST_OS_RANDOM`. +#[cfg(test)] +fn test_os_random() -> Option> { + TEST_OS_RANDOM.with(std::cell::Cell::get) +} + +#[cfg(not(test))] +fn test_os_random() -> Option> { + None } /// [`random_seed`] from what the OS random source returned. diff --git a/crates/pdf/src/encrypt.rs b/crates/pdf/src/encrypt.rs index 4807763598..e9d845756c 100644 --- a/crates/pdf/src/encrypt.rs +++ b/crates/pdf/src/encrypt.rs @@ -163,22 +163,50 @@ fn hash6(password: &[u8], salt: &[u8], udata: &[u8]) -> Result<[u8; 32], PdfErro } /// Unpredictable bytes: SHA-256 of a seed and a counter. -pub(crate) struct Entropy { +struct Entropy { seed: [u8; 32], counter: u64, } +/// What the OS random source returned, and the time. +type SeedSources = (Result<[u8; 32], getrandom::Error>, i64); + +#[cfg(test)] +thread_local! { + /// What the OS random source and the clock return to [`Entropy::new`] on this thread, when set. + pub(crate) static TEST_SEED_SOURCES: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +/// 32 bytes from the OS random source, and the time. +fn seed_sources() -> SeedSources { + test_seed_sources().unwrap_or_else(|| { + let mut os = [0u8; 32]; + let os = getrandom::fill(&mut os).map(|()| os); + (os, vectorcraft_doc::metadata::now_unix().unwrap_or_default()) + }) +} + +/// What a test set in `TEST_SEED_SOURCES`. +#[cfg(test)] +fn test_seed_sources() -> Option { + TEST_SEED_SOURCES.with(std::cell::Cell::get) +} + +#[cfg(not(test))] +fn test_seed_sources() -> Option { + None +} + impl Entropy { /// Seeded from the OS random source, with the time and `material` mixed in. fn new(material: &[&[u8]]) -> Result { - let mut os = [0u8; 32]; - let os = getrandom::fill(&mut os).map(|()| os); - Self::seeded(os, vectorcraft_doc::metadata::now_unix().unwrap_or_default(), material) + let (os, now) = seed_sources(); + Self::seeded(os, now, material) } /// [`Entropy::new`] from what the OS random source returned and the time. Nothing else goes /// into the seed, and a failed OS read is an error. - pub(crate) fn seeded(os: Result<[u8; 32], getrandom::Error>, now: i64, material: &[&[u8]]) -> Result { + fn seeded(os: Result<[u8; 32], getrandom::Error>, now: i64, material: &[&[u8]]) -> Result { let os = os.map_err(|e| failed(&format!("no random numbers ({e})")))?; let mut h = Sha256::new(); h.update(os); @@ -190,7 +218,7 @@ impl Entropy { Ok(Self { seed: h.finalize().into(), counter: 0 }) } - pub(crate) fn bytes(&mut self) -> [u8; N] { + fn bytes(&mut self) -> [u8; N] { let mut out = [0u8; N]; for chunk in out.chunks_mut(32) { self.counter += 1; diff --git a/crates/pdf/src/tests/encrypt.rs b/crates/pdf/src/tests/encrypt.rs index 89c2542266..5e586bec6f 100644 --- a/crates/pdf/src/tests/encrypt.rs +++ b/crates/pdf/src/tests/encrypt.rs @@ -195,15 +195,24 @@ fn the_same_file_and_passwords_get_fresh_keys_each_time() { fn the_file_key_is_seeded_from_the_os_random_source() { // The OS bytes, the time and the file are the whole seed: equal inputs give equal streams, so // no other source (such as `RandomState`, whose keys are fixed on the web) is mixed in, and - // other OS bytes alone give another stream. - use crate::encrypt::Entropy; - let file: &[&[u8]] = &[b"%PDF-2.0 same file"]; - let stream = |os: [u8; 32]| match Entropy::seeded(Ok(os), 1_700_000_000, file) { - Ok(mut e) => e.bytes::<48>(), + // other OS bytes alone give another stream. The exports set what the OS and the clock return. + use crate::encrypt::TEST_SEED_SOURCES; + let mut opts = PdfOptions::default(); + opts.settings.compatibility = Compatibility::Pdf20; + let plain = export(&doc(), &opts).unwrap(); + opts.settings.security = security("pw", "own"); + let protect_with = |os: Result<[u8; 32], getrandom::Error>| { + TEST_SEED_SOURCES.with(|c| c.set(Some((os, 1_700_000_000)))); + let out = protect(plain.clone(), &opts.settings); + TEST_SEED_SOURCES.with(|c| c.set(None)); + out + }; + let dict = |os: [u8; 32]| match protect_with(Ok(os)) { + Ok(bytes) => encrypt_dict(&bytes), Err(e) => panic!("{e:?}"), }; - assert_eq!(stream([7; 32]), stream([7; 32])); - assert_ne!(stream([7; 32]), stream([8; 32])); + assert_eq!(dict([7; 32]), dict([7; 32])); + assert_ne!(dict([7; 32]), dict([8; 32])); // A failed OS read is an error, not a weaker seed. - assert!(Entropy::seeded(Err(getrandom::Error::UNSUPPORTED), 1_700_000_000, file).is_err()); + assert!(protect_with(Err(getrandom::Error::UNSUPPORTED)).is_err()); }