← back to the page

workers/public/chat/ui/src/crypto.rs

be the server: chat's end-to-end sealing · 516 lines · compiled into this Worker from the repository as it is

1//! End-to-end encryption. Everything readable leaves this browser sealed:
2//! the Worker, D1, the Hub and the SFU only ever handle ciphertext.
3//!
4//! Keys:
5//! - **App key** (32 bytes): this person's chat key, derived by the account
6//! host from their account key and handed over by the key bridge.
7//! - **Identity** (hybrid ML-KEM-768 + X25519): both key pairs derived
8//! from the app key; both public halves are published so others can make
9//! DM keys with them.
10//! - **Server key** (32 random bytes): made by the server's creator. Members
11//! keep it in their *keyring* (wrapped under their own app key, stored by
12//! the Worker). It travels to new members in the invite link's fragment,
13//! which browsers never send anywhere.
14//! - **DM key**: hybrid, so nobody else has it, a quantum computer
15//! included. The first of the two to open the DM encapsulates a fresh
16//! ML-KEM-768 secret to the other's ML-KEM key; the ciphertext is stored
17//! with the DM, beside the same secret sealed under the encapsulating
18//! side's own key (for their other devices). The key is HKDF-SHA-512 over
19//! the X25519 shared secret *and* the ML-KEM secret: opening it takes
20//! breaking both. DMs from before (X25519 alone) also keep a
21//! [`LegacyKey`], which only opens what was sealed with it.
22//! - **Scope key**: the server key or the DM key; it seals names, nicknames,
23//! messages, and (through a media key per channel) call audio and video.
24//!
25//! Sealed values are `base64url(iv ‖ AES-256-GCM(ciphertext ‖ tag))`, bound
26//! by their associated data to what they are (`msg/<channel>`, …), so one
27//! can't stand in for another.
28
29use aes_gcm::aead::{Aead, KeyInit, Payload};
30use aes_gcm::{Aes256Gcm, Nonce};
31use base64::engine::general_purpose::URL_SAFE_NO_PAD as B64;
32use base64::Engine;
33use hkdf::Hkdf;
34use ml_kem::kem::{Decapsulate, Encapsulate};
35use ml_kem::{EncodedSizeUser, KemCore};
36use sha2::{Sha256, Sha512};
37
38pub type Key = [u8; 32];
39
40fn derive(ikm: &[u8], info: &str) -> Key {
41 let mut out = [0u8; 32];
42 Hkdf::<Sha256>::new(Some(b"chat/v1"), ikm).expand(info.as_bytes(), &mut out).expect("32 bytes");
43 out
44}
45
46/// HKDF-SHA-512, for the post-quantum derivations (the ML-KEM seed, hybrid
47/// DM keys).
48fn derive512<const N: usize>(ikm: &[u8], info: &[&[u8]]) -> [u8; N] {
49 let mut out = [0u8; N];
50 Hkdf::<Sha512>::new(Some(b"chat/v2"), ikm).expand_multi_info(info, &mut out).expect("short output");
51 out
52}
53
54fn random<const N: usize>() -> [u8; N] {
55 let mut b = [0u8; N];
56 getrandom::getrandom(&mut b).expect("random");
57 b
58}
59
60pub fn new_server_key() -> Key {
61 random()
62}
63
64/// Random hex ID (for servers and channels: their IDs are bound into what
65/// seals their names, so the browser picks them).
66pub fn new_id() -> String {
67 random::<8>().iter().map(|b| format!("{b:02x}")).collect()
68}
69
70pub fn b64(bytes: &[u8]) -> String {
71 B64.encode(bytes)
72}
73
74pub fn unb64(s: &str) -> Option<Vec<u8>> {
75 B64.decode(s.trim()).ok()
76}
77
78pub fn key_from(bytes: &[u8]) -> Option<Key> {
79 bytes.try_into().ok()
80}
81
82/// Seals and opens values under one key.
83#[derive(Clone)]
84pub struct Sealer {
85 cipher: Aes256Gcm,
86}
87
88impl Sealer {
89 pub fn new(key: &Key) -> Sealer {
90 Sealer { cipher: Aes256Gcm::new_from_slice(key).expect("32-byte key") }
91 }
92
93 pub fn seal(&self, ad: &str, plain: &str) -> String {
94 self.seal_bytes(ad, plain.as_bytes())
95 }
96
97 pub fn open(&self, ad: &str, sealed: &str) -> Option<String> {
98 String::from_utf8(self.open_bytes(ad, sealed)?).ok()
99 }
100
101 pub fn seal_bytes(&self, ad: &str, plain: &[u8]) -> String {
102 let iv = random::<12>();
103 let ct = self.cipher.encrypt(Nonce::from_slice(&iv), Payload { msg: plain, aad: ad.as_bytes() }).expect("seal");
104 let mut out = iv.to_vec();
105 out.extend_from_slice(&ct);
106 b64(&out)
107 }
108
109 pub fn open_bytes(&self, ad: &str, sealed: &str) -> Option<Vec<u8>> {
110 let raw = unb64(sealed)?;
111 if raw.len() < 28 {
112 return None;
113 }
114 let (iv, ct) = raw.split_at(12);
115 self.cipher.decrypt(Nonce::from_slice(iv), Payload { msg: ct, aad: ad.as_bytes() }).ok()
116 }
117}
118
119/// What each sealed value is bound to.
120pub mod ad {
121 pub fn server_name(server: &str) -> String {
122 format!("server-name/{server}")
123 }
124 pub fn channel_name(channel: &str) -> String {
125 format!("channel-name/{channel}")
126 }
127 pub fn nickname(scope: &str, user: &str) -> String {
128 format!("nick/{scope}/{user}")
129 }
130 pub fn message(channel: &str) -> String {
131 format!("msg/{channel}")
132 }
133 pub fn keyring(server: &str) -> String {
134 format!("keyring/{server}")
135 }
136 pub fn picture(id: &str) -> String {
137 format!("picture/{id}")
138 }
139 pub fn server_icon(server: &str, id: &str) -> String {
140 format!("server-icon/{server}/{id}")
141 }
142 pub fn dm_kem(dm: &str) -> String {
143 format!("dm-kem/{dm}")
144 }
145}
146
147/// A published ML-KEM-768 key, as encapsulated to.
148type KemEk = ml_kem::kem::EncapsulationKey<ml_kem::MlKem768Params>;
149
150/// This person's keys.
151#[derive(Clone)]
152pub struct Me {
153 keyring: Sealer,
154 /// The identity: both halves, used together for every new DM key.
155 kem: ml_kem::kem::DecapsulationKey<ml_kem::MlKem768Params>,
156 x25519: x25519_dalek::StaticSecret,
157 /// Seals the ML-KEM secrets this person encapsulated, for their other
158 /// devices (the ciphertext only opens for the other side).
159 kem_wrap: Sealer,
160 /// The published X25519 public key (base64url, 32 bytes).
161 pub public: String,
162 /// The published ML-KEM-768 encapsulation key (base64url).
163 pub kem_public: String,
164 /// Seals what only this person reads (their own nickname, kept for
165 /// when they're in no server yet).
166 pub own: Key,
167}
168
169/// A DM's ML-KEM share as stored with it: `ct` encapsulated to one side's
170/// ML-KEM key, `wrap` the same secret sealed for the other (the side that
171/// encapsulated).
172pub struct Share<'a> {
173 /// Whether `ct` was encapsulated to this person.
174 pub to_me: bool,
175 pub ct: &'a str,
176 pub wrap: &'a str,
177}
178
179/// A DM key from before DMs went hybrid (X25519 alone). It only opens what
180/// was sealed with it: nothing new is ever sealed under a classical key.
181#[derive(Clone)]
182pub struct LegacyKey(Key);
183
184impl LegacyKey {
185 pub fn open(&self, ad: &str, sealed: &str) -> Option<String> {
186 Sealer::new(&self.0).open(ad, sealed)
187 }
188
189 /// The 16-byte tag HKDF-SHA-256 (`salt`, `info`) gives under this key:
190 /// to recognise identifiers made with it before (reaction tags), never
191 /// to make new ones.
192 pub fn tag(&self, salt: &[u8], info: &str) -> [u8; 16] {
193 tag16(&self.0, salt, info)
194 }
195
196 /// Seals under the old key. Only the dev-only test hook uses it
197 /// (`reseal::expose_test`: chat-e2e makes an item from before the
198 /// migration and watches it get re-sealed); nothing else ever does.
199 pub fn seal_for_test(&self, ad: &str, plain: &str) -> String {
200 Sealer::new(&self.0).seal(ad, plain)
201 }
202}
203
204/// The 16-byte tag HKDF-SHA-256 (`salt`, `info`) gives under `key`: an
205/// identifier everyone with the key makes alike (reaction tags).
206pub fn tag16(key: &Key, salt: &[u8], info: &str) -> [u8; 16] {
207 let mut out = [0u8; 16];
208 Hkdf::<Sha256>::new(Some(salt), key).expand(info.as_bytes(), &mut out).expect("16 bytes");
209 out
210}
211
212/// `sealed` (bound to `ad`) sealed again under a DM's hybrid key: it opens
213/// with that key (sealed since the migration) or with the DM's old one.
214/// `(plaintext, new ciphertext)`; `None` when neither opens it.
215pub fn reseal(hybrid: &Key, legacy: Option<&LegacyKey>, ad: &str, sealed: &str) -> Option<(String, String)> {
216 let new = Sealer::new(hybrid);
217 let plain = new.open(ad, sealed).or_else(|| legacy?.open(ad, sealed))?;
218 let ct = new.seal(ad, &plain);
219 Some((plain, ct))
220}
221
222impl Me {
223 pub fn new(app_key: &Key) -> Me {
224 // Both halves from the app key: the same identity on every device,
225 // nothing to store.
226 let seed: [u8; 64] = derive512(app_key, &[b"identity/ml-kem-768"]);
227 let (d, z) = seed.split_at(32);
228 let (kem, ek) = ml_kem::MlKem768::generate_deterministic(&ml_kem::B32::try_from(d).expect("32"), &ml_kem::B32::try_from(z).expect("32"));
229 let x25519 = x25519_dalek::StaticSecret::from(derive(app_key, "identity"));
230 let public = b64(x25519_dalek::PublicKey::from(&x25519).as_bytes());
231 Me {
232 keyring: Sealer::new(&derive(app_key, "keyring")),
233 kem,
234 x25519,
235 kem_wrap: Sealer::new(&derive512(app_key, &[b"dm-kem-wrap"])),
236 public,
237 kem_public: b64(&ek.as_bytes()),
238 own: derive(app_key, "own"),
239 }
240 }
241
242 /// A server key, wrapped for this person's keyring.
243 pub fn wrap(&self, server: &str, key: &Key) -> String {
244 self.keyring.seal(&ad::keyring(server), &b64(key))
245 }
246
247 pub fn unwrap(&self, server: &str, wrapped: &str) -> Option<Key> {
248 key_from(&unb64(&self.keyring.open(&ad::keyring(server), wrapped)?)?)
249 }
250
251 /// A new DM's ML-KEM share: a fresh secret encapsulated to `them_kem`
252 /// (their published ML-KEM key), and the same secret sealed for this
253 /// person. `(ct, wrap)`, for the Worker to keep with the DM.
254 pub fn new_share(&self, dm: &str, them_kem: &str) -> Option<(String, String)> {
255 let ek = KemEk::from_bytes(&ml_kem::Encoded::<KemEk>::try_from(unb64(them_kem)?.as_slice()).ok()?);
256 let (ct, ss) = ek.encapsulate(&mut rand_core::OsRng).ok()?;
257 Some((b64(&ct), self.kem_wrap.seal_bytes(&ad::dm_kem(dm), &ss)))
258 }
259
260 /// The key this person shares with `them` (their published X25519 key)
261 /// in DM `dm`: HKDF-SHA-512 over the share's ML-KEM secret and the
262 /// X25519 shared secret, bound to the DM, both X25519 keys and the
263 /// ciphertext. Both sides get the same key; neither secret alone does.
264 pub fn dm_key(&self, dm: &str, them: &str, share: &Share) -> Option<Key> {
265 // ML-KEM-768: decapsulated when the share was made for this person,
266 // else (they made it) their own sealed copy of the secret.
267 let ct = ml_kem::Ciphertext::<ml_kem::MlKem768>::try_from(unb64(share.ct)?.as_slice()).ok()?;
268 let kem: [u8; 32] = if share.to_me { self.kem.decapsulate(&ct).ok()?.into() } else { self.kem_wrap.open_bytes(&ad::dm_kem(dm), share.wrap)?.try_into().ok()? };
269 // X25519 between the two identities.
270 let pk: [u8; 32] = unb64(them)?.try_into().ok()?;
271 let x = self.x25519.diffie_hellman(&x25519_dalek::PublicKey::from(pk));
272 if !x.was_contributory() {
273 return None;
274 }
275 // The encapsulating side's key first, so both sides agree.
276 let (first, second) = if share.to_me { (them, self.public.as_str()) } else { (self.public.as_str(), them) };
277 let mut ikm = [0u8; 64];
278 ikm[..32].copy_from_slice(&kem);
279 ikm[32..].copy_from_slice(x.as_bytes());
280 let key = derive512(&ikm, &[b"dm/", dm.as_bytes(), b"/", first.as_bytes(), b"/", second.as_bytes(), b"/", share.ct.as_bytes()]);
281 ikm.fill(0);
282 Some(key)
283 }
284
285 /// The pre-migration key of DM `dm`, X25519 alone: it opens messages
286 /// (and reactions, votes, nicknames) sealed before the DM went hybrid,
287 /// and can't seal.
288 pub fn legacy_dm_key(&self, dm: &str, them: &str) -> Option<LegacyKey> {
289 let pk: [u8; 32] = unb64(them)?.try_into().ok()?;
290 let shared = self.x25519.diffie_hellman(&x25519_dalek::PublicKey::from(pk)); // nosemgrep: pq-no-classical-public-key (reading pre-migration messages only)
291 if !shared.was_contributory() {
292 return None;
293 }
294 Some(LegacyKey(derive(shared.as_bytes(), &format!("dm/{dm}"))))
295 }
296}
297
298/// The key for a call's audio and video in `channel`.
299pub fn media_key(scope_key: &Key, channel: &str) -> Key {
300 derive(scope_key, &format!("media/{channel}"))
301}
302
303/// An invite link's fragment: the join code, the server key and the
304/// account invite (`INV-…`, one sign-up on the account host; may be empty).
305pub fn invite_fragment(code: &str, key: &Key, signup: &str) -> String {
306 if signup.is_empty() { format!("{code}.{}", b64(key)) } else { format!("{code}.{}.{signup}", b64(key)) }
307}
308
309/// The join code and the server key of a link or fragment (the account
310/// invite is the account host's business).
311pub fn parse_invite(fragment: &str) -> Option<(String, Key)> {
312 let f = fragment.trim().trim_start_matches('#');
313 let f = f.rsplit(['#', '/']).next().unwrap_or(f);
314 let mut parts = f.split('.');
315 let (code, key) = (parts.next()?, parts.next()?);
316 if parts.count() > 1 {
317 return None;
318 }
319 Some((code.to_string(), key_from(&unb64(key)?)?))
320}
321
322/// Call media frames: the first `clear` bytes stay readable (the codec
323/// header the SFU needs to tell keyframes), the rest is AES-GCM sealed and
324/// the IV appended: `header ‖ ciphertext ‖ tag ‖ iv`.
325pub struct FrameCipher {
326 cipher: Aes256Gcm,
327}
328
329impl FrameCipher {
330 pub fn new(key: &Key) -> FrameCipher {
331 FrameCipher { cipher: Aes256Gcm::new_from_slice(key).expect("32-byte key") }
332 }
333
334 pub fn encrypt(&self, frame: &[u8], clear: usize) -> Vec<u8> {
335 let clear = clear.min(frame.len());
336 let (head, body) = frame.split_at(clear);
337 let iv = random::<12>();
338 let ct = self.cipher.encrypt(Nonce::from_slice(&iv), Payload { msg: body, aad: head }).expect("seal frame");
339 let mut out = Vec::with_capacity(frame.len() + 28);
340 out.extend_from_slice(head);
341 out.extend_from_slice(&ct);
342 out.extend_from_slice(&iv);
343 out
344 }
345
346 /// `None` for frames that aren't ours (wrong key, damaged, unencrypted).
347 pub fn decrypt(&self, frame: &[u8], clear: usize) -> Option<Vec<u8>> {
348 if frame.len() < clear + 28 {
349 return None;
350 }
351 let (head, rest) = frame.split_at(clear);
352 let (ct, iv) = rest.split_at(rest.len() - 12);
353 let body = self.cipher.decrypt(Nonce::from_slice(iv), Payload { msg: ct, aad: head }).ok()?;
354 let mut out = head.to_vec();
355 out.extend_from_slice(&body);
356 Some(out)
357 }
358}
359
360/// Bytes left readable at the front of a frame: VP8 keyframes 10, other
361/// VP8 frames 3 (the SFU reads the keyframe bit), Opus audio 1.
362pub fn clear_bytes(kind: &str, frame_type: &str) -> usize {
363 match (kind, frame_type) {
364 ("audio", _) => 1,
365 (_, "key") => 10,
366 _ => 3,
367 }
368}
369
370#[cfg(test)]
371mod tests {
372 use super::*;
373
374 #[test]
375 fn sealed_values_need_the_key_and_the_right_binding() {
376 let k = new_server_key();
377 let s = Sealer::new(&k);
378 let c = s.seal(&ad::message("c1"), "hello");
379 assert_eq!(s.open(&ad::message("c1"), &c).as_deref(), Some("hello"));
380 assert_eq!(s.open(&ad::message("c2"), &c), None, "another channel");
381 assert_eq!(Sealer::new(&new_server_key()).open(&ad::message("c1"), &c), None, "another key");
382 assert!(!c.contains("hello"));
383 }
384
385 #[test]
386 fn keyrings_are_personal() {
387 let (a, b) = (Me::new(&[1; 32]), Me::new(&[2; 32]));
388 let k = new_server_key();
389 let w = a.wrap("s1", &k);
390 assert_eq!(a.unwrap("s1", &w), Some(k));
391 assert_eq!(a.unwrap("s2", &w), None, "bound to its server");
392 assert_eq!(b.unwrap("s1", &w), None, "someone else's keyring");
393 assert_eq!(Me::new(&[1; 32]).public, a.public, "identity is stable");
394 }
395
396 #[test]
397 fn identities_are_hybrid_and_stable() {
398 let a = Me::new(&[1; 32]);
399 assert_eq!(a.public.len(), 43);
400 assert_eq!(a.kem_public.len(), 1579);
401 assert_eq!(unb64(&a.kem_public).unwrap().len(), 1184, "ML-KEM-768");
402 let again = Me::new(&[1; 32]);
403 assert_eq!((again.public, again.kem_public), (a.public.clone(), a.kem_public.clone()), "the same on every device");
404 assert_ne!(Me::new(&[2; 32]).kem_public, a.kem_public);
405 }
406
407 #[test]
408 fn both_sides_of_a_hybrid_dm_get_the_same_key() {
409 let (a, b, c) = (Me::new(&[1; 32]), Me::new(&[2; 32]), Me::new(&[3; 32]));
410 // a opens the DM: encapsulates to b.
411 let (ct, wrap) = a.new_share("d1", &b.kem_public).unwrap();
412 assert_eq!(unb64(&ct).unwrap().len(), 1088, "an ML-KEM-768 ciphertext");
413 assert_eq!((ct.len(), wrap.len()), (1451, 80), "what the Worker accepts (chat_proto::kem_ct_ok, kem_wrap_ok)");
414 let ab = a.dm_key("d1", &b.public, &Share { to_me: false, ct: &ct, wrap: &wrap }).unwrap();
415 assert_eq!(b.dm_key("d1", &a.public, &Share { to_me: true, ct: &ct, wrap: &wrap }), Some(ab), "b decapsulates");
416 assert_eq!(Me::new(&[1; 32]).dm_key("d1", &b.public, &Share { to_me: false, ct: &ct, wrap: &wrap }), Some(ab), "a's other device");
417 assert_ne!(c.dm_key("d1", &a.public, &Share { to_me: true, ct: &ct, wrap: &wrap }), Some(ab), "a third person can't");
418 assert_eq!(c.dm_key("d1", &b.public, &Share { to_me: false, ct: &ct, wrap: &wrap }), None, "nor open a's copy");
419 assert_eq!(a.dm_key("d2", &b.public, &Share { to_me: false, ct: &ct, wrap: &wrap }), None, "the copy is bound to its DM");
420 assert_ne!(b.dm_key("d2", &a.public, &Share { to_me: true, ct: &ct, wrap: &wrap }), Some(ab), "per DM");
421 assert_eq!(a.dm_key("d1", "not a key", &Share { to_me: false, ct: &ct, wrap: &wrap }), None);
422 // A fresh share is a fresh key.
423 let (ct2, wrap2) = a.new_share("d1", &b.kem_public).unwrap();
424 assert_ne!(b.dm_key("d1", &a.public, &Share { to_me: true, ct: &ct2, wrap: &wrap2 }), Some(ab));
425 assert_eq!(a.new_share("d1", "not a key"), None);
426 }
427
428 #[test]
429 fn a_new_dm_never_derives_without_the_kem_secret() {
430 let (a, b) = (Me::new(&[1; 32]), Me::new(&[2; 32]));
431 let (ct, wrap) = a.new_share("d1", &b.kem_public).unwrap();
432 let ab = a.dm_key("d1", &b.public, &Share { to_me: false, ct: &ct, wrap: &wrap }).unwrap();
433 // No ciphertext, a cut one, or no sealed copy: no key at all.
434 assert_eq!(a.dm_key("d1", &b.public, &Share { to_me: false, ct: "", wrap: &wrap }), None);
435 assert_eq!(b.dm_key("d1", &a.public, &Share { to_me: true, ct: &ct[..ct.len() - 4], wrap: "" }), None);
436 assert_eq!(a.dm_key("d1", &b.public, &Share { to_me: false, ct: &ct, wrap: "" }), None);
437 // The KEM secret counts: another one (a ciphertext the server
438 // swapped) gives another key, though X25519 is the same.
439 let (other, _) = Me::new(&[9; 32]).new_share("d1", &b.kem_public).unwrap();
440 assert_ne!(b.dm_key("d1", &a.public, &Share { to_me: true, ct: &other, wrap: "" }), Some(ab));
441 // Not the classical key, nor anything X25519 alone gives.
442 let x = a.x25519.diffie_hellman(&x25519_dalek::PublicKey::from(<[u8; 32]>::try_from(unb64(&b.public).unwrap()).unwrap())); // nosemgrep: pq-no-classical-public-key (test: the classical key it must not be)
443 assert_ne!(ab, derive(x.as_bytes(), "dm/d1"));
444 assert_ne!(ab, derive512::<32>(x.as_bytes(), &[b"dm/d1"]));
445 let sealed = Sealer::new(&ab).seal(&ad::message("d1"), "hi");
446 assert_eq!(a.legacy_dm_key("d1", &b.public).unwrap().open(&ad::message("d1"), &sealed), None, "the classical key can't open new messages");
447 }
448
449 #[test]
450 fn messages_from_before_the_migration_still_open() {
451 let (a, b, c) = (Me::new(&[1; 32]), Me::new(&[2; 32]), Me::new(&[3; 32]));
452 // Sealed the way DMs were before: HKDF-SHA-256 of the X25519 secret.
453 let x = a.x25519.diffie_hellman(&x25519_dalek::PublicKey::from(<[u8; 32]>::try_from(unb64(&b.public).unwrap()).unwrap())); // nosemgrep: pq-no-classical-public-key (test: a pre-migration message)
454 let old = Sealer::new(&derive(x.as_bytes(), "dm/d1")).seal(&ad::message("d1"), "from before");
455 let from_b = b.legacy_dm_key("d1", &a.public).unwrap();
456 assert_eq!(from_b.open(&ad::message("d1"), &old).as_deref(), Some("from before"));
457 assert_eq!(a.legacy_dm_key("d1", &b.public).unwrap().open(&ad::message("d1"), &old).as_deref(), Some("from before"));
458 assert_eq!(c.legacy_dm_key("d1", &a.public).unwrap().open(&ad::message("d1"), &old), None, "a third person can't");
459 assert_eq!(a.legacy_dm_key("d2", &b.public).unwrap().open(&ad::message("d1"), &old), None, "per DM");
460 assert!(a.legacy_dm_key("d1", "not a key").is_none());
461 }
462
463 #[test]
464 fn a_legacy_item_reseals_under_the_hybrid_key() {
465 let (a, b, c) = (Me::new(&[1; 32]), Me::new(&[2; 32]), Me::new(&[3; 32]));
466 let x = a.x25519.diffie_hellman(&x25519_dalek::PublicKey::from(<[u8; 32]>::try_from(unb64(&b.public).unwrap()).unwrap())); // nosemgrep: pq-no-classical-public-key (test: a pre-migration message)
467 let old = Sealer::new(&derive(x.as_bytes(), "dm/d1")).seal(&ad::message("d1"), "from before");
468 let (ct, wrap) = a.new_share("d1", &b.kem_public).unwrap();
469 let hybrid = a.dm_key("d1", &b.public, &Share { to_me: false, ct: &ct, wrap: &wrap }).unwrap();
470 let legacy = a.legacy_dm_key("d1", &b.public).unwrap();
471 let (plain, new) = reseal(&hybrid, Some(&legacy), &ad::message("d1"), &old).unwrap();
472 assert_eq!(plain, "from before", "the same plaintext");
473 // The other side opens it with the hybrid key alone; the old key can't.
474 let theirs = b.dm_key("d1", &a.public, &Share { to_me: true, ct: &ct, wrap: &wrap }).unwrap();
475 assert_eq!(Sealer::new(&theirs).open(&ad::message("d1"), &new).as_deref(), Some("from before"));
476 assert_eq!(legacy.open(&ad::message("d1"), &new), None, "no longer under the classical key");
477 assert_eq!(Sealer::new(&theirs).open(&ad::message("d2"), &new), None, "still bound to its DM");
478 // Already hybrid: sealed again (a fresh IV), the same plaintext.
479 let (again, newer) = reseal(&hybrid, None, &ad::message("d1"), &new).unwrap();
480 assert_eq!(again, "from before");
481 assert_ne!(newer, new);
482 // Nothing to re-seal without a key that opens it.
483 assert_eq!(reseal(&hybrid, None, &ad::message("d1"), &old), None);
484 assert_eq!(reseal(&hybrid, Some(&c.legacy_dm_key("d1", &a.public).unwrap()), &ad::message("d1"), &old), None);
485 assert_eq!(reseal(&hybrid, Some(&legacy), &ad::message("d9"), &old), None, "another binding");
486 }
487
488 #[test]
489 fn invites_carry_code_and_key() {
490 let k = new_server_key();
491 let f = invite_fragment("abc123", &k, "");
492 assert_eq!(parse_invite(&format!("https://chat-dev.example.com/join#{f}")), Some(("abc123".into(), k)));
493 assert_eq!(parse_invite(&f), Some(("abc123".into(), k)));
494 assert_eq!(parse_invite("abc123"), None, "a code alone can't open anything");
495 // With the account invite: the third part, which the join page sends
496 // on to the account host (and nothing else).
497 let inv = "INV-0123A-BCDEF-GHJKM-NPQRS-TVWXY-Z";
498 let f = invite_fragment("abc123", &k, inv);
499 assert_eq!(f.split('.').nth(2), Some(inv));
500 assert_eq!(parse_invite(&format!("https://chat-dev.example.com/join#{f}")), Some(("abc123".into(), k)));
501 assert_eq!(parse_invite(&format!("{f}.extra")), None);
502 }
503
504 #[test]
505 fn frames_keep_their_header_and_hide_the_rest() {
506 let fc = FrameCipher::new(&media_key(&[9; 32], "voice1"));
507 let frame: Vec<u8> = (0..200u8).collect();
508 let enc = fc.encrypt(&frame, 10);
509 assert_eq!(&enc[..10], &frame[..10], "keyframe header readable");
510 assert_ne!(&enc[10..20], &frame[10..20]);
511 assert_eq!(fc.decrypt(&enc, 10), Some(frame.clone()));
512 assert_eq!(FrameCipher::new(&media_key(&[9; 32], "voice2")).decrypt(&enc, 10), None, "another call");
513 assert_eq!(fc.decrypt(&frame, 10), None, "plain frames are dropped");
514 assert_eq!(fc.decrypt(&fc.encrypt(&[7], 1), 1), Some(vec![7]), "audio-sized");
515 }
516}