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