Cotton code
422 lines · 19.2 KB · RustRaw
use super::*;/// One invented device: its chat key, its store, and the handle it is published under.struct Device {    chat: [u8; 32],    store: Store,    handle: String,    /// One-time keys it published, as the Worker holds them.    shelf: Vec<Prekey>,}impl Device {    fn new(seed: u8, handle: &str) -> Self {        let mut store = Store::new(0);        let shelf = store.prekeys(0);        store.published();        Self { chat: [seed; 32], store, handle: handle.into(), shelf }    }    fn chat_pub(&self) -> [u8; 32] {        crate::vault::wrap::public_of(&self.chat)    }    fn verified(&self) -> Verified {        verify_record(&self.chat_pub(), &self.store.record(&self.chat_pub())).expect("its own record verifies")    }    /// One of its one-time keys, taken off the Worker's shelf.    fn claim(&mut self) -> Prekey {        self.shelf.pop().expect("a one-time key left")    }    fn sender(&self) -> (String, Verified) {        (self.handle.clone(), self.verified())    }}/// `from` seals `words` for `to`, claiming one of `to`'s keys when it must.fn seal(from: &mut Device, to: &mut Device, words: &str) -> String {    let v = to.verified();    let claimed = from.store.needs_prekey(&v).then(|| to.claim());    from.store.seal(&to.handle, &v, claimed.as_ref(), words.as_bytes()).expect("sealed")}fn open(to: &mut Device, from: &Device, item: &str, sealed: &str) -> Result<String, OpenError> {    to.store.open(item, sealed, &[from.sender()], 1).map(|o| String::from_utf8(o.payload).unwrap())}#[test]fn both_ways_on_one_session() {    let (mut a, mut b) = (Device::new(1, "a"), Device::new(2, "b"));    let first = seal(&mut a, &mut b, "hello");    assert!(first.starts_with(BOX_PREFIX));    assert_eq!(open(&mut b, &a, "m1", &first).unwrap(), "hello");    // Bob answers on the session Alice's first message made: no key of hers is claimed.    let shelf = a.shelf.len();    let answer = seal(&mut b, &mut a, "hi back");    assert_eq!(a.shelf.len(), shelf);    assert_eq!(open(&mut a, &b, "m2", &answer).unwrap(), "hi back");    for n in 0..5 {        let words = format!("again {n}");        let sealed = seal(&mut a, &mut b, &words);        assert_eq!(open(&mut b, &a, &format!("x{n}"), &sealed).unwrap(), words);    }    // Each side spoke c2 with the other's handle: pinned.    assert!(a.store.pinned("b") && b.store.pinned("a"));}#[test]fn a_one_time_key_opens_one_session_only() {    let (mut a, mut b, mut c) = (Device::new(1, "a"), Device::new(2, "b"), Device::new(3, "c"));    // The Worker hands the same one-time key of Bob's to two senders.    let key = b.claim();    let v = b.verified();    let from_a = a.store.seal("b", &v, Some(&key), b"from a").unwrap();    let from_c = c.store.seal("b", &v, Some(&key), b"from c").unwrap();    assert_eq!(open(&mut b, &a, "1", &from_a).unwrap(), "from a");    // The key is used up: the second first-message opens nothing.    assert_eq!(open(&mut b, &c, "2", &from_c), Err(OpenError::Replayed));}#[test]fn out_of_order_opens_every_one() {    let (mut a, mut b) = (Device::new(1, "a"), Device::new(2, "b"));    let boxes: Vec<String> = (0..6).map(|n| seal(&mut a, &mut b, &format!("m{n}"))).collect();    for n in [5, 2, 0, 4, 1, 3] {        assert_eq!(open(&mut b, &a, &format!("m{n}"), &boxes[n]).unwrap(), format!("m{n}"));    }    // After a reply, a new chain: its boxes too in any order.    let r = seal(&mut b, &mut a, "reply");    open(&mut a, &b, "r", &r).unwrap();    let later: Vec<String> = (0..3).map(|n| seal(&mut a, &mut b, &format!("l{n}"))).collect();    for n in [2, 0, 1] {        assert_eq!(open(&mut b, &a, &format!("l{n}"), &later[n]).unwrap(), format!("l{n}"));    }}#[test]fn a_replay_is_refused() {    let (mut a, mut b) = (Device::new(1, "a"), Device::new(2, "b"));    let first = seal(&mut a, &mut b, "hello");    open(&mut b, &a, "m1", &first).unwrap();    // The same first message again, as another envelope: its key is gone.    assert_eq!(open(&mut b, &a, "m1-again", &first), Err(OpenError::Replayed));    let r = seal(&mut b, &mut a, "reply");    open(&mut a, &b, "r", &r).unwrap();    let later = seal(&mut a, &mut b, "later");    open(&mut b, &a, "l", &later).unwrap();    assert_eq!(open(&mut b, &a, "l-again", &later), Err(OpenError::Replayed));    // A replay is not a lost session: nothing resets.    assert!(!b.store.due_reset(&a.verified().identity));}#[test]fn a_box_held_back_opens_again_until_it_is_taken() {    let (mut a, mut b) = (Device::new(1, "a"), Device::new(2, "b"));    let first = seal(&mut a, &mut b, "hello");    assert_eq!(open(&mut b, &a, "message:m1:+1:false", &first).unwrap(), "hello");    // Read again before it was taken (a group message that had to wait, or a crash before the ack): the same words.    assert_eq!(open(&mut b, &a, "message:m1:+1:false", &first).unwrap(), "hello");    // The same envelope with another box is not the one kept.    let other = seal(&mut a, &mut b, "other");    assert_eq!(open(&mut b, &a, "message:m1:+1:false", &other).unwrap(), "other");    assert!(b.store.taken(["message:m1:+1:false"]));    assert_eq!(open(&mut b, &a, "message:m1:+1:false", &other), Err(OpenError::Replayed));}#[test]fn skipped_keys_are_limited() {    let (mut a, mut b) = (Device::new(1, "a"), Device::new(2, "b"));    let first = seal(&mut a, &mut b, "hello");    open(&mut b, &a, "m0", &first).unwrap();    let r = seal(&mut b, &mut a, "reply");    open(&mut a, &b, "r", &r).unwrap();    // Fifty sent, the last opened first: the ratchet keeps the newest forty skipped keys, no more.    let boxes: Vec<String> = (0..50).map(|n| seal(&mut a, &mut b, &format!("s{n}"))).collect();    open(&mut b, &a, "s49", &boxes[49]).unwrap();    assert_eq!(open(&mut b, &a, "s0", &boxes[0]), Err(OpenError::Replayed));    assert_eq!(open(&mut b, &a, "s9", &boxes[9]), Ok("s9".into()));    assert_eq!(open(&mut b, &a, "s48", &boxes[48]), Ok("s48".into()));}#[test]fn a_gap_wider_than_the_ratchet_keeps_is_refused() {    let (mut a, mut b) = (Device::new(1, "a"), Device::new(2, "b"));    let first = seal(&mut a, &mut b, "hello");    open(&mut b, &a, "m0", &first).unwrap();    let r = seal(&mut b, &mut a, "reply");    open(&mut a, &b, "r", &r).unwrap();    let mut last = String::new();    let v = b.verified();    for n in 0..2003 {        last = a.store.seal("b", &v, None, format!("g{n}").as_bytes()).unwrap();    }    assert_eq!(open(&mut b, &a, "g", &last), Err(OpenError::TooFarAhead));    assert!(!b.store.due_reset(&a.verified().identity));}#[test]fn a_lost_session_is_reset_by_a_fresh_one() {    let (mut a, mut b) = (Device::new(1, "a"), Device::new(2, "b"));    // Bob's ratchet file as it stood before Alice ever wrote.    let before = b.store.to_bytes(&b.chat).unwrap();    let first = seal(&mut a, &mut b, "hello");    open(&mut b, &a, "m0", &first).unwrap();    let r = seal(&mut b, &mut a, "reply");    open(&mut a, &b, "r", &r).unwrap();    // The file goes back to that older copy (a backup put back): the same identity, no session.    b.store = Store::from_bytes(&b.chat, &before).unwrap();    let lost = seal(&mut a, &mut b, "lost");    let identity = a.verified().identity;    assert_eq!(open(&mut b, &a, "lost", &lost), Err(OpenError::Undecryptable { identity }));    assert!(b.store.due_reset(&identity) && b.store.needs_prekey(&a.verified()));    // Bob's next box starts a fresh session on one of Alice's keys; Alice's answers go on it.    let notice = seal(&mut b, &mut a, "unreadable: lost");    assert!(!b.store.due_reset(&identity));    assert_eq!(open(&mut a, &b, "n", &notice).unwrap(), "unreadable: lost");    let healed = seal(&mut a, &mut b, "healed");    assert_eq!(open(&mut b, &a, "h", &healed).unwrap(), "healed");}#[test]fn a_new_identity_on_the_same_device_gets_a_new_session() {    let (mut a, mut b) = (Device::new(1, "a"), Device::new(2, "b"));    let first = seal(&mut a, &mut b, "hello");    open(&mut b, &a, "m0", &first).unwrap();    // Bob's ratchet file is gone and a new account published (an iPhone's Keychain keeps the chat key).    let mut fresh = Store::new(0);    b.shelf = fresh.prekeys(0);    fresh.published();    b.store = fresh;    // Alice sees a new identity in his record: a fresh session on one of his new keys, nothing lost from then on.    let next = seal(&mut a, &mut b, "after");    assert_eq!(open(&mut b, &a, "m1", &next).unwrap(), "after");    assert!(a.store.pinned("b"));}#[test]fn both_starting_at_once_settles_on_one_session() {    let (mut a, mut b) = (Device::new(1, "a"), Device::new(2, "b"));    let from_a = seal(&mut a, &mut b, "a first");    let from_b = seal(&mut b, &mut a, "b first");    assert_eq!(open(&mut b, &a, "1", &from_a).unwrap(), "a first");    assert_eq!(open(&mut a, &b, "2", &from_b).unwrap(), "b first");    for n in 0..4 {        let x = seal(&mut a, &mut b, &format!("a{n}"));        assert_eq!(open(&mut b, &a, &format!("a{n}"), &x).unwrap(), format!("a{n}"));        let y = seal(&mut b, &mut a, &format!("b{n}"));        assert_eq!(open(&mut a, &b, &format!("b{n}"), &y).unwrap(), format!("b{n}"));    }}#[test]fn two_devices_each_side() {    let mut a1 = Device::new(1, "a1");    let mut a2 = Device::new(2, "a2");    let mut b1 = Device::new(3, "b1");    let mut b2 = Device::new(4, "b2");    // A1 writes: a box for each of Bob's devices and for her own other one, each on its own session.    let to_b1 = seal(&mut a1, &mut b1, "hi");    let to_b2 = seal(&mut a1, &mut b2, "hi");    let to_a2 = seal(&mut a1, &mut a2, "hi");    assert_ne!(to_b1, to_b2);    let senders = [a1.sender(), a2.sender()];    for (device, sealed) in [(&mut b1, &to_b1), (&mut b2, &to_b2), (&mut a2, &to_a2)] {        assert_eq!(device.store.open("m", sealed, &senders, 1).unwrap().payload, b"hi");    }    // A box for B1 opens on no other device.    assert!(b2.store.open("m-b1", &to_b1, &senders, 1).is_err());    // B2 answers both of Alice's devices; each opens its own.    let back1 = seal(&mut b2, &mut a1, "yes");    let back2 = seal(&mut b2, &mut a2, "yes");    let bobs = [b1.sender(), b2.sender()];    let opened = a1.store.open("r", &back1, &bobs, 1).unwrap();    assert_eq!((opened.handle.as_str(), opened.payload.as_slice()), ("b2", b"yes".as_slice()));    assert_eq!(a2.store.open("r", &back2, &bobs, 1).unwrap().payload, b"yes");}#[test]fn a_box_from_an_identity_the_sender_does_not_publish_is_dropped() {    let (mut a, mut b) = (Device::new(1, "a"), Device::new(2, "b"));    let mallory = Device::new(9, "m");    let sealed = seal(&mut a, &mut b, "hello");    assert_eq!(b.store.open("m", &sealed, &[mallory.sender()], 1), Err(OpenError::UnknownSender));    // Its sender named in the box swapped for another published one: it opens nothing.    let mut body = URL_SAFE_NO_PAD.decode(sealed.strip_prefix(BOX_PREFIX).unwrap()).unwrap();    body[2..34].copy_from_slice(&mallory.verified().identity);    let swapped = format!("{BOX_PREFIX}{}", URL_SAFE_NO_PAD.encode(body));    assert!(b.store.open("m", &swapped, &[mallory.sender(), a.sender()], 1).is_err());    assert_eq!(b.store.open("m", "c2:AAAA", &[a.sender()], 1), Err(OpenError::Unreadable));    assert_eq!(b.store.open("m", "c1:abc", &[a.sender()], 1), Err(OpenError::Unreadable));}#[test]fn a_tampered_box_opens_nothing() {    let (mut a, mut b) = (Device::new(1, "a"), Device::new(2, "b"));    let first = seal(&mut a, &mut b, "hello");    open(&mut b, &a, "m0", &first).unwrap();    let later = seal(&mut a, &mut b, "later");    let mut body = URL_SAFE_NO_PAD.decode(later.strip_prefix(BOX_PREFIX).unwrap()).unwrap();    let last = body.len() - 12;    body[last] ^= 1;    let tampered = format!("{BOX_PREFIX}{}", URL_SAFE_NO_PAD.encode(body));    assert!(open(&mut b, &a, "t", &tampered).is_err());    // The real one still opens.    assert_eq!(open(&mut b, &a, "l", &later).unwrap(), "later");}#[test]fn records_and_keys_are_checked() {    let (mut a, mut b) = (Device::new(1, "a"), Device::new(2, "b"));    let record = b.store.record(&b.chat_pub());    assert!(verify_record(&b.chat_pub(), &record).is_some());    // Bob's ratchet published beside someone else's chat key: refused.    assert!(verify_record(&a.chat_pub(), &record).is_none());    let mut forged = record.clone();    forged.identity = a.store.record(&a.chat_pub()).identity;    assert!(verify_record(&b.chat_pub(), &forged).is_none());    // A one-time key signed by nobody of Bob's: no session is made on it.    let mut stray = a.claim();    assert!(verify_prekey(&b.verified(), &stray).is_none());    let v = b.verified();    assert_eq!(a.store.seal("b", &v, Some(&stray), b"x"), Err(SealError::BadPrekey));    assert_eq!(a.store.seal("b", &v, None, b"x"), Err(SealError::NeedPrekey));    stray.key = b.claim().key;    assert_eq!(a.store.seal("b", &v, Some(&stray), b"x"), Err(SealError::BadPrekey));}#[test]fn one_time_keys_top_up_and_the_fallback_turns_over() {    let mut store = Store::new(0);    let first = store.prekeys(0);    assert_eq!(first.len(), PREKEYS_TARGET);    let fallback = store.fallback(0).expect("the first fallback key");    assert!(fallback.fallback);    // Not yet taken by the Worker: the same ones again, none made.    assert_eq!(store.prekeys(0), first);    store.published();    assert!(store.prekeys(PREKEYS_LOW).is_empty());    assert_eq!(store.prekeys(10).len(), PREKEYS_TARGET - 10);    assert!(store.fallback(FALLBACK_MS).is_none());    let next = store.fallback(FALLBACK_MS + 1).expect("a new fallback after a week");    assert_ne!(next.key, fallback.key);}#[test]fn a_session_runs_on_after_the_store_is_read_back() {    let (mut a, mut b) = (Device::new(1, "a"), Device::new(2, "b"));    let first = seal(&mut a, &mut b, "hello");    open(&mut b, &a, "m0", &first).unwrap();    let bytes = b.store.to_bytes(&b.chat).unwrap();    assert!(Store::from_bytes(&a.chat, &bytes).is_none(), "another chat key opens nothing");    let mut flipped = bytes.clone();    *flipped.last_mut().unwrap() ^= 1;    assert!(Store::from_bytes(&b.chat, &flipped).is_none());    b.store = Store::from_bytes(&b.chat, &bytes).unwrap();    assert!(b.store.pinned("a"));    let r = seal(&mut b, &mut a, "after");    assert_eq!(open(&mut a, &b, "r", &r).unwrap(), "after");    let more = seal(&mut a, &mut b, "more");    assert_eq!(open(&mut b, &a, "more", &more).unwrap(), "more");}#[test]fn a_peek_opens_without_changing_anything() {    let (mut a, mut b) = (Device::new(1, "a"), Device::new(2, "b"));    let first = seal(&mut a, &mut b, "hello");    // A first message of a session Bob does not hold yet: the extension cannot open it (no record to check it against).    assert_eq!(b.store.peek("m0", &first), None);    open(&mut b, &a, "m0", &first).unwrap();    // Opened and not yet taken: peeked from what was kept.    assert_eq!(b.store.peek("m0", &first).map(|(_, p)| p), Some(b"hello".to_vec()));    b.store.taken(["m0"]);    let later = seal(&mut a, &mut b, "later");    let (identity, words) = b.store.peek("m1", &later).expect("peeked");    assert_eq!((identity, words.as_slice()), (a.verified().identity, b"later".as_slice()));    // Peeked twice, then opened for real: nothing was used up.    assert!(b.store.peek("m1", &later).is_some());    assert_eq!(open(&mut b, &a, "m1", &later).unwrap(), "later");    // A box from nobody it has a session with, or not a c2 box: nothing.    let mut c = Device::new(3, "c");    let stray = seal(&mut c, &mut b, "stray");    assert_eq!(b.store.peek("m2", &stray), None);    assert_eq!(b.store.peek("m3", "c1:abc"), None);}// ── known answers ───────────────────────────────────────────────────────fn vectors() -> serde_json::Value {    serde_json::from_str(include_str!("ratchet_vectors.json")).unwrap()}fn hex32(v: &serde_json::Value) -> [u8; 32] {    hex::decode(v.as_str().unwrap()).unwrap().try_into().unwrap()}/// The state file's sealing, fixed key and nonce: the bytes this build writes.#[test]fn the_state_file_is_sealed_as_the_vectors_say() {    let v = &vectors()["store"];    let secret = hex32(&v["chatSecret"]);    let nonce: [u8; 12] = hex::decode(v["nonce"].as_str().unwrap()).unwrap().try_into().unwrap();    let sealed = seal_store_with(&secret, &nonce, v["plain"].as_str().unwrap().as_bytes()).unwrap();    assert_eq!(hex::encode(&sealed), v["sealed"].as_str().unwrap());    assert_eq!(open_store(&secret, &sealed).unwrap().as_slice(), v["plain"].as_str().unwrap().as_bytes());}/// A record and a one-time key signed by a fixed Ed25519 key, as the Worker signs a made-up device's:/// Ed25519 is deterministic, so the Worker's test holds the same signatures.#[test]fn a_record_signed_as_the_vectors_say_verifies() {    use ed25519_dalek::Signer;    let v = &vectors()["record"];    let signer = ed25519_dalek::SigningKey::from_bytes(&hex32(&v["signingSeed"]));    let chat = hex32(&v["chatKey"]);    let identity = hex32(&v["identity"]);    let prekey = hex32(&v["prekey"]);    let sig = signer.sign(&device_statement(&chat, &identity));    assert_eq!(hex::encode(sig.to_bytes()), v["deviceSig"].as_str().unwrap());    let record = Record { identity: text(&identity), signing: text(signer.verifying_key().as_bytes()), sig: URL_SAFE_NO_PAD.encode(sig.to_bytes()) };    let verified = verify_record(&chat, &record).expect("verifies");    let psig = signer.sign(&prekey_statement(&identity, &prekey));    assert_eq!(hex::encode(psig.to_bytes()), v["prekeySig"].as_str().unwrap());    assert_eq!(verify_prekey(&verified, &Prekey { key: text(&prekey), sig: URL_SAFE_NO_PAD.encode(psig.to_bytes()), fallback: false }), Some(prekey));}/// A conversation recorded by this build: Bob's store as it stood, and Alice's first and second/// boxes. A later build must still open them (the state file and the box are formats people keep).#[test]fn a_recorded_conversation_still_opens() {    let v = &vectors()["conversation"];    let bob_chat = hex32(&v["bobChat"]);    let bytes = hex::decode(v["bobStore"].as_str().unwrap()).unwrap();    let mut bob = Store::from_bytes(&bob_chat, &bytes).expect("Bob's store reads");    let alice: Record = serde_json::from_value(v["alice"].clone()).unwrap();    let alice = verify_record(&hex32(&v["aliceChatPub"]), &alice).expect("Alice's record verifies");    let senders = [("alice".to_string(), alice)];    for (n, sealed) in v["boxes"].as_array().unwrap().iter().enumerate() {        let opened = bob.open(&format!("m{n}"), sealed.as_str().unwrap(), &senders, 1).expect("opens");        assert_eq!(String::from_utf8(opened.payload).unwrap(), v["words"][n].as_str().unwrap());    }}/// Prints a fresh `conversation` vector (run once, by hand, when the format changes on purpose).#[test]#[ignore]fn record_a_conversation() {    let (mut a, mut b) = (Device::new(1, "alice"), Device::new(2, "bob"));    let words = ["the first words", "and the second"];    let boxes: Vec<String> = words.iter().map(|w| seal(&mut a, &mut b, w)).collect();    println!(        "{}",        serde_json::json!({            "bobChat": hex::encode(b.chat),            "bobStore": hex::encode(b.store.to_bytes(&b.chat).unwrap()),            "aliceChatPub": hex::encode(a.chat_pub()),            "alice": a.store.record(&a.chat_pub()),            "boxes": boxes,            "words": words,        })    );}