//! Helpers shared by the integration tests: deterministic randomness, fixture loading, an independent GF(2^8) //! reference, and builders for video and audio streams. Test code: panics are the way a test fails. #![allow(dead_code, unreachable_pub, clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing)] use std::collections::HashMap; use domistream::RandomSource; // ------------------------------------------------------------------------------------------------ assertions /// Asserts that `$e` is `Err` matching `$p` (an `Error` pattern), printing the actual value otherwise. #[macro_export] macro_rules! assert_err { ($e:expr, $p:pat) => { match $e { Err($p) => {} other => panic!("expected Err({}), got {:?}", stringify!($p), other), } }; ($e:expr, $p:pat, $($ctx:tt)+) => { match $e { Err($p) => {} other => panic!("expected Err({}), got {:?}: {}", stringify!($p), other, format!($($ctx)+)), } }; } /// Asserts `Err(TooLarge { max, actual, .. })` with the given numbers. #[macro_export] macro_rules! assert_too_large { ($e:expr, $max:expr, $actual:expr) => { match $e { Err(domistream::Error::TooLarge { max, actual, .. }) => { assert_eq!(max, $max, "TooLarge.max"); assert_eq!(actual, $actual, "TooLarge.actual"); } other => panic!("expected Err(TooLarge {{ max: {}, actual: {} }}), got {:?}", $max, $actual, other), } }; } /// False for `Err(Unimplemented)`. "Never panics" properties assert this on every result, so they cannot pass /// against a stub that returns `Unimplemented` for everything. pub fn implemented(r: &domistream::Result) -> bool { !matches!(r, Err(domistream::Error::Unimplemented)) } // ------------------------------------------------------------------------------------------------ randomness /// A seeded, deterministic random source (splitmix64). Never for production. #[derive(Clone, Debug)] pub struct SeqRng(u64); impl SeqRng { pub fn new(seed: u64) -> Self { Self(seed) } pub fn next_u64(&mut self) -> u64 { self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15); let mut z = self.0; z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); z ^ (z >> 31) } /// Uniform in `0..n` (n > 0); bias is irrelevant for test data. pub fn below(&mut self, n: usize) -> usize { (self.next_u64() % n as u64) as usize } pub fn bytes(&mut self, n: usize) -> Vec { let mut v = vec![0; n]; self.fill(&mut v); v } /// `count` distinct indices from `0..n`, sorted. pub fn subset(&mut self, n: usize, count: usize) -> Vec { let mut all: Vec = (0..n).collect(); for i in 0..count.min(n) { let j = i + self.below(n - i); all.swap(i, j); } let mut chosen = all[..count.min(n)].to_vec(); chosen.sort_unstable(); chosen } pub fn shuffle(&mut self, items: &mut [T]) { for i in (1..items.len()).rev() { let j = self.below(i + 1); items.swap(i, j); } } } impl RandomSource for SeqRng { fn fill(&mut self, dest: &mut [u8]) { for chunk in dest.chunks_mut(8) { let word = self.next_u64().to_le_bytes(); chunk.copy_from_slice(&word[..chunk.len()]); } } } /// Hands out a fixed byte stream (a recorded transcript's randomness) and fails the test when the code under /// test draws more than was recorded. #[derive(Debug)] pub struct ScriptedRng { bytes: Vec, pos: usize, } impl ScriptedRng { pub fn new(bytes: Vec) -> Self { Self { bytes, pos: 0 } } pub fn drawn(&self) -> usize { self.pos } } impl RandomSource for ScriptedRng { fn fill(&mut self, dest: &mut [u8]) { let end = self.pos + dest.len(); assert!( end <= self.bytes.len(), "the code drew {} random bytes but the recorded transcript holds only {} \ (fixture assumption: salt, then C, then secret_c, 16 bytes each)", end, self.bytes.len() ); dest.copy_from_slice(&self.bytes[self.pos..end]); self.pos = end; } } // ------------------------------------------------------------------------------------------------ fixtures pub fn hex(s: &str) -> Vec { let s: String = s.chars().filter(|c| !c.is_whitespace()).collect(); if s == "-" { return Vec::new(); } assert!(s.len().is_multiple_of(2), "odd hex length"); (0..s.len()).step_by(2).map(|i| u8::from_str_radix(&s[i..i + 2], 16).expect("hex digit")).collect() } pub fn to_hex(b: &[u8]) -> String { b.iter().map(|x| format!("{x:02x}")).collect() } pub fn to_hex_upper(b: &[u8]) -> String { b.iter().map(|x| format!("{x:02X}")).collect() } /// A `name = value` fixture file written by `tools/vectors/gen_vectors.py`. pub struct Vectors(HashMap); impl Vectors { pub fn parse(text: &str) -> Self { let mut map = HashMap::new(); for line in text.lines() { let line = line.trim(); if line.is_empty() || line.starts_with('#') { continue; } let (k, v) = line.split_once(" = ").expect("fixture line `name = value`"); map.insert(k.to_string(), v.to_string()); } Self(map) } pub fn str(&self, name: &str) -> &str { self.0.get(name).unwrap_or_else(|| panic!("fixture value `{name}` missing")) } pub fn bytes(&self, name: &str) -> Vec { hex(self.str(name)) } pub fn arr16(&self, name: &str) -> [u8; 16] { self.bytes(name).try_into().unwrap_or_else(|_| panic!("`{name}` is not 16 bytes")) } pub fn u32_hex(&self, name: &str) -> u32 { u32::from_str_radix(self.str(name), 16).expect("hex u32") } } pub fn pairing_vectors() -> Vectors { Vectors::parse(include_str!("../fixtures/pairing.txt")) } pub fn control_vectors() -> Vectors { Vectors::parse(include_str!("../fixtures/control_gcm.txt")) } pub fn video_vectors() -> Vectors { Vectors::parse(include_str!("../fixtures/video_gcm.txt")) } pub fn audio_vectors() -> Vectors { Vectors::parse(include_str!("../fixtures/audio_cbc.txt")) } pub const HOST_CERT_PEM: &str = include_str!("../fixtures/test-only-host-cert.pem"); pub const CLIENT_CERT_PEM: &str = include_str!("../fixtures/test-only-client-cert.pem"); pub const ROGUE_CERT_PEM: &str = include_str!("../fixtures/test-only-rogue-cert.pem"); pub const EC_CERT_PEM: &str = include_str!("../fixtures/test-only-ec-cert.pem"); pub const CLIENT_KEY_PEM: &str = include_str!("../fixtures/test-only-client-key.pem"); /// Base64 (RFC 4648, standard alphabet, padding allowed) to bytes; panics on anything else. pub fn base64_decode(s: &str) -> Vec { let mut out = Vec::new(); let mut acc = 0u32; let mut bits = 0; for c in s.bytes().filter(|c| !c.is_ascii_whitespace()) { let v = match c { b'A'..=b'Z' => c - b'A', b'a'..=b'z' => c - b'a' + 26, b'0'..=b'9' => c - b'0' + 52, b'+' => 62, b'/' => 63, b'=' => break, _ => panic!("not base64: {c:#x}"), }; acc = (acc << 6) | u32::from(v); bits += 6; if bits >= 8 { bits -= 8; out.push((acc >> bits) as u8); } } out } /// The DER inside every `-----BEGIN