Skip to main content

bitwarden_sync/
sync_client.rs

1use std::sync::Arc;
2
3use bitwarden_api_api::models::SyncResponseModel;
4use bitwarden_core::{
5    Client,
6    client::{ApiConfigurations, FromClientPart},
7};
8use bitwarden_state::PersistedValue;
9use chrono::{DateTime, Utc};
10use serde::{Deserialize, Serialize};
11use thiserror::Error;
12use tokio::sync::Mutex;
13
14use crate::{
15    SyncErrorHandler, SyncHandler, SyncHandlerError, registry::HandlerRegistry, state::LAST_SYNC,
16};
17
18#[allow(missing_docs)]
19#[derive(Debug, Error)]
20pub enum SyncError {
21    #[error(transparent)]
22    Api(#[from] bitwarden_core::ApiError),
23
24    #[error("Sync event handler failed: {0}")]
25    HandlerFailed(#[source] SyncHandlerError),
26
27    #[error("Account has been deleted on the server.")]
28    AccountDeleted,
29
30    #[error(transparent)]
31    State(#[from] bitwarden_state::PersistedValueError),
32
33    #[error("Server returned an unrepresentable revision date.")]
34    InvalidRevisionDate,
35}
36
37#[allow(missing_docs)]
38#[derive(Serialize, Deserialize, Debug, Clone)]
39#[serde(rename_all = "camelCase", deny_unknown_fields)]
40pub struct SyncRequest {
41    /// Skip the revision-date check and always sync.
42    #[serde(default)]
43    pub force: bool,
44    /// Exclude the subdomains from the response, defaults to false
45    pub exclude_subdomains: Option<bool>,
46}
47
48/// Client for performing sync operations with event support
49///
50/// This client wraps the core sync functionality and provides hooks
51/// for registering event handlers that can respond to sync operations.
52pub struct SyncClient {
53    api_configurations: Arc<ApiConfigurations>,
54    sync_handlers: HandlerRegistry<dyn SyncHandler>,
55    error_handlers: HandlerRegistry<dyn SyncErrorHandler>,
56    sync_lock: Mutex<()>,
57    last_sync: PersistedValue<LAST_SYNC>,
58}
59
60impl SyncClient {
61    /// Create a new SyncClient from a Bitwarden client
62    pub fn new(client: Client) -> Self {
63        Self {
64            api_configurations: client.get_part(),
65            sync_handlers: HandlerRegistry::new(),
66            error_handlers: HandlerRegistry::new(),
67            sync_lock: Mutex::new(()),
68            last_sync: client.get_part(),
69        }
70    }
71
72    /// Get the timestamp of the last successful sync or confirmed-up-to-date skip, if any.
73    pub async fn last_sync(&self) -> Option<DateTime<Utc>> {
74        self.last_sync.try_get().await.ok().flatten()
75    }
76
77    /// Register a sync handler for sync operations
78    ///
79    /// Handlers are called in registration order. If any handler returns an error,
80    /// the sync operation is aborted immediately and subsequent handlers are not called.
81    pub fn register_sync_handler(&self, handler: Arc<dyn SyncHandler>) {
82        self.sync_handlers.register(handler);
83    }
84
85    /// Register an error handler for sync operations
86    ///
87    /// Error handlers are called when any error occurs during sync, including
88    /// API errors and handler errors. All error handlers are always called
89    /// regardless of individual failures.
90    pub fn register_error_handler(&self, handler: Arc<dyn SyncErrorHandler>) {
91        self.error_handlers.register(handler);
92    }
93
94    /// Perform a sync operation, skipping the server call when nothing has changed.
95    ///
96    /// Returns `Ok(true)` if a full sync was performed, or `Ok(false)` if the revision-date
97    /// check determined that the server has no new changes and the sync was skipped.
98    ///
99    /// ## Control flow
100    ///
101    /// Unless `request.force` is `true`, this method first fetches the account revision date
102    /// from the server and compares it to the stored `last_sync` timestamp. If the revision
103    /// is not newer, the sync is skipped: `last_sync` is bumped to now and `Ok(false)` is
104    /// returned without calling any sync or error handlers.
105    ///
106    /// When a full sync is performed:
107    /// 1. Fetches the full sync response from the Bitwarden API.
108    /// 2. Dispatches `on_sync` with the response to all registered handlers in order; stops on the
109    ///    first handler error.
110    /// 3. Dispatches `on_sync_complete` to all handlers for post-processing.
111    /// 4. On success, bumps `last_sync` to now and returns `Ok(true)`.
112    ///
113    /// ## Errors
114    ///
115    /// Any error (revision-date fetch, API call, or handler failure) is forwarded to all
116    /// registered error handlers before being returned to the caller. `last_sync` is never
117    /// bumped on an error path.
118    pub async fn sync(&self, request: SyncRequest) -> Result<bool, SyncError> {
119        // Wait for any in-progress sync to complete before starting a new one
120        let _guard = self.sync_lock.lock().await;
121
122        // Capture the sync start time before any server interaction. Using the start time
123        // (not the finish time) as last_sync guarantees that any server-side change committed
124        // during the sync window has a revision date strictly greater than last_sync, so the
125        // next needs_sync check will pick it up. Matches the Node CLI pattern:
126        // `const now = new Date()` before `needsSyncing()`.
127        let sync_start = Utc::now();
128
129        let needs_sync = if request.force {
130            true
131        } else {
132            match self.needs_sync().await {
133                Ok(needed) => needed,
134                Err(e) => {
135                    self.run_error_handlers(&e).await;
136                    return Err(e);
137                }
138            }
139        };
140
141        if !needs_sync {
142            // Persistent clock-skew note: if the local clock is permanently ahead of the
143            // server, every revision check will say "no sync needed" and we keep bumping
144            // lastSync to a future-skewed `now` — server-side changes are never picked up
145            // until the clock is corrected. Matches Node CLI behaviour.
146            self.update_last_sync(sync_start).await;
147            return Ok(false);
148        }
149
150        let result = async {
151            let response = self.perform_sync(&request).await?;
152            self.run_handlers(&response).await?;
153            Ok(response)
154        }
155        .await;
156
157        match result {
158            Ok(_) => {
159                self.update_last_sync(sync_start).await;
160                Ok(true)
161            }
162            Err(error) => {
163                self.run_error_handlers(&error).await;
164                Err(error)
165            }
166        }
167    }
168
169    async fn needs_sync(&self) -> Result<bool, SyncError> {
170        let Some(last_sync) = self.last_sync.try_get().await? else {
171            return Ok(true); // First sync — skip revision check
172        };
173
174        let revision_ms = self
175            .api_configurations
176            .api_client
177            .accounts_api()
178            .get_account_revision_date()
179            .await?;
180
181        if revision_ms < 0 {
182            return Err(SyncError::AccountDeleted);
183        }
184
185        Ok(DateTime::<Utc>::from_timestamp_millis(revision_ms)
186            .ok_or(SyncError::InvalidRevisionDate)?
187            > last_sync)
188    }
189
190    async fn update_last_sync(&self, now: DateTime<Utc>) {
191        let _ = self.last_sync.set(now).await;
192    }
193
194    /// Run sync handlers for a completed sync operation
195    ///
196    /// Executes two phases sequentially:
197    /// 1. Calls [`SyncHandler::on_sync`] on all handlers with the response
198    /// 2. Calls [`SyncHandler::on_sync_complete`] on all handlers
199    ///
200    /// Stops on first error and returns it immediately.
201    async fn run_handlers(&self, response: &SyncResponseModel) -> Result<(), SyncError> {
202        let handlers = self.sync_handlers.handlers();
203
204        for handler in &handlers {
205            handler
206                .on_sync(response)
207                .await
208                .map_err(SyncError::HandlerFailed)?;
209        }
210
211        for handler in &handlers {
212            handler.on_sync_complete().await;
213        }
214
215        Ok(())
216    }
217
218    /// Run all error handlers for a sync error
219    ///
220    /// All error handlers are called sequentially in registration order.
221    async fn run_error_handlers(&self, error: &SyncError) {
222        for handler in &self.error_handlers.handlers() {
223            handler.on_error(error).await;
224        }
225    }
226
227    /// Performs the actual sync operation with the Bitwarden API
228    async fn perform_sync(&self, input: &SyncRequest) -> Result<SyncResponseModel, SyncError> {
229        let sync = self
230            .api_configurations
231            .api_client
232            .sync_api()
233            .get(input.exclude_subdomains)
234            .await?;
235
236        Ok(sync)
237    }
238}
239
240/// Extension trait to add sync() method to Client
241///
242/// This trait provides a convenient way to create a SyncClient from
243/// a Bitwarden Client instance.
244pub trait SyncClientExt {
245    /// Create a new SyncClient for this client
246    fn sync(&self) -> SyncClient;
247}
248
249impl SyncClientExt for Client {
250    fn sync(&self) -> SyncClient {
251        SyncClient::new(self.clone())
252    }
253}
254
255#[cfg(test)]
256mod tests {
257    use std::sync::{Arc, Mutex};
258
259    use chrono::{Duration, Utc};
260
261    use super::*;
262
263    struct TestHandler {
264        name: String,
265        execution_log: Arc<Mutex<Vec<String>>>,
266        should_fail: bool,
267    }
268
269    #[async_trait::async_trait]
270    impl SyncHandler for TestHandler {
271        async fn on_sync(&self, _response: &SyncResponseModel) -> Result<(), SyncHandlerError> {
272            self.execution_log.lock().unwrap().push(self.name.clone());
273            if self.should_fail {
274                Err("Handler failed".into())
275            } else {
276                Ok(())
277            }
278        }
279    }
280
281    struct TestErrorHandler {
282        name: String,
283        error_log: Arc<Mutex<Vec<String>>>,
284    }
285
286    #[async_trait::async_trait]
287    impl SyncErrorHandler for TestErrorHandler {
288        async fn on_error(&self, _error: &SyncError) {
289            self.error_log.lock().unwrap().push(self.name.clone());
290        }
291    }
292
293    /// Helper to create a SyncClient with a mocked API client.
294    fn test_client(api_client: bitwarden_api_api::apis::ApiClient) -> SyncClient {
295        let dummy_config = bitwarden_api_api::Configuration::new(String::new());
296        SyncClient {
297            api_configurations: Arc::new(ApiConfigurations {
298                api_client,
299                identity_client: bitwarden_api_identity::apis::ApiClient::new_mocked(|_| {}),
300                api_config: dummy_config.clone(),
301                identity_config: dummy_config,
302                device_type: bitwarden_core::client::DeviceType::SDK,
303            }),
304            sync_handlers: HandlerRegistry::new(),
305            error_handlers: HandlerRegistry::new(),
306            sync_lock: tokio::sync::Mutex::new(()),
307            last_sync: bitwarden_test::MemoryPersistedValue::create(),
308        }
309    }
310
311    /// Helper to create a SyncClient with a state-backed last_sync value.
312    ///
313    /// If `stored_last_sync` is `Some`, it is written into the in-memory value so
314    /// that subsequent calls to `needs_sync` see it.
315    async fn test_client_with_last_sync(
316        api_client: bitwarden_api_api::apis::ApiClient,
317        stored_last_sync: Option<DateTime<Utc>>,
318    ) -> SyncClient {
319        let last_sync = bitwarden_test::MemoryPersistedValue::create::<LAST_SYNC>();
320        if let Some(dt) = stored_last_sync {
321            last_sync.set(dt).await.expect("pre-populate last_sync");
322        }
323        let mut client = test_client(api_client);
324        client.last_sync = last_sync;
325        client
326    }
327
328    #[tokio::test]
329    async fn test_handlers_execute_in_registration_order() {
330        let client = test_client(bitwarden_api_api::apis::ApiClient::new_mocked(|_| {}));
331        let log = Arc::new(Mutex::new(Vec::new()));
332
333        client.register_sync_handler(Arc::new(TestHandler {
334            name: "first".to_string(),
335            execution_log: log.clone(),
336            should_fail: false,
337        }));
338        client.register_sync_handler(Arc::new(TestHandler {
339            name: "second".to_string(),
340            execution_log: log.clone(),
341            should_fail: false,
342        }));
343        client.register_sync_handler(Arc::new(TestHandler {
344            name: "third".to_string(),
345            execution_log: log.clone(),
346            should_fail: false,
347        }));
348
349        let response = SyncResponseModel::default();
350        client.run_handlers(&response).await.unwrap();
351
352        assert_eq!(
353            *log.lock().unwrap(),
354            vec!["first", "second", "third"],
355            "Handlers should execute in registration order"
356        );
357    }
358
359    #[tokio::test]
360    async fn test_handler_error_stops_subsequent_handlers() {
361        let client = test_client(bitwarden_api_api::apis::ApiClient::new_mocked(|_| {}));
362        let log = Arc::new(Mutex::new(Vec::new()));
363
364        client.register_sync_handler(Arc::new(TestHandler {
365            name: "first".to_string(),
366            execution_log: log.clone(),
367            should_fail: false,
368        }));
369        client.register_sync_handler(Arc::new(TestHandler {
370            name: "second".to_string(),
371            execution_log: log.clone(),
372            should_fail: true,
373        }));
374        client.register_sync_handler(Arc::new(TestHandler {
375            name: "third".to_string(),
376            execution_log: log.clone(),
377            should_fail: false,
378        }));
379
380        let response = SyncResponseModel::default();
381        let result = client.run_handlers(&response).await;
382
383        assert!(result.is_err(), "Should return error when handler fails");
384        assert_eq!(
385            *log.lock().unwrap(),
386            vec!["first", "second"],
387            "Third handler should not execute after second handler fails"
388        );
389    }
390
391    #[tokio::test]
392    async fn test_sync_success_calls_handlers_and_returns_response() {
393        let client = test_client(bitwarden_api_api::apis::ApiClient::new_mocked(|mock| {
394            mock.sync_api
395                .expect_get()
396                .returning(|_| Ok(SyncResponseModel::default()));
397        }));
398        let sync_log = Arc::new(Mutex::new(Vec::new()));
399        let error_log = Arc::new(Mutex::new(Vec::new()));
400
401        client.register_sync_handler(Arc::new(TestHandler {
402            name: "handler".to_string(),
403            execution_log: sync_log.clone(),
404            should_fail: false,
405        }));
406        client.register_error_handler(Arc::new(TestErrorHandler {
407            name: "error_handler".to_string(),
408            error_log: error_log.clone(),
409        }));
410
411        let result = client
412            .sync(SyncRequest {
413                force: false,
414                exclude_subdomains: None,
415            })
416            .await;
417
418        assert!(result.is_ok(), "Sync should succeed");
419        assert_eq!(
420            *sync_log.lock().unwrap(),
421            vec!["handler"],
422            "Sync handler should be called on success"
423        );
424        assert!(
425            error_log.lock().unwrap().is_empty(),
426            "Error handlers should not be called on success"
427        );
428    }
429
430    #[tokio::test]
431    async fn test_sync_error_notifies_error_handlers() {
432        let client = test_client(bitwarden_api_api::apis::ApiClient::new_mocked(|mock| {
433            mock.sync_api
434                .expect_get()
435                .returning(|_| Err(std::io::Error::other("test error").into()));
436        }));
437        let error_log = Arc::new(Mutex::new(Vec::new()));
438
439        client.register_error_handler(Arc::new(TestErrorHandler {
440            name: "first".to_string(),
441            error_log: error_log.clone(),
442        }));
443        client.register_error_handler(Arc::new(TestErrorHandler {
444            name: "second".to_string(),
445            error_log: error_log.clone(),
446        }));
447
448        // sync() will fail due to the mocked error, which should trigger all error handlers
449        let result = client
450            .sync(SyncRequest {
451                force: false,
452                exclude_subdomains: None,
453            })
454            .await;
455
456        assert!(result.is_err());
457        assert_eq!(
458            *error_log.lock().unwrap(),
459            vec!["first", "second"],
460            "All error handlers should be called on sync failure"
461        );
462    }
463
464    #[tokio::test]
465    async fn test_first_sync_skips_revision_check() {
466        // The value exists but has none stored — revision check must not be called.
467        let client = test_client_with_last_sync(
468            bitwarden_api_api::apis::ApiClient::new_mocked(|mock| {
469                mock.sync_api
470                    .expect_get()
471                    .returning(|_| Ok(SyncResponseModel::default()));
472                // accounts_api has no expectation — mock panics on unexpected calls
473            }),
474            None,
475        )
476        .await;
477
478        let result = client
479            .sync(SyncRequest {
480                force: false,
481                exclude_subdomains: None,
482            })
483            .await;
484
485        assert!(result.is_ok_and(|v| v));
486    }
487
488    #[tokio::test]
489    async fn test_revision_check_skips_sync_when_up_to_date() {
490        let stored_last_sync = Utc::now();
491        // Server revision is 60 seconds older than our stored last_sync.
492        let server_revision_ms = (stored_last_sync - Duration::seconds(60)).timestamp_millis();
493
494        let sync_log = Arc::new(Mutex::new(Vec::<String>::new()));
495        let sync_log_clone = sync_log.clone();
496
497        let client = test_client_with_last_sync(
498            bitwarden_api_api::apis::ApiClient::new_mocked(move |mock| {
499                mock.accounts_api
500                    .expect_get_account_revision_date()
501                    .returning(move || Ok(server_revision_ms));
502                // sync_api has no expectation — must not be called
503            }),
504            Some(stored_last_sync),
505        )
506        .await;
507
508        client.register_sync_handler(Arc::new(TestHandler {
509            name: "should_not_run".to_string(),
510            execution_log: sync_log_clone,
511            should_fail: false,
512        }));
513
514        let result = client
515            .sync(SyncRequest {
516                force: false,
517                exclude_subdomains: None,
518            })
519            .await;
520
521        assert!(result.is_ok_and(|v| !v), "Expected Ok(false) skip result");
522        assert!(
523            sync_log.lock().unwrap().is_empty(),
524            "Sync handler must not be called on skip"
525        );
526    }
527
528    #[tokio::test]
529    async fn test_force_bypasses_revision_check() {
530        let stored_last_sync = Utc::now();
531
532        let client = test_client_with_last_sync(
533            bitwarden_api_api::apis::ApiClient::new_mocked(|mock| {
534                mock.sync_api
535                    .expect_get()
536                    .returning(|_| Ok(SyncResponseModel::default()));
537                // accounts_api has no expectation
538            }),
539            Some(stored_last_sync),
540        )
541        .await;
542
543        let result = client
544            .sync(SyncRequest {
545                force: true,
546                exclude_subdomains: None,
547            })
548            .await;
549
550        assert!(result.is_ok_and(|v| v));
551    }
552
553    #[tokio::test]
554    async fn test_account_deleted_error() {
555        let stored_last_sync = Utc::now();
556        let error_log = Arc::new(Mutex::new(Vec::<String>::new()));
557        let error_log_clone = error_log.clone();
558
559        let client = test_client_with_last_sync(
560            bitwarden_api_api::apis::ApiClient::new_mocked(|mock| {
561                mock.accounts_api
562                    .expect_get_account_revision_date()
563                    .returning(|| Ok(-1i64));
564            }),
565            Some(stored_last_sync),
566        )
567        .await;
568
569        client.register_error_handler(Arc::new(TestErrorHandler {
570            name: "error_handler".to_string(),
571            error_log: error_log_clone,
572        }));
573
574        let result = client
575            .sync(SyncRequest {
576                force: false,
577                exclude_subdomains: None,
578            })
579            .await;
580
581        assert!(
582            matches!(result, Err(SyncError::AccountDeleted)),
583            "Expected AccountDeleted error"
584        );
585        assert_eq!(
586            *error_log.lock().unwrap(),
587            vec!["error_handler"],
588            "Error handler must be called for AccountDeleted"
589        );
590    }
591
592    #[tokio::test]
593    async fn test_revision_fetch_failure_does_not_bump_last_sync() {
594        let stored_last_sync =
595            DateTime::<Utc>::from_timestamp_millis(1_000_000).expect("valid timestamp");
596        let error_log = Arc::new(Mutex::new(Vec::<String>::new()));
597        let error_log_clone = error_log.clone();
598
599        // Build the value manually so we can inspect it after sync.
600        let last_sync = bitwarden_test::MemoryPersistedValue::create::<LAST_SYNC>();
601        last_sync
602            .set(stored_last_sync)
603            .await
604            .expect("pre-populate last_sync");
605
606        let mut client = test_client(bitwarden_api_api::apis::ApiClient::new_mocked(|mock| {
607            mock.accounts_api
608                .expect_get_account_revision_date()
609                .returning(|| Err(std::io::Error::other("network error").into()));
610        }));
611        client.last_sync = last_sync.clone();
612
613        client.register_error_handler(Arc::new(TestErrorHandler {
614            name: "error_handler".to_string(),
615            error_log: error_log_clone,
616        }));
617
618        let result = client
619            .sync(SyncRequest {
620                force: false,
621                exclude_subdomains: None,
622            })
623            .await;
624
625        assert!(
626            result.is_err(),
627            "Expected error from revision fetch failure"
628        );
629        assert_eq!(
630            last_sync.get().await.unwrap(),
631            stored_last_sync,
632            "last_sync must not be bumped on error"
633        );
634        assert!(
635            !error_log.lock().unwrap().is_empty(),
636            "Error handler must be called"
637        );
638    }
639}