1use std::{collections::HashMap, sync::Arc};
2
3use core_crypto_keystore::{
4 Database as CryptoKeystore,
5 connection::FetchFromDatabase,
6 entities::{ProteusIdentity, ProteusSession},
7};
8use proteus_wasm::{
9 keys::{IdentityKeyPair, PreKeyBundle},
10 message::Envelope,
11 session::Session,
12};
13
14use crate::{
15 CoreCrypto, Error, KeystoreError, LeafError, ProteusError, Result,
16 group_store::{GroupStore, GroupStoreEntity, GroupStoreValue},
17};
18
19pub type SessionIdentifier = String;
21
22#[derive(Debug)]
24pub struct ProteusConversationSession {
25 pub(crate) identifier: SessionIdentifier,
26 pub(crate) session: Session<Arc<IdentityKeyPair>>,
27}
28
29impl ProteusConversationSession {
30 pub fn encrypt(&mut self, plaintext: &[u8]) -> Result<Vec<u8>> {
32 self.session
33 .encrypt(plaintext)
34 .and_then(|e| e.serialise())
35 .map_err(ProteusError::wrap("encrypting message for proteus session"))
36 .map_err(Into::into)
37 }
38
39 pub async fn decrypt(&mut self, store: &mut core_crypto_keystore::Database, ciphertext: &[u8]) -> Result<Vec<u8>> {
41 let envelope = Envelope::deserialise(ciphertext).map_err(ProteusError::wrap("deserializing envelope"))?;
42 self.session
43 .decrypt(store, &envelope)
44 .await
45 .map_err(ProteusError::wrap("decrypting message for proteus session"))
46 .map_err(Into::into)
47 }
48
49 pub fn identifier(&self) -> &str {
51 &self.identifier
52 }
53
54 pub fn fingerprint_local(&self) -> String {
56 self.session.local_identity().fingerprint()
57 }
58
59 pub fn fingerprint_remote(&self) -> String {
61 self.session.remote_identity().fingerprint()
62 }
63}
64
65#[cfg_attr(target_family = "wasm", async_trait::async_trait(?Send))]
66#[cfg_attr(not(target_family = "wasm"), async_trait::async_trait)]
67impl GroupStoreEntity for ProteusConversationSession {
68 type RawStoreValue = core_crypto_keystore::entities::ProteusSession;
69 type IdentityType = Arc<proteus_wasm::keys::IdentityKeyPair>;
70
71 async fn fetch_from_id(
72 id: impl AsRef<[u8]> + Send,
73 identity: Option<Self::IdentityType>,
74 keystore: &impl FetchFromDatabase,
75 ) -> crate::Result<Option<Self>> {
76 let result = keystore
77 .find::<Self::RawStoreValue>(id)
78 .await
79 .map_err(KeystoreError::wrap("finding raw group store entity by id"))?;
80 let Some(store_value) = result else {
81 return Ok(None);
82 };
83
84 let Some(identity) = identity else {
85 return Err(crate::Error::ProteusNotInitialized);
86 };
87
88 let session = proteus_wasm::session::Session::deserialise(identity, &store_value.session)
89 .map_err(ProteusError::wrap("deserializing session"))?;
90
91 Ok(Some(Self {
92 identifier: store_value.id.clone(),
93 session,
94 }))
95 }
96}
97
98impl CoreCrypto {
99 pub async fn proteus_session(
105 &self,
106 session_id: &str,
107 ) -> Result<Option<GroupStoreValue<ProteusConversationSession>>> {
108 let mut mutex = self.proteus.lock().await;
109 let proteus = mutex.as_mut().ok_or(Error::ProteusNotInitialized)?;
110 let keystore = self.mls.crypto_provider.keystore();
111 proteus.session(session_id, &keystore).await
112 }
113
114 pub async fn proteus_session_exists(&self, session_id: &str) -> Result<bool> {
120 let mut mutex = self.proteus.lock().await;
121 let proteus = mutex.as_mut().ok_or(Error::ProteusNotInitialized)?;
122 let keystore = self.mls.crypto_provider.keystore();
123 Ok(proteus.session_exists(session_id, &keystore).await)
124 }
125
126 pub fn proteus_last_resort_prekey_id() -> u16 {
128 ProteusCentral::last_resort_prekey_id()
129 }
130
131 pub async fn proteus_fingerprint(&self) -> Result<String> {
137 let mutex = self.proteus.lock().await;
138 let proteus = mutex.as_ref().ok_or(Error::ProteusNotInitialized)?;
139 Ok(proteus.fingerprint())
140 }
141
142 pub async fn proteus_fingerprint_local(&self, session_id: &str) -> Result<String> {
148 let mut mutex = self.proteus.lock().await;
149 let proteus = mutex.as_mut().ok_or(Error::ProteusNotInitialized)?;
150 let keystore = self.mls.crypto_provider.keystore();
151 proteus.fingerprint_local(session_id, &keystore).await
152 }
153
154 pub async fn proteus_fingerprint_remote(&self, session_id: &str) -> Result<String> {
160 let mut mutex = self.proteus.lock().await;
161 let proteus = mutex.as_mut().ok_or(Error::ProteusNotInitialized)?;
162 let keystore = self.mls.crypto_provider.keystore();
163 proteus.fingerprint_remote(session_id, &keystore).await
164 }
165}
166
167#[derive(Debug)]
172pub struct ProteusCentral {
173 proteus_identity: Arc<IdentityKeyPair>,
174 proteus_sessions: GroupStore<ProteusConversationSession>,
175}
176
177impl ProteusCentral {
178 pub async fn try_new(keystore: &CryptoKeystore) -> Result<Self> {
180 let proteus_identity: Arc<IdentityKeyPair> = Arc::new(Self::load_or_create_identity(keystore).await?);
181 let proteus_sessions = Self::restore_sessions(keystore, &proteus_identity).await?;
182
183 Ok(Self {
184 proteus_identity,
185 proteus_sessions,
186 })
187 }
188
189 pub(crate) async fn reload_sessions(&mut self, keystore: &CryptoKeystore) -> Result<()> {
191 self.proteus_sessions = Self::restore_sessions(keystore, &self.proteus_identity).await?;
192 Ok(())
193 }
194
195 async fn load_or_create_identity(keystore: &CryptoKeystore) -> Result<IdentityKeyPair> {
198 let Some(identity) = keystore
199 .find::<ProteusIdentity>(ProteusIdentity::ID)
200 .await
201 .map_err(KeystoreError::wrap("finding proteus identity"))?
202 else {
203 return Self::create_identity(keystore).await;
204 };
205
206 let sk = identity.sk_raw();
207 let pk = identity.pk_raw();
208
209 IdentityKeyPair::from_raw_key_pair(*sk, *pk)
211 .map_err(ProteusError::wrap("constructing identity keypair"))
212 .map_err(Into::into)
213 }
214
215 async fn create_identity(keystore: &CryptoKeystore) -> Result<IdentityKeyPair> {
217 let kp = IdentityKeyPair::new();
218 let pk = kp.public_key.public_key.as_slice().to_vec();
219
220 let ks_identity = ProteusIdentity {
221 sk: kp.secret_key.to_keypair_bytes().into(),
222 pk,
223 };
224 keystore
225 .save(ks_identity)
226 .await
227 .map_err(KeystoreError::wrap("saving new proteus identity"))?;
228
229 Ok(kp)
230 }
231
232 async fn restore_sessions(
234 keystore: &core_crypto_keystore::Database,
235 identity: &Arc<IdentityKeyPair>,
236 ) -> Result<GroupStore<ProteusConversationSession>> {
237 let mut proteus_sessions = GroupStore::new_with_limit(crate::group_store::ITEM_LIMIT * 2);
238 for session in keystore
239 .find_all::<ProteusSession>(Default::default())
240 .await
241 .map_err(KeystoreError::wrap("finding all proteus sessions"))?
242 .into_iter()
243 {
244 let proteus_session = Session::deserialise(identity.clone(), &session.session)
245 .map_err(ProteusError::wrap("deserializing session"))?;
246
247 let identifier = session.id.clone();
248
249 let proteus_conversation = ProteusConversationSession {
250 identifier: identifier.clone(),
251 session: proteus_session,
252 };
253
254 if proteus_sessions
255 .try_insert(identifier.into_bytes(), proteus_conversation)
256 .is_err()
257 {
258 break;
259 }
260 }
261
262 Ok(proteus_sessions)
263 }
264
265 pub async fn session_from_prekey(
267 &mut self,
268 session_id: &str,
269 key: &[u8],
270 ) -> Result<GroupStoreValue<ProteusConversationSession>> {
271 let prekey = PreKeyBundle::deserialise(key).map_err(ProteusError::wrap("deserializing prekey bundle"))?;
272 let proteus_session = Session::init_from_prekey::<core_crypto_keystore::CryptoKeystoreError>(
304 self.proteus_identity.clone(),
305 prekey,
306 )
307 .map_err(ProteusError::wrap("initializing session from prekey"))?;
308
309 let proteus_conversation = ProteusConversationSession {
310 identifier: session_id.into(),
311 session: proteus_session,
312 };
313
314 self.proteus_sessions
315 .insert(session_id.as_bytes(), proteus_conversation);
316
317 Ok(self.proteus_sessions.get(session_id.as_bytes()).unwrap().clone())
318 }
319
320 pub(crate) async fn session_from_message(
322 &mut self,
323 keystore: &mut CryptoKeystore,
324 session_id: &str,
325 envelope: &[u8],
326 ) -> Result<(GroupStoreValue<ProteusConversationSession>, Vec<u8>)> {
327 let message = Envelope::deserialise(envelope).map_err(ProteusError::wrap("deserialising envelope"))?;
328 let (session, payload) = Session::init_from_message(self.proteus_identity.clone(), keystore, &message)
329 .await
330 .map_err(ProteusError::wrap("initializing session from message"))?;
331
332 let proteus_conversation = ProteusConversationSession {
333 identifier: session_id.into(),
334 session,
335 };
336
337 self.proteus_sessions
338 .insert(session_id.as_bytes(), proteus_conversation);
339
340 Ok((
341 self.proteus_sessions.get(session_id.as_bytes()).unwrap().clone(),
342 payload,
343 ))
344 }
345
346 pub(crate) async fn session_save(&mut self, keystore: &CryptoKeystore, session_id: &str) -> Result<()> {
350 if let Some(session) = self
351 .proteus_sessions
352 .get_fetch(session_id.as_bytes(), keystore, Some(self.proteus_identity.clone()))
353 .await?
354 {
355 Self::session_save_by_ref(keystore, session).await?;
356 }
357
358 Ok(())
359 }
360
361 pub(crate) async fn session_save_by_ref(
362 keystore: &CryptoKeystore,
363 session: GroupStoreValue<ProteusConversationSession>,
364 ) -> Result<()> {
365 let session = session.read().await;
366 let db_session = ProteusSession {
367 id: session.identifier().to_string(),
368 session: session
369 .session
370 .serialise()
371 .map_err(ProteusError::wrap("serializing session"))?,
372 };
373 keystore
374 .save(db_session)
375 .await
376 .map_err(KeystoreError::wrap("saving proteus session"))?;
377 Ok(())
378 }
379
380 pub(crate) async fn session_delete(&mut self, keystore: &CryptoKeystore, session_id: &str) -> Result<()> {
382 if keystore.remove::<ProteusSession, _>(session_id).await.is_ok() {
383 let _ = self.proteus_sessions.remove(session_id.as_bytes());
384 }
385 Ok(())
386 }
387
388 pub(crate) async fn session(
390 &mut self,
391 session_id: &str,
392 keystore: &CryptoKeystore,
393 ) -> Result<Option<GroupStoreValue<ProteusConversationSession>>> {
394 self.proteus_sessions
395 .get_fetch(session_id.as_bytes(), keystore, Some(self.proteus_identity.clone()))
396 .await
397 }
398
399 pub(crate) async fn session_exists(&mut self, session_id: &str, keystore: &CryptoKeystore) -> bool {
401 self.session(session_id, keystore).await.ok().flatten().is_some()
402 }
403
404 pub(crate) async fn decrypt(
407 &mut self,
408 keystore: &mut CryptoKeystore,
409 session_id: &str,
410 ciphertext: &[u8],
411 ) -> Result<Vec<u8>> {
412 let session = self
413 .proteus_sessions
414 .get_fetch(session_id.as_bytes(), keystore, Some(self.proteus_identity.clone()))
415 .await?
416 .ok_or(LeafError::ConversationNotFound(session_id.as_bytes().into()))
417 .map_err(ProteusError::wrap("getting session"))?;
418
419 let plaintext = session.write().await.decrypt(keystore, ciphertext).await?;
420 ProteusCentral::session_save_by_ref(keystore, session).await?;
421
422 Ok(plaintext)
423 }
424
425 pub(crate) async fn encrypt(
427 &mut self,
428 keystore: &mut CryptoKeystore,
429 session_id: &str,
430 plaintext: &[u8],
431 ) -> Result<Vec<u8>> {
432 let session = self
433 .session(session_id, keystore)
434 .await?
435 .ok_or(LeafError::ConversationNotFound(session_id.as_bytes().into()))
436 .map_err(ProteusError::wrap("getting session"))?;
437
438 let ciphertext = session.write().await.encrypt(plaintext)?;
439 ProteusCentral::session_save_by_ref(keystore, session).await?;
440
441 Ok(ciphertext)
442 }
443
444 pub(crate) async fn encrypt_batched(
447 &mut self,
448 keystore: &mut CryptoKeystore,
449 sessions: &[impl AsRef<str>],
450 plaintext: &[u8],
451 ) -> Result<HashMap<String, Vec<u8>>> {
452 let mut acc = HashMap::new();
453 for session_id in sessions {
454 if let Some(session) = self.session(session_id.as_ref(), keystore).await? {
455 let mut session_w = session.write().await;
456 acc.insert(session_w.identifier.clone(), session_w.encrypt(plaintext)?);
457 drop(session_w);
458
459 ProteusCentral::session_save_by_ref(keystore, session).await?;
460 }
461 }
462 Ok(acc)
463 }
464
465 pub(crate) async fn new_prekey(&self, id: u16, keystore: &CryptoKeystore) -> Result<Vec<u8>> {
467 use proteus_wasm::keys::{PreKey, PreKeyId};
468
469 let prekey_id = PreKeyId::new(id);
470 let prekey = PreKey::new(prekey_id);
471 let keystore_prekey = core_crypto_keystore::entities::ProteusPrekey::from_raw(
472 id,
473 prekey.serialise().map_err(ProteusError::wrap("serialising prekey"))?,
474 );
475 let bundle = PreKeyBundle::new(self.proteus_identity.as_ref().public_key.clone(), &prekey);
476 let bundle = bundle
477 .serialise()
478 .map_err(ProteusError::wrap("serialising prekey bundle"))?;
479 keystore
480 .save(keystore_prekey)
481 .await
482 .map_err(KeystoreError::wrap("saving keystore prekey"))?;
483 Ok(bundle)
484 }
485
486 pub(crate) async fn new_prekey_auto(&self, keystore: &CryptoKeystore) -> Result<(u16, Vec<u8>)> {
490 let id = core_crypto_keystore::entities::ProteusPrekey::get_free_id(keystore)
491 .await
492 .map_err(KeystoreError::wrap("getting proteus prekey by id"))?;
493 Ok((id, self.new_prekey(id, keystore).await?))
494 }
495
496 pub fn last_resort_prekey_id() -> u16 {
498 proteus_wasm::keys::MAX_PREKEY_ID.value()
499 }
500
501 pub(crate) async fn last_resort_prekey(&self, keystore: &CryptoKeystore) -> Result<Vec<u8>> {
504 let last_resort = if let Some(last_resort) = keystore
505 .find::<core_crypto_keystore::entities::ProteusPrekey>(
506 Self::last_resort_prekey_id().to_le_bytes().as_slice(),
507 )
508 .await
509 .map_err(KeystoreError::wrap("finding proteus prekey"))?
510 {
511 proteus_wasm::keys::PreKey::deserialise(&last_resort.prekey)
512 .map_err(ProteusError::wrap("deserialising proteus prekey"))?
513 } else {
514 let last_resort = proteus_wasm::keys::PreKey::last_resort();
515
516 use core_crypto_keystore::CryptoKeystoreProteus as _;
517 keystore
518 .proteus_store_prekey(
519 Self::last_resort_prekey_id(),
520 &last_resort
521 .serialise()
522 .map_err(ProteusError::wrap("serialising last resort prekey"))?,
523 )
524 .await
525 .map_err(KeystoreError::wrap("storing proteus prekey"))?;
526
527 last_resort
528 };
529
530 let bundle = PreKeyBundle::new(self.proteus_identity.as_ref().public_key.clone(), &last_resort);
531 let bundle = bundle
532 .serialise()
533 .map_err(ProteusError::wrap("serialising prekey bundle"))?;
534
535 Ok(bundle)
536 }
537
538 pub fn identity(&self) -> &IdentityKeyPair {
540 self.proteus_identity.as_ref()
541 }
542
543 pub fn fingerprint(&self) -> String {
545 self.proteus_identity.as_ref().public_key.fingerprint()
546 }
547
548 pub(crate) async fn fingerprint_local(&mut self, session_id: &str, keystore: &CryptoKeystore) -> Result<String> {
553 let session = self
554 .session(session_id, keystore)
555 .await?
556 .ok_or(LeafError::ConversationNotFound(session_id.as_bytes().into()))
557 .map_err(ProteusError::wrap("getting session"))?;
558 let fingerprint = session.read().await.fingerprint_local();
559 Ok(fingerprint)
560 }
561
562 pub(crate) async fn fingerprint_remote(&mut self, session_id: &str, keystore: &CryptoKeystore) -> Result<String> {
567 let session = self
568 .session(session_id, keystore)
569 .await?
570 .ok_or(LeafError::ConversationNotFound(session_id.as_bytes().into()))
571 .map_err(ProteusError::wrap("getting session"))?;
572 let fingerprint = session.read().await.fingerprint_remote();
573 Ok(fingerprint)
574 }
575
576 pub fn fingerprint_prekeybundle(prekey: &[u8]) -> Result<String> {
581 let prekey = PreKeyBundle::deserialise(prekey).map_err(ProteusError::wrap("deserialising prekey bundle"))?;
582 Ok(prekey.identity_key.fingerprint())
583 }
584}
585
586#[cfg(test)]
587mod tests {
588 use core_crypto_keystore::{ConnectionType, Database, DatabaseKey};
589
590 use super::*;
591 use crate::{
592 CertificateBundle, ClientId, ClientIdentifier, CredentialType, Session,
593 test_utils::{proteus_utils::*, x509::X509TestChain, *},
594 };
595
596 #[apply(all_cred_cipher)]
597 async fn cc_can_init(case: TestContext) {
598 #[cfg(not(target_family = "wasm"))]
599 let (path, db_file) = tmp_db_file();
600 #[cfg(target_family = "wasm")]
601 let (path, _) = tmp_db_file();
602 let client_id = ClientId::from("alice").into();
603 let db = Database::open(ConnectionType::Persistent(&path), &DatabaseKey::generate())
604 .await
605 .unwrap();
606
607 let cc: CoreCrypto = Session::try_new(&db).await.unwrap().into();
608 cc.init(client_id, &[case.ciphersuite().signature_algorithm()])
609 .await
610 .unwrap();
611 let context = cc.new_transaction().await.unwrap();
612 assert!(context.proteus_init().await.is_ok());
613 assert!(context.proteus_new_prekey(1).await.is_ok());
614 context.finish().await.unwrap();
615 #[cfg(not(target_family = "wasm"))]
616 drop(db_file);
617 }
618
619 #[apply(all_cred_cipher)]
620 async fn cc_can_2_phase_init(case: TestContext) {
621 use crate::{ClientId, Credential};
622
623 #[cfg(not(target_family = "wasm"))]
624 let (path, db_file) = tmp_db_file();
625 #[cfg(target_family = "wasm")]
626 let (path, _) = tmp_db_file();
627 let db = Database::open(ConnectionType::Persistent(&path), &DatabaseKey::generate())
628 .await
629 .unwrap();
630
631 let cc: CoreCrypto = Session::try_new(&db).await.unwrap().into();
632 let transaction = cc.new_transaction().await.unwrap();
633 let x509_test_chain = X509TestChain::init_empty(case.signature_scheme());
634 x509_test_chain.register_with_central(&transaction).await;
635 assert!(transaction.proteus_init().await.is_ok());
636 assert!(transaction.proteus_new_prekey(1).await.is_ok());
638 let client_id = ClientId::from("alice");
640 let identifier = match case.credential_type {
641 CredentialType::Basic => ClientIdentifier::Basic(client_id),
642 CredentialType::X509 => {
643 CertificateBundle::rand_identifier(&client_id, &[x509_test_chain.find_local_intermediate_ca()])
644 }
645 };
646 transaction
647 .mls_init(identifier.clone(), &[case.ciphersuite()])
648 .await
649 .unwrap();
650
651 let credential =
652 Credential::from_identifier(&identifier, case.signature_scheme(), &cc.mls.crypto_provider).unwrap();
653 cc.add_credential(credential).await.unwrap();
654
655 assert_eq!(
657 transaction
658 .get_or_create_client_keypackages(case.ciphersuite(), case.credential_type, 2)
659 .await
660 .unwrap()
661 .len(),
662 2
663 );
664 #[cfg(not(target_family = "wasm"))]
665 drop(db_file);
666 }
667
668 #[macro_rules_attribute::apply(smol_macros::test)]
669 async fn can_init() {
670 #[cfg(not(target_family = "wasm"))]
671 let (path, db_file) = tmp_db_file();
672 #[cfg(target_family = "wasm")]
673 let (path, _) = tmp_db_file();
674 let key = DatabaseKey::generate();
675 let keystore = core_crypto_keystore::Database::open(ConnectionType::Persistent(&path), &key)
676 .await
677 .unwrap();
678 keystore.new_transaction().await.unwrap();
679 let central = ProteusCentral::try_new(&keystore).await.unwrap();
680 let identity = (*central.proteus_identity).clone();
681 keystore.commit_transaction().await.unwrap();
682
683 let keystore = core_crypto_keystore::Database::open(ConnectionType::Persistent(&path), &key)
684 .await
685 .unwrap();
686 keystore.new_transaction().await.unwrap();
687 let central = ProteusCentral::try_new(&keystore).await.unwrap();
688 keystore.commit_transaction().await.unwrap();
689 assert_eq!(identity, *central.proteus_identity);
690
691 keystore.wipe().await.unwrap();
692 #[cfg(not(target_family = "wasm"))]
693 drop(db_file);
694 }
695
696 #[macro_rules_attribute::apply(smol_macros::test)]
697 async fn can_talk_with_proteus() {
698 #[cfg(not(target_family = "wasm"))]
699 let (path, db_file) = tmp_db_file();
700 #[cfg(target_family = "wasm")]
701 let (path, _) = tmp_db_file();
702
703 let session_id = uuid::Uuid::new_v4().hyphenated().to_string();
704
705 let key = DatabaseKey::generate();
706 let mut keystore = core_crypto_keystore::Database::open(ConnectionType::Persistent(&path), &key)
707 .await
708 .unwrap();
709 keystore.new_transaction().await.unwrap();
710
711 let mut alice = ProteusCentral::try_new(&keystore).await.unwrap();
712
713 let mut bob = CryptoboxLike::init();
714 let bob_pk_bundle = bob.new_prekey();
715
716 alice
717 .session_from_prekey(&session_id, &bob_pk_bundle.serialise().unwrap())
718 .await
719 .unwrap();
720
721 let message = b"Hello world";
722
723 let encrypted = alice.encrypt(&mut keystore, &session_id, message).await.unwrap();
724 let decrypted = bob.decrypt(&session_id, &encrypted).await;
725 assert_eq!(decrypted, message);
726
727 let encrypted = bob.encrypt(&session_id, message);
728 let decrypted = alice.decrypt(&mut keystore, &session_id, &encrypted).await.unwrap();
729 assert_eq!(decrypted, message);
730
731 keystore.commit_transaction().await.unwrap();
732 keystore.wipe().await.unwrap();
733 #[cfg(not(target_family = "wasm"))]
734 drop(db_file);
735 }
736
737 #[macro_rules_attribute::apply(smol_macros::test)]
738 async fn can_produce_proteus_consumed_prekeys() {
739 #[cfg(not(target_family = "wasm"))]
740 let (path, db_file) = tmp_db_file();
741 #[cfg(target_family = "wasm")]
742 let (path, _) = tmp_db_file();
743
744 let session_id = uuid::Uuid::new_v4().hyphenated().to_string();
745
746 let key = DatabaseKey::generate();
747 let mut keystore = core_crypto_keystore::Database::open(ConnectionType::Persistent(&path), &key)
748 .await
749 .unwrap();
750 keystore.new_transaction().await.unwrap();
751 let mut alice = ProteusCentral::try_new(&keystore).await.unwrap();
752
753 let mut bob = CryptoboxLike::init();
754
755 let alice_prekey_bundle_ser = alice.new_prekey(1, &keystore).await.unwrap();
756
757 bob.init_session_from_prekey_bundle(&session_id, &alice_prekey_bundle_ser);
758 let message = b"Hello world!";
759 let encrypted = bob.encrypt(&session_id, message);
760
761 let (_, decrypted) = alice
762 .session_from_message(&mut keystore, &session_id, &encrypted)
763 .await
764 .unwrap();
765
766 assert_eq!(message, decrypted.as_slice());
767
768 let encrypted = alice.encrypt(&mut keystore, &session_id, message).await.unwrap();
769 let decrypted = bob.decrypt(&session_id, &encrypted).await;
770
771 assert_eq!(message, decrypted.as_slice());
772 keystore.commit_transaction().await.unwrap();
773 keystore.wipe().await.unwrap();
774 #[cfg(not(target_family = "wasm"))]
775 drop(db_file);
776 }
777
778 #[macro_rules_attribute::apply(smol_macros::test)]
779 async fn auto_prekeys_are_sequential() {
780 use core_crypto_keystore::entities::ProteusPrekey;
781 const GAP_AMOUNT: u16 = 5;
782 const ID_TEST_RANGE: std::ops::RangeInclusive<u16> = 1..=30;
783
784 #[cfg(not(target_family = "wasm"))]
785 let (path, db_file) = tmp_db_file();
786 #[cfg(target_family = "wasm")]
787 let (path, _) = tmp_db_file();
788
789 let key = DatabaseKey::generate();
790 let keystore = core_crypto_keystore::Database::open(ConnectionType::Persistent(&path), &key)
791 .await
792 .unwrap();
793 keystore.new_transaction().await.unwrap();
794 let alice = ProteusCentral::try_new(&keystore).await.unwrap();
795
796 for i in ID_TEST_RANGE {
797 let (pk_id, pkb) = alice.new_prekey_auto(&keystore).await.unwrap();
798 assert_eq!(i, pk_id);
799 let prekey = proteus_wasm::keys::PreKeyBundle::deserialise(&pkb).unwrap();
800 assert_eq!(prekey.prekey_id.value(), pk_id);
801 }
802
803 use rand::Rng as _;
804 let mut rng = rand::thread_rng();
805 let mut gap_ids: Vec<u16> = (0..GAP_AMOUNT).map(|_| rng.gen_range(ID_TEST_RANGE)).collect();
806 gap_ids.sort();
807 gap_ids.dedup();
808 while gap_ids.len() < GAP_AMOUNT as usize {
809 gap_ids.push(rng.gen_range(ID_TEST_RANGE));
810 gap_ids.sort();
811 gap_ids.dedup();
812 }
813 for gap_id in gap_ids.iter() {
814 keystore.remove::<ProteusPrekey, _>(gap_id.to_le_bytes()).await.unwrap();
815 }
816
817 gap_ids.sort();
818
819 for gap_id in gap_ids.iter() {
820 let (pk_id, pkb) = alice.new_prekey_auto(&keystore).await.unwrap();
821 assert_eq!(pk_id, *gap_id);
822 let prekey = proteus_wasm::keys::PreKeyBundle::deserialise(&pkb).unwrap();
823 assert_eq!(prekey.prekey_id.value(), *gap_id);
824 }
825
826 let mut gap_ids: Vec<u16> = (0..GAP_AMOUNT).map(|_| rng.gen_range(ID_TEST_RANGE)).collect();
827 gap_ids.sort();
828 gap_ids.dedup();
829 while gap_ids.len() < GAP_AMOUNT as usize {
830 gap_ids.push(rng.gen_range(ID_TEST_RANGE));
831 gap_ids.sort();
832 gap_ids.dedup();
833 }
834 for gap_id in gap_ids.iter() {
835 keystore.remove::<ProteusPrekey, _>(gap_id.to_le_bytes()).await.unwrap();
836 }
837
838 let potential_range = *ID_TEST_RANGE.end()..=(*ID_TEST_RANGE.end() * 2);
839 let potential_range_check = potential_range.clone();
840 for _ in potential_range {
841 let (pk_id, pkb) = alice.new_prekey_auto(&keystore).await.unwrap();
842 assert!(gap_ids.contains(&pk_id) || potential_range_check.contains(&pk_id));
843 let prekey = proteus_wasm::keys::PreKeyBundle::deserialise(&pkb).unwrap();
844 assert_eq!(prekey.prekey_id.value(), pk_id);
845 }
846 keystore.commit_transaction().await.unwrap();
847 keystore.wipe().await.unwrap();
848 #[cfg(not(target_family = "wasm"))]
849 drop(db_file);
850 }
851}