Skip to main content

bitwarden_auth/
auth_client.rs

1use bitwarden_core::Client;
2
3use crate::{login::LoginClient, registration::RegistrationClient, send_access::SendAccessClient};
4
5/// Subclient containing auth functionality.
6#[derive(Clone)]
7#[bitwarden_ffi::wasm_object]
8pub struct AuthClient {
9    // TODO: The AuthClient should probably not contain the whole bitwarden-core client.
10    // Instead, it should contain the ApiConfigurations and Tokens struct to do API requests and
11    // handle token renewals, and those structs should be shared between core and auth.
12    pub(crate) client: Client,
13}
14
15impl AuthClient {
16    /// Constructs a new `AuthClient` with the given `Client`.
17    pub fn new(client: Client) -> Self {
18        Self { client }
19    }
20}
21
22#[bitwarden_ffi::wasm_export]
23impl AuthClient {
24    /// Client for login functionality
25    pub fn login(&self) -> LoginClient {
26        LoginClient::new(self.client.clone())
27    }
28
29    /// Client for send access functionality
30    pub fn send_access(&self) -> SendAccessClient {
31        SendAccessClient::new(self.client.clone())
32    }
33
34    /// Client for initializing user account cryptography and unlock methods after JIT provisioning
35    pub fn registration(&self) -> RegistrationClient {
36        RegistrationClient::new(self.client.clone())
37    }
38}
39
40/// Extension trait for `Client` to provide access to the `AuthClient`.
41pub trait AuthClientExt {
42    /// Creates a new `AuthClient` instance.
43    fn auth_new(&self) -> AuthClient;
44}
45
46impl AuthClientExt for Client {
47    fn auth_new(&self) -> AuthClient {
48        AuthClient {
49            client: self.clone(),
50        }
51    }
52}
53
54#[cfg(test)]
55mod tests {
56    use std::sync::Arc;
57
58    use super::*;
59
60    #[test]
61    fn login_client_shares_the_auth_clients_backing_client() {
62        let client = Client::new(None);
63        let auth_client = AuthClient::new(client.clone());
64
65        let login_client = auth_client.login();
66
67        assert!(
68            Arc::ptr_eq(&client.internal, &login_client.client.internal),
69            "LoginClient must reuse the same Client instance backing the AuthClient it came \
70             from, otherwise login requests can target a different server than the rest of the \
71             SDK"
72        );
73    }
74}