Skip to main content

bitwarden_pm/
lib.rs

1#![doc = include_str!("../README.md")]
2
3#[cfg(feature = "bitwarden-license")]
4mod commercial;
5
6/// Dev-only debug-capability tree rooted on the top-level client. Compiled only
7/// under the `debug-capabilities` feature.
8#[cfg(feature = "debug-capabilities")]
9pub mod debug;
10
11use std::sync::Arc;
12
13use bitwarden_auth::AuthClientExt as _;
14use bitwarden_core::{
15    ClientBuilder, FromClient,
16    auth::{ClientManagedTokenHandler, ClientManagedTokens},
17    client::tracing_middleware::ReqwestTracingMiddleware,
18};
19use bitwarden_crypto_cipher_suite::CryptoCipherSuiteClientExt as _;
20#[cfg(not(target_arch = "wasm32"))]
21use bitwarden_crypto_sync_handler::CryptoSyncHandler;
22use bitwarden_crypto_sync_handler::CryptoSyncHandlerClientExt as _;
23use bitwarden_emergency_access::EmergencyAccessClientExt as _;
24use bitwarden_encrypted_migrator::EncryptedMigratorClientExt as _;
25use bitwarden_exporters::ExporterClientExt as _;
26use bitwarden_generators::GeneratorClientsExt as _;
27use bitwarden_importers::ImporterClientExt as _;
28use bitwarden_managed_settings::{ManagedSettingsClient, ManagedSettingsClientExt as _};
29use bitwarden_member_administration::OrganizationUsersManagementClientExt as _;
30use bitwarden_organization_crypto_management::OrganizationCryptoManagementClientExt as _;
31use bitwarden_organization_domains::OrganizationDomainsClientExt as _;
32use bitwarden_organization_invite_link::InviteLinkClientExt as _;
33use bitwarden_organizations::OrganizationsClientExt as _;
34use bitwarden_policies::{PoliciesClientExt as _, PolicySyncHandler};
35use bitwarden_send::{SendClientExt as _, SendSyncHandler, SendSyncHandlerClientExt as _};
36use bitwarden_sync::SyncClientExt as _;
37use bitwarden_unlock::UnlockClientExt as _;
38use bitwarden_user_crypto_management::UserCryptoManagementClientExt;
39use bitwarden_vault::{FolderSyncHandler, VaultClientExt as _};
40
41#[cfg(feature = "uniffi")]
42uniffi::setup_scaffolding!();
43
44/// Re-export subclients for easier access
45pub mod clients {
46    pub use bitwarden_auth::AuthClient;
47    pub use bitwarden_collections::collection_client::CollectionsClient;
48    pub use bitwarden_core::key_management::CryptoClient;
49    pub use bitwarden_crypto_cipher_suite::CryptoCipherSuiteClient;
50    pub use bitwarden_crypto_sync_handler::CryptoSyncHandlerClient;
51    pub use bitwarden_emergency_access::EmergencyAccessClient;
52    pub use bitwarden_encrypted_migrator::EncryptedMigratorClient;
53    pub use bitwarden_exporters::ExporterClient;
54    pub use bitwarden_generators::GeneratorClient;
55    pub use bitwarden_importers::ImporterClient;
56    pub use bitwarden_member_administration::OrganizationUsersManagementClient;
57    pub use bitwarden_organization_crypto_management::OrganizationCryptoManagementClient;
58    pub use bitwarden_organization_domains::OrganizationDomainsClient;
59    pub use bitwarden_organization_invite_link::InviteLinkClient;
60    pub use bitwarden_organizations::OrganizationsClient;
61    pub use bitwarden_policies::PolicyClient;
62    pub use bitwarden_send::{SendClient, SendSyncHandlerClient};
63    pub use bitwarden_sync::SyncClient;
64    pub use bitwarden_unlock::UnlockClient;
65    pub use bitwarden_vault::VaultClient;
66}
67#[cfg(feature = "bitwarden-license")]
68pub use commercial::CommercialPasswordManagerClient;
69
70mod builder;
71pub mod migrations;
72pub use bitwarden_core::{RehydrationError, SaveStateData};
73pub use bitwarden_unlock::{SessionKey, UnlockError, UnlockMethod};
74pub use builder::PasswordManagerClientBuilder;
75
76/// The main entry point for the Bitwarden Password Manager SDK
77#[derive(Clone)]
78pub struct PasswordManagerClient(pub bitwarden_core::Client);
79
80impl PasswordManagerClient {
81    /// Initialize a new instance of the SDK client
82    pub fn new(settings: Option<bitwarden_core::ClientSettings>) -> Self {
83        let mut builder = PasswordManagerClientBuilder::new();
84        if let Some(s) = settings {
85            builder = builder.with_settings(s);
86        }
87        builder.build()
88    }
89
90    /// Returns a [`PasswordManagerClientBuilder`] for constructing a new [`PasswordManagerClient`].
91    pub fn builder() -> PasswordManagerClientBuilder {
92        PasswordManagerClientBuilder::new()
93    }
94
95    /// Initialize a new instance of the SDK client with client-managed tokens and a shared
96    /// managed-settings handle.
97    ///
98    /// `managed_settings` is owned by the host application, which acquires a management profile
99    /// from the operating system's device-management channel and pushes it in. Only its cell is
100    /// captured, so profiles the host pushes later are visible to this client.
101    pub fn new_with_client_tokens(
102        settings: Option<bitwarden_core::ClientSettings>,
103        tokens: Arc<dyn ClientManagedTokens>,
104        managed_settings: &ManagedSettingsClient,
105    ) -> Self {
106        let mut builder = ClientBuilder::new()
107            .with_token_handler(ClientManagedTokenHandler::new(tokens))
108            .with_middleware(vec![Arc::new(ReqwestTracingMiddleware)])
109            .with_managed_profile(managed_settings.cell());
110        if let Some(s) = settings {
111            builder = builder.with_settings(s);
112        }
113        Self(builder.build())
114    }
115
116    /// Initialize a new instance of the SDK client with SDK managed state and sync handlers
117    /// registered
118    ///
119    /// This will eventually replace `new` when the SDK fully owns sync on all clients.
120    pub fn new_with_sync(settings: Option<bitwarden_core::ClientSettings>) -> Self {
121        let client = Self::new(settings);
122
123        let sync = client.sync();
124        #[cfg(not(target_arch = "wasm32"))]
125        sync.register_sync_handler(Arc::new(CryptoSyncHandler::new(client.0.clone())));
126        sync.register_sync_handler(Arc::new(FolderSyncHandler::from_client(&client.0)));
127        sync.register_sync_handler(Arc::new(SendSyncHandler::from_client(&client.0)));
128        sync.register_sync_handler(Arc::new(PolicySyncHandler::from_client(&client.0)));
129
130        // TODO: Add more sync handlers here!
131
132        client
133    }
134
135    /// Platform operations
136    pub fn platform(&self) -> bitwarden_core::platform::PlatformClient {
137        self.0.platform()
138    }
139
140    /// Administrator-enforced settings operations.
141    pub fn managed_settings(&self) -> ManagedSettingsClient {
142        self.0.managed_settings()
143    }
144
145    /// Auth operations
146    pub fn auth(&self) -> bitwarden_auth::AuthClient {
147        self.0.auth_new()
148    }
149
150    /// Bitwarden licensed operations
151    #[cfg(feature = "bitwarden-license")]
152    pub fn commercial(&self) -> CommercialPasswordManagerClient {
153        CommercialPasswordManagerClient::new(self.0.clone())
154    }
155
156    /// Crypto operations
157    pub fn crypto(&self) -> bitwarden_core::key_management::CryptoClient {
158        self.0.crypto()
159    }
160
161    /// Crypto cipher suite operations
162    pub fn crypto_cipher_suite(&self) -> bitwarden_crypto_cipher_suite::CryptoCipherSuiteClient {
163        self.0.crypto_cipher_suite()
164    }
165
166    /// Feature flag operations
167    pub fn flags(&self) -> bitwarden_core::FlagsClient {
168        self.0.flags()
169    }
170
171    /// Key management operations that run on every sync
172    pub fn crypto_sync_handler(&self) -> bitwarden_crypto_sync_handler::CryptoSyncHandlerClient {
173        self.0.crypto_sync_handler()
174    }
175
176    /// Operations that manage the cryptographic machinery of a user account, including key-rotation
177    pub fn user_crypto_management(
178        &self,
179    ) -> bitwarden_user_crypto_management::UserCryptoManagementClient {
180        self.0.user_crypto_management()
181    }
182
183    /// Operations that manage the cryptographic state of the user's organizations
184    pub fn organization_crypto_management(
185        &self,
186    ) -> bitwarden_organization_crypto_management::OrganizationCryptoManagementClient {
187        self.0.organization_crypto_management()
188    }
189
190    /// Vault item operations
191    pub fn vault(&self) -> bitwarden_vault::VaultClient {
192        self.0.vault()
193    }
194
195    /// Collection related operations.
196    ///
197    /// This is registered directly on the top-level client in addition to being nested under
198    /// [`vault`](Self::vault); once all consumers have migrated to this accessor, the nested one
199    /// will be removed.
200    pub fn collections(&self) -> bitwarden_collections::collection_client::CollectionsClient {
201        bitwarden_collections::collection_client::CollectionsClient::from_client(&self.0)
202    }
203
204    /// Exporter operations
205    pub fn exporters(&self) -> bitwarden_exporters::ExporterClient {
206        self.0.exporters()
207    }
208
209    /// Importer operations
210    pub fn importers(&self) -> bitwarden_importers::ImporterClient {
211        self.0.importers()
212    }
213
214    /// Generator operations
215    pub fn generator(&self) -> bitwarden_generators::GeneratorClient {
216        self.0.generator()
217    }
218
219    /// Send operations
220    pub fn sends(&self) -> bitwarden_send::SendClient {
221        self.0.sends()
222    }
223
224    /// Send sync handler operations
225    pub fn send_sync_handler(&self) -> bitwarden_send::SendSyncHandlerClient {
226        self.0.send_sync_handler()
227    }
228
229    /// Policy operations
230    pub fn policies(&self) -> bitwarden_policies::PolicyClient {
231        self.0.policies()
232    }
233
234    /// Operations on the current user's organizations
235    pub fn organizations(&self) -> bitwarden_organizations::OrganizationsClient {
236        self.0.organizations()
237    }
238
239    /// Organization invite link operations
240    pub fn invite_link(&self) -> bitwarden_organization_invite_link::InviteLinkClient {
241        self.0.invite_link()
242    }
243
244    /// Organization verified domain operations.
245    pub fn organization_domains(
246        &self,
247    ) -> bitwarden_organization_domains::OrganizationDomainsClient {
248        self.0.organization_domains()
249    }
250
251    /// Emergency access operations, performed as the grantee.
252    pub fn emergency_access(&self) -> bitwarden_emergency_access::EmergencyAccessClient {
253        self.0.emergency_access()
254    }
255
256    /// Organization member administration operations.
257    pub fn organization_users_management(
258        &self,
259    ) -> bitwarden_member_administration::OrganizationUsersManagementClient {
260        self.0.organization_users_management()
261    }
262
263    /// Encrypted migrations that bring the account's keys and encrypted data to the current format.
264    pub fn encrypted_migrator(&self) -> bitwarden_encrypted_migrator::EncryptedMigratorClient {
265        self.0.encrypted_migrator()
266    }
267
268    /// Sync operations
269    pub fn sync(&self) -> bitwarden_sync::SyncClient {
270        self.0.sync()
271    }
272
273    /// Returns true when the user's symmetric key is loaded into the key store.
274    pub fn is_unlocked(&self) -> bool {
275        use bitwarden_core::key_management::SymmetricKeySlotId;
276        self.0
277            .internal
278            .get_key_store()
279            .context()
280            .has_symmetric_key(SymmetricKeySlotId::User)
281    }
282
283    /// Unlock operations
284    pub fn unlock(&self) -> bitwarden_unlock::UnlockClient {
285        self.0.unlock()
286    }
287
288    /// Write rehydration state to a StateRegistry.
289    ///
290    /// Delegates to [`Client::save_to_state`](bitwarden_core::Client::save_to_state).
291    pub async fn save_to_state(
292        data: SaveStateData,
293        reg: &bitwarden_state::registry::StateRegistry,
294    ) -> Result<(), RehydrationError> {
295        bitwarden_core::Client::save_to_state(data, reg).await
296    }
297
298    /// Reconstruct a locked PasswordManagerClient from a populated StateRegistry.
299    ///
300    /// Delegates to [`Client::load_from_state`](bitwarden_core::Client::load_from_state).
301    pub async fn load_from_state(
302        token_handler: std::sync::Arc<dyn bitwarden_core::auth::auth_tokens::TokenHandler>,
303        registry: bitwarden_state::registry::StateRegistry,
304    ) -> Result<Self, RehydrationError> {
305        let client = bitwarden_core::Client::load_from_state(token_handler, registry).await?;
306        Ok(PasswordManagerClient(client))
307    }
308}
309
310#[cfg(test)]
311mod tests {
312    use std::sync::Arc;
313
314    use super::*;
315
316    #[test]
317    fn new_with_server_communication_config_constructs() {
318        struct MockCookieProvider;
319
320        #[async_trait::async_trait]
321        impl bitwarden_server_communication_config::CookieProvider for MockCookieProvider {
322            async fn cookies(&self, _hostname: &str) -> Vec<(String, String)> {
323                vec![]
324            }
325
326            async fn acquire_cookie(
327                &self,
328                _hostname: &str,
329            ) -> Result<(), bitwarden_server_communication_config::AcquireCookieError> {
330                Ok(())
331            }
332
333            async fn needs_bootstrap(&self, _hostname: &str) -> bool {
334                false
335            }
336        }
337
338        let _client = PasswordManagerClient::builder()
339            .with_server_communication_config(Arc::new(MockCookieProvider))
340            .build();
341    }
342}