1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
use openmls_traits::{random::OpenMlsRand, OpenMlsCryptoProvider};

use crate::context::CentralContext;
use crate::prelude::{CryptoError, CryptoResult, E2eiEnrollment};
use core_crypto_keystore::CryptoKeystoreMls;
use mls_crypto_provider::MlsCryptoProvider;

/// A unique identifier for an enrollment a consumer can use to fetch it from the keystore when he
/// wants to resume the process
pub(crate) type EnrollmentHandle = Vec<u8>;

impl E2eiEnrollment {
    pub(crate) async fn stash(self, backend: &MlsCryptoProvider) -> CryptoResult<EnrollmentHandle> {
        // should be enough to prevent collisions
        const HANDLE_SIZE: usize = 32;

        let content = serde_json::to_vec(&self)?;
        let handle = backend.crypto().random_vec(HANDLE_SIZE).map_err(CryptoError::from)?;
        backend
            .key_store()
            .save_e2ei_enrollment(&handle, &content)
            .await
            .map_err(CryptoError::from)?;
        Ok(handle)
    }

    pub(crate) async fn stash_pop(backend: &MlsCryptoProvider, handle: EnrollmentHandle) -> CryptoResult<Self> {
        let content = backend
            .key_store()
            .pop_e2ei_enrollment(&handle)
            .await
            .map_err(CryptoError::from)?;
        Ok(serde_json::from_slice(&content)?)
    }
}

impl CentralContext {
    /// Allows persisting an active enrollment (for example while redirecting the user during OAuth)
    /// in order to resume it later with [CentralContext::e2ei_enrollment_stash_pop]
    ///
    /// # Arguments
    /// * `enrollment` - the enrollment instance to persist
    ///
    /// # Returns
    /// A handle for retrieving the enrollment later on
    pub async fn e2ei_enrollment_stash(&self, enrollment: E2eiEnrollment) -> CryptoResult<EnrollmentHandle> {
        enrollment.stash(&self.mls_provider().await?).await
    }

    /// Fetches the persisted enrollment and deletes it from the keystore
    ///
    /// # Arguments
    /// * `handle` - returned by [CentralContext::e2ei_enrollment_stash]
    pub async fn e2ei_enrollment_stash_pop(&self, handle: EnrollmentHandle) -> CryptoResult<E2eiEnrollment> {
        E2eiEnrollment::stash_pop(&self.mls_provider().await?, handle).await
    }
}

#[cfg(test)]
mod tests {

    use mls_crypto_provider::MlsCryptoProvider;
    use wasm_bindgen_test::*;

    use crate::{
        e2e_identity::id::WireQualifiedClientId,
        e2e_identity::tests::*,
        prelude::{E2eiEnrollment, INITIAL_KEYING_MATERIAL_COUNT},
        test_utils::{x509::X509TestChain, *},
    };

    wasm_bindgen_test_configure!(run_in_browser);

    #[apply(all_cred_cipher)]
    #[wasm_bindgen_test]
    async fn stash_and_pop_should_not_abort_enrollment(case: TestCase) {
        run_test_wo_clients(case.clone(), move |mut cc| {
            Box::pin(async move {
                let x509_test_chain = X509TestChain::init_empty(case.signature_scheme());

                let is_renewal = false;
                let (mut enrollment, cert) = e2ei_enrollment(
                    &mut cc,
                    &case,
                    &x509_test_chain,
                    Some(E2EI_CLIENT_ID_URI),
                    is_renewal,
                    init_enrollment,
                    |e, cc| {
                        Box::pin(async move {
                            let handle = cc.e2ei_enrollment_stash(e).await.unwrap();
                            cc.e2ei_enrollment_stash_pop(handle).await.unwrap()
                        })
                    },
                )
                .await
                .unwrap();

                assert!(cc
                    .context
                    .e2ei_mls_init_only(&mut enrollment, cert, Some(INITIAL_KEYING_MATERIAL_COUNT))
                    .await
                    .is_ok());
            })
        })
        .await
    }

    // this ensures the nominal test does its job
    #[apply(all_cred_cipher)]
    #[wasm_bindgen_test]
    async fn should_fail_when_restoring_invalid(case: TestCase) {
        run_test_wo_clients(case.clone(), move |mut cc| {
            Box::pin(async move {
                let x509_test_chain = X509TestChain::init_empty(case.signature_scheme());

                let is_renewal = false;
                let result = e2ei_enrollment(
                    &mut cc,
                    &case,
                    &x509_test_chain,
                    Some(E2EI_CLIENT_ID_URI),
                    is_renewal,
                    init_enrollment,
                    move |e, _cc| {
                        Box::pin(async move {
                            // this restore recreates a partial enrollment
                            let backend = MlsCryptoProvider::try_new_in_memory("new").await.unwrap();
                            backend.new_transaction().await.unwrap();
                            let client_id = e.client_id.parse::<WireQualifiedClientId>().unwrap();
                            E2eiEnrollment::try_new(
                                client_id.into(),
                                e.display_name,
                                e.handle,
                                e.team,
                                1,
                                &backend,
                                e.ciphersuite,
                                None,
                                #[cfg(not(target_family = "wasm"))]
                                None,
                            )
                            .unwrap()
                        })
                    },
                )
                .await;
                assert!(result.is_err());
            })
        })
        .await
    }
}