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, 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 fn mls_credential(&self) -> &MlsCredential {
111 &self.mls_credential
112 }
113
114 pub fn credential_type(&self) -> CredentialType {
116 self.credential_type
117 }
118
119 pub(crate) fn signature_key(&self) -> &SignatureKeyPair {
121 &self.signature_key_pair
122 }
123
124 pub fn signature_key_bytes(&self) -> &[u8] {
127 self.signature_key_pair.private()
128 }
129
130 pub fn signature_scheme(&self) -> SignatureScheme {
132 self.signature_key_pair.signature_scheme()
133 }
134
135 pub fn cipher_suite(&self) -> CipherSuite {
137 self.cipher_suite
138 }
139
140 pub fn to_mls_credential_with_key(&self) -> CredentialWithKey {
142 CredentialWithKey {
143 credential: self.mls_credential.clone(),
144 signature_key: self.signature_key_pair.to_public_vec().into(),
145 }
146 }
147
148 pub fn earliest_validity(&self) -> u64 {
156 self.earliest_validity
157 }
158
159 pub fn client_id(&self) -> &ClientIdRef {
161 self.mls_credential.identity().into()
162 }
163}
164
165impl From<Credential> for CredentialWithKey {
166 fn from(cb: Credential) -> Self {
167 Self {
168 credential: cb.mls_credential,
169 signature_key: cb.signature_key_pair.public().into(),
170 }
171 }
172}
173
174impl Eq for Credential {}
175impl PartialEq for Credential {
176 fn eq(&self, other: &Self) -> bool {
177 self.mls_credential == other.mls_credential && self.earliest_validity == other.earliest_validity && {
178 let sk = &self.signature_key_pair;
179 let ok = &other.signature_key_pair;
180 sk.signature_scheme() == ok.signature_scheme() && sk.public() == ok.public()
181 }
183 }
184}
185
186#[cfg(test)]
187mod tests {
188 use super::{x509::CertificateBundle, *};
189 use crate::{
190 CredentialType, E2eiConversationState,
191 mls::credential::x509::CertificatePrivateKey,
192 mls_provider::PkiKeypair,
193 test_utils::{
194 x509::{CertificateParams, X509TestChain},
195 *,
196 },
197 };
198
199 #[apply(all_cred_cipher)]
200 async fn basic_clients_can_send_messages(case: TestContext) {
201 if !case.is_basic() {
202 return;
203 }
204 let [alice, bob] = case.sessions_basic().await;
205 let conversation = case.create_conversation([&alice, &bob]).await;
206 assert!(conversation.is_functional_and_contains([&alice, &bob]).await);
207 }
208
209 #[apply(all_cred_cipher)]
210 async fn certificate_clients_can_send_messages(case: TestContext) {
211 if !case.is_x509() {
212 return;
213 }
214 let [alice, bob] = case.sessions_x509().await;
215 let conversation = case.create_conversation([&alice, &bob]).await;
216 assert!(conversation.is_functional_and_contains([&alice, &bob]).await);
217 }
218
219 #[apply(all_cred_cipher)]
220 async fn heterogeneous_clients_can_send_messages(case: TestContext) {
221 let ([x509_session], [basic_session]) = case.sessions_mixed_credential_types().await;
223
224 let (alice, bob) = match case.credential_type {
226 CredentialType::Basic => (x509_session, basic_session),
227 CredentialType::X509 => (basic_session, x509_session),
228 };
229
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 should_fail_when_certificate_chain_is_empty(case: TestContext) {
236 let x509_test_chain = X509TestChain::init_empty(case.signature_scheme());
237
238 let x509_intermediate = x509_test_chain.find_local_intermediate_ca();
239
240 let mut cert = CertificateBundle::rand(&"alice".into(), x509_intermediate);
241 cert.certificate_chain = vec![];
242 let err = Credential::x509(case.cipher_suite(), cert).unwrap_err();
243
244 assert!(innermost_source_matches!(err, Error::InvalidIdentity));
245 }
246
247 #[apply(all_cred_cipher)]
248 async fn should_fail_when_signature_key_doesnt_match_certificate_public_key(case: TestContext) {
249 if !case.is_x509() {
250 return;
251 }
252 let x509_test_chain = X509TestChain::init_empty(case.signature_scheme());
253 let x509_intermediate = x509_test_chain.find_local_intermediate_ca();
254
255 let certs = CertificateBundle::rand(&"alice".into(), x509_intermediate);
256 let new_pki_kp = PkiKeypair::rand(case.signature_scheme(), CRYPTO.as_ref()).unwrap();
257
258 let eve_key = CertificatePrivateKey::new(new_pki_kp.signing_key_bytes());
259 let cb = CertificateBundle {
260 certificate_chain: certs.certificate_chain,
261 private_key: eve_key,
262 signature_scheme: case.cipher_suite().signature_algorithm(),
263 };
264 let err = Credential::x509(case.cipher_suite(), cb).unwrap_err();
265
266 assert!(innermost_source_matches!(
267 err,
268 crate::OpenMlsErrorKind::MlsCryptoError(openmls::prelude::CryptoError::MismatchKeypair),
269 ));
270 }
271
272 #[apply(all_cred_cipher)]
273 async fn should_fail_when_certificate_signature_doesnt_match_ciphersuite(case: TestContext) {
274 use openmls::prelude::Ciphersuite;
275 if !case.is_x509() {
276 return;
277 }
278
279 let [alice] = case.sessions_x509().await;
280 let conversation = case.create_conversation([&alice]).await;
281
282 let other_cipher_suite = match case.cipher_suite() {
283 CipherSuite(Ciphersuite::MLS_128_DHKEMX25519_AES128GCM_SHA256_Ed25519) => {
284 CipherSuite(Ciphersuite::MLS_128_DHKEMP256_AES128GCM_SHA256_P256)
285 }
286 _ => CipherSuite(Ciphersuite::MLS_128_DHKEMX25519_AES128GCM_SHA256_Ed25519),
287 };
288
289 let mixed_cipher_suite_case = TestContext::new(CredentialType::X509, *other_cipher_suite);
290 let [bob] = mixed_cipher_suite_case.sessions_x509().await;
291
292 let bob_kp = bob
293 .transaction
294 .generate_key_package(&bob.initial_credential, None)
295 .await
296 .unwrap()
297 .into();
298
299 assert!(conversation.guard().await.add_members(vec![bob_kp]).await.is_err());
300 }
301
302 #[apply(all_cred_cipher)]
303 async fn should_not_fail_but_degrade_when_certificate_expired(case: TestContext) {
304 if !case.is_x509() {
305 return;
306 }
307 Box::pin(async move {
308 let mut x509_test_chain = case.set_test_chain(&[], &[], None).await;
309 let expiration_time = core::time::Duration::from_secs(14);
310 let start = web_time::Instant::now();
311
312 let alice_cert = x509_test_chain.issue_simple_certificate_bundle("alice", None);
313 let alice_cred = Credential::x509(case.cipher_suite(), alice_cert).unwrap();
314 let bob_cert = x509_test_chain.issue_simple_certificate_bundle("bob", Some(expiration_time));
315 let bob_cred = Credential::x509(case.cipher_suite(), bob_cert).unwrap();
316 let alice = SessionContext::new_with_credential(&case, alice_cred).await.unwrap();
317 let bob = SessionContext::new_with_credential(&case, bob_cred).await.unwrap();
318
319 let conversation = case.create_conversation([&alice, &bob]).await;
320 assert!(conversation.is_functional_and_contains([&alice, &bob]).await);
322
323 assert_eq!(
324 conversation.guard().await.e2ei_conversation_state().await.unwrap(),
325 E2eiConversationState::Verified
326 );
327
328 let elapsed = start.elapsed();
329 if expiration_time > elapsed {
331 smol::Timer::after(expiration_time - elapsed + core::time::Duration::from_secs(2)).await;
332 }
333
334 assert!(conversation.is_functional_and_contains([&alice, &bob]).await);
335 assert_eq!(
336 conversation.guard().await.e2ei_conversation_state().await.unwrap(),
337 E2eiConversationState::NotVerified
338 );
339 })
340 .await;
341 }
342
343 #[apply(all_cred_cipher)]
344 async fn should_not_fail_but_degrade_when_basic_joins(case: TestContext) {
345 if !case.is_x509() {
346 return;
347 }
348 Box::pin(async {
349 let ([alice, bob], [charlie]) = case.sessions_mixed_credential_types().await;
350 let conversation = case.create_conversation([&alice, &bob]).await;
351
352 assert!(conversation.is_functional_and_contains([&alice, &bob]).await);
354 assert_eq!(
355 conversation.guard().await.e2ei_conversation_state().await.unwrap(),
356 E2eiConversationState::Verified
357 );
358 assert_eq!(
359 conversation
360 .guard_of(&bob)
361 .await
362 .e2ei_conversation_state()
363 .await
364 .unwrap(),
365 E2eiConversationState::Verified
366 );
367
368 let conversation = conversation
370 .invite_with_credential_notify([(&charlie, &charlie.initial_credential)])
371 .await;
372
373 assert_eq!(
374 conversation.guard().await.e2ei_conversation_state().await.unwrap(),
375 E2eiConversationState::NotVerified
376 );
377 assert!(conversation.is_functional_and_contains([&alice, &bob, &charlie]).await);
378 assert_eq!(
379 conversation.guard().await.e2ei_conversation_state().await.unwrap(),
380 E2eiConversationState::NotVerified
381 );
382 })
383 .await;
384 }
385
386 #[apply(all_cred_cipher)]
387 async fn should_fail_when_certificate_not_valid_yet(case: TestContext) {
388 use crate::OpenMlsErrorKind;
389
390 if !case.is_x509() {
391 return;
392 }
393 let x509_test_chain = X509TestChain::init_empty(case.signature_scheme());
394
395 let tomorrow = now_std() + core::time::Duration::from_secs(3600 * 24);
396 let local_ca = x509_test_chain.find_local_intermediate_ca();
397 let alice_cert = {
398 let name = "alice";
399 let common_name = format!("{name} Smith");
400 let handle = format!("{}_wire", name.to_lowercase());
401 let [client_id] = case.client_ids();
402 local_ca.create_and_sign_end_identity(CertificateParams {
403 common_name: Some(common_name.clone()),
404 handle: Some(handle.clone()),
405 client_id: Some(client_id.clone()),
406 validity_start: Some(tomorrow),
407 ..Default::default()
408 })
409 };
410 let cb = CertificateBundle::from_certificate_and_issuer(&alice_cert, local_ca);
411 let err = Credential::x509(case.cipher_suite(), cb).unwrap_err();
412
413 assert!(innermost_source_matches!(
414 err,
415 OpenMlsErrorKind::MlsCryptoError(openmls::prelude::CryptoError::ExpiredCertificate),
416 ))
417 }
418
419 pub(crate) fn now_std() -> std::time::Duration {
425 let now = web_time::SystemTime::now();
426 now.duration_since(web_time::UNIX_EPOCH).unwrap()
427 }
428}