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,
53}
54
55impl TryFrom<Arc<StoredCredential>> for Credential {
56 type Error = Error;
57
58 fn try_from(stored_credential: Arc<StoredCredential>) -> Result<Credential> {
59 let mls_credential = MlsCredential::tls_deserialize(&mut stored_credential.credential.as_slice())
60 .map_err(TlsCodecError::deserialize("mls credential"))?;
61 let cipher_suite = CipherSuite::try_from(stored_credential.ciphersuite)?;
62 let signature_key_pair = openmls_basic_credential::SignatureKeyPair::from_raw(
63 cipher_suite.signature_algorithm(),
64 stored_credential.private_key.to_owned(),
65 stored_credential.public_key.to_owned(),
66 );
67 let credential_type = mls_credential
68 .credential_type()
69 .try_into()
70 .map_err(RecursiveError::context("loading credential from db"))?;
71 let earliest_validity = stored_credential.created_at;
72 Ok(Credential {
73 cipher_suite,
74 signature_key_pair,
75 credential_type,
76 mls_credential,
77 earliest_validity,
78 })
79 }
80}
81
82impl Credential {
83 pub fn basic(cipher_suite: CipherSuite, client_id: ClientId) -> Result<Self> {
90 let signature_scheme = cipher_suite.signature_algorithm();
91 let (private_key, public_key) = CRYPTO
92 .signature_key_gen(signature_scheme)
93 .map_err(OpenMlsError::wrap("generating signature key"))?;
94 let signature_key_pair = SignatureKeyPair::from_raw(signature_scheme, private_key, public_key);
95
96 Ok(Self {
97 cipher_suite,
98 credential_type: CredentialType::Basic,
99 mls_credential: MlsCredential::new_basic(client_id.into_inner()),
100 signature_key_pair,
101 earliest_validity: 0,
102 })
103 }
104
105 pub(crate) fn public_only(key_package: &KeyPackage) -> Result<Self> {
112 let cipher_suite = CipherSuite::from(key_package.ciphersuite());
113 let leaf_node = key_package.leaf_node();
114 let mls_credential = leaf_node.credential().clone();
115 let credential_type = mls_credential.credential_type().try_into()?;
116 let signature_key_pair = SignatureKeyPair::from_raw(
117 cipher_suite.signature_algorithm(),
118 Vec::new(),
119 leaf_node.signature_key().as_slice().to_vec(),
120 );
121
122 Ok(Self {
123 cipher_suite,
124 credential_type,
125 mls_credential,
126 signature_key_pair,
127 earliest_validity: 0,
128 })
129 }
130
131 pub fn mls_credential(&self) -> &MlsCredential {
135 &self.mls_credential
136 }
137
138 pub fn credential_type(&self) -> CredentialType {
140 self.credential_type
141 }
142
143 pub(crate) fn signature_key(&self) -> &SignatureKeyPair {
145 &self.signature_key_pair
146 }
147
148 pub fn signature_key_bytes(&self) -> &[u8] {
150 self.signature_key_pair.private()
151 }
152
153 pub fn signature_scheme(&self) -> SignatureScheme {
155 self.signature_key_pair.signature_scheme()
156 }
157
158 pub fn cipher_suite(&self) -> CipherSuite {
160 self.cipher_suite
161 }
162
163 pub fn to_mls_credential_with_key(&self) -> CredentialWithKey {
165 CredentialWithKey {
166 credential: self.mls_credential.clone(),
167 signature_key: self.signature_key_pair.to_public_vec().into(),
168 }
169 }
170
171 pub fn earliest_validity(&self) -> u64 {
176 self.earliest_validity
177 }
178
179 pub fn client_id(&self) -> &ClientIdRef {
181 self.mls_credential.identity().into()
182 }
183}
184
185impl From<Credential> for CredentialWithKey {
186 fn from(cb: Credential) -> Self {
187 Self {
188 credential: cb.mls_credential,
189 signature_key: cb.signature_key_pair.public().into(),
190 }
191 }
192}
193
194impl Eq for Credential {}
195impl PartialEq for Credential {
196 fn eq(&self, other: &Self) -> bool {
197 self.mls_credential == other.mls_credential && self.earliest_validity == other.earliest_validity && {
198 let sk = &self.signature_key_pair;
199 let ok = &other.signature_key_pair;
200 sk.signature_scheme() == ok.signature_scheme() && sk.public() == ok.public()
201 }
203 }
204}
205
206#[cfg(test)]
207mod tests {
208 use super::{x509::CertificateBundle, *};
209 use crate::{
210 CredentialType, E2eiConversationState,
211 mls::credential::x509::CertificatePrivateKey,
212 test_utils::{
213 x509::{CertificateParams, PkiKeypair, X509TestChain},
214 *,
215 },
216 };
217
218 #[apply(all_cred_cipher)]
219 async fn basic_clients_can_send_messages(case: TestContext) {
220 if !case.is_basic() {
221 return;
222 }
223 let [alice, bob] = case.sessions_basic().await;
224 let conversation = case.create_conversation([&alice, &bob]).await;
225 assert!(conversation.is_functional_and_contains([&alice, &bob]).await);
226 }
227
228 #[apply(all_cred_cipher)]
229 async fn certificate_clients_can_send_messages(case: TestContext) {
230 if !case.is_x509() {
231 return;
232 }
233 let [alice, bob] = case.sessions_x509().await;
234 let conversation = case.create_conversation([&alice, &bob]).await;
235 assert!(conversation.is_functional_and_contains([&alice, &bob]).await);
236 }
237
238 #[apply(all_cred_cipher)]
239 async fn heterogeneous_clients_can_send_messages(case: TestContext) {
240 if !case.supports_x509() {
241 return;
242 }
243
244 let ([x509_session], [basic_session]) = case.sessions_mixed_credential_types().await;
246
247 let (alice, bob) = match case.credential_type {
249 CredentialType::Basic => (x509_session, basic_session),
250 CredentialType::X509 => (basic_session, x509_session),
251 };
252
253 let conversation = case.create_conversation([&alice, &bob]).await;
254 assert!(conversation.is_functional_and_contains([&alice, &bob]).await);
255 }
256
257 #[apply(all_cred_cipher)]
258 async fn should_fail_when_certificate_chain_is_empty(case: TestContext) {
259 if !case.supports_x509() {
260 return;
261 }
262 let x509_test_chain = X509TestChain::init_empty(case.signature_scheme());
263
264 let x509_intermediate = x509_test_chain.find_local_intermediate_ca();
265
266 let mut cert = CertificateBundle::rand(&"alice".into(), x509_intermediate);
267 cert.certificate_chain = vec![];
268 let err = Credential::x509(case.cipher_suite(), cert).unwrap_err();
269
270 assert!(innermost_source_matches!(err, Error::InvalidIdentity));
271 }
272
273 #[apply(all_cred_cipher)]
274 async fn should_fail_when_signature_key_doesnt_match_certificate_public_key(case: TestContext) {
275 if !case.is_x509() {
276 return;
277 }
278 let x509_test_chain = X509TestChain::init_empty(case.signature_scheme());
279 let x509_intermediate = x509_test_chain.find_local_intermediate_ca();
280
281 let certs = CertificateBundle::rand(&"alice".into(), x509_intermediate);
282 let new_keypair = CRYPTO.signature_key_gen(case.signature_scheme()).unwrap();
283 let new_pki_kp = PkiKeypair::new(case.signature_scheme(), new_keypair.0).unwrap();
284
285 let eve_key = CertificatePrivateKey::new(new_pki_kp.signing_key_bytes());
286 let cb = CertificateBundle {
287 certificate_chain: certs.certificate_chain,
288 private_key: eve_key,
289 signature_scheme: case.cipher_suite().signature_algorithm(),
290 };
291 let err = Credential::x509(case.cipher_suite(), cb).unwrap_err();
292
293 assert!(innermost_source_matches!(
294 err,
295 crate::OpenMlsErrorKind::MlsCryptoError(openmls::prelude::CryptoError::MismatchKeypair),
296 ));
297 }
298
299 #[apply(all_cred_cipher)]
300 async fn should_fail_when_certificate_signature_doesnt_match_ciphersuite(case: TestContext) {
301 use openmls::prelude::Ciphersuite;
302 if !case.is_x509() {
303 return;
304 }
305
306 let [alice] = case.sessions_x509().await;
307 let conversation = case.create_conversation([&alice]).await;
308
309 let other_cipher_suite = match case.cipher_suite() {
310 CipherSuite(Ciphersuite::MLS_128_DHKEMX25519_AES128GCM_SHA256_Ed25519) => {
311 CipherSuite(Ciphersuite::MLS_128_DHKEMP256_AES128GCM_SHA256_P256)
312 }
313 _ => CipherSuite(Ciphersuite::MLS_128_DHKEMX25519_AES128GCM_SHA256_Ed25519),
314 };
315
316 let mixed_cipher_suite_case = TestContext::new(CredentialType::X509, *other_cipher_suite);
317 let [bob] = mixed_cipher_suite_case.sessions_x509().await;
318
319 let bob_kp = bob
320 .transaction
321 .generate_key_package(&bob.initial_credential, None)
322 .await
323 .unwrap()
324 .into();
325
326 assert!(conversation.guard().await.add_members(vec![bob_kp]).await.is_err());
327 }
328
329 #[apply(all_cred_cipher)]
330 async fn should_not_fail_but_degrade_when_certificate_expired(case: TestContext) {
331 if !case.is_x509() {
332 return;
333 }
334 let mut x509_test_chain = case.set_test_chain(&[], &[], None).await;
335 let expiration_time = core::time::Duration::from_secs(8);
336 let start = web_time::Instant::now();
337
338 let alice_cert = x509_test_chain.issue_simple_certificate_bundle("alice", None);
339 let alice_cred = Credential::x509(case.cipher_suite(), alice_cert).unwrap();
340 let bob_cert = x509_test_chain.issue_simple_certificate_bundle("bob", Some(expiration_time));
341 let bob_cred = Credential::x509(case.cipher_suite(), bob_cert).unwrap();
342 let alice = SessionContext::new_with_credential(&case, alice_cred, case.sessions_in_memory)
343 .await
344 .unwrap();
345 let bob = SessionContext::new_with_credential(&case, bob_cred, case.sessions_in_memory)
346 .await
347 .unwrap();
348
349 let conversation = case.create_conversation([&alice, &bob]).await;
350 assert!(conversation.is_functional_and_contains([&alice, &bob]).await);
352
353 assert_eq!(
354 conversation.guard().await.e2ei_conversation_state().await.unwrap(),
355 E2eiConversationState::Verified
356 );
357
358 let elapsed = start.elapsed();
359 if expiration_time > elapsed {
361 smol::Timer::after(expiration_time - elapsed + core::time::Duration::from_secs(1)).await;
362 }
363
364 assert!(conversation.is_functional_and_contains([&alice, &bob]).await);
365 assert_eq!(
366 conversation.guard().await.e2ei_conversation_state().await.unwrap(),
367 E2eiConversationState::NotVerified
368 );
369 }
370
371 #[apply(all_cred_cipher)]
372 async fn should_not_fail_but_degrade_when_basic_joins(case: TestContext) {
373 if !case.is_x509() {
374 return;
375 }
376 Box::pin(async {
377 let ([alice, bob], [charlie]) = case.sessions_mixed_credential_types().await;
378 let conversation = case.create_conversation([&alice, &bob]).await;
379
380 assert!(conversation.is_functional_and_contains([&alice, &bob]).await);
382 assert_eq!(
383 conversation.guard().await.e2ei_conversation_state().await.unwrap(),
384 E2eiConversationState::Verified
385 );
386 assert_eq!(
387 conversation
388 .guard_of(&bob)
389 .await
390 .e2ei_conversation_state()
391 .await
392 .unwrap(),
393 E2eiConversationState::Verified
394 );
395
396 let conversation = conversation
398 .invite_with_credential_notify([(&charlie, &charlie.initial_credential)])
399 .await;
400
401 assert_eq!(
402 conversation.guard().await.e2ei_conversation_state().await.unwrap(),
403 E2eiConversationState::NotVerified
404 );
405 assert!(conversation.is_functional_and_contains([&alice, &bob, &charlie]).await);
406 assert_eq!(
407 conversation.guard().await.e2ei_conversation_state().await.unwrap(),
408 E2eiConversationState::NotVerified
409 );
410 })
411 .await;
412 }
413
414 #[apply(all_cred_cipher)]
420 async fn saving_an_x509_credential_keeps_the_certificate_validity(case: TestContext) {
421 if !case.is_x509() {
422 return;
423 }
424 let [alice] = case.sessions().await;
425 Box::pin(async move {
426 let x509_test_chain = X509TestChain::init_empty(case.signature_scheme());
427 let local_ca = x509_test_chain.find_local_intermediate_ca();
428
429 let an_hour_ago = now_std() - core::time::Duration::from_secs(3600);
431 let client_id = alice.get_client_id().await;
434 let cert = local_ca.create_and_sign_end_identity(CertificateParams {
435 common_name: Some("Alice Smith".to_string()),
436 handle: Some("alice_wire".to_string()),
437 client_id: Some(client_id),
438 validity_start: Some(an_hour_ago),
439 ..Default::default()
440 });
441 let bundle = CertificateBundle::from_certificate_and_issuer(&cert, local_ca);
442 let credential = Credential::x509(case.cipher_suite(), bundle).unwrap();
443
444 let from_certificate = credential.earliest_validity();
447 assert!(
448 from_certificate.abs_diff(an_hour_ago.as_secs()) <= 5,
449 "the credential must start out carrying the certificate's `not_before`: \
450 got {from_certificate}, expected about {}",
451 an_hour_ago.as_secs()
452 );
453
454 let credential_ref = alice
455 .add_credential(credential)
456 .await
457 .expect("adding the credential should succeed");
458
459 assert_eq!(
460 credential_ref.earliest_validity(),
461 from_certificate,
462 "persisting must not replace the certificate claim with the insertion time"
463 );
464 })
465 .await;
466 }
467
468 #[apply(all_cred_cipher)]
469 async fn should_fail_when_certificate_not_valid_yet(case: TestContext) {
470 use crate::OpenMlsErrorKind;
471
472 if !case.is_x509() {
473 return;
474 }
475 let x509_test_chain = X509TestChain::init_empty(case.signature_scheme());
476
477 let tomorrow = now_std() + core::time::Duration::from_secs(3600 * 24);
478 let local_ca = x509_test_chain.find_local_intermediate_ca();
479 let alice_cert = {
480 let name = "alice";
481 let common_name = format!("{name} Smith");
482 let handle = format!("{}_wire", name.to_lowercase());
483 let [client_id] = case.client_ids();
484 local_ca.create_and_sign_end_identity(CertificateParams {
485 common_name: Some(common_name.clone()),
486 handle: Some(handle.clone()),
487 client_id: Some(client_id.clone()),
488 validity_start: Some(tomorrow),
489 ..Default::default()
490 })
491 };
492 let cb = CertificateBundle::from_certificate_and_issuer(&alice_cert, local_ca);
493 let err = Credential::x509(case.cipher_suite(), cb).unwrap_err();
494
495 assert!(innermost_source_matches!(
496 err,
497 OpenMlsErrorKind::MlsCryptoError(openmls::prelude::CryptoError::ExpiredCertificate),
498 ))
499 }
500
501 pub(crate) fn now_std() -> std::time::Duration {
507 let now = web_time::SystemTime::now();
508 now.duration_since(web_time::UNIX_EPOCH).unwrap()
509 }
510}