logins/
store.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4use crate::db::{LoginDb, LoginsDeletionMetrics};
5use crate::encryption::EncryptorDecryptor;
6use crate::error::*;
7use crate::login::{BulkResultEntry, EncryptedLogin, Login, LoginEntry, LoginEntryWithMeta};
8use crate::schema;
9use crate::LoginsSyncEngine;
10use parking_lot::Mutex;
11use sql_support::run_maintenance;
12use std::path::Path;
13use std::sync::{Arc, Weak};
14use sync15::{
15    engine::{EngineSyncAssociation, SyncEngine, SyncEngineId},
16    ServerTimestamp,
17};
18
19#[derive(uniffi::Enum)]
20pub enum LoginOrErrorMessage {
21    Login,
22    String,
23}
24
25// Our "sync manager" will use whatever is stashed here.
26lazy_static::lazy_static! {
27    // Mutex: just taken long enough to update the inner stuff - needed
28    //        to wrap the RefCell as they aren't `Sync`
29    static ref STORE_FOR_MANAGER: Mutex<Weak<LoginStore>> = Mutex::new(Weak::new());
30}
31
32/// Called by the sync manager to get a sync engine via the store previously
33/// registered with the sync manager.
34pub fn get_registered_sync_engine(engine_id: &SyncEngineId) -> Option<Box<dyn SyncEngine>> {
35    let weak = STORE_FOR_MANAGER.lock();
36    match weak.upgrade() {
37        None => None,
38        Some(store) => match create_sync_engine(store, engine_id) {
39            Ok(engine) => Some(engine),
40            Err(e) => {
41                report_error!("logins-sync-engine-create-error", "{e}");
42                None
43            }
44        },
45    }
46}
47
48fn create_sync_engine(
49    store: Arc<LoginStore>,
50    engine_id: &SyncEngineId,
51) -> Result<Box<dyn SyncEngine>> {
52    match engine_id {
53        SyncEngineId::Passwords => Ok(Box::new(LoginsSyncEngine::new(Arc::clone(&store))?)),
54        // panicking here seems reasonable - it's a static error if this
55        // it hit, not something that runtime conditions can influence.
56        _ => unreachable!("can't provide unknown engine: {}", engine_id),
57    }
58}
59
60fn map_bulk_result_entry(
61    enc_login: Result<EncryptedLogin>,
62    encdec: &dyn EncryptorDecryptor,
63) -> BulkResultEntry {
64    match enc_login {
65        Ok(enc_login) => match enc_login.decrypt(encdec) {
66            Ok(login) => BulkResultEntry::Success { login },
67            Err(error) => {
68                warn!("Login could not be decrypted. This indicates a fundamental problem with the encryption key.");
69                BulkResultEntry::Error {
70                    message: error.to_string(),
71                }
72            }
73        },
74        Err(error) => BulkResultEntry::Error {
75            message: error.to_string(),
76        },
77    }
78}
79
80pub struct LoginStore {
81    pub db: Mutex<Option<LoginDb>>,
82}
83
84impl LoginStore {
85    #[handle_error(Error)]
86    pub fn new(path: impl AsRef<Path>, encdec: Arc<dyn EncryptorDecryptor>) -> ApiResult<Self> {
87        let db = Mutex::new(Some(LoginDb::open(path, encdec)?));
88        Ok(Self { db })
89    }
90
91    pub fn new_from_db(db: LoginDb) -> Self {
92        let db = Mutex::new(Some(db));
93        Self { db }
94    }
95
96    // Only used for tests, but it's `pub` the `sync-test` crate uses it.
97    #[cfg(test)]
98    pub fn new_in_memory() -> Self {
99        let db = Mutex::new(Some(LoginDb::open_in_memory()));
100        Self { db }
101    }
102
103    pub fn lock_db(&self) -> Result<parking_lot::MappedMutexGuard<'_, LoginDb>> {
104        parking_lot::MutexGuard::try_map(self.db.lock(), |db| db.as_mut())
105            .map_err(|_| Error::DatabaseClosed)
106    }
107
108    #[handle_error(Error)]
109    pub fn is_empty(&self) -> ApiResult<bool> {
110        Ok(self.lock_db()?.count_all()? == 0)
111    }
112
113    #[handle_error(Error)]
114    pub fn list(&self) -> ApiResult<Vec<Login>> {
115        let db = self.lock_db()?;
116        db.get_all().and_then(|logins| {
117            logins
118                .into_iter()
119                .map(|login| login.decrypt(db.encdec.as_ref()))
120                .collect()
121        })
122    }
123
124    #[handle_error(Error)]
125    pub fn count(&self) -> ApiResult<i64> {
126        self.lock_db()?.count_all()
127    }
128
129    #[handle_error(Error)]
130    pub fn count_by_origin(&self, origin: &str) -> ApiResult<i64> {
131        self.lock_db()?.count_by_origin(origin)
132    }
133
134    #[handle_error(Error)]
135    pub fn count_by_form_action_origin(&self, form_action_origin: &str) -> ApiResult<i64> {
136        self.lock_db()?
137            .count_by_form_action_origin(form_action_origin)
138    }
139
140    #[handle_error(Error)]
141    pub fn get(&self, id: &str) -> ApiResult<Option<Login>> {
142        let db = self.lock_db()?;
143        match db.get_by_id(id) {
144            Ok(result) => match result {
145                Some(enc_login) => enc_login.decrypt(db.encdec.as_ref()).map(Some),
146                None => Ok(None),
147            },
148            Err(err) => Err(err),
149        }
150    }
151
152    #[handle_error(Error)]
153    pub fn get_by_base_domain(&self, base_domain: &str) -> ApiResult<Vec<Login>> {
154        let db = self.lock_db()?;
155        db.get_by_base_domain(base_domain).and_then(|logins| {
156            logins
157                .into_iter()
158                .map(|login| login.decrypt(db.encdec.as_ref()))
159                .collect()
160        })
161    }
162
163    #[handle_error(Error)]
164    pub fn has_logins_by_base_domain(&self, base_domain: &str) -> ApiResult<bool> {
165        self.lock_db()?
166            .get_by_base_domain(base_domain)
167            .map(|logins| !logins.is_empty())
168    }
169
170    #[handle_error(Error)]
171    pub fn find_login_to_update(&self, entry: LoginEntry) -> ApiResult<Option<Login>> {
172        let db = self.lock_db()?;
173        db.find_login_to_update(entry, db.encdec.as_ref())
174    }
175
176    #[handle_error(Error)]
177    pub fn touch(&self, id: &str) -> ApiResult<()> {
178        self.lock_db()?.touch(id)
179    }
180
181    #[handle_error(Error)]
182    pub fn delete(&self, id: &str) -> ApiResult<bool> {
183        self.lock_db()?.delete(id)
184    }
185
186    #[handle_error(Error)]
187    pub fn delete_many(&self, ids: Vec<String>) -> ApiResult<Vec<bool>> {
188        // Note we need to receive a vector of String here because `Vec<&str>` is not supported
189        // with UDL.
190        let ids: Vec<&str> = ids.iter().map(|id| &**id).collect();
191        self.lock_db()?.delete_many(ids)
192    }
193
194    #[handle_error(Error)]
195    pub fn delete_undecryptable_records_for_remote_replacement(
196        self: Arc<Self>,
197    ) -> ApiResult<LoginsDeletionMetrics> {
198        // This function was created for the iOS logins verification logic that will
199        // remove records that prevent logins syncing. Once the verification logic is
200        // removed from iOS, this function can be removed from the store.
201
202        // Creating an engine requires locking the DB, so make sure to do this first
203        let engine = LoginsSyncEngine::new(Arc::clone(&self))?;
204
205        let db = self.lock_db()?;
206        let deletion_stats =
207            db.delete_undecryptable_records_for_remote_replacement(db.encdec.as_ref())?;
208        engine.set_last_sync(&db, ServerTimestamp(0))?;
209        Ok(deletion_stats)
210    }
211
212    #[handle_error(Error)]
213    pub fn wipe_local(&self) -> ApiResult<()> {
214        self.lock_db()?.wipe_local()?;
215        Ok(())
216    }
217
218    #[handle_error(Error)]
219    pub fn reset(self: Arc<Self>) -> ApiResult<()> {
220        // Reset should not exist here - all resets should be done via the
221        // sync manager. It seems that actual consumers don't use this, but
222        // some tests do, so it remains for now.
223        let engine = LoginsSyncEngine::new(Arc::clone(&self))?;
224        engine.do_reset(&EngineSyncAssociation::Disconnected)?;
225        Ok(())
226    }
227
228    #[handle_error(Error)]
229    pub fn update(&self, id: &str, entry: LoginEntry) -> ApiResult<Login> {
230        let db = self.lock_db()?;
231        db.update(id, entry, db.encdec.as_ref())
232            .and_then(|enc_login| enc_login.decrypt(db.encdec.as_ref()))
233    }
234
235    #[handle_error(Error)]
236    pub fn add(&self, entry: LoginEntry) -> ApiResult<Login> {
237        let db = self.lock_db()?;
238        db.add(entry, db.encdec.as_ref())
239            .and_then(|enc_login| enc_login.decrypt(db.encdec.as_ref()))
240    }
241
242    #[handle_error(Error)]
243    pub fn add_many(&self, entries: Vec<LoginEntry>) -> ApiResult<Vec<BulkResultEntry>> {
244        let db = self.lock_db()?;
245        db.add_many(entries, db.encdec.as_ref()).map(|enc_logins| {
246            enc_logins
247                .into_iter()
248                .map(|enc_login| map_bulk_result_entry(enc_login, db.encdec.as_ref()))
249                .collect()
250        })
251    }
252
253    /// This method is intended to preserve metadata (LoginMeta) during a migration.
254    /// In normal operation, this method should not be used; instead,
255    /// use `add(entry)`, which manages the corresponding fields itself.
256    #[handle_error(Error)]
257    pub fn add_with_meta(&self, entry_with_meta: LoginEntryWithMeta) -> ApiResult<Login> {
258        let db = self.lock_db()?;
259        db.add_with_meta(entry_with_meta, db.encdec.as_ref())
260            .and_then(|enc_login| enc_login.decrypt(db.encdec.as_ref()))
261    }
262
263    #[handle_error(Error)]
264    pub fn add_many_with_meta(
265        &self,
266        entries_with_meta: Vec<LoginEntryWithMeta>,
267    ) -> ApiResult<Vec<BulkResultEntry>> {
268        let db = self.lock_db()?;
269        db.add_many_with_meta(entries_with_meta, db.encdec.as_ref())
270            .map(|enc_logins| {
271                enc_logins
272                    .into_iter()
273                    .map(|enc_login| map_bulk_result_entry(enc_login, db.encdec.as_ref()))
274                    .collect()
275            })
276    }
277
278    #[handle_error(Error)]
279    pub fn add_or_update(&self, entry: LoginEntry) -> ApiResult<Login> {
280        let db = self.lock_db()?;
281        db.add_or_update(entry, db.encdec.as_ref())
282            .and_then(|enc_login| enc_login.decrypt(db.encdec.as_ref()))
283    }
284
285    #[handle_error(Error)]
286    pub fn set_checkpoint(&self, checkpoint: &str) -> ApiResult<()> {
287        self.lock_db()?
288            .put_meta(schema::CHECKPOINT_KEY, &checkpoint)
289    }
290
291    #[handle_error(Error)]
292    pub fn get_checkpoint(&self) -> ApiResult<Option<String>> {
293        self.lock_db()?.get_meta(schema::CHECKPOINT_KEY)
294    }
295
296    #[handle_error(Error)]
297    pub fn run_maintenance(&self) -> ApiResult<()> {
298        let conn = self.lock_db()?;
299        run_maintenance(&conn)?;
300        Ok(())
301    }
302
303    pub fn shutdown(&self) {
304        if let Some(db) = self.db.lock().take() {
305            let _ = db.shutdown();
306        }
307    }
308
309    // This allows the embedding app to say "make this instance available to
310    // the sync manager". The implementation is more like "offer to sync mgr"
311    // (thereby avoiding us needing to link with the sync manager) but
312    // `register_with_sync_manager()` is logically what's happening so that's
313    // the name it gets.
314    pub fn register_with_sync_manager(self: Arc<Self>) {
315        let mut state = STORE_FOR_MANAGER.lock();
316        *state = Arc::downgrade(&self);
317    }
318
319    // this isn't exposed by uniffi - currently the
320    // only consumer of this is our "example" (and hence why they
321    // are `pub` and not `pub(crate)`).
322    // We could probably make the example work with the sync manager - but then
323    // our example would link with places and logins etc, and it's not a big
324    // deal really.
325    #[handle_error(Error)]
326    pub fn create_logins_sync_engine(self: Arc<Self>) -> ApiResult<Box<dyn SyncEngine>> {
327        Ok(Box::new(LoginsSyncEngine::new(self)?) as Box<dyn SyncEngine>)
328    }
329}
330
331#[cfg(not(feature = "keydb"))]
332#[cfg(test)]
333mod test {
334    use super::*;
335    use crate::encryption::test_utils::TEST_ENCDEC;
336    use crate::util;
337    use more_asserts::*;
338    use nss::ensure_initialized;
339    use std::cmp::Reverse;
340    use std::time::SystemTime;
341
342    fn assert_logins_equiv(a: &LoginEntry, b: &Login) {
343        assert_eq!(a.origin, b.origin);
344        assert_eq!(a.form_action_origin, b.form_action_origin);
345        assert_eq!(a.http_realm, b.http_realm);
346        assert_eq!(a.username_field, b.username_field);
347        assert_eq!(a.password_field, b.password_field);
348        assert_eq!(b.username, a.username);
349        assert_eq!(b.password, a.password);
350    }
351
352    #[test]
353    fn test_general() {
354        ensure_initialized();
355
356        let store = LoginStore::new_in_memory();
357        let list = store.list().expect("Grabbing Empty list to work");
358        assert_eq!(list.len(), 0);
359        let start_us = util::system_time_ms_i64(SystemTime::now());
360
361        let a = LoginEntry {
362            origin: "https://www.example.com".into(),
363            form_action_origin: Some("https://www.example.com".into()),
364            username_field: "user_input".into(),
365            password_field: "pass_input".into(),
366            username: "coolperson21".into(),
367            password: "p4ssw0rd".into(),
368            ..Default::default()
369        };
370
371        let b = LoginEntry {
372            origin: "https://www.example2.com".into(),
373            http_realm: Some("Some String Here".into()),
374            username: "asdf".into(),
375            password: "fdsa".into(),
376            ..Default::default()
377        };
378        let a_id = store.add(a.clone()).expect("added a").id;
379        let b_id = store.add(b.clone()).expect("added b").id;
380
381        let a_from_db = store
382            .get(&a_id)
383            .expect("Not to error getting a")
384            .expect("a to exist");
385
386        assert_logins_equiv(&a, &a_from_db);
387        assert_ge!(a_from_db.time_created, start_us);
388        assert_ge!(a_from_db.time_password_changed, start_us);
389        assert_ge!(a_from_db.time_last_used, start_us);
390        assert_eq!(a_from_db.times_used, 1);
391
392        let b_from_db = store
393            .get(&b_id)
394            .expect("Not to error getting b")
395            .expect("b to exist");
396
397        assert_logins_equiv(&LoginEntry { ..b.clone() }, &b_from_db);
398        assert_ge!(b_from_db.time_created, start_us);
399        assert_ge!(b_from_db.time_password_changed, start_us);
400        assert_ge!(b_from_db.time_last_used, start_us);
401        assert_eq!(b_from_db.times_used, 1);
402
403        let mut list = store.list().expect("Grabbing list to work");
404        assert_eq!(list.len(), 2);
405
406        let mut expect = vec![a_from_db, b_from_db.clone()];
407
408        list.sort_by_key(|b| Reverse(b.guid()));
409        expect.sort_by_key(|b| Reverse(b.guid()));
410        assert_eq!(list, expect);
411
412        store.delete(&a_id).expect("Successful delete");
413        assert!(store
414            .get(&a_id)
415            .expect("get after delete should still work")
416            .is_none());
417
418        let list = store.list().expect("Grabbing list to work");
419        assert_eq!(list.len(), 1);
420        assert_eq!(list[0], b_from_db);
421
422        let has_logins = store
423            .has_logins_by_base_domain("example2.com")
424            .expect("Expect a result for this origin");
425        assert!(has_logins);
426
427        let list = store
428            .get_by_base_domain("example2.com")
429            .expect("Expect a list for this origin");
430        assert_eq!(list.len(), 1);
431        assert_eq!(list[0], b_from_db);
432
433        let has_logins = store
434            .has_logins_by_base_domain("www.example.com")
435            .expect("Expect a result for this origin");
436        assert!(!has_logins);
437
438        let list = store
439            .get_by_base_domain("www.example.com")
440            .expect("Expect an empty list");
441        assert_eq!(list.len(), 0);
442
443        let now_us = util::system_time_ms_i64(SystemTime::now());
444        let b2 = LoginEntry {
445            username: b.username.to_owned(),
446            password: "newpass".into(),
447            ..b
448        };
449
450        store
451            .update(&b_id, b2.clone())
452            .expect("update b should work");
453
454        let b_after_update = store
455            .get(&b_id)
456            .expect("Not to error getting b")
457            .expect("b to exist");
458
459        assert_logins_equiv(&b2, &b_after_update);
460        assert_ge!(b_after_update.time_created, start_us);
461        assert_le!(b_after_update.time_created, now_us);
462        assert_ge!(b_after_update.time_password_changed, now_us);
463        assert_ge!(b_after_update.time_last_used, now_us);
464        // Should be two even though we updated twice
465        assert_eq!(b_after_update.times_used, 2);
466    }
467
468    #[test]
469    fn test_checkpoint() {
470        ensure_initialized();
471        let store = LoginStore::new_in_memory();
472        let checkpoint = "a-checkpoint";
473        store.set_checkpoint(checkpoint).ok();
474        assert_eq!(store.get_checkpoint().unwrap().unwrap(), checkpoint);
475    }
476
477    #[test]
478    fn test_sync_manager_registration() {
479        ensure_initialized();
480        let store = Arc::new(LoginStore::new_in_memory());
481        assert_eq!(Arc::strong_count(&store), 1);
482        assert_eq!(Arc::weak_count(&store), 0);
483        Arc::clone(&store).register_with_sync_manager();
484        assert_eq!(Arc::strong_count(&store), 1);
485        assert_eq!(Arc::weak_count(&store), 1);
486        let registered = STORE_FOR_MANAGER.lock().upgrade().expect("should upgrade");
487        assert!(Arc::ptr_eq(&store, &registered));
488        drop(registered);
489        // should be no new references
490        assert_eq!(Arc::strong_count(&store), 1);
491        assert_eq!(Arc::weak_count(&store), 1);
492        // dropping the registered object should drop the registration.
493        drop(store);
494        assert!(STORE_FOR_MANAGER.lock().upgrade().is_none());
495    }
496
497    #[test]
498    fn test_wipe_local_on_a_fresh_database_is_a_noop() {
499        ensure_initialized();
500        // If the database has data, then wipe_local() returns > 0 rows deleted
501        let db = LoginDb::open_in_memory();
502        db.add_or_update(
503            LoginEntry {
504                origin: "https://www.example.com".into(),
505                form_action_origin: Some("https://www.example.com".into()),
506                username_field: "user_input".into(),
507                password_field: "pass_input".into(),
508                username: "coolperson21".into(),
509                password: "p4ssw0rd".into(),
510                ..Default::default()
511            },
512            &TEST_ENCDEC.clone(),
513        )
514        .unwrap();
515        assert!(db.wipe_local().unwrap() > 0);
516
517        // If the database is empty, then wipe_local() returns 0 rows deleted
518        let db = LoginDb::open_in_memory();
519        assert_eq!(db.wipe_local().unwrap(), 0);
520    }
521
522    #[test]
523    fn test_shutdown() {
524        ensure_initialized();
525        let store = LoginStore::new_in_memory();
526        store.shutdown();
527        assert!(matches!(
528            store.list(),
529            Err(LoginsApiError::UnexpectedLoginsApiError { reason: _ })
530        ));
531        assert!(store.db.lock().is_none());
532    }
533
534    #[test]
535    fn test_delete_undecryptable_records_for_remote_replacement() {
536        ensure_initialized();
537        let store = Arc::new(LoginStore::new_in_memory());
538        // Not much of a test, but let's make sure this doesn't deadlock at least.
539        store
540            .delete_undecryptable_records_for_remote_replacement()
541            .unwrap();
542    }
543}
544
545#[test]
546fn test_send() {
547    fn ensure_send<T: Send>() {}
548    ensure_send::<LoginStore>();
549}