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 MlsCiphersuite, GroupEpoch, KeyPackage, KeyPackageIn, KeyPackageRef, MlsMessageIn, Node,
37        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::Ciphersuite,
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::{
68            Credential, CredentialRef, CredentialType, FindFilters as CredentialFindFilters, x509::CertificateBundle,
69        },
70        proposal::{MlsProposal, MlsProposalRef},
71        session::{
72            EpochObserver, HistoryObserver, Session,
73            id::{ClientId, ClientIdRef},
74            identifier::ClientIdentifier,
75            key_package::INITIAL_KEYING_MATERIAL_COUNT,
76            user_id::UserId,
77        },
78    },
79    transaction_context::e2e_identity::conversation_state::E2eiConversationState,
80};
81
82/// Response from the delivery service
83pub enum MlsTransportResponse {
84    /// The message was accepted by the delivery service
85    Success,
86    /// A client should have consumed all incoming messages before re-trying.
87    Retry,
88    /// The message was rejected by the delivery service and there's no recovery.
89    Abort {
90        /// Why did the delivery service reject the message?
91        reason: String,
92    },
93}
94
95/// An entity / data which has been packaged by the application to be encrypted
96/// and transmitted in an application message.
97#[derive(Debug, derive_more::From, derive_more::Deref, serde::Serialize, serde::Deserialize)]
98pub struct MlsTransportData(pub Vec<u8>);
99
100/// Client callbacks to allow communication with the delivery service.
101/// There are two different endpoints, one for messages and one for commit bundles.
102#[cfg_attr(target_family = "wasm", async_trait::async_trait(?Send))]
103#[cfg_attr(not(target_family = "wasm"), async_trait::async_trait)]
104pub trait MlsTransport: std::fmt::Debug + Send + Sync {
105    /// Send a commit bundle to the corresponding endpoint.
106    async fn send_commit_bundle(&self, commit_bundle: MlsCommitBundle) -> Result<MlsTransportResponse>;
107    /// Send a message to the corresponding endpoint.
108    async fn send_message(&self, mls_message: Vec<u8>) -> Result<MlsTransportResponse>;
109
110    /// This function will be called before a history secret is sent to the mls transport to allow
111    /// the application to package it in a suitable transport container (json, protobuf, ...).
112    ///
113    /// The `secret` parameter contain the history client's secrets which will be sent over the mls transport.
114    ///
115    /// Returns the history secret packaged for transport
116    async fn prepare_for_transport(&self, secret: &HistorySecret) -> Result<MlsTransportData>;
117}
118
119/// Wrapper superstruct for both [mls::session::Session] and [proteus::ProteusCentral]
120///
121/// As [std::ops::Deref] is implemented, this struct is automatically dereferred to [mls::session::Session] apart from
122/// `proteus_*` calls
123///
124/// This is cheap to clone as all internal members have `Arc` wrappers or are `Copy`.
125#[derive(Debug, Clone)]
126pub struct CoreCrypto {
127    mls: mls::session::Session,
128    #[cfg(feature = "proteus")]
129    proteus: Arc<Mutex<Option<proteus::ProteusCentral>>>,
130    #[cfg(not(feature = "proteus"))]
131    #[allow(dead_code)]
132    proteus: (),
133}
134
135impl From<mls::session::Session> for CoreCrypto {
136    fn from(mls: mls::session::Session) -> Self {
137        Self {
138            mls,
139            proteus: Default::default(),
140        }
141    }
142}
143
144impl std::ops::Deref for CoreCrypto {
145    type Target = mls::session::Session;
146
147    fn deref(&self) -> &Self::Target {
148        &self.mls
149    }
150}
151
152impl std::ops::DerefMut for CoreCrypto {
153    fn deref_mut(&mut self) -> &mut Self::Target {
154        &mut self.mls
155    }
156}
157
158impl CoreCrypto {
159    /// Allows to extract the MLS Client from the wrapper superstruct
160    #[inline]
161    pub fn take(self) -> mls::session::Session {
162        self.mls
163    }
164}