//! Every way [`wrap`] can be right, and every way it must refuse. //! //! No key here is real and none was ever used for anything: each is a counted //! byte pattern, chosen so a failure names the vector rather than a random //! draw. use super::*; /// A private scalar built from one byte, so a failing assertion says which. fn scalar(seed: u8) -> [u8; 32] { let mut bytes = [seed; 32]; // Not a uniform fill: two scalars differing only in the last byte would // clamp to the same value, and the vectors would be testing one key twice. bytes[0] = seed.wrapping_mul(7).wrapping_add(1); bytes[31] = seed.wrapping_mul(13).wrapping_add(3); bytes } fn nonce(seed: u8) -> [u8; 12] { [seed; 12] } /// RULE: A password key sealed for one device opens again only with that device's own key. #[test] fn a_wrap_comes_back_out_for_the_key_it_was_made_for() { let recipient = scalar(1); let public = public_of(&recipient); let wrapped = wrap(&public, b"thirty-two bytes of vault master").expect("wraps"); assert!(wrapped.starts_with(WRAP_PREFIX), "got {wrapped}"); assert_eq!( unwrap(&recipient, &wrapped).as_deref(), Some(&b"thirty-two bytes of vault master"[..]) ); } #[test] fn the_same_plaintext_wraps_differently_every_time() { // A fresh ephemeral pair and a fresh nonce per wrap: two identical wraps // would say, to anybody reading the file, that two devices hold the same // key — and would make the nonce reuse AES-GCM cannot survive possible at // all. let public = public_of(&scalar(2)); let first = wrap(&public, b"the same bytes").expect("wraps"); let second = wrap(&public, b"the same bytes").expect("wraps"); assert_ne!(first, second); } #[test] fn the_wrapping_side_and_the_opening_side_derive_the_same_key() { // The vector form: the randomness is supplied, so this is an equality // between two stated computations rather than a round trip that could pass // because both halves are wrong in the same way. let recipient = scalar(3); let public = public_of(&recipient); let wrapped = wrap_with(&scalar(4), &nonce(9), &public, b"a payload").expect("wraps"); assert_eq!(unwrap(&recipient, &wrapped).as_deref(), Some(&b"a payload"[..])); // And it is DETERMINISTIC in its inputs, which is what makes it a vector. assert_eq!( wrapped, wrap_with(&scalar(4), &nonce(9), &public, b"a payload").expect("wraps") ); } #[test] fn the_wrong_key_opens_nothing() { let public = public_of(&scalar(5)); let wrapped = wrap(&public, b"not for you").expect("wraps"); assert_eq!(unwrap(&scalar(6), &wrapped), None); } /// RULE: Changing a single byte of a sealed key makes it refuse to open, rather than opening something wrong. #[test] fn a_tampered_ciphertext_opens_nothing() { let recipient = scalar(7); let wrapped = wrap(&public_of(&recipient), b"a payload worth changing").expect("wraps"); let body = URL_SAFE_NO_PAD .decode(wrapped.strip_prefix(WRAP_PREFIX).expect("the prefix")) .expect("base64url"); // Every byte of the body, one at a time: the ephemeral key, the nonce and // the ciphertext are all covered by the tag or by the key derivation, and a // flip anywhere must fail rather than fail only where the tag reaches. for index in 0..body.len() { let mut broken = body.clone(); broken[index] ^= 0x01; let value = format!("{WRAP_PREFIX}{}", URL_SAFE_NO_PAD.encode(&broken)); assert_eq!( unwrap(&recipient, &value), None, "a flipped bit at byte {index} still opened" ); } } /// RULE: A sealed key copied from one device's row into another's does not open, so a row cannot be moved between devices. #[test] fn a_wrap_made_for_one_device_does_not_open_as_a_wrap_made_for_another() { // The aad is the recipient's public key, so a row copied from one device's // line into another's fails at the tag rather than opening something it // should not. Built by hand, because nothing in the API lets a caller make // this mistake — the point is that the FILE cannot make it either. let ephemeral = scalar(8); let first = public_of(&scalar(9)); let second_secret = scalar(10); let wrapped = wrap_with(&ephemeral, &nonce(1), &first, b"for the first").expect("wraps"); assert_eq!(unwrap(&second_secret, &wrapped), None); } #[test] fn a_value_that_is_not_a_wrap_is_refused_rather_than_guessed_at() { let recipient = scalar(11); for value in [ "", "w1:", "not a wrap at all", "v2:c2VhbGVk", // a SEALED value, not a wrap "w1:!!!not base64url!!!", "w1:c2hvcnQ", // valid base64url, far too short ] { assert_eq!(unwrap(&recipient, value), None, "opened {value:?}"); } } #[test] fn an_all_zero_shared_secret_is_refused_rather_than_wrapped_to_nobody() { // X25519 answers all zeroes for a small-order public key. A key derived // from those zeroes is a key whoever chose the public key also knows, so a // wrap made to one is a wrap made to NOBODY — and it would look like a // wrap. These five are the documented small-order points; the first two are // the ones a caller could plausibly arrive at by accident (an all-zero // buffer, and a one). let low_order: [[u8; 32]; 3] = [ [0u8; 32], { let mut bytes = [0u8; 32]; bytes[0] = 1; bytes }, { // 2^255 - 19 - 1, the order-1 point. let mut bytes = [0xffu8; 32]; bytes[0] = 0xec; bytes[31] = 0x7f; bytes }, ]; for public in low_order { assert_eq!( wrap(&public, b"a vault master key"), None, "wrapped to a small-order point" ); } } #[test] fn a_minted_key_is_thirty_two_bytes_and_not_the_last_one() { let first = mint_vault_key(); let second = mint_vault_key(); assert_eq!(first.len(), 32); assert_ne!(first.as_slice(), second.as_slice()); assert_ne!(public_of(&first), public_of(&second)); // And a minted key wraps and opens like any other. let wrapped = wrap(&public_of(&first), b"a vault master key").expect("wraps"); assert_eq!( unwrap(&first, &wrapped).as_deref(), Some(&b"a vault master key"[..]) ); } /// RULE: The phone and the database agree on what a device's password key is, held by one fixed example written out in both. /// The vector the SWIFT half is pinned to. /// /// `apps/cotton/Tests/CottonKitTests/VaultKeyTests.swift` derives the public /// half of these same 32 bytes through CryptoKit and asserts this same string. /// **Neither side reads the other's file**: the vector is the contract, written /// out in both, so a change to either derivation is a red run in that language /// rather than a phone that publishes a key nothing can wrap for. /// /// Curve25519 CLAMPS the scalar, and both libraries do it on use — so 32 raw /// bytes are a valid private key in each and this is what agreement looks like. #[test] fn the_public_half_of_a_known_scalar_is_the_vector_swift_derives_too() { use base64::engine::general_purpose::URL_SAFE_NO_PAD; use base64::Engine as _; let mut secret = [0u8; 32]; for (index, byte) in secret.iter_mut().enumerate() { *byte = index as u8; } assert_eq!( URL_SAFE_NO_PAD.encode(public_of(&secret)), "j0DFrbaPJWJK5bIU6nZ6bslNgp09e14a0bpvPiE4KF8", "if this moved, the phone and the file disagree about what this device's \ vault key IS" ); } #[test] fn a_fingerprint_is_four_groups_of_hex_and_only_a_32_byte_key_has_one() { let public = URL_SAFE_NO_PAD.encode(public_of(&[26u8; 32])); let print = fingerprint(&public).unwrap(); assert_eq!(print.len(), 19); assert_eq!(print.split(' ').count(), 4); assert!(print.chars().all(|c| c == ' ' || c.is_ascii_hexdigit())); assert_eq!(fingerprint(&public), Some(print.clone())); assert_ne!(fingerprint(&URL_SAFE_NO_PAD.encode(public_of(&[27u8; 32]))), Some(print)); assert_eq!(fingerprint("short"), None); assert_eq!(fingerprint(&URL_SAFE_NO_PAD.encode([1u8; 31])), None); }