bitwarden_core/client/
client.rs

1use std::sync::{Arc, OnceLock, RwLock};
2
3use bitwarden_crypto::KeyStore;
4#[cfg(feature = "internal")]
5use bitwarden_state::registry::StateRegistry;
6use reqwest::header::{self, HeaderValue};
7
8use super::internal::InternalClient;
9#[cfg(feature = "internal")]
10use crate::client::flags::Flags;
11use crate::client::{
12    client_settings::{ClientName, ClientSettings},
13    internal::{ApiConfigurations, ClientManagedTokens, SdkManagedTokens, Tokens},
14};
15
16/// The main struct to interact with the Bitwarden SDK.
17#[derive(Debug, Clone)]
18pub struct Client {
19    // Important: The [`Client`] struct requires its `Clone` implementation to return an owned
20    // reference to the same instance. This is required to properly use the FFI API, where we can't
21    // just use normal Rust references effectively. For this to happen, any mutable state needs
22    // to be behind an Arc, ideally as part of the existing [`InternalClient`] struct.
23    #[doc(hidden)]
24    pub internal: Arc<InternalClient>,
25}
26
27impl Client {
28    /// Create a new Bitwarden client with SDK-managed tokens.
29    pub fn new(settings: Option<ClientSettings>) -> Self {
30        Self::new_internal(settings, Tokens::SdkManaged(SdkManagedTokens::default()))
31    }
32
33    /// Create a new Bitwarden client with client-managed tokens.
34    pub fn new_with_client_tokens(
35        settings: Option<ClientSettings>,
36        tokens: Arc<dyn ClientManagedTokens>,
37    ) -> Self {
38        Self::new_internal(settings, Tokens::ClientManaged(tokens))
39    }
40
41    fn new_internal(settings_input: Option<ClientSettings>, tokens: Tokens) -> Self {
42        let settings = settings_input.unwrap_or_default();
43
44        let external_http_client = new_http_client_builder()
45            .build()
46            .expect("External HTTP Client build should not fail");
47
48        let headers = build_default_headers(&settings);
49
50        let bw_http_client = new_http_client_builder()
51            .default_headers(headers)
52            .build()
53            .expect("Bw HTTP Client build should not fail");
54
55        let identity = bitwarden_api_identity::apis::configuration::Configuration {
56            base_path: settings.identity_url,
57            user_agent: Some(settings.user_agent.clone()),
58            client: bw_http_client.clone(),
59            basic_auth: None,
60            oauth_access_token: None,
61            bearer_access_token: None,
62            api_key: None,
63        };
64
65        let api = bitwarden_api_api::apis::configuration::Configuration {
66            base_path: settings.api_url,
67            user_agent: Some(settings.user_agent),
68            client: bw_http_client,
69            basic_auth: None,
70            oauth_access_token: None,
71            bearer_access_token: None,
72            api_key: None,
73        };
74
75        Self {
76            internal: Arc::new(InternalClient {
77                user_id: OnceLock::new(),
78                tokens: RwLock::new(tokens),
79                login_method: RwLock::new(None),
80                #[cfg(feature = "internal")]
81                flags: RwLock::new(Flags::default()),
82                __api_configurations: RwLock::new(ApiConfigurations::new(
83                    identity,
84                    api,
85                    settings.device_type,
86                )),
87                external_http_client,
88                key_store: KeyStore::default(),
89                #[cfg(feature = "internal")]
90                security_state: RwLock::new(None),
91                #[cfg(feature = "internal")]
92                repository_map: StateRegistry::new(),
93            }),
94        }
95    }
96}
97
98fn new_http_client_builder() -> reqwest::ClientBuilder {
99    #[allow(unused_mut)]
100    let mut client_builder = reqwest::Client::builder();
101
102    #[cfg(not(target_arch = "wasm32"))]
103    {
104        use rustls::ClientConfig;
105        use rustls_platform_verifier::ConfigVerifierExt;
106        client_builder = client_builder.use_preconfigured_tls(
107            ClientConfig::with_platform_verifier().expect("Failed to create platform verifier"),
108        );
109
110        // Enforce HTTPS for all requests in non-debug builds
111        #[cfg(not(debug_assertions))]
112        {
113            client_builder = client_builder.https_only(true);
114        }
115    }
116
117    client_builder
118}
119
120/// Build default headers for Bitwarden HttpClient
121fn build_default_headers(settings: &ClientSettings) -> header::HeaderMap {
122    let mut headers = header::HeaderMap::new();
123
124    // Handle optional headers
125
126    if let Some(device_identifier) = &settings.device_identifier {
127        headers.append(
128            "Device-Identifier",
129            HeaderValue::from_str(device_identifier)
130                .expect("Device identifier should be a valid header value"),
131        );
132    }
133
134    if let Some(client_type) = Into::<Option<ClientName>>::into(settings.device_type) {
135        headers.append(
136            "Bitwarden-Client-Name",
137            HeaderValue::from_str(&client_type.to_string())
138                .expect("All ASCII strings are valid header values"),
139        );
140    }
141
142    if let Some(version) = &settings.bitwarden_client_version {
143        headers.append(
144            "Bitwarden-Client-Version",
145            HeaderValue::from_str(version).expect("Version should be a valid header value"),
146        );
147    }
148
149    if let Some(package_type) = &settings.bitwarden_package_type {
150        headers.append(
151            "Bitwarden-Package-Type",
152            HeaderValue::from_str(package_type)
153                .expect("Package type should be a valid header value"),
154        );
155    }
156
157    // Handle required headers
158
159    headers.append(
160        "Device-Type",
161        HeaderValue::from_str(&(settings.device_type as u8).to_string())
162            .expect("All numbers are valid ASCII"),
163    );
164
165    // TODO: PM-29938 - Since we now add this header always, we need to remove this from the
166    // auto-generated code
167    headers.append(
168        reqwest::header::USER_AGENT,
169        HeaderValue::from_str(&settings.user_agent)
170            .expect("User agent should be a valid header value"),
171    );
172
173    headers
174}