proptest_inputs.rs 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. //! `test(proptest_inputs)` — wire, TOTP, and at+jwt input properties (todo 19).
  2. //!
  3. //! Pure `proptest` properties over the untrusted-input seams:
  4. //! [`parse_pairs`]/[`values_of`]/[`single_valued_map`] (form wire order and
  5. //! last-wins), [`verify_window`] (a generated code verifies only inside the
  6. //! ±1-step window), and [`JwtAccessSigner::verify`] (arbitrary tokens never
  7. //! panic, an accepted token carries the expected audience, and a wrong
  8. //! audience always rejects). No `unwrap`/`expect`/`panic` anywhere.
  9. //!
  10. //! TOTP note: a far-off 6-digit code can collide with a windowed candidate
  11. //! (about 3e-6 per case), so the property never asserts `None` for a far code;
  12. //! it only bounds any `Some(step)` to the counter ± 1.
  13. use std::sync::OnceLock;
  14. use d_oauth::{
  15. config::{JwtSigningAlg, JwtSigningKey},
  16. crypto::totp::{TOTP_SKEW_STEPS, TOTP_STEP_SECS, build_totp, verify_window},
  17. jose::jwt_access::{JwtAccessSigner, JwtClaims},
  18. keys::KeyId,
  19. protocol::params::{MAX_FORM_PAIRS, parse_pairs, single_valued_map, values_of},
  20. };
  21. use proptest::prelude::*;
  22. use secrecy::SecretString;
  23. use time::OffsetDateTime;
  24. /// Issuer every at+jwt fixture token asserts.
  25. const TEST_ISSUER: &str = "https://as.example.test";
  26. /// Audience the fixture token is minted for.
  27. const TEST_AUDIENCE: &str = "https://rs.example.test";
  28. /// Audience the fixture token must never satisfy.
  29. const WRONG_AUDIENCE: &str = "https://other.example.test";
  30. /// Fixture token lifetime: one day, so a test process stays inside `exp`.
  31. const FIXTURE_TTL_SECS: i64 = 86_400;
  32. /// RFC 4648 base32 alphabet, uppercase, no padding.
  33. const BASE32_ALPHABET: &[u8; 32] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
  34. /// Characters a mutated token position may carry: all still base64url/decode
  35. /// clean, so the mutation is well-formed UTF-8 and the decoder is reached.
  36. const JWT_MUTATION_ALPHABET: &[u8] = b"-_.A0az";
  37. /// Encode raw bytes as canonical RFC 4648 base32 (uppercase, no padding).
  38. ///
  39. /// Canonical output always decodes under [`build_totp`], so the TOTP property
  40. /// exercises the verifier rather than the malformed-secret error path.
  41. fn to_base32(bytes: &[u8]) -> String {
  42. let mut out = String::with_capacity(bytes.len().div_ceil(5) * 8);
  43. let mut accumulator = 0u32;
  44. let mut bits = 0u32;
  45. for byte in bytes {
  46. accumulator = (accumulator << 8) | u32::from(*byte);
  47. bits += 8;
  48. while bits >= 5 {
  49. bits -= 5;
  50. let index = ((accumulator >> bits) & 0x1f) as usize;
  51. out.push(char::from(BASE32_ALPHABET[index]));
  52. }
  53. // Keep only the unflushed low bits so the accumulator cannot overflow.
  54. accumulator &= (1u32 << bits) - 1;
  55. }
  56. if bits > 0 {
  57. let index = ((accumulator << (5 - bits)) & 0x1f) as usize;
  58. out.push(char::from(BASE32_ALPHABET[index]));
  59. }
  60. out
  61. }
  62. /// Bounded arbitrary UTF-8 input, a shape that exceeds the pair cap so both
  63. /// the `Ok` and cap-error branches of [`parse_pairs`] are reachable, and a
  64. /// duplicate-heavy shape so last-wins is genuinely exercised.
  65. fn form_input() -> impl Strategy<Value = String> {
  66. prop_oneof![
  67. proptest::collection::vec(any::<char>(), 0..=512)
  68. .prop_map(|chars| chars.into_iter().collect::<String>()),
  69. proptest::collection::vec("[A-Za-z0-9_.~%-]{0,8}", 0..=(MAX_FORM_PAIRS + 8))
  70. .prop_map(|segments| segments.join("&")),
  71. proptest::collection::vec(
  72. (
  73. prop_oneof![Just("a"), Just("resource"), Just("b"), Just("")],
  74. "[A-Za-z0-9]{0,6}",
  75. ),
  76. 0..=40,
  77. )
  78. .prop_map(|segments| {
  79. segments
  80. .into_iter()
  81. .map(|(name, value)| format!("{name}={value}"))
  82. .collect::<Vec<String>>()
  83. .join("&")
  84. }),
  85. ]
  86. }
  87. /// The fixed at+jwt fixture: one signer and one already-signed valid token.
  88. struct JwtFixture {
  89. /// ES256 signer over a fixed 32-byte scalar.
  90. signer: JwtAccessSigner,
  91. /// A valid token minted once for this process.
  92. token: String,
  93. /// The audience the fixture token carries.
  94. audience: Vec<String>,
  95. }
  96. static JWT_FIXTURE: OnceLock<Option<JwtFixture>> = OnceLock::new();
  97. /// Build the fixture once; a key-construction failure is tolerated as "skip".
  98. fn jwt_fixture() -> Option<&'static JwtFixture> {
  99. JWT_FIXTURE
  100. .get_or_init(|| {
  101. let raw = SecretString::from("C".repeat(32));
  102. let key = JwtSigningKey::from_raw(
  103. KeyId::new("v2"),
  104. JwtSigningAlg::Es256,
  105. &raw,
  106. "proptest_jwt_signing_key",
  107. )
  108. .ok()?;
  109. let signer = JwtAccessSigner::new(TEST_ISSUER.to_owned(), key, Vec::new());
  110. let now = OffsetDateTime::now_utc().unix_timestamp();
  111. let claims = JwtClaims {
  112. iss: TEST_ISSUER.to_owned(),
  113. sub: "proptest-subject@example.test".to_owned(),
  114. aud: vec![TEST_AUDIENCE.to_owned()],
  115. scope: "orders:read".to_owned(),
  116. exp: now + FIXTURE_TTL_SECS,
  117. iat: now,
  118. jti: "proptest-jti".to_owned(),
  119. client_id: "proptest-client".to_owned(),
  120. cnf: None,
  121. act: None,
  122. };
  123. let token = signer.sign(&claims).ok()?;
  124. Some(JwtFixture {
  125. signer,
  126. token,
  127. audience: claims.aud,
  128. })
  129. })
  130. .as_ref()
  131. }
  132. proptest! {
  133. #[test]
  134. fn params_parse_pairs_never_panics_and_preserves_wire_order(raw in form_input()) {
  135. // Only two outcomes exist: the parsed pairs, or the single cap error.
  136. let pairs = match parse_pairs(&raw) {
  137. Ok(pairs) => pairs,
  138. Err(_) => return Ok(()),
  139. };
  140. // `values_of("resource")` keeps the wire order and is a subset of all
  141. // values (one entry per matching pair, no reordering, no loss).
  142. let resource_values = values_of(&pairs, "resource");
  143. let expected: Vec<String> = pairs
  144. .iter()
  145. .filter(|(name, _)| name == "resource")
  146. .map(|(_, value)| value.clone())
  147. .collect();
  148. prop_assert_eq!(&resource_values, &expected);
  149. prop_assert!(resource_values.len() <= pairs.len());
  150. // `single_valued_map` is last-wins: one entry per distinct name, and each
  151. // entry equals the final pair carrying that name.
  152. let map = single_valued_map(&pairs);
  153. let distinct: std::collections::HashSet<&str> =
  154. pairs.iter().map(|(name, _)| name.as_str()).collect();
  155. prop_assert_eq!(map.len(), distinct.len());
  156. for (name, value) in &map {
  157. let last = pairs
  158. .iter()
  159. .rev()
  160. .find(|(candidate, _)| candidate == name)
  161. .map(|(_, value)| value);
  162. prop_assert_eq!(Some(value), last);
  163. }
  164. }
  165. #[test]
  166. fn totp_verify_window_accepts_only_generated_codes(
  167. secret_bytes in proptest::collection::vec(any::<u8>(), 16..=32),
  168. counter in 0u64..=(u64::MAX / TOTP_STEP_SECS),
  169. arbitrary_code in proptest::collection::vec(any::<char>(), 0..=16)
  170. .prop_map(|chars| chars.into_iter().collect::<String>()),
  171. ) {
  172. let secret = to_base32(&secret_bytes);
  173. let totp = match build_totp(&secret) {
  174. Ok(totp) => totp,
  175. Err(_) => {
  176. prop_assert!(false, "a 16..=32-byte base32 secret must build");
  177. return Ok(());
  178. }
  179. };
  180. let now = counter.saturating_mul(TOTP_STEP_SECS);
  181. let generated = totp.generate(now).to_string();
  182. let skew = u64::from(TOTP_SKEW_STEPS);
  183. // A code generated for this step verifies, at this step or an adjacent one.
  184. match verify_window(&secret, &generated, now) {
  185. Ok(Some(step)) => prop_assert!(step.abs_diff(counter) <= skew),
  186. Ok(None) => prop_assert!(false, "a generated code must verify"),
  187. Err(_) => prop_assert!(false, "a canonical base32 secret must build"),
  188. }
  189. // Any arbitrary code is handled without panic; a match must be adjacent
  190. // to the counter (a far code is NOT asserted absent: 6-digit collisions
  191. // are possible at roughly 3e-6 per case).
  192. if let Ok(Some(step)) = verify_window(&secret, &arbitrary_code, now) {
  193. prop_assert!(step.abs_diff(counter) <= skew);
  194. }
  195. }
  196. #[test]
  197. fn jwt_verify_never_panics_on_arbitrary_tokens(
  198. raw in proptest::collection::vec(any::<char>(), 0..=512)
  199. .prop_map(|chars| chars.into_iter().collect::<String>()),
  200. selector in 0u8..3,
  201. position in any::<usize>(),
  202. replacement in 0u8..8,
  203. ) {
  204. let Some(fixture) = jwt_fixture() else {
  205. prop_assert!(false, "the fixed JWT fixture must build");
  206. return Ok(());
  207. };
  208. // Selector 0 replays the fixed valid token (accepted branch); selector 1
  209. // mutates it at one base64url position; selector 2 is arbitrary UTF-8.
  210. let candidate = match selector {
  211. 0 => fixture.token.clone(),
  212. 1 => {
  213. let mut bytes = fixture.token.clone().into_bytes();
  214. if bytes.is_empty() {
  215. return Ok(());
  216. }
  217. let index = position % bytes.len();
  218. let index_in_alphabet = usize::from(replacement) % JWT_MUTATION_ALPHABET.len();
  219. let mut next = JWT_MUTATION_ALPHABET[index_in_alphabet];
  220. if next == bytes[index] {
  221. next = if bytes[index] == b'A' { b'B' } else { b'A' };
  222. }
  223. bytes[index] = next;
  224. match String::from_utf8(bytes) {
  225. Ok(candidate) => candidate,
  226. Err(_) => return Ok(()),
  227. }
  228. }
  229. _ => raw,
  230. };
  231. // Arbitrary strings never panic: the outcome is a typed error or a token.
  232. match fixture.signer.verify(&candidate, Some(fixture.audience.as_slice())) {
  233. Ok(verified) => {
  234. prop_assert!(
  235. verified
  236. .claims
  237. .aud
  238. .iter()
  239. .any(|audience| audience.as_str() == TEST_AUDIENCE)
  240. );
  241. if selector == 0 {
  242. // The accepted branch is reachable only from the fixed token, and
  243. // it round-trips the exact audience set.
  244. prop_assert_eq!(verified.claims.aud.as_slice(), fixture.audience.as_slice());
  245. }
  246. }
  247. Err(_) => {
  248. if selector == 0 {
  249. prop_assert!(false, "the fixed signed token must verify");
  250. }
  251. }
  252. }
  253. // A wrong audience always rejects, whether the token is valid or not.
  254. prop_assert!(
  255. fixture
  256. .signer
  257. .verify(
  258. &candidate,
  259. Some(&[WRONG_AUDIENCE.to_owned()]),
  260. )
  261. .is_err()
  262. );
  263. }
  264. }