Skip to main content

bitwarden_core/global/
global_client.rs

1use std::sync::Arc;
2
3use bitwarden_api_base::new_http_client_builder;
4
5use crate::{client::build_default_headers, global::GlobalInternalClient};
6
7/// The entry point for unauthenticated SDK operations.
8///
9/// `GlobalClient` internally contains an [`Arc`] so is cheap to clone.
10///
11/// Headers are sourced from the process-wide
12/// [`crate::HostPlatformInfo`] singleton, which must be initialized via
13/// [`crate::init_host_platform_info`] before constructing a `GlobalClient`.
14#[derive(Clone)]
15pub struct GlobalClient {
16    internal: Arc<GlobalInternalClient>,
17}
18
19impl GlobalClient {
20    /// Build a `GlobalClient` using the process-wide
21    /// [`crate::HostPlatformInfo`].
22    ///
23    /// # Panics
24    /// Panics if [`crate::init_host_platform_info`] has not been called.
25    pub fn new() -> Self {
26        let info = crate::client::get_host_platform_info();
27        let http_client = new_http_client_builder()
28            .default_headers(build_default_headers(info))
29            .build()
30            .expect("Global HTTP Client build should not fail")
31            .into();
32        Self {
33            internal: Arc::new(GlobalInternalClient { http_client }),
34        }
35    }
36
37    /// Build an API client targeting `base_url`.
38    pub fn make_api_client(&self, base_url: String) -> bitwarden_api_api::apis::ApiClient {
39        self.internal.make_api_client(base_url)
40    }
41
42    /// Build an identity client targeting `base_url`.
43    pub fn make_identity_client(
44        &self,
45        base_url: String,
46    ) -> bitwarden_api_identity::apis::ApiClient {
47        self.internal.make_identity_client(base_url)
48    }
49}
50
51impl Default for GlobalClient {
52    fn default() -> Self {
53        Self::new()
54    }
55}
56
57#[cfg(test)]
58mod tests {
59    use reqwest_middleware::ClientBuilder;
60
61    use super::*;
62
63    fn dummy_client() -> GlobalClient {
64        GlobalClient {
65            internal: Arc::new(GlobalInternalClient {
66                http_client: ClientBuilder::new(bitwarden_api_base::new_http_client()).build(),
67            }),
68        }
69    }
70
71    #[test]
72    fn clone_shares_internal_state() {
73        let original = dummy_client();
74        let cloned = original.clone();
75        assert!(Arc::ptr_eq(&original.internal, &cloned.internal));
76    }
77}