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.
This commit is contained in:
dotCooCoo committed 2026-12-01 02:17:47 -08:00
1 parent c175089a20
commit 9730c888fb
3 files changed
+64 -23

No files matched your search

+13 -9
View File
@@ -547,22 +547,26 @@ fn random_seed() -> u64 {
random_seed_from(os_random())
}
/// The OS random source.
#[cfg(not(test))]
fn os_random() -> Result<u64, getrandom::Error> {
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<Option<Result<u64, getrandom::Error>>> = 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<u64, getrandom::Error> {
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<Result<u64, getrandom::Error>> {
TEST_OS_RANDOM.with(std::cell::Cell::get)
}
#[cfg(not(test))]
fn test_os_random() -> Option<Result<u64, getrandom::Error>> {
None
}
/// [`random_seed`] from what the OS random source returned.
+34 -6
View File
@@ -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<Option<SeedSources>> = 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<SeedSources> {
TEST_SEED_SOURCES.with(std::cell::Cell::get)
}
#[cfg(not(test))]
fn test_seed_sources() -> Option<SeedSources> {
None
}
impl Entropy {
/// Seeded from the OS random source, with the time and `material` mixed in.
fn new(material: &[&[u8]]) -> Result<Self, PdfError> {
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<Self, PdfError> {
fn seeded(os: Result<[u8; 32], getrandom::Error>, now: i64, material: &[&[u8]]) -> Result<Self, PdfError> {
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<const N: usize>(&mut self) -> [u8; N] {
fn bytes<const N: usize>(&mut self) -> [u8; N] {
let mut out = [0u8; N];
for chunk in out.chunks_mut(32) {
self.counter += 1;
+17 -8
View File
@@ -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());
}