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::{ClientSettings, auth::ClientManagedTokens};
9
10#[allow(missing_docs)]
11pub mod auth;
12#[allow(missing_docs)]
13pub mod crypto;
14#[allow(missing_docs)]
15pub mod error;
16mod log_callback;
17#[allow(missing_docs)]
18pub mod platform;
19#[allow(missing_docs)]
20pub mod policies;
21#[allow(missing_docs)]
22pub mod tool;
23mod uniffi_support;
24#[allow(missing_docs)]
25pub mod vault;
26
27#[cfg(target_os = "android")]
28mod android_support;
29
30use crypto::CryptoClient;
31use error::{Error, Result};
32pub use log_callback::LogCallback;
33use platform::PlatformClient;
34pub use platform::{
35    AcquiredCookie, BootstrapConfig, ServerCommunicationConfig, ServerCommunicationConfigClient,
36    ServerCommunicationConfigRepository, SsoCookieVendorConfig,
37};
38use tool::{ExporterClient, GeneratorClients, ImporterClient, SendClient, SshClient};
39use vault::VaultClient;
40
41#[allow(missing_docs)]
42#[derive(uniffi::Object)]
43pub struct Client(pub(crate) bitwarden_pm::PasswordManagerClient);
44
45#[uniffi::export(async_runtime = "tokio")]
46impl Client {
47    /// Initialize a new instance of the SDK client
48    #[uniffi::constructor]
49    pub fn new(
50        token_provider: Arc<dyn ClientManagedTokens>,
51        settings: Option<ClientSettings>,
52    ) -> Self {
53        init_logger(None, None);
54        setup_error_converter();
55
56        #[cfg(target_os = "android")]
57        android_support::init();
58
59        Self(bitwarden_pm::PasswordManagerClient::new_with_client_tokens(
60            settings,
61            token_provider,
62        ))
63    }
64
65    /// Crypto operations
66    pub fn crypto(&self) -> CryptoClient {
67        CryptoClient(self.0.crypto())
68    }
69
70    /// Returns the key-management state bridge client used to register a
71    /// host-supplied storage implementation.
72    pub fn km_state_bridge(
73        &self,
74    ) -> bitwarden_core::key_management::state_bridge::StateBridgeClient {
75        self.0.0.km_state_bridge()
76    }
77
78    /// Returns the user-crypto-management sub-client (PIN settings, key rotation, etc).
79    pub fn user_crypto_management(
80        &self,
81    ) -> bitwarden_user_crypto_management::UserCryptoManagementClient {
82        self.0.user_crypto_management()
83    }
84
85    /// Vault item operations
86    pub fn vault(&self) -> VaultClient {
87        VaultClient(self.0.vault())
88    }
89
90    #[allow(missing_docs)]
91    pub fn platform(&self) -> PlatformClient {
92        PlatformClient(self.0.0.clone())
93    }
94
95    /// Generator operations
96    pub fn generators(&self) -> GeneratorClients {
97        GeneratorClients(self.0.generator())
98    }
99
100    /// Exporters
101    pub fn exporters(&self) -> ExporterClient {
102        ExporterClient(self.0.exporters())
103    }
104
105    /// Importers
106    pub fn importers(&self) -> ImporterClient {
107        ImporterClient(self.0.importers())
108    }
109
110    /// Sends operations
111    pub fn sends(&self) -> SendClient {
112        SendClient(self.0.sends())
113    }
114
115    /// SSH operations
116    pub fn ssh(&self) -> SshClient {
117        SshClient()
118    }
119
120    /// Random-number generation operations
121    pub fn random(&self) -> bitwarden_random::SdkRandomNumberClient {
122        bitwarden_random::SdkRandomNumberClient::new()
123    }
124
125    /// Auth operations
126    pub fn auth(&self) -> AuthClient {
127        AuthClient(self.0.0.clone())
128    }
129
130    /// Whether the client is in Gov Mode.
131    pub fn gov_mode(&self) -> bool {
132        self.0.0.gov_mode()
133    }
134
135    /// Policy operations
136    pub fn policies(&self) -> policies::PoliciesClient {
137        use bitwarden_policies::PoliciesClientExt;
138        policies::PoliciesClient(self.0.0.policies())
139    }
140
141    /// Test method, echoes back the input
142    pub fn echo(&self, msg: String) -> String {
143        msg
144    }
145
146    /// Test method, calls http endpoint
147    pub async fn http_get(&self, url: String) -> Result<String> {
148        let client = self.0.0.internal.get_http_client();
149        let res = client
150            .get(&url)
151            .send()
152            .await
153            .map_err(|e| Error::Api(e.into()))?;
154
155        res.text().await.map_err(|e| Error::Api(e.into()))
156    }
157}
158
159static INIT: Once = Once::new();
160
161/// Log level for SDK logging
162#[derive(uniffi::Enum)]
163pub enum LogLevel {
164    /// Most verbose: all trace, debug, info, warn, and error messages
165    Trace,
166    /// Verbose: debug, info, warn, and error messages
167    Debug,
168    /// Default: info, warn, and error messages
169    Info,
170    /// Only warn and error messages
171    Warn,
172    /// Only error messages
173    Error,
174}
175
176impl LogLevel {
177    fn as_str(&self) -> &'static str {
178        match self {
179            LogLevel::Trace => "trace",
180            LogLevel::Debug => "debug",
181            LogLevel::Info => "info",
182            LogLevel::Warn => "warn",
183            LogLevel::Error => "error",
184        }
185    }
186}
187
188/// Initialize the SDK logger
189///
190/// This function should be called once before creating any SDK clients.
191/// It initializes the tracing infrastructure for the SDK and optionally
192/// registers a callback to receive log events.
193///
194/// # Parameters
195/// - `callback`: Optional callback to receive SDK log events. Pass `None` to use only platform
196///   loggers (oslog on iOS, logcat on Android).
197/// - `level`: Optional log level. Defaults to `Info` if not specified. Can be overridden by
198///   `RUST_LOG` environment variable at runtime or compile time.
199///
200/// # Example
201/// ```kotlin
202/// // Initialize with callback and trace-level logging before creating clients
203/// initLogger(FlightRecorderCallback(), LogLevel.TRACE)
204/// val client = Client(tokenProvider, settings)
205/// ```
206///
207/// # Notes
208/// - This function can only be called once - subsequent calls are ignored
209/// - If not called explicitly, logging is auto-initialized when first client is created
210/// - Platform loggers (oslog/logcat) are always enabled regardless of callback
211#[uniffi::export]
212pub fn init_logger(callback: Option<Arc<dyn LogCallback>>, level: Option<LogLevel>) {
213    use tracing_subscriber::{EnvFilter, layer::SubscriberExt as _, util::SubscriberInitExt as _};
214
215    INIT.call_once(|| {
216        // the log level prioritization is determined by:
217        //    1. if RUST_LOG is detected at runtime
218        //    2. if RUST_LOG is provided at compile time
219        //    3. the level parameter passed by the caller
220        //    4. default to INFO
221        let level = level.as_ref().map(|l| l.as_str()).unwrap_or("info");
222        let filter = EnvFilter::builder()
223            .with_default_directive(
224                option_env!("RUST_LOG")
225                    .unwrap_or(level)
226                    .parse()
227                    .expect("should provide valid log level at compile time."),
228            )
229            .from_env_lossy();
230
231        let fmtlayer = tracing_subscriber::fmt::layer()
232            .with_ansi(true)
233            .with_file(true)
234            .with_line_number(true)
235            .with_target(true)
236            .pretty();
237
238        // Build base registry once instead of duplicating per-platform
239        let registry = tracing_subscriber::registry().with(fmtlayer).with(filter);
240
241        // Conditionally add callback layer if provided
242        // Use Option to avoid type incompatibility between Some/None branches
243        let callback_layer = callback.map(log_callback::CallbackLayer::new);
244        let registry = registry.with(callback_layer);
245        #[cfg(target_os = "ios")]
246        {
247            const TAG: &str = "com.8bit.bitwarden";
248            registry
249                .with(tracing_oslog::OsLogger::new(TAG, "default"))
250                .init();
251        }
252
253        #[cfg(target_os = "android")]
254        {
255            const TAG: &str = "com.bitwarden.sdk";
256            registry
257                .with(
258                    tracing_android::layer(TAG)
259                        .expect("initialization of android logcat tracing layer"),
260                )
261                .init();
262        }
263
264        #[cfg(not(any(target_os = "android", target_os = "ios")))]
265        {
266            registry.init();
267        }
268        #[cfg(feature = "dangerous-crypto-debug")]
269        tracing::warn!(
270            "Dangerous crypto debug features are enabled. THIS MUST NOT BE USED IN PRODUCTION BUILDS!!"
271        );
272    });
273}
274
275/// Setup the error converter to ensure conversion errors don't cause panics
276/// Check [`bitwarden_uniffi_error`] for more details
277fn setup_error_converter() {
278    bitwarden_uniffi_error::set_error_to_uniffi_error(|e| {
279        crate::error::BitwardenError::Conversion(e.to_string()).into()
280    });
281}
282#[cfg(test)]
283mod tests {
284    use std::sync::Mutex;
285
286    use super::*;
287    // Mock token provider for testing
288    #[derive(Debug)]
289    struct MockTokenProvider;
290
291    #[async_trait::async_trait]
292    impl ClientManagedTokens for MockTokenProvider {
293        async fn get_access_token(&self) -> Option<String> {
294            Some("mock_token".to_string())
295        }
296    }
297    /// Mock LogCallback implementation for testing
298    struct TestLogCallback {
299        logs: Arc<Mutex<Vec<(String, String, String)>>>,
300    }
301    impl LogCallback for TestLogCallback {
302        fn on_log(&self, level: String, target: String, message: String) -> Result<()> {
303            self.logs
304                .lock()
305                .expect("Failed to lock logs mutex")
306                .push((level, target, message));
307            Ok(())
308        }
309    }
310
311    // Log callback unit tests only test happy path because running this with
312    // Once means we get one registered callback per test run. There are
313    // other tests written as integration tests in the /tests/ folder that
314    // assert more specific details.
315    #[test]
316    fn test_callback_receives_logs() {
317        let logs = Arc::new(Mutex::new(Vec::new()));
318        let callback = Arc::new(TestLogCallback { logs: logs.clone() });
319
320        // Initialize logger with callback before creating client
321        init_logger(Some(callback), None);
322
323        // Create client
324        let _client = Client::new(Arc::new(MockTokenProvider), None);
325
326        // Trigger a log
327        tracing::info!("test message from SDK");
328
329        // Verify callback received it
330        let captured = logs.lock().expect("Failed to lock logs mutex");
331        assert!(!captured.is_empty(), "Callback should receive logs");
332
333        // Find our specific test log (there may be other SDK logs during init)
334        let test_log = captured
335            .iter()
336            .find(|(_, _, msg)| msg.contains("test message"))
337            .expect("Should find our test log message");
338
339        assert_eq!(test_log.0, "INFO");
340        assert!(test_log.2.contains("test message"));
341    }
342}