Skip to main content

bitwarden_uniffi/
lib.rs

1#![doc = include_str!("../README.md")]
2
3uniffi::setup_scaffolding!();
4
5use std::sync::{Arc, Once};
6
7use auth::AuthClient;
8use bitwarden_core::{ClientCertificate, ClientSettings, auth::ClientManagedTokens};
9
10#[allow(missing_docs)]
11pub mod auth;
12#[allow(missing_docs)]
13pub mod crypto;
14/// Dev-only debug-capability tree, exposed to the mobile bindings. Compiled only
15/// under the `debug-capabilities` feature; never ship in production.
16#[cfg(feature = "debug-capabilities")]
17pub mod debug;
18#[allow(missing_docs)]
19pub mod error;
20mod log_callback;
21#[allow(missing_docs)]
22pub mod managed_settings;
23#[allow(missing_docs)]
24pub mod platform;
25#[allow(missing_docs)]
26pub mod policies;
27#[allow(missing_docs)]
28pub mod tools;
29mod uniffi_support;
30#[allow(missing_docs)]
31pub mod vault;
32
33#[cfg(target_os = "android")]
34mod android_support;
35
36use crypto::CryptoClient;
37use error::{Error, Result};
38pub use log_callback::LogCallback;
39pub use managed_settings::ManagedSettingsBindingClient;
40use platform::PlatformClient;
41pub use platform::{
42    AcquiredCookie, BootstrapConfig, ServerCommunicationConfig, ServerCommunicationConfigClient,
43    ServerCommunicationConfigRepository, SsoCookieVendorConfig,
44};
45use tools::{ExporterClient, GeneratorClients, ImporterClient, SendClient, SshClient};
46use vault::VaultClient;
47
48#[allow(missing_docs)]
49#[derive(uniffi::Object)]
50pub struct Client(pub(crate) bitwarden_pm::PasswordManagerClient);
51
52#[uniffi::export(async_runtime = "tokio")]
53impl Client {
54    /// Initialize a new instance of the SDK client
55    ///
56    /// `managed_settings` is the host-owned handle onto the operating system's Unified Endpoint
57    /// Management profile. The client shares its profile, so profiles pushed after construction
58    /// are visible here. Pass a fresh `ManagedSettingsBindingClient` where the host has no UEM
59    /// source.
60    ///
61    /// `client_certificate` is presented when the Bitwarden server requests client authentication
62    /// (mTLS).
63    #[uniffi::constructor(default(client_certificate = None))]
64    pub fn new(
65        token_provider: Arc<dyn ClientManagedTokens>,
66        settings: Option<ClientSettings>,
67        managed_settings: Arc<ManagedSettingsBindingClient>,
68        client_certificate: Option<Arc<ClientCertificate>>,
69    ) -> Self {
70        init_logger(None, None, true);
71        setup_error_converter();
72
73        #[cfg(target_os = "android")]
74        android_support::init();
75
76        Self(
77            bitwarden_pm::PasswordManagerClient::new_with_client_tokens_and_certificate(
78                settings,
79                token_provider,
80                &managed_settings.0,
81                client_certificate,
82            ),
83        )
84    }
85
86    /// Crypto operations
87    pub fn crypto(&self) -> CryptoClient {
88        CryptoClient(self.0.crypto())
89    }
90
91    /// Returns the key-management state bridge client used to register a
92    /// host-supplied storage implementation.
93    pub fn km_state_bridge(
94        &self,
95    ) -> bitwarden_core::key_management::state_bridge::StateBridgeClient {
96        self.0.0.km_state_bridge()
97    }
98
99    /// Returns the user-crypto-management sub-client (PIN settings, key rotation, etc).
100    pub fn user_crypto_management(
101        &self,
102    ) -> bitwarden_user_crypto_management::UserCryptoManagementClient {
103        self.0.user_crypto_management()
104    }
105
106    /// Unlock related operations.
107    pub fn unlock(&self) -> bitwarden_unlock::UnlockClient {
108        self.0.unlock()
109    }
110
111    /// Key management operations that run on every sync.
112    pub fn crypto_sync_handler(&self) -> bitwarden_crypto_sync_handler::CryptoSyncHandlerClient {
113        self.0.crypto_sync_handler()
114    }
115
116    /// Vault item operations
117    pub fn vault(&self) -> VaultClient {
118        VaultClient(self.0.vault())
119    }
120
121    /// Collection related operations.
122    ///
123    /// This is registered directly on the top-level client in addition to being nested under
124    /// [`vault`](Self::vault). Once mobile clients have migrated to this accessor, the nested one
125    /// will be removed.
126    pub fn collections(&self) -> vault::collections::CollectionsClient {
127        vault::collections::CollectionsClient(self.0.collections())
128    }
129
130    #[allow(missing_docs)]
131    pub fn platform(&self) -> PlatformClient {
132        PlatformClient(self.0.0.clone())
133    }
134
135    /// Generator operations
136    pub fn generators(&self) -> GeneratorClients {
137        GeneratorClients(self.0.generator())
138    }
139
140    /// Exporters
141    pub fn exporters(&self) -> ExporterClient {
142        ExporterClient(self.0.exporters())
143    }
144
145    /// Importers
146    pub fn importers(&self) -> ImporterClient {
147        ImporterClient(self.0.importers())
148    }
149
150    /// Sends operations
151    pub fn sends(&self) -> SendClient {
152        SendClient(self.0.sends())
153    }
154
155    /// Send sync handler operations
156    pub fn send_sync_handler(&self) -> bitwarden_send::SendSyncHandlerClient {
157        self.0.send_sync_handler()
158    }
159
160    /// SSH operations
161    pub fn ssh(&self) -> SshClient {
162        SshClient()
163    }
164
165    /// Random-number generation operations
166    pub fn random(&self) -> bitwarden_random::SdkRandomNumberClient {
167        bitwarden_random::SdkRandomNumberClient::new()
168    }
169
170    /// Auth operations
171    pub fn auth(&self) -> AuthClient {
172        AuthClient(self.0.0.clone())
173    }
174
175    /// Whether the client is in Gov Mode.
176    pub fn gov_mode(&self) -> bool {
177        self.0.0.gov_mode()
178    }
179
180    /// Policy operations
181    pub fn policies(&self) -> policies::PoliciesClient {
182        use bitwarden_policies::PoliciesClientExt;
183        policies::PoliciesClient(self.0.0.policies())
184    }
185
186    /// Test method, echoes back the input
187    pub fn echo(&self, msg: String) -> String {
188        msg
189    }
190
191    /// Test method, calls http endpoint
192    pub async fn http_get(&self, url: String) -> Result<String> {
193        let client = self.0.0.internal.get_http_client();
194        let res = client
195            .get(&url)
196            .send()
197            .await
198            .map_err(|e| Error::Api(e.into()))?;
199
200        res.text().await.map_err(|e| Error::Api(e.into()))
201    }
202}
203
204#[cfg(feature = "debug-capabilities")]
205#[uniffi::export]
206impl Client {
207    /// Dev-only debug capabilities that reach past the public API into internal
208    /// state, for automated tooling. Available only when built with the
209    /// `debug-capabilities` feature, which must never be enabled in production.
210    pub fn debug(&self) -> debug::DebugClient {
211        debug::DebugClient(self.0.debug())
212    }
213}
214
215static INIT: Once = Once::new();
216
217/// Log level for SDK logging
218#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)]
219pub enum LogLevel {
220    /// Very detailed diagnostic information
221    Trace,
222    /// Diagnostic information for debugging
223    Debug,
224    /// Informational message
225    Info,
226    /// Potential problem that doesn't prevent the operation from completing
227    Warn,
228    /// Failure of an operation
229    Error,
230}
231
232impl LogLevel {
233    fn as_str(&self) -> &'static str {
234        match self {
235            LogLevel::Trace => "trace",
236            LogLevel::Debug => "debug",
237            LogLevel::Info => "info",
238            LogLevel::Warn => "warn",
239            LogLevel::Error => "error",
240        }
241    }
242}
243
244impl From<&tracing::Level> for LogLevel {
245    fn from(level: &tracing::Level) -> Self {
246        match *level {
247            tracing::Level::TRACE => LogLevel::Trace,
248            tracing::Level::DEBUG => LogLevel::Debug,
249            tracing::Level::INFO => LogLevel::Info,
250            tracing::Level::WARN => LogLevel::Warn,
251            tracing::Level::ERROR => LogLevel::Error,
252        }
253    }
254}
255
256/// Initialize the SDK logger
257///
258/// This function should be called once before creating any SDK clients.
259/// It initializes the tracing infrastructure for the SDK and optionally
260/// registers a callback to receive log events.
261///
262/// # Parameters
263/// - `callback`: Optional callback to receive SDK log events. Pass `None` to use only platform
264///   loggers (oslog on iOS, logcat on Android).
265/// - `level`: Optional minimum log level; events below it are dropped. Defaults to `Info` if not
266///   specified. Can be overridden by the `RUST_LOG` environment variable at runtime or compile
267///   time.
268/// - `platform_logger`: Whether the SDK writes log events to the platform logger (oslog on iOS,
269///   logcat on Android, stdout elsewhere). Defaults to `true`. Disable it when `callback` already
270///   forwards events there, otherwise every event is logged twice.
271///
272/// # Example
273/// ```kotlin
274/// // Initialize with callback and trace-level logging before creating clients
275/// initLogger(FlightRecorderCallback(), LogLevel.TRACE)
276/// val client = Client(tokenProvider, settings, ManagedSettingsBindingClient())
277/// ```
278///
279/// # Notes
280/// - This function can only be called once - subsequent calls are ignored
281/// - If not called explicitly, logging is auto-initialized when first client is created
282#[uniffi::export(default(platform_logger = true))]
283pub fn init_logger(
284    callback: Option<Arc<dyn LogCallback>>,
285    level: Option<LogLevel>,
286    platform_logger: bool,
287) {
288    use tracing_subscriber::{EnvFilter, layer::SubscriberExt as _, util::SubscriberInitExt as _};
289
290    INIT.call_once(|| {
291        // the log level prioritization is determined by:
292        //    1. if RUST_LOG is detected at runtime
293        //    2. if RUST_LOG is provided at compile time
294        //    3. the level parameter passed by the caller
295        //    4. default to INFO
296        let level = level.as_ref().map(|l| l.as_str()).unwrap_or("info");
297        let filter = EnvFilter::builder()
298            .with_default_directive(
299                option_env!("RUST_LOG")
300                    .unwrap_or(level)
301                    .parse()
302                    .expect("should provide valid log level at compile time."),
303            )
304            .from_env_lossy();
305
306        // `Option<L>` is a `Layer`, so disabled sinks are attached as `None`
307        let fmtlayer = platform_logger.then(|| {
308            tracing_subscriber::fmt::layer()
309                .with_ansi(true)
310                .with_file(true)
311                .with_line_number(true)
312                .with_target(true)
313                .pretty()
314        });
315
316        // Build base registry once instead of duplicating per-platform
317        let registry = tracing_subscriber::registry().with(fmtlayer).with(filter);
318
319        // Conditionally add callback layer if provided
320        // Use Option to avoid type incompatibility between Some/None branches
321        let callback_layer = callback.map(log_callback::CallbackLayer::new);
322        let registry = registry.with(callback_layer);
323        #[cfg(target_os = "ios")]
324        {
325            const TAG: &str = "com.8bit.bitwarden";
326            registry
327                .with(platform_logger.then(|| tracing_oslog::OsLogger::new(TAG, "default")))
328                .init();
329        }
330
331        #[cfg(target_os = "android")]
332        {
333            const TAG: &str = "com.bitwarden.sdk";
334            registry
335                .with(platform_logger.then(|| {
336                    tracing_android::layer(TAG)
337                        .expect("initialization of android logcat tracing layer")
338                }))
339                .init();
340        }
341
342        #[cfg(not(any(target_os = "android", target_os = "ios")))]
343        {
344            registry.init();
345        }
346        #[cfg(feature = "dangerous-crypto-debug")]
347        tracing::warn!(
348            "Dangerous crypto debug features are enabled. THIS MUST NOT BE USED IN PRODUCTION BUILDS!!"
349        );
350    });
351}
352
353/// Setup the error converter to ensure conversion errors don't cause panics
354/// Check [`bitwarden_uniffi_error`] for more details
355fn setup_error_converter() {
356    bitwarden_uniffi_error::set_error_to_uniffi_error(|e| {
357        crate::error::BitwardenError::Conversion(e.to_string()).into()
358    });
359}
360#[cfg(test)]
361mod tests {
362    use std::sync::Mutex;
363
364    use super::*;
365    // Mock token provider for testing
366    #[derive(Debug)]
367    struct MockTokenProvider;
368
369    #[async_trait::async_trait]
370    impl ClientManagedTokens for MockTokenProvider {
371        async fn get_access_token(&self) -> Option<String> {
372            Some("mock_token".to_string())
373        }
374    }
375    /// Mock LogCallback implementation for testing
376    struct TestLogCallback {
377        logs: Arc<Mutex<Vec<(LogLevel, String, String)>>>,
378    }
379    impl LogCallback for TestLogCallback {
380        fn on_log(&self, level: LogLevel, target: String, message: String) -> Result<()> {
381            self.logs
382                .lock()
383                .expect("Failed to lock logs mutex")
384                .push((level, target, message));
385            Ok(())
386        }
387    }
388
389    // Log callback unit tests only test happy path because running this with
390    // Once means we get one registered callback per test run. There are
391    // other tests written as integration tests in the /tests/ folder that
392    // assert more specific details.
393    #[test]
394    fn test_callback_receives_logs() {
395        let logs = Arc::new(Mutex::new(Vec::new()));
396        let callback = Arc::new(TestLogCallback { logs: logs.clone() });
397
398        // Initialize logger with callback before creating client
399        init_logger(Some(callback), None, true);
400
401        // Create client
402        let _client = Client::new(
403            Arc::new(MockTokenProvider),
404            None,
405            Arc::new(ManagedSettingsBindingClient::new()),
406            None,
407        );
408
409        // Trigger a log
410        tracing::info!("test message from SDK");
411
412        // Verify callback received it
413        let captured = logs.lock().expect("Failed to lock logs mutex");
414        assert!(!captured.is_empty(), "Callback should receive logs");
415
416        // Find our specific test log (there may be other SDK logs during init)
417        let test_log = captured
418            .iter()
419            .find(|(_, _, msg)| msg.contains("test message"))
420            .expect("Should find our test log message");
421
422        assert_eq!(test_log.0, LogLevel::Info);
423        assert!(test_log.2.contains("test message"));
424    }
425}