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#[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 #[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 pub fn crypto(&self) -> CryptoClient {
88 CryptoClient(self.0.crypto())
89 }
90
91 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 pub fn user_crypto_management(
101 &self,
102 ) -> bitwarden_user_crypto_management::UserCryptoManagementClient {
103 self.0.user_crypto_management()
104 }
105
106 pub fn unlock(&self) -> bitwarden_unlock::UnlockClient {
108 self.0.unlock()
109 }
110
111 pub fn crypto_sync_handler(&self) -> bitwarden_crypto_sync_handler::CryptoSyncHandlerClient {
113 self.0.crypto_sync_handler()
114 }
115
116 pub fn vault(&self) -> VaultClient {
118 VaultClient(self.0.vault())
119 }
120
121 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 pub fn generators(&self) -> GeneratorClients {
137 GeneratorClients(self.0.generator())
138 }
139
140 pub fn exporters(&self) -> ExporterClient {
142 ExporterClient(self.0.exporters())
143 }
144
145 pub fn importers(&self) -> ImporterClient {
147 ImporterClient(self.0.importers())
148 }
149
150 pub fn sends(&self) -> SendClient {
152 SendClient(self.0.sends())
153 }
154
155 pub fn send_sync_handler(&self) -> bitwarden_send::SendSyncHandlerClient {
157 self.0.send_sync_handler()
158 }
159
160 pub fn ssh(&self) -> SshClient {
162 SshClient()
163 }
164
165 pub fn random(&self) -> bitwarden_random::SdkRandomNumberClient {
167 bitwarden_random::SdkRandomNumberClient::new()
168 }
169
170 pub fn auth(&self) -> AuthClient {
172 AuthClient(self.0.0.clone())
173 }
174
175 pub fn gov_mode(&self) -> bool {
177 self.0.0.gov_mode()
178 }
179
180 pub fn policies(&self) -> policies::PoliciesClient {
182 use bitwarden_policies::PoliciesClientExt;
183 policies::PoliciesClient(self.0.0.policies())
184 }
185
186 pub fn echo(&self, msg: String) -> String {
188 msg
189 }
190
191 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 pub fn debug(&self) -> debug::DebugClient {
211 debug::DebugClient(self.0.debug())
212 }
213}
214
215static INIT: Once = Once::new();
216
217#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)]
219pub enum LogLevel {
220 Trace,
222 Debug,
224 Info,
226 Warn,
228 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#[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 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 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 let registry = tracing_subscriber::registry().with(fmtlayer).with(filter);
318
319 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
353fn 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 #[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 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 #[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 init_logger(Some(callback), None, true);
400
401 let _client = Client::new(
403 Arc::new(MockTokenProvider),
404 None,
405 Arc::new(ManagedSettingsBindingClient::new()),
406 None,
407 );
408
409 tracing::info!("test message from SDK");
411
412 let captured = logs.lock().expect("Failed to lock logs mutex");
414 assert!(!captured.is_empty(), "Callback should receive logs");
415
416 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}