core_crypto/
lib.rs

1//! Core Crypto is a wrapper on top of OpenMLS aimed to provide an ergonomic API for usage in web
2//! through Web Assembly and in mobile devices through FFI.
3//!
4//! The goal is provide a easier and less verbose API to create, manage and interact with MLS
5//! groups.
6#![doc = include_str!(env!("STRIPPED_README_PATH"))]
7#![cfg_attr(not(test), deny(missing_docs))]
8#![allow(clippy::single_component_path_imports)]
9
10#[cfg(test)]
11#[macro_use]
12pub mod test_utils;
13// both imports above have to be defined at the beginning of the crate for rstest to work
14
15mod build_metadata;
16mod ephemeral;
17mod error;
18mod group_store;
19
20/// re-export [rusty-jwt-tools](https://github.com/wireapp/rusty-jwt-tools) API
21pub mod e2e_identity;
22/// MLS Abstraction
23pub mod mls;
24/// Proteus Abstraction
25#[cfg(feature = "proteus")]
26pub mod proteus;
27pub mod transaction_context;
28
29pub use core_crypto_keystore::{ConnectionType, Database, DatabaseKey};
30#[cfg(test)]
31pub use core_crypto_macros::{dispotent, durable, idempotent};
32pub use mls_crypto_provider::{EntropySeed, MlsCryptoProvider, RawEntropySeed};
33pub use openmls::{
34    group::{MlsGroup, MlsGroupConfig},
35    prelude::{
36        Ciphersuite as CiphersuiteName, Credential, GroupEpoch, KeyPackage, KeyPackageIn, KeyPackageRef, MlsMessageIn,
37        Node, group_info::VerifiableGroupInfo,
38    },
39};
40#[cfg(feature = "proteus")]
41use {async_lock::Mutex, std::sync::Arc};
42
43pub use crate::{
44    build_metadata::{BUILD_METADATA, BuildMetadata},
45    e2e_identity::{
46        E2eiEnrollment,
47        device_status::DeviceStatus,
48        identity::{WireIdentity, X509Identity},
49        types::{E2eiAcmeChallenge, E2eiAcmeDirectory, E2eiNewAcmeAuthz, E2eiNewAcmeOrder},
50    },
51    ephemeral::{HISTORY_CLIENT_ID_PREFIX, HistorySecret},
52    error::{
53        Error, InnermostErrorMessage, KeystoreError, LeafError, MlsError, MlsErrorKind, ProteusError, ProteusErrorKind,
54        RecursiveError, Result, ToRecursiveError,
55    },
56    mls::{
57        ciphersuite::MlsCiphersuite,
58        conversation::{
59            ConversationId, MlsConversation,
60            commit::MlsCommitBundle,
61            config::{MlsConversationConfiguration, MlsCustomConfiguration, MlsWirePolicy},
62            conversation_guard::decrypt::{MlsBufferedConversationDecryptMessage, MlsConversationDecryptMessage},
63            group_info::{GroupInfoPayload, MlsGroupInfoBundle, MlsGroupInfoEncryptionType, MlsRatchetTreeType},
64            proposal::MlsProposalBundle,
65            welcome::WelcomeBundle,
66        },
67        credential::{typ::MlsCredentialType, x509::CertificateBundle},
68        proposal::{MlsProposal, MlsProposalRef},
69        session::{
70            EpochObserver, HistoryObserver, Session,
71            config::{SessionConfig, ValidatedSessionConfig},
72            id::ClientId,
73            identifier::ClientIdentifier,
74            key_package::INITIAL_KEYING_MATERIAL_COUNT,
75            user_id::UserId,
76        },
77    },
78    transaction_context::e2e_identity::conversation_state::E2eiConversationState,
79};
80
81/// Response from the delivery service
82pub enum MlsTransportResponse {
83    /// The message was accepted by the delivery service
84    Success,
85    /// A client should have consumed all incoming messages before re-trying.
86    Retry,
87    /// The message was rejected by the delivery service and there's no recovery.
88    Abort {
89        /// Why did the delivery service reject the message?
90        reason: String,
91    },
92}
93
94/// An entity / data which has been packaged by the application to be encrypted
95/// and transmitted in an application message.
96#[derive(Debug, derive_more::From, derive_more::Deref, serde::Serialize, serde::Deserialize)]
97pub struct MlsTransportData(pub Vec<u8>);
98
99/// Client callbacks to allow communication with the delivery service.
100/// There are two different endpoints, one for messages and one for commit bundles.
101#[cfg_attr(target_family = "wasm", async_trait::async_trait(?Send))]
102#[cfg_attr(not(target_family = "wasm"), async_trait::async_trait)]
103pub trait MlsTransport: std::fmt::Debug + Send + Sync {
104    /// Send a commit bundle to the corresponding endpoint.
105    async fn send_commit_bundle(&self, commit_bundle: MlsCommitBundle) -> Result<MlsTransportResponse>;
106    /// Send a message to the corresponding endpoint.
107    async fn send_message(&self, mls_message: Vec<u8>) -> Result<MlsTransportResponse>;
108
109    /// This function will be called before a history secret is sent to the mls transport to allow
110    /// the application to package it in a suitable transport container (json, protobuf, ...).
111    ///
112    /// The `secret` parameter contain the history client's secrets which will be sent over the mls transport.
113    ///
114    /// Returns the history secret packaged for transport
115    async fn prepare_for_transport(&self, secret: &HistorySecret) -> Result<MlsTransportData>;
116}
117
118/// Wrapper superstruct for both [mls::session::Session] and [proteus::ProteusCentral]
119///
120/// As [std::ops::Deref] is implemented, this struct is automatically dereferred to [mls::session::Session] apart from `proteus_*` calls
121///
122/// This is cheap to clone as all internal members have `Arc` wrappers or are `Copy`.
123#[derive(Debug, Clone)]
124pub struct CoreCrypto {
125    mls: mls::session::Session,
126    #[cfg(feature = "proteus")]
127    proteus: Arc<Mutex<Option<proteus::ProteusCentral>>>,
128    #[cfg(not(feature = "proteus"))]
129    #[allow(dead_code)]
130    proteus: (),
131}
132
133impl From<mls::session::Session> for CoreCrypto {
134    fn from(mls: mls::session::Session) -> Self {
135        Self {
136            mls,
137            proteus: Default::default(),
138        }
139    }
140}
141
142impl std::ops::Deref for CoreCrypto {
143    type Target = mls::session::Session;
144
145    fn deref(&self) -> &Self::Target {
146        &self.mls
147    }
148}
149
150impl std::ops::DerefMut for CoreCrypto {
151    fn deref_mut(&mut self) -> &mut Self::Target {
152        &mut self.mls
153    }
154}
155
156impl CoreCrypto {
157    /// Allows to extract the MLS Client from the wrapper superstruct
158    #[inline]
159    pub fn take(self) -> mls::session::Session {
160        self.mls
161    }
162}