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 tests {
334    use super::*;
335    use crate::encryption::test_utils::TEST_ENCDEC;
336    use crate::util;
337    use nss::ensure_initialized;
338    use std::cmp::Reverse;
339    use std::time::SystemTime;
340
341    fn assert_logins_equiv(a: &LoginEntry, b: &Login) {
342        assert_eq!(a.origin, b.origin);
343        assert_eq!(a.form_action_origin, b.form_action_origin);
344        assert_eq!(a.http_realm, b.http_realm);
345        assert_eq!(a.username_field, b.username_field);
346        assert_eq!(a.password_field, b.password_field);
347        assert_eq!(b.username, a.username);
348        assert_eq!(b.password, a.password);
349    }
350
351    #[test]
352    fn test_general() {
353        ensure_initialized();
354
355        let store = LoginStore::new_in_memory();
356        let list = store.list().expect("Grabbing Empty list to work");
357        assert_eq!(list.len(), 0);
358        let start_us = util::system_time_ms_i64(SystemTime::now());
359
360        let a = LoginEntry {
361            origin: "https://www.example.com".into(),
362            form_action_origin: Some("https://www.example.com".into()),
363            username_field: "user_input".into(),
364            password_field: "pass_input".into(),
365            username: "coolperson21".into(),
366            password: "p4ssw0rd".into(),
367            ..Default::default()
368        };
369
370        let b = LoginEntry {
371            origin: "https://www.example2.com".into(),
372            http_realm: Some("Some String Here".into()),
373            username: "asdf".into(),
374            password: "fdsa".into(),
375            ..Default::default()
376        };
377        let a_id = store.add(a.clone()).expect("added a").id;
378        let b_id = store.add(b.clone()).expect("added b").id;
379
380        let a_from_db = store
381            .get(&a_id)
382            .expect("Not to error getting a")
383            .expect("a to exist");
384
385        assert_logins_equiv(&a, &a_from_db);
386        assert!(a_from_db.time_created >= start_us);
387        assert!(a_from_db.time_password_changed >= start_us);
388        assert!(a_from_db.time_last_used >= start_us);
389        assert_eq!(a_from_db.times_used, 1);
390
391        let b_from_db = store
392            .get(&b_id)
393            .expect("Not to error getting b")
394            .expect("b to exist");
395
396        assert_logins_equiv(&LoginEntry { ..b.clone() }, &b_from_db);
397        assert!(b_from_db.time_created >= start_us);
398        assert!(b_from_db.time_password_changed >= start_us);
399        assert!(b_from_db.time_last_used >= start_us);
400        assert_eq!(b_from_db.times_used, 1);
401
402        let mut list = store.list().expect("Grabbing list to work");
403        assert_eq!(list.len(), 2);
404
405        let mut expect = vec![a_from_db, b_from_db.clone()];
406
407        list.sort_by_key(|b| Reverse(b.guid()));
408        expect.sort_by_key(|b| Reverse(b.guid()));
409        assert_eq!(list, expect);
410
411        store.delete(&a_id).expect("Successful delete");
412        assert!(store
413            .get(&a_id)
414            .expect("get after delete should still work")
415            .is_none());
416
417        let list = store.list().expect("Grabbing list to work");
418        assert_eq!(list.len(), 1);
419        assert_eq!(list[0], b_from_db);
420
421        let has_logins = store
422            .has_logins_by_base_domain("example2.com")
423            .expect("Expect a result for this origin");
424        assert!(has_logins);
425
426        let list = store
427            .get_by_base_domain("example2.com")
428            .expect("Expect a list for this origin");
429        assert_eq!(list.len(), 1);
430        assert_eq!(list[0], b_from_db);
431
432        let has_logins = store
433            .has_logins_by_base_domain("www.example.com")
434            .expect("Expect a result for this origin");
435        assert!(!has_logins);
436
437        let list = store
438            .get_by_base_domain("www.example.com")
439            .expect("Expect an empty list");
440        assert_eq!(list.len(), 0);
441
442        let now_us = util::system_time_ms_i64(SystemTime::now());
443        let b2 = LoginEntry {
444            username: b.username.to_owned(),
445            password: "newpass".into(),
446            ..b
447        };
448
449        store
450            .update(&b_id, b2.clone())
451            .expect("update b should work");
452
453        let b_after_update = store
454            .get(&b_id)
455            .expect("Not to error getting b")
456            .expect("b to exist");
457
458        assert_logins_equiv(&b2, &b_after_update);
459        assert!(b_after_update.time_created >= start_us);
460        assert!(b_after_update.time_created <= now_us);
461        assert!(b_after_update.time_password_changed >= now_us);
462        assert!(b_after_update.time_last_used >= now_us);
463        // Should be two even though we updated twice
464        assert_eq!(b_after_update.times_used, 2);
465    }
466
467    #[test]
468    fn test_checkpoint() {
469        ensure_initialized();
470        let store = LoginStore::new_in_memory();
471        let checkpoint = "a-checkpoint";
472        store.set_checkpoint(checkpoint).ok();
473        assert_eq!(store.get_checkpoint().unwrap().unwrap(), checkpoint);
474    }
475
476    #[test]
477    fn test_sync_manager_registration() {
478        ensure_initialized();
479        let store = Arc::new(LoginStore::new_in_memory());
480        assert_eq!(Arc::strong_count(&store), 1);
481        assert_eq!(Arc::weak_count(&store), 0);
482        Arc::clone(&store).register_with_sync_manager();
483        assert_eq!(Arc::strong_count(&store), 1);
484        assert_eq!(Arc::weak_count(&store), 1);
485        let registered = STORE_FOR_MANAGER.lock().upgrade().expect("should upgrade");
486        assert!(Arc::ptr_eq(&store, &registered));
487        drop(registered);
488        // should be no new references
489        assert_eq!(Arc::strong_count(&store), 1);
490        assert_eq!(Arc::weak_count(&store), 1);
491        // dropping the registered object should drop the registration.
492        drop(store);
493        assert!(STORE_FOR_MANAGER.lock().upgrade().is_none());
494    }
495
496    #[test]
497    fn test_wipe_local_on_a_fresh_database_is_a_noop() {
498        ensure_initialized();
499        // If the database has data, then wipe_local() returns > 0 rows deleted
500        let db = LoginDb::open_in_memory();
501        db.add_or_update(
502            LoginEntry {
503                origin: "https://www.example.com".into(),
504                form_action_origin: Some("https://www.example.com".into()),
505                username_field: "user_input".into(),
506                password_field: "pass_input".into(),
507                username: "coolperson21".into(),
508                password: "p4ssw0rd".into(),
509                ..Default::default()
510            },
511            &TEST_ENCDEC.clone(),
512        )
513        .unwrap();
514        assert!(db.wipe_local().unwrap() > 0);
515
516        // If the database is empty, then wipe_local() returns 0 rows deleted
517        let db = LoginDb::open_in_memory();
518        assert_eq!(db.wipe_local().unwrap(), 0);
519    }
520
521    #[test]
522    fn test_shutdown() {
523        ensure_initialized();
524        let store = LoginStore::new_in_memory();
525        store.shutdown();
526        assert!(matches!(
527            store.list(),
528            Err(LoginsApiError::UnexpectedLoginsApiError { reason: _ })
529        ));
530        assert!(store.db.lock().is_none());
531    }
532
533    #[test]
534    fn test_delete_undecryptable_records_for_remote_replacement() {
535        ensure_initialized();
536        let store = Arc::new(LoginStore::new_in_memory());
537        // Not much of a test, but let's make sure this doesn't deadlock at least.
538        store
539            .delete_undecryptable_records_for_remote_replacement()
540            .unwrap();
541    }
542}
543
544#[test]
545fn test_send() {
546    fn ensure_send<T: Send>() {}
547    ensure_send::<LoginStore>();
548}
549
550#[cfg(feature = "keydb")]
551#[cfg(test)]
552mod tests_keydb {
553    use super::*;
554    use crate::{ManagedEncryptorDecryptor, NSSKeyManager, PrimaryPasswordAuthenticator};
555    use async_trait::async_trait;
556    use nss::ensure_initialized_with_profile_dir;
557    use std::path::PathBuf;
558
559    struct MockPrimaryPasswordAuthenticator {
560        password: String,
561    }
562
563    #[async_trait]
564    impl PrimaryPasswordAuthenticator for MockPrimaryPasswordAuthenticator {
565        async fn get_primary_password(&self) -> ApiResult<String> {
566            Ok(self.password.clone())
567        }
568        async fn on_authentication_success(&self) -> ApiResult<()> {
569            Ok(())
570        }
571        async fn on_authentication_failure(&self) -> ApiResult<()> {
572            Ok(())
573        }
574    }
575
576    fn profile_path() -> PathBuf {
577        std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
578            .join("../support/rc_crypto/nss/fixtures/profile")
579    }
580
581    #[test]
582    fn decrypting_logins_with_primary_password() {
583        ensure_initialized_with_profile_dir(profile_path());
584
585        // `password` is the primary password of the profile fixture
586        let primary_password_authenticator = MockPrimaryPasswordAuthenticator {
587            password: "password".to_string(),
588        };
589        let key_manager = NSSKeyManager::new(Arc::new(primary_password_authenticator));
590        let encdec = ManagedEncryptorDecryptor::new(Arc::new(key_manager));
591        let store = LoginStore::new(profile_path().join("logins.db"), Arc::new(encdec))
592            .expect("store from fixtures");
593        let list = store.list().expect("Grabbing list to work");
594
595        assert_eq!(list.len(), 1);
596
597        assert_eq!(list[0].origin, "https://www.example.com");
598        assert_eq!(list[0].username, "test");
599        assert_eq!(list[0].password, "test");
600    }
601}