Skip to main content

core_crypto/transaction_context/credential/
mod.rs

1mod check;
2
3use std::sync::Arc;
4
5use super::{Error, Result};
6use crate::{Credential, CredentialRef, RecursiveError, transaction_context::TransactionContext};
7
8impl TransactionContext {
9    /// Add a credential to the database of this session without validating that its client ID matches the session
10    /// client id.
11    ///
12    /// This is rarely useful and should only be used when absolutely necessary. You'll know it if you need it.
13    ///
14    /// Prefer [`Self::add_credential`].
15    pub(crate) fn add_credential_without_clientid_check(&self, mut credential: Credential) -> Result<Arc<Credential>> {
16        let inner = self.inner()?;
17        let _credential_ref = credential
18            .save(&inner.transaction)
19            .map_err(RecursiveError::context("saving credential"))?;
20
21        Ok(Arc::new(credential))
22    }
23    /// Add a credential to the database of this session.
24    pub async fn add_credential(&self, credential: Credential) -> Result<CredentialRef> {
25        let credential = self.add_credential_producing_arc(credential).await?;
26        Ok(CredentialRef::from_credential(&credential))
27    }
28
29    /// Add a credential to the database of this session.
30    ///
31    /// Returns the actual credential instance which was loaded from the DB.
32    /// This is a convenience for internal use and should _not_ be propagated across
33    /// the FFI boundary. Instead, use [`Self::add_credential`] to produce a [`CredentialRef`].
34    pub(crate) async fn add_credential_producing_arc(&self, credential: Credential) -> Result<Arc<Credential>> {
35        if *credential.client_id() != self.session().await?.id() {
36            return Err(Error::WrongCredential);
37        }
38
39        self.add_credential_without_clientid_check(credential)
40    }
41
42    /// Remove a credential from the database of this session.
43    ///
44    /// First checks that the credential is not used in any conversation.
45    /// Removes both the credential itself and also any key packages which were generated from it.
46    pub async fn remove_credential(&self, credential_ref: &CredentialRef) -> Result<bool> {
47        // setup
48        if *credential_ref.client_id() != self.session().await?.id() {
49            return Err(Error::WrongCredential);
50        }
51
52        let inner = self.inner()?;
53
54        let removed = credential_ref.delete(&inner.transaction).map_err(|err| -> Error {
55            let crate::KeystoreError { source, .. } = &err;
56            let Some(core_crypto_keystore::CryptoKeystoreError::DbError(rusqlite_err)) = source.downcast_ref() else {
57                return err.into();
58            };
59            if rusqlite_err
60                .sqlite_error_code()
61                .is_some_and(|code| code == core_crypto_keystore::RusqliteErrorCode::ConstraintViolation)
62            {
63                Error::CredentialStillInUse
64            } else {
65                err.into()
66            }
67        })?;
68
69        Ok(removed)
70    }
71}
72
73#[cfg(test)]
74mod tests {
75    use core_crypto_keystore::{
76        entities::{StoredCredential, StoredKeyPackage},
77        traits::FetchFromDatabase as _,
78    };
79
80    use super::*;
81    use crate::{CertificateBundle, test_utils::*};
82
83    async fn credential_is_stored(session: &SessionContext, credential: &CredentialRef) -> bool {
84        session
85            .transaction
86            .database()
87            .unwrap()
88            .get::<StoredCredential>(&credential.keystore_pk())
89            .await
90            .unwrap()
91            .is_some()
92    }
93
94    /// How many stored key packages were generated from `credential`.
95    async fn count_key_packages_for(session: &SessionContext, credential: &CredentialRef) -> usize {
96        session
97            .transaction
98            .database()
99            .unwrap()
100            .search::<StoredKeyPackage, _>(&credential.keystore_pk())
101            .await
102            .unwrap()
103            .len()
104    }
105
106    /// A credential a conversation still uses cannot be removed, and the refused removal writes nothing: neither the
107    /// credential nor the key packages generated from it go missing. Once the conversation moves on to another
108    /// credential, the old one can be removed.
109    #[apply(all_cred_cipher)]
110    async fn credential_in_use_by_a_conversation_cannot_be_removed(case: TestContext) {
111        const KEY_PACKAGES: usize = 2;
112
113        let [alice] = case.sessions().await;
114        let conversation = case.create_conversation([&alice]).await;
115        let credential = alice.initial_credential.clone();
116
117        for _ in 0..KEY_PACKAGES {
118            alice.new_keypackage_from_ref(credential.clone(), None).await;
119        }
120        assert_eq!(count_key_packages_for(&alice, &credential).await, KEY_PACKAGES);
121
122        let result = alice.transaction.remove_credential(&credential).await;
123        assert!(
124            matches!(result, Err(Error::CredentialStillInUse)),
125            "removing a credential in use must fail with `CredentialStillInUse`, but got {result:?}"
126        );
127
128        // The caller may catch the error and carry on with this transaction, so the failed removal must not have
129        // written anything.
130        assert!(
131            credential_is_stored(&alice, &credential).await,
132            "a refused removal must keep the credential"
133        );
134        assert_eq!(
135            count_key_packages_for(&alice, &credential).await,
136            KEY_PACKAGES,
137            "a refused removal must keep the key packages generated from the credential"
138        );
139
140        // A basic credential is just our client id, so a "new" one for the same client compares equal to the old one
141        // and openmls declines to rotate anything. Only x509 can rotate here.
142        if !case.is_x509() {
143            return;
144        }
145
146        let intermediate_ca = alice.x509_chain_unchecked().find_local_intermediate_ca();
147        let certificate = CertificateBundle::new_with_default_values(intermediate_ca, None);
148        let new_credential = Credential::x509(case.cipher_suite(), certificate).unwrap();
149        alice
150            .transaction
151            .add_credential_without_clientid_check(new_credential.clone())
152            .unwrap();
153        let new_credential = CredentialRef::from_credential(&new_credential);
154        conversation.set_credential_by_ref_notify(&new_credential).await;
155
156        let removed = alice
157            .transaction
158            .remove_credential(&credential)
159            .await
160            .expect("a credential no conversation uses any more can be removed");
161        assert!(removed, "removal must report that the credential was deleted");
162        assert!(!credential_is_stored(&alice, &credential).await);
163        assert_eq!(count_key_packages_for(&alice, &credential).await, 0);
164    }
165
166    /// Unix timestamps in seconds of two certificates for the same key: one issued two days ago, and the one which
167    /// replaced it a day later. Both are still valid.
168    fn rotation_not_before() -> [u64; 2] {
169        let now = std::time::SystemTime::now()
170            .duration_since(std::time::UNIX_EPOCH)
171            .unwrap()
172            .as_secs();
173        [now - 2 * 86_400, now - 86_400]
174    }
175
176    /// A reissued certificate can certify the signature key of the one it replaces. Both credentials are kept side by
177    /// side, each keeps its own key packages, and either can be removed without touching the other.
178    #[apply(all_cred_cipher)]
179    async fn x509_credentials_sharing_a_signature_key_are_kept_apart(case: TestContext) {
180        if !case.is_x509() {
181            return;
182        }
183
184        let [alice] = case.sessions().await;
185        let [old, new] = alice
186            .add_x509_credentials_sharing_a_key(case.cipher_suite(), rotation_not_before())
187            .await;
188        assert_eq!(
189            old.public_key_hash(),
190            new.public_key_hash(),
191            "the test needs a shared key"
192        );
193
194        assert!(credential_is_stored(&alice, &old).await);
195        assert!(credential_is_stored(&alice, &new).await);
196
197        // a different number for each, so that one credential's key packages can't pass for the other's
198        alice.new_keypackage_from_ref(old.clone(), None).await;
199        for _ in 0..2 {
200            alice.new_keypackage_from_ref(new.clone(), None).await;
201        }
202        assert_eq!(count_key_packages_for(&alice, &old).await, 1);
203        assert_eq!(count_key_packages_for(&alice, &new).await, 2);
204
205        let removed = alice
206            .transaction
207            .remove_credential(&old)
208            .await
209            .expect("a credential no conversation uses can be removed");
210        assert!(removed, "removal must report that the credential was deleted");
211        assert!(!credential_is_stored(&alice, &old).await);
212        assert_eq!(count_key_packages_for(&alice, &old).await, 0);
213        assert!(
214            credential_is_stored(&alice, &new).await,
215            "removing one credential must leave the other with the same key alone"
216        );
217        assert_eq!(count_key_packages_for(&alice, &new).await, 2);
218    }
219}