bitwarden_uniffi/platform/
fido2.rs

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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
use std::sync::Arc;

use bitwarden::{
    error::Error,
    fido::{
        CheckUserOptions, ClientData, ClientFido2Ext, Fido2CallbackError as BitFido2CallbackError,
        GetAssertionRequest, GetAssertionResult, MakeCredentialRequest, MakeCredentialResult,
        PublicKeyCredentialAuthenticatorAssertionResponse,
        PublicKeyCredentialAuthenticatorAttestationResponse, PublicKeyCredentialRpEntity,
        PublicKeyCredentialUserEntity,
    },
    vault::{Cipher, CipherView, Fido2CredentialNewView},
};
use bitwarden_fido::{Fido2CredentialAutofillView, Origin};

use crate::{error::Result, Client};

#[derive(uniffi::Object)]
pub struct ClientFido2(pub(crate) Arc<Client>);

#[uniffi::export]
impl ClientFido2 {
    pub fn authenticator(
        self: Arc<Self>,
        user_interface: Arc<dyn Fido2UserInterface>,
        credential_store: Arc<dyn Fido2CredentialStore>,
    ) -> Arc<ClientFido2Authenticator> {
        Arc::new(ClientFido2Authenticator(
            self.0.clone(),
            user_interface,
            credential_store,
        ))
    }

    pub fn client(
        self: Arc<Self>,
        user_interface: Arc<dyn Fido2UserInterface>,
        credential_store: Arc<dyn Fido2CredentialStore>,
    ) -> Arc<ClientFido2Client> {
        Arc::new(ClientFido2Client(ClientFido2Authenticator(
            self.0.clone(),
            user_interface,
            credential_store,
        )))
    }

    pub fn decrypt_fido2_autofill_credentials(
        self: Arc<Self>,
        cipher_view: CipherView,
    ) -> Result<Vec<Fido2CredentialAutofillView>> {
        let result = self
            .0
             .0
            .fido2()
            .decrypt_fido2_autofill_credentials(cipher_view)
            .map_err(Error::DecryptFido2AutofillCredentialsError)?;

        Ok(result)
    }
}

#[derive(uniffi::Object)]
pub struct ClientFido2Authenticator(
    pub(crate) Arc<Client>,
    pub(crate) Arc<dyn Fido2UserInterface>,
    pub(crate) Arc<dyn Fido2CredentialStore>,
);

#[uniffi::export]
impl ClientFido2Authenticator {
    pub async fn make_credential(
        &self,
        request: MakeCredentialRequest,
    ) -> Result<MakeCredentialResult> {
        let fido2 = self.0 .0.fido2();
        let ui = UniffiTraitBridge(self.1.as_ref());
        let cs = UniffiTraitBridge(self.2.as_ref());
        let mut auth = fido2.create_authenticator(&ui, &cs);

        let result = auth
            .make_credential(request)
            .await
            .map_err(Error::MakeCredential)?;
        Ok(result)
    }

    pub async fn get_assertion(&self, request: GetAssertionRequest) -> Result<GetAssertionResult> {
        let fido2 = self.0 .0.fido2();
        let ui = UniffiTraitBridge(self.1.as_ref());
        let cs = UniffiTraitBridge(self.2.as_ref());
        let mut auth = fido2.create_authenticator(&ui, &cs);

        let result = auth
            .get_assertion(request)
            .await
            .map_err(Error::GetAssertion)?;
        Ok(result)
    }

    pub async fn silently_discover_credentials(
        &self,
        rp_id: String,
    ) -> Result<Vec<Fido2CredentialAutofillView>> {
        let fido2 = self.0 .0.fido2();

        let ui = UniffiTraitBridge(self.1.as_ref());
        let cs = UniffiTraitBridge(self.2.as_ref());
        let mut auth = fido2.create_authenticator(&ui, &cs);

        let result = auth
            .silently_discover_credentials(rp_id)
            .await
            .map_err(Error::SilentlyDiscoverCredentials)?;
        Ok(result)
    }

    pub async fn credentials_for_autofill(&self) -> Result<Vec<Fido2CredentialAutofillView>> {
        let fido2 = self.0 .0.fido2();
        let ui = UniffiTraitBridge(self.1.as_ref());
        let cs = UniffiTraitBridge(self.2.as_ref());
        let mut auth = fido2.create_authenticator(&ui, &cs);

        let result = auth
            .credentials_for_autofill()
            .await
            .map_err(Error::CredentialsForAutofillError)?;
        Ok(result)
    }
}

#[derive(uniffi::Object)]
pub struct ClientFido2Client(pub(crate) ClientFido2Authenticator);

#[uniffi::export]
impl ClientFido2Client {
    pub async fn register(
        &self,
        origin: Origin,
        request: String,
        client_data: ClientData,
    ) -> Result<PublicKeyCredentialAuthenticatorAttestationResponse> {
        let fido2 = self.0 .0 .0.fido2();
        let ui = UniffiTraitBridge(self.0 .1.as_ref());
        let cs = UniffiTraitBridge(self.0 .2.as_ref());
        let mut client = fido2.create_client(&ui, &cs);

        let result = client
            .register(origin, request, client_data)
            .await
            .map_err(Error::Fido2Client)?;
        Ok(result)
    }

    pub async fn authenticate(
        &self,
        origin: Origin,
        request: String,
        client_data: ClientData,
    ) -> Result<PublicKeyCredentialAuthenticatorAssertionResponse> {
        let fido2 = self.0 .0 .0.fido2();
        let ui = UniffiTraitBridge(self.0 .1.as_ref());
        let cs = UniffiTraitBridge(self.0 .2.as_ref());
        let mut client = fido2.create_client(&ui, &cs);

        let result = client
            .authenticate(origin, request, client_data)
            .await
            .map_err(Error::Fido2Client)?;
        Ok(result)
    }
}

// Note that uniffi doesn't support external traits for now it seems, so we have to duplicate them
// here.

#[allow(dead_code)]
#[derive(uniffi::Record)]
pub struct CheckUserResult {
    user_present: bool,
    user_verified: bool,
}

impl From<CheckUserResult> for bitwarden::fido::CheckUserResult {
    fn from(val: CheckUserResult) -> Self {
        Self {
            user_present: val.user_present,
            user_verified: val.user_verified,
        }
    }
}

#[allow(dead_code)]
#[derive(uniffi::Record)]
pub struct CheckUserAndPickCredentialForCreationResult {
    cipher: CipherViewWrapper,
    check_user_result: CheckUserResult,
}

#[derive(Debug, thiserror::Error, uniffi::Error)]
pub enum Fido2CallbackError {
    #[error("The operation requires user interaction")]
    UserInterfaceRequired,

    #[error("The operation was cancelled by the user")]
    OperationCancelled,

    #[error("Unknown error: {reason}")]
    Unknown { reason: String },
}

// Need to implement this From<> impl in order to handle unexpected callback errors.  See the
// following page in the Uniffi user guide:
// <https://mozilla.github.io/uniffi-rs/foreign_traits.html#error-handling>
impl From<uniffi::UnexpectedUniFFICallbackError> for Fido2CallbackError {
    fn from(e: uniffi::UnexpectedUniFFICallbackError) -> Self {
        Self::Unknown { reason: e.reason }
    }
}

impl From<Fido2CallbackError> for BitFido2CallbackError {
    fn from(val: Fido2CallbackError) -> Self {
        match val {
            Fido2CallbackError::UserInterfaceRequired => Self::UserInterfaceRequired,
            Fido2CallbackError::OperationCancelled => Self::OperationCancelled,
            Fido2CallbackError::Unknown { reason } => Self::Unknown(reason),
        }
    }
}

#[uniffi::export(with_foreign)]
#[async_trait::async_trait]
pub trait Fido2UserInterface: Send + Sync {
    async fn check_user(
        &self,
        options: CheckUserOptions,
        hint: UIHint,
    ) -> Result<CheckUserResult, Fido2CallbackError>;
    async fn pick_credential_for_authentication(
        &self,
        available_credentials: Vec<CipherView>,
    ) -> Result<CipherViewWrapper, Fido2CallbackError>;
    async fn check_user_and_pick_credential_for_creation(
        &self,
        options: CheckUserOptions,
        new_credential: Fido2CredentialNewView,
    ) -> Result<CheckUserAndPickCredentialForCreationResult, Fido2CallbackError>;
    async fn is_verification_enabled(&self) -> bool;
}

#[uniffi::export(with_foreign)]
#[async_trait::async_trait]
pub trait Fido2CredentialStore: Send + Sync {
    async fn find_credentials(
        &self,
        ids: Option<Vec<Vec<u8>>>,
        rip_id: String,
    ) -> Result<Vec<CipherView>, Fido2CallbackError>;

    async fn all_credentials(&self) -> Result<Vec<CipherView>, Fido2CallbackError>;

    async fn save_credential(&self, cred: Cipher) -> Result<(), Fido2CallbackError>;
}

// Because uniffi doesn't support external traits, we have to make a copy of the trait here.
// Ideally we'd want to implement the original trait for every item that implements our local copy,
// but the orphan rules don't allow us to blanket implement an external trait. So we have to wrap
// the trait in a newtype and implement the trait for the newtype.
struct UniffiTraitBridge<T>(T);

#[async_trait::async_trait]
impl bitwarden::fido::Fido2CredentialStore for UniffiTraitBridge<&dyn Fido2CredentialStore> {
    async fn find_credentials(
        &self,
        ids: Option<Vec<Vec<u8>>>,
        rip_id: String,
    ) -> Result<Vec<CipherView>, BitFido2CallbackError> {
        self.0
            .find_credentials(ids, rip_id)
            .await
            .map_err(Into::into)
    }

    async fn all_credentials(&self) -> Result<Vec<CipherView>, BitFido2CallbackError> {
        self.0.all_credentials().await.map_err(Into::into)
    }

    async fn save_credential(&self, cred: Cipher) -> Result<(), BitFido2CallbackError> {
        self.0.save_credential(cred).await.map_err(Into::into)
    }
}

// Uniffi seems to have trouble generating code for Android when a local trait returns a type from
// an external crate. If the type is small we can just copy it over and convert back and forth, but
// Cipher is too big for that to be practical. So we wrap it in a newtype, which is local to the
// trait and so we can sidestep the Uniffi issue
#[derive(uniffi::Record)]
pub struct CipherViewWrapper {
    cipher: CipherView,
}

#[derive(uniffi::Enum)]
pub enum UIHint {
    InformExcludedCredentialFound(CipherView),
    InformNoCredentialsFound,
    RequestNewCredential(PublicKeyCredentialUserEntity, PublicKeyCredentialRpEntity),
    RequestExistingCredential(CipherView),
}

impl From<bitwarden::fido::UIHint<'_, CipherView>> for UIHint {
    fn from(hint: bitwarden::fido::UIHint<'_, CipherView>) -> Self {
        use bitwarden::fido::UIHint as BWUIHint;
        match hint {
            BWUIHint::InformExcludedCredentialFound(cipher) => {
                UIHint::InformExcludedCredentialFound(cipher.clone())
            }
            BWUIHint::InformNoCredentialsFound => UIHint::InformNoCredentialsFound,
            BWUIHint::RequestNewCredential(user, rp) => UIHint::RequestNewCredential(
                PublicKeyCredentialUserEntity {
                    id: user.id.clone().into(),
                    name: user.name.clone().unwrap_or_default(),
                    display_name: user.display_name.clone().unwrap_or_default(),
                },
                PublicKeyCredentialRpEntity {
                    id: rp.id.clone(),
                    name: rp.name.clone(),
                },
            ),
            BWUIHint::RequestExistingCredential(cipher) => {
                UIHint::RequestExistingCredential(cipher.clone())
            }
        }
    }
}

#[async_trait::async_trait]
impl bitwarden::fido::Fido2UserInterface for UniffiTraitBridge<&dyn Fido2UserInterface> {
    async fn check_user<'a>(
        &self,
        options: CheckUserOptions,
        hint: bitwarden::fido::UIHint<'a, CipherView>,
    ) -> Result<bitwarden::fido::CheckUserResult, BitFido2CallbackError> {
        self.0
            .check_user(options.clone(), hint.into())
            .await
            .map(Into::into)
            .map_err(Into::into)
    }
    async fn pick_credential_for_authentication(
        &self,
        available_credentials: Vec<CipherView>,
    ) -> Result<CipherView, BitFido2CallbackError> {
        self.0
            .pick_credential_for_authentication(available_credentials)
            .await
            .map(|v| v.cipher)
            .map_err(Into::into)
    }
    async fn check_user_and_pick_credential_for_creation(
        &self,
        options: CheckUserOptions,
        new_credential: Fido2CredentialNewView,
    ) -> Result<(CipherView, bitwarden::fido::CheckUserResult), BitFido2CallbackError> {
        self.0
            .check_user_and_pick_credential_for_creation(options, new_credential)
            .await
            .map(|v| (v.cipher.cipher, v.check_user_result.into()))
            .map_err(Into::into)
    }
    async fn is_verification_enabled(&self) -> bool {
        self.0.is_verification_enabled().await
    }
}