core_crypto/mls/conversation/
config.rs1use openmls::prelude::{
7 Capabilities, Credential, CredentialType, ExternalSender, OpenMlsSignaturePublicKey,
8 PURE_CIPHERTEXT_WIRE_FORMAT_POLICY, PURE_PLAINTEXT_WIRE_FORMAT_POLICY, ProtocolVersion,
9 RequiredCapabilitiesExtension, SenderRatchetConfiguration, WireFormatPolicy,
10};
11use openmls_traits::{
12 crypto::OpenMlsCrypto,
13 types::{Ciphersuite as MlsCiphersuite, SignatureScheme},
14};
15use serde::{Deserialize, Serialize};
16use wire_e2e_identity::parse_json_jwk;
17
18use super::Result;
19use crate::{Ciphersuite, MlsError, RecursiveError, mls_provider::MlsCryptoProvider};
20
21pub(crate) const MAX_PAST_EPOCHS: usize = 3;
23
24pub(crate) const OUT_OF_ORDER_TOLERANCE: u32 = 2;
27
28pub(crate) const MAXIMUM_FORWARD_DISTANCE: u32 = 1000;
30
31#[derive(Debug, Clone, Default)]
33pub struct MlsConversationConfiguration {
34 pub ciphersuite: Ciphersuite,
36 pub external_senders: Vec<ExternalSender>,
38 pub custom: MlsCustomConfiguration,
40}
41
42impl MlsConversationConfiguration {
43 const WIRE_SERVER_IDENTITY: &'static str = "wire-server";
44
45 const PADDING_SIZE: usize = 128;
46
47 pub(crate) const DEFAULT_PROTOCOL_VERSION: ProtocolVersion = ProtocolVersion::Mls10;
49
50 pub(crate) const DEFAULT_SUPPORTED_CREDENTIALS: &'static [CredentialType] =
52 &[CredentialType::Basic, CredentialType::X509];
53
54 pub(crate) const DEFAULT_SUPPORTED_CIPHERSUITES: &'static [MlsCiphersuite] = &[
56 MlsCiphersuite::MLS_128_DHKEMX25519_AES128GCM_SHA256_Ed25519,
57 MlsCiphersuite::MLS_128_DHKEMP256_AES128GCM_SHA256_P256,
58 MlsCiphersuite::MLS_128_DHKEMX25519_CHACHA20POLY1305_SHA256_Ed25519,
59 MlsCiphersuite::MLS_256_DHKEMP384_AES256GCM_SHA384_P384,
60 MlsCiphersuite::MLS_256_DHKEMP521_AES256GCM_SHA512_P521,
61 ];
62
63 const NUMBER_RESUMPTION_PSK: usize = 1;
65
66 #[inline(always)]
68 pub fn as_openmls_default_configuration(&self) -> Result<openmls::group::MlsGroupConfig> {
69 let crypto_config = openmls::prelude::CryptoConfig {
70 version: Self::DEFAULT_PROTOCOL_VERSION,
71 ciphersuite: self.ciphersuite.into(),
72 };
73 Ok(openmls::group::MlsGroupConfig::builder()
74 .wire_format_policy(self.custom.wire_policy.into())
75 .max_past_epochs(MAX_PAST_EPOCHS)
76 .padding_size(Self::PADDING_SIZE)
77 .number_of_resumption_psks(Self::NUMBER_RESUMPTION_PSK)
78 .leaf_capabilities(Self::default_leaf_capabilities())
79 .required_capabilities(self.default_required_capabilities())
80 .sender_ratchet_configuration(SenderRatchetConfiguration::new(
81 self.custom.out_of_order_tolerance,
82 self.custom.maximum_forward_distance,
83 ))
84 .use_ratchet_tree_extension(true)
85 .external_senders(self.external_senders.clone())
86 .crypto_config(crypto_config)
87 .build())
88 }
89
90 pub fn default_leaf_capabilities() -> Capabilities {
92 Capabilities::new(
93 Some(&[Self::DEFAULT_PROTOCOL_VERSION]),
94 Some(Self::DEFAULT_SUPPORTED_CIPHERSUITES),
95 Some(&[]),
96 Some(&[]),
97 Some(Self::DEFAULT_SUPPORTED_CREDENTIALS),
98 )
99 }
100
101 fn default_required_capabilities(&self) -> RequiredCapabilitiesExtension {
102 RequiredCapabilitiesExtension::new(&[], &[], Self::DEFAULT_SUPPORTED_CREDENTIALS)
103 }
104
105 pub async fn set_raw_external_senders(
108 &mut self,
109 mls_crypto_provider: &MlsCryptoProvider,
110 external_senders: impl IntoIterator<Item = Vec<u8>>,
111 ) -> Result<()> {
112 self.external_senders = external_senders
113 .into_iter()
114 .map(|key| {
115 MlsConversationConfiguration::parse_external_sender(&key).or_else(|_| {
116 MlsConversationConfiguration::legacy_external_sender(
117 key,
118 self.ciphersuite.signature_algorithm(),
119 mls_crypto_provider,
120 )
121 })
122 })
123 .collect::<crate::mls::conversation::Result<_>>()
124 .map_err(RecursiveError::mls_conversation("setting external sender"))?;
125 Ok(())
126 }
127
128 pub(crate) fn parse_external_sender(jwk: &[u8]) -> Result<ExternalSender> {
130 let pk = parse_json_jwk(jwk)
131 .map_err(wire_e2e_identity::E2eIdentityError::from)
132 .map_err(RecursiveError::e2e_identity("parsing jwk"))?;
133 Ok(ExternalSender::new(
134 pk.into(),
135 Credential::new_basic(Self::WIRE_SERVER_IDENTITY.into()),
136 ))
137 }
138
139 pub(crate) fn legacy_external_sender(
143 key: Vec<u8>,
144 signature_scheme: SignatureScheme,
145 backend: &MlsCryptoProvider,
146 ) -> Result<ExternalSender> {
147 backend
148 .validate_signature_key(signature_scheme, &key[..])
149 .map_err(MlsError::wrap("validating signature key"))?;
150 let key = OpenMlsSignaturePublicKey::new(key.into(), signature_scheme)
151 .map_err(MlsError::wrap("creating new signature public key"))?;
152 Ok(ExternalSender::new(
153 key.into(),
154 Credential::new_basic(Self::WIRE_SERVER_IDENTITY.into()),
155 ))
156 }
157}
158
159#[derive(Debug, Clone, Serialize, Deserialize)]
161pub struct MlsCustomConfiguration {
162 pub key_rotation_span: Option<std::time::Duration>,
165 pub wire_policy: MlsWirePolicy,
167 pub out_of_order_tolerance: u32,
171 pub maximum_forward_distance: u32,
174}
175
176impl Default for MlsCustomConfiguration {
177 fn default() -> Self {
178 Self {
179 wire_policy: MlsWirePolicy::Plaintext,
180 key_rotation_span: Default::default(),
181 out_of_order_tolerance: OUT_OF_ORDER_TOLERANCE,
182 maximum_forward_distance: MAXIMUM_FORWARD_DISTANCE,
183 }
184 }
185}
186
187#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Serialize, Deserialize)]
189#[repr(u8)]
190pub enum MlsWirePolicy {
191 #[default]
193 Plaintext = 1,
194 Ciphertext = 2,
196}
197
198impl From<MlsWirePolicy> for WireFormatPolicy {
199 fn from(policy: MlsWirePolicy) -> Self {
200 match policy {
201 MlsWirePolicy::Ciphertext => PURE_CIPHERTEXT_WIRE_FORMAT_POLICY,
202 MlsWirePolicy::Plaintext => PURE_PLAINTEXT_WIRE_FORMAT_POLICY,
203 }
204 }
205}
206
207#[cfg(test)]
208mod tests {
209 use openmls::prelude::ProtocolVersion;
210 use openmls_traits::{
211 OpenMlsCryptoProvider,
212 crypto::OpenMlsCrypto,
213 types::{SignatureScheme, VerifiableCiphersuite},
214 };
215 use wire_e2e_identity::JwsAlgorithm;
216
217 use crate::{MlsConversationConfiguration, mls::conversation::ConversationWithMls as _, test_utils::*};
218
219 #[macro_rules_attribute::apply(smol_macros::test)]
220 async fn group_should_have_required_capabilities() {
221 let case = TestContext::default();
222
223 let [session] = case.sessions().await;
224 Box::pin(async move {
225 let conversation = case.create_conversation([&session]).await;
226 let guard = conversation.guard().await;
227 let group = guard.conversation().await;
228
229 let capabilities = group.group.group_context_extensions().required_capabilities().unwrap();
230
231 assert!(capabilities.extension_types().is_empty());
233 assert!(capabilities.proposal_types().is_empty());
234 assert_eq!(
235 capabilities.credential_types(),
236 MlsConversationConfiguration::DEFAULT_SUPPORTED_CREDENTIALS
237 );
238 })
239 .await
240 }
241
242 #[apply(all_cred_cipher)]
243 pub async fn creator_leaf_node_should_have_default_capabilities(case: TestContext) {
244 let [session] = case.sessions().await;
245 Box::pin(async move {
246 let conversation = case.create_conversation([&session]).await;
247 let guard = conversation.guard().await;
248 let group = guard.conversation().await;
249
250 let creator_capabilities = group.group.own_leaf().unwrap().capabilities();
252
253 assert_eq!(creator_capabilities.versions(), &[ProtocolVersion::Mls10]);
256
257 assert_eq!(
259 creator_capabilities.ciphersuites().to_vec(),
260 MlsConversationConfiguration::DEFAULT_SUPPORTED_CIPHERSUITES
261 .iter()
262 .map(|c| VerifiableCiphersuite::from(*c))
263 .collect::<Vec<_>>()
264 );
265
266 assert!(creator_capabilities.proposals().is_empty());
268
269 assert!(creator_capabilities.extensions().is_empty(),);
271
272 assert_eq!(
274 creator_capabilities.credentials(),
275 MlsConversationConfiguration::DEFAULT_SUPPORTED_CREDENTIALS
276 );
277 })
278 .await
279 }
280
281 #[apply(all_cred_cipher)]
282 pub async fn should_support_raw_external_sender(case: TestContext) {
283 let [cc] = case.sessions().await;
284 Box::pin(async move {
285 let (_sk, pk) = cc
286 .transaction
287 .mls_provider()
288 .await
289 .unwrap()
290 .crypto()
291 .signature_key_gen(case.signature_scheme())
292 .unwrap();
293
294 assert!(
295 case.cfg
296 .clone()
297 .set_raw_external_senders(&cc.session().await.crypto_provider, vec![pk])
298 .await
299 .is_ok()
300 );
301 })
302 .await
303 }
304
305 #[apply(all_cred_cipher)]
306 pub async fn should_support_jwk_external_sender(case: TestContext) {
307 let [cc] = case.sessions().await;
308 Box::pin(async move {
309 let sc = case.signature_scheme();
310
311 let alg = match sc {
312 SignatureScheme::ED25519 => JwsAlgorithm::Ed25519,
313 SignatureScheme::ECDSA_SECP256R1_SHA256 => JwsAlgorithm::P256,
314 SignatureScheme::ECDSA_SECP384R1_SHA384 => JwsAlgorithm::P384,
315 SignatureScheme::ECDSA_SECP521R1_SHA512 => JwsAlgorithm::P521,
316 SignatureScheme::ED448 => unreachable!(),
317 };
318
319 let jwk = wire_e2e_identity::generate_jwk(alg);
320 assert!(
321 case.cfg
322 .clone()
323 .set_raw_external_senders(&cc.session().await.crypto_provider, vec![jwk])
324 .await
325 .is_ok()
326 );
327 })
328 .await;
329 }
330}