From c47fdb89746fc6b85859bc75e6eb903194eaa1f5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 22:58:06 -0800 Subject: [PATCH 1/3] Tests: check the PDF key and Math.random seeds by behavior The PDF encryption and Math.random seed tests read their source files and searched for names. They now build the seed from given OS bytes: equal bytes give an equal stream, other bytes give another stream, and a failed OS read is an error for the PDF key. Mixing any other source into either seed fails the tests. The PDF seed is split into Entropy::seeded, which takes the OS bytes and the time, and the module doc now names the OS random source. --- crates/js/src/builtins_tests.rs | 13 ++++++++----- crates/js/src/realm.rs | 9 +++++++++ crates/pdf/src/encrypt.rs | 17 ++++++++++++----- crates/pdf/src/tests/encrypt.rs | 17 +++++++++++++---- 4 files changed, 42 insertions(+), 14 deletions(-) diff --git a/crates/js/src/builtins_tests.rs b/crates/js/src/builtins_tests.rs index 6a6867b270..c262216c1c 100644 --- a/crates/js/src/builtins_tests.rs +++ b/crates/js/src/builtins_tests.rs @@ -624,11 +624,14 @@ fn math_functions_follow_the_special_cases() { fn math_random_is_seeded_from_the_os_random_source() { // On wasm32-unknown-unknown `RandomState`'s keys come from memory addresses, which are the // same on every page load: the seed must come from the OS (the browser's crypto) instead. - let src = include_str!("interp.rs"); - let Some(start) = src.find("fn random_seed()") else { panic!("interp.rs has no random_seed") }; - let body = &src[start..]; - let body = &body[..body.find("\n}").unwrap_or(body.len())]; - assert!(body.contains("random_seed_from(getrandom::u64())"), "Math.random isn't seeded from the OS random source"); + // The OS value is the generator's only state: realms given the same value draw the same + // numbers, and a different value draws different ones. + let draws = |os: u64| match Realm::with_os_random(Ok(os)).run("[Math.random(), Math.random(), Math.random()].join()") { + Ok(JsValue::String(s)) => s, + other => panic!("{other:?}"), + }; + assert_eq!(draws(0x1234_5678_9abc_def0), draws(0x1234_5678_9abc_def0)); + assert_ne!(draws(0x1234_5678_9abc_def0), draws(0x0fed_cba9_8765_4321)); // The OS value is the seed, made odd so it's never zero; a failed read still gives a seed. assert_eq!(crate::interp::random_seed_from(Ok(0x40)), 0x41); assert_eq!(crate::interp::random_seed_from(Ok(0)), 1); diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index d673c92d26..1032b01a17 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -209,6 +209,15 @@ impl Realm { Self::with_options(Options::default(), Limits::default()) } + /// A realm whose `Math.random` starts from the seed made of `os`, as if the OS random source + /// had returned it. + #[cfg(test)] + pub(crate) fn with_os_random(os: Result) -> Self { + let mut realm = Self::new(); + realm.interp.random = crate::interp::random_seed_from(os); + realm + } + /// A realm whose scripts (and the source given to `eval` and `Function`) are read with /// `options`; [`Options::max_source_units`] caps the source parsed in one run, all of it /// counted together. diff --git a/crates/pdf/src/encrypt.rs b/crates/pdf/src/encrypt.rs index 6ee43ef05d..4807763598 100644 --- a/crates/pdf/src/encrypt.rs +++ b/crates/pdf/src/encrypt.rs @@ -6,7 +6,7 @@ //! algorithm follows the compatibility ([`Encryption`]): 40-bit RC4 for PDF 1.3 (revision 2), //! 128-bit RC4 for PDF 1.4 (revision 3) and 1.5 (revision 4), 128-bit AES for 1.6 (revision 4) and //! 256-bit AES for 1.7 and 2.0 (revision 6). The random file key, salts and initialisation vectors -//! come from a SHA-256 stream seeded with the process's random hash keys, the time and the file +//! come from a SHA-256 stream seeded with the OS random source, the time and the file //! itself. A linearised file is encrypted between its two steps ([`protect_keeping`]): what //! encrypted it then encrypts the hint stream written last ([`Cipher`]). //! @@ -163,7 +163,7 @@ fn hash6(password: &[u8], salt: &[u8], udata: &[u8]) -> Result<[u8; 32], PdfErro } /// Unpredictable bytes: SHA-256 of a seed and a counter. -struct Entropy { +pub(crate) struct Entropy { seed: [u8; 32], counter: u64, } @@ -172,10 +172,17 @@ 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]; - getrandom::fill(&mut os).map_err(|e| failed(&format!("no random numbers ({e})")))?; + let os = getrandom::fill(&mut os).map(|()| os); + Self::seeded(os, vectorcraft_doc::metadata::now_unix().unwrap_or_default(), 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 { + let os = os.map_err(|e| failed(&format!("no random numbers ({e})")))?; let mut h = Sha256::new(); h.update(os); - h.update(vectorcraft_doc::metadata::now_unix().unwrap_or_default().to_le_bytes()); + h.update(now.to_le_bytes()); for m in material { h.update((m.len() as u64).to_le_bytes()); h.update(m); @@ -183,7 +190,7 @@ impl Entropy { Ok(Self { seed: h.finalize().into(), counter: 0 }) } - fn bytes(&mut self) -> [u8; N] { + pub(crate) 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 c6b8772ff3..89c2542266 100644 --- a/crates/pdf/src/tests/encrypt.rs +++ b/crates/pdf/src/tests/encrypt.rs @@ -193,8 +193,17 @@ fn the_same_file_and_passwords_get_fresh_keys_each_time() { #[test] fn the_file_key_is_seeded_from_the_os_random_source() { - // `RandomState` is no CSPRNG and its keys are fixed on the web: the seed must come from the OS. - let src = include_str!("../encrypt.rs"); - assert!(!src.contains("RandomState"), "encrypt.rs seeds its keys from RandomState"); - assert!(src.contains("getrandom::fill"), "encrypt.rs doesn't seed its keys 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>(), + Err(e) => panic!("{e:?}"), + }; + assert_eq!(stream([7; 32]), stream([7; 32])); + assert_ne!(stream([7; 32]), stream([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()); } From c175089a206dfb53e544a99307022f890419a38f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 01:32:39 -0800 Subject: [PATCH 2/3] Tests: seed the Math.random test realm through Interp::new Realm::with_os_random made a realm and then replaced its seed, so the test still passed if Interp::new stopped seeding from the OS random source. The OS read now goes through os_random(), which a test can set for the realms made on its thread, and with_os_random builds its realm with Realm::new. The test fails when Interp::new uses a fixed seed. --- crates/js/src/interp.rs | 20 +++++++++++++++++++- crates/js/src/realm.rs | 8 +++++--- 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 517caa9c06..05e704b08e 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -544,7 +544,25 @@ fn index_names_bytes(len: usize, per_entry: usize) -> usize { /// random source (the browser's crypto on the web), or the standard library's randomly keyed /// hasher when that fails; never zero. fn random_seed() -> u64 { - random_seed_from(getrandom::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)] +fn os_random() -> Result { + TEST_OS_RANDOM.with(std::cell::Cell::get).unwrap_or_else(getrandom::u64) } /// [`random_seed`] from what the OS random source returned. diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index 1032b01a17..822477780f 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -210,11 +210,13 @@ impl Realm { } /// A realm whose `Math.random` starts from the seed made of `os`, as if the OS random source - /// had returned it. + /// had returned it. The realm is made by [`Realm::new`], so its seed comes through the same + /// path as any other realm's. #[cfg(test)] pub(crate) fn with_os_random(os: Result) -> Self { - let mut realm = Self::new(); - realm.interp.random = crate::interp::random_seed_from(os); + crate::interp::TEST_OS_RANDOM.with(|c| c.set(Some(os))); + let realm = Self::new(); + crate::interp::TEST_OS_RANDOM.with(|c| c.set(None)); realm } From 9730c888fba05ee9d477e0bd49017ea55ff0355f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 02:01:10 -0800 Subject: [PATCH 3/3] 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()); }