core_crypto/mls/credential/
mod.rs1pub(crate) mod credential_ref;
6pub(crate) mod credential_type;
7pub(crate) mod crl;
8mod error;
9mod export_pem;
10pub(crate) mod ext;
11mod persistence;
12pub(crate) mod x509;
13
14use std::sync::Arc;
15
16use core_crypto_keystore::entities::StoredCredential;
17use openmls::prelude::{Credential as MlsCredential, CredentialWithKey, KeyPackage, SignatureScheme};
18use openmls_basic_credential::SignatureKeyPair;
19use openmls_traits::crypto::OpenMlsCrypto;
20use tls_codec::Deserialize as _;
21
22pub(crate) use self::error::Result;
23pub use self::{
24 credential_ref::{CredentialRef, FindFilters, FindFiltersBuilder},
25 credential_type::CredentialType,
26 error::Error,
27};
28use crate::{CipherSuite, ClientId, ClientIdRef, OpenMlsError, RecursiveError, TlsCodecError, mls_provider::CRYPTO};
29
30#[derive(core_crypto_macros::Debug, Clone, serde::Serialize, serde::Deserialize)]
38pub struct Credential {
39 pub(crate) cipher_suite: CipherSuite,
41 pub(crate) credential_type: CredentialType,
43 pub(crate) mls_credential: MlsCredential,
45 #[sensitive]
47 pub(crate) signature_key_pair: SignatureKeyPair,
48 pub(crate) earliest_validity: u64,
55}
56
57impl TryFrom<Arc<StoredCredential>> for Credential {
58 type Error = Error;
59
60 fn try_from(stored_credential: Arc<StoredCredential>) -> Result<Credential> {
61 let mls_credential = MlsCredential::tls_deserialize(&mut stored_credential.credential.as_slice())
62 .map_err(TlsCodecError::deserialize("mls credential"))?;
63 let cipher_suite = CipherSuite::try_from(stored_credential.ciphersuite)?;
64 let signature_key_pair = openmls_basic_credential::SignatureKeyPair::from_raw(
65 cipher_suite.signature_algorithm(),
66 stored_credential.private_key.to_owned(),
67 stored_credential.public_key.to_owned(),
68 );
69 let credential_type = mls_credential
70 .credential_type()
71 .try_into()
72 .map_err(RecursiveError::context("loading credential from db"))?;
73 let earliest_validity = stored_credential.created_at;
74 Ok(Credential {
75 cipher_suite,
76 signature_key_pair,
77 credential_type,
78 mls_credential,
79 earliest_validity,
80 })
81 }
82}
83
84impl Credential {
85 pub fn basic(cipher_suite: CipherSuite, client_id: ClientId) -> Result<Self> {
92 let signature_scheme = cipher_suite.signature_algorithm();
93 let (private_key, public_key) = CRYPTO
94 .signature_key_gen(signature_scheme)
95 .map_err(OpenMlsError::wrap("generating signature key"))?;
96 let signature_key_pair = SignatureKeyPair::from_raw(signature_scheme, private_key, public_key);
97
98 Ok(Self {
99 cipher_suite,
100 credential_type: CredentialType::Basic,
101 mls_credential: MlsCredential::new_basic(client_id.into_inner()),
102 signature_key_pair,
103 earliest_validity: 0,
104 })
105 }
106
107 pub(crate) fn public_only(key_package: &KeyPackage) -> Result<Self> {
114 let cipher_suite = CipherSuite::from(key_package.ciphersuite());
115 let leaf_node = key_package.leaf_node();
116 let mls_credential = leaf_node.credential().clone();
117 let credential_type = mls_credential.credential_type().try_into()?;
118 let signature_key_pair = SignatureKeyPair::from_raw(
119 cipher_suite.signature_algorithm(),
120 Vec::new(),
121 leaf_node.signature_key().as_slice().to_vec(),
122 );
123
124 Ok(Self {
125 cipher_suite,
126 credential_type,
127 mls_credential,
128 signature_key_pair,
129 earliest_validity: 0,
130 })
131 }
132
133 pub fn mls_credential(&self) -> &MlsCredential {
137 &self.mls_credential
138 }
139
140 pub fn credential_type(&self) -> CredentialType {
142 self.credential_type
143 }
144
145 pub(crate) fn signature_key(&self) -> &SignatureKeyPair {
147 &self.signature_key_pair
148 }
149
150 pub fn signature_key_bytes(&self) -> &[u8] {
153 self.signature_key_pair.private()
154 }
155
156 pub fn signature_scheme(&self) -> SignatureScheme {
158 self.signature_key_pair.signature_scheme()
159 }
160
161 pub fn cipher_suite(&self) -> CipherSuite {
163 self.cipher_suite
164 }
165
166 pub fn to_mls_credential_with_key(&self) -> CredentialWithKey {
168 CredentialWithKey {
169 credential: self.mls_credential.clone(),
170 signature_key: self.signature_key_pair.to_public_vec().into(),
171 }
172 }
173
174 pub fn earliest_validity(&self) -> u64 {
182 self.earliest_validity
183 }
184
185 pub fn client_id(&self) -> &ClientIdRef {
187 self.mls_credential.identity().into()
188 }
189}
190
191impl From<Credential> for CredentialWithKey {
192 fn from(cb: Credential) -> Self {
193 Self {
194 credential: cb.mls_credential,
195 signature_key: cb.signature_key_pair.public().into(),
196 }
197 }
198}
199
200impl Eq for Credential {}
201impl PartialEq for Credential {
202 fn eq(&self, other: &Self) -> bool {
203 self.mls_credential == other.mls_credential && self.earliest_validity == other.earliest_validity && {
204 let sk = &self.signature_key_pair;
205 let ok = &other.signature_key_pair;
206 sk.signature_scheme() == ok.signature_scheme() && sk.public() == ok.public()
207 }
209 }
210}
211
212#[cfg(test)]
213mod tests {
214 use super::{x509::CertificateBundle, *};
215 use crate::{
216 CredentialType, E2eiConversationState,
217 mls::credential::x509::CertificatePrivateKey,
218 test_utils::{
219 x509::{CertificateParams, PkiKeypair, X509TestChain},
220 *,
221 },
222 };
223
224 #[apply(all_cred_cipher)]
225 async fn basic_clients_can_send_messages(case: TestContext) {
226 if !case.is_basic() {
227 return;
228 }
229 let [alice, bob] = case.sessions_basic().await;
230 let conversation = case.create_conversation([&alice, &bob]).await;
231 assert!(conversation.is_functional_and_contains([&alice, &bob]).await);
232 }
233
234 #[apply(all_cred_cipher)]
235 async fn certificate_clients_can_send_messages(case: TestContext) {
236 if !case.is_x509() {
237 return;
238 }
239 let [alice, bob] = case.sessions_x509().await;
240 let conversation = case.create_conversation([&alice, &bob]).await;
241 assert!(conversation.is_functional_and_contains([&alice, &bob]).await);
242 }
243
244 #[apply(all_cred_cipher)]
245 async fn heterogeneous_clients_can_send_messages(case: TestContext) {
246 let ([x509_session], [basic_session]) = case.sessions_mixed_credential_types().await;
248
249 let (alice, bob) = match case.credential_type {
251 CredentialType::Basic => (x509_session, basic_session),
252 CredentialType::X509 => (basic_session, x509_session),
253 };
254
255 let conversation = case.create_conversation([&alice, &bob]).await;
256 assert!(conversation.is_functional_and_contains([&alice, &bob]).await);
257 }
258
259 #[apply(all_cred_cipher)]
260 async fn should_fail_when_certificate_chain_is_empty(case: TestContext) {
261 let x509_test_chain = X509TestChain::init_empty(case.signature_scheme());
262
263 let x509_intermediate = x509_test_chain.find_local_intermediate_ca();
264
265 let mut cert = CertificateBundle::rand(&"alice".into(), x509_intermediate);
266 cert.certificate_chain = vec![];
267 let err = Credential::x509(case.cipher_suite(), cert).unwrap_err();
268
269 assert!(innermost_source_matches!(err, Error::InvalidIdentity));
270 }
271
272 #[apply(all_cred_cipher)]
273 async fn should_fail_when_signature_key_doesnt_match_certificate_public_key(case: TestContext) {
274 if !case.is_x509() {
275 return;
276 }
277 let x509_test_chain = X509TestChain::init_empty(case.signature_scheme());
278 let x509_intermediate = x509_test_chain.find_local_intermediate_ca();
279
280 let certs = CertificateBundle::rand(&"alice".into(), x509_intermediate);
281 let new_keypair = CRYPTO.signature_key_gen(case.signature_scheme()).unwrap();
282 let new_pki_kp = PkiKeypair::new(case.signature_scheme(), new_keypair.0).unwrap();
283
284 let eve_key = CertificatePrivateKey::new(new_pki_kp.signing_key_bytes());
285 let cb = CertificateBundle {
286 certificate_chain: certs.certificate_chain,
287 private_key: eve_key,
288 signature_scheme: case.cipher_suite().signature_algorithm(),
289 };
290 let err = Credential::x509(case.cipher_suite(), cb).unwrap_err();
291
292 assert!(innermost_source_matches!(
293 err,
294 crate::OpenMlsErrorKind::MlsCryptoError(openmls::prelude::CryptoError::MismatchKeypair),
295 ));
296 }
297
298 #[apply(all_cred_cipher)]
299 async fn should_fail_when_certificate_signature_doesnt_match_ciphersuite(case: TestContext) {
300 use openmls::prelude::Ciphersuite;
301 if !case.is_x509() {
302 return;
303 }
304
305 let [alice] = case.sessions_x509().await;
306 let conversation = case.create_conversation([&alice]).await;
307
308 let other_cipher_suite = match case.cipher_suite() {
309 CipherSuite(Ciphersuite::MLS_128_DHKEMX25519_AES128GCM_SHA256_Ed25519) => {
310 CipherSuite(Ciphersuite::MLS_128_DHKEMP256_AES128GCM_SHA256_P256)
311 }
312 _ => CipherSuite(Ciphersuite::MLS_128_DHKEMX25519_AES128GCM_SHA256_Ed25519),
313 };
314
315 let mixed_cipher_suite_case = TestContext::new(CredentialType::X509, *other_cipher_suite);
316 let [bob] = mixed_cipher_suite_case.sessions_x509().await;
317
318 let bob_kp = bob
319 .transaction
320 .generate_key_package(&bob.initial_credential, None)
321 .await
322 .unwrap()
323 .into();
324
325 assert!(conversation.guard().await.add_members(vec![bob_kp]).await.is_err());
326 }
327
328 #[apply(all_cred_cipher)]
329 async fn should_not_fail_but_degrade_when_certificate_expired(case: TestContext) {
330 if !case.is_x509() {
331 return;
332 }
333 let mut x509_test_chain = case.set_test_chain(&[], &[], None).await;
334 let expiration_time = core::time::Duration::from_secs(8);
335 let start = web_time::Instant::now();
336
337 let alice_cert = x509_test_chain.issue_simple_certificate_bundle("alice", None);
338 let alice_cred = Credential::x509(case.cipher_suite(), alice_cert).unwrap();
339 let bob_cert = x509_test_chain.issue_simple_certificate_bundle("bob", Some(expiration_time));
340 let bob_cred = Credential::x509(case.cipher_suite(), bob_cert).unwrap();
341 let alice = SessionContext::new_with_credential(&case, alice_cred, case.sessions_in_memory)
342 .await
343 .unwrap();
344 let bob = SessionContext::new_with_credential(&case, bob_cred, case.sessions_in_memory)
345 .await
346 .unwrap();
347
348 let conversation = case.create_conversation([&alice, &bob]).await;
349 assert!(conversation.is_functional_and_contains([&alice, &bob]).await);
351
352 assert_eq!(
353 conversation.guard().await.e2ei_conversation_state().await.unwrap(),
354 E2eiConversationState::Verified
355 );
356
357 let elapsed = start.elapsed();
358 if expiration_time > elapsed {
360 smol::Timer::after(expiration_time - elapsed + core::time::Duration::from_secs(1)).await;
361 }
362
363 assert!(conversation.is_functional_and_contains([&alice, &bob]).await);
364 assert_eq!(
365 conversation.guard().await.e2ei_conversation_state().await.unwrap(),
366 E2eiConversationState::NotVerified
367 );
368 }
369
370 #[apply(all_cred_cipher)]
371 async fn should_not_fail_but_degrade_when_basic_joins(case: TestContext) {
372 if !case.is_x509() {
373 return;
374 }
375 Box::pin(async {
376 let ([alice, bob], [charlie]) = case.sessions_mixed_credential_types().await;
377 let conversation = case.create_conversation([&alice, &bob]).await;
378
379 assert!(conversation.is_functional_and_contains([&alice, &bob]).await);
381 assert_eq!(
382 conversation.guard().await.e2ei_conversation_state().await.unwrap(),
383 E2eiConversationState::Verified
384 );
385 assert_eq!(
386 conversation
387 .guard_of(&bob)
388 .await
389 .e2ei_conversation_state()
390 .await
391 .unwrap(),
392 E2eiConversationState::Verified
393 );
394
395 let conversation = conversation
397 .invite_with_credential_notify([(&charlie, &charlie.initial_credential)])
398 .await;
399
400 assert_eq!(
401 conversation.guard().await.e2ei_conversation_state().await.unwrap(),
402 E2eiConversationState::NotVerified
403 );
404 assert!(conversation.is_functional_and_contains([&alice, &bob, &charlie]).await);
405 assert_eq!(
406 conversation.guard().await.e2ei_conversation_state().await.unwrap(),
407 E2eiConversationState::NotVerified
408 );
409 })
410 .await;
411 }
412
413 #[apply(all_cred_cipher)]
414 async fn should_fail_when_certificate_not_valid_yet(case: TestContext) {
415 use crate::OpenMlsErrorKind;
416
417 if !case.is_x509() {
418 return;
419 }
420 let x509_test_chain = X509TestChain::init_empty(case.signature_scheme());
421
422 let tomorrow = now_std() + core::time::Duration::from_secs(3600 * 24);
423 let local_ca = x509_test_chain.find_local_intermediate_ca();
424 let alice_cert = {
425 let name = "alice";
426 let common_name = format!("{name} Smith");
427 let handle = format!("{}_wire", name.to_lowercase());
428 let [client_id] = case.client_ids();
429 local_ca.create_and_sign_end_identity(CertificateParams {
430 common_name: Some(common_name.clone()),
431 handle: Some(handle.clone()),
432 client_id: Some(client_id.clone()),
433 validity_start: Some(tomorrow),
434 ..Default::default()
435 })
436 };
437 let cb = CertificateBundle::from_certificate_and_issuer(&alice_cert, local_ca);
438 let err = Credential::x509(case.cipher_suite(), cb).unwrap_err();
439
440 assert!(innermost_source_matches!(
441 err,
442 OpenMlsErrorKind::MlsCryptoError(openmls::prelude::CryptoError::ExpiredCertificate),
443 ))
444 }
445
446 pub(crate) fn now_std() -> std::time::Duration {
452 let now = web_time::SystemTime::now();
453 now.duration_since(web_time::UNIX_EPOCH).unwrap()
454 }
455}