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 is_potentially_breached(&self, id: &str) -> ApiResult<bool> {
183        self.lock_db()?.is_potentially_breached(id)
184    }
185
186    #[handle_error(Error)]
187    pub fn record_breach(&self, id: &str, timestamp: i64) -> ApiResult<()> {
188        self.lock_db()?.record_breach(id, timestamp)
189    }
190
191    #[handle_error(Error)]
192    pub fn reset_all_breaches(&self) -> ApiResult<()> {
193        self.lock_db()?.reset_all_breaches()
194    }
195
196    #[handle_error(Error)]
197    pub fn is_breach_alert_dismissed(&self, id: &str) -> ApiResult<bool> {
198        self.lock_db()?.is_breach_alert_dismissed(id)
199    }
200
201    #[handle_error(Error)]
202    pub fn record_breach_alert_dismissal(&self, id: &str) -> ApiResult<()> {
203        self.lock_db()?.record_breach_alert_dismissal(id)
204    }
205
206    #[handle_error(Error)]
207    pub fn record_breach_alert_dismissal_time(&self, id: &str, timestamp: i64) -> ApiResult<()> {
208        self.lock_db()?
209            .record_breach_alert_dismissal_time(id, timestamp)
210    }
211
212    #[handle_error(Error)]
213    pub fn delete(&self, id: &str) -> ApiResult<bool> {
214        self.lock_db()?.delete(id)
215    }
216
217    #[handle_error(Error)]
218    pub fn delete_many(&self, ids: Vec<String>) -> ApiResult<Vec<bool>> {
219        // Note we need to receive a vector of String here because `Vec<&str>` is not supported
220        // with UDL.
221        let ids: Vec<&str> = ids.iter().map(|id| &**id).collect();
222        self.lock_db()?.delete_many(ids)
223    }
224
225    #[handle_error(Error)]
226    pub fn delete_undecryptable_records_for_remote_replacement(
227        self: Arc<Self>,
228    ) -> ApiResult<LoginsDeletionMetrics> {
229        // This function was created for the iOS logins verification logic that will
230        // remove records that prevent logins syncing. Once the verification logic is
231        // removed from iOS, this function can be removed from the store.
232
233        // Creating an engine requires locking the DB, so make sure to do this first
234        let engine = LoginsSyncEngine::new(Arc::clone(&self))?;
235
236        let db = self.lock_db()?;
237        let deletion_stats =
238            db.delete_undecryptable_records_for_remote_replacement(db.encdec.as_ref())?;
239        engine.set_last_sync(&db, ServerTimestamp(0))?;
240        Ok(deletion_stats)
241    }
242
243    #[handle_error(Error)]
244    pub fn wipe_local(&self) -> ApiResult<()> {
245        self.lock_db()?.wipe_local()?;
246        Ok(())
247    }
248
249    #[handle_error(Error)]
250    pub fn reset(self: Arc<Self>) -> ApiResult<()> {
251        // Reset should not exist here - all resets should be done via the
252        // sync manager. It seems that actual consumers don't use this, but
253        // some tests do, so it remains for now.
254        let engine = LoginsSyncEngine::new(Arc::clone(&self))?;
255        engine.do_reset(&EngineSyncAssociation::Disconnected)?;
256        Ok(())
257    }
258
259    #[handle_error(Error)]
260    pub fn update(&self, id: &str, entry: LoginEntry) -> ApiResult<Login> {
261        let db = self.lock_db()?;
262        db.update(id, entry, db.encdec.as_ref())
263            .and_then(|enc_login| enc_login.decrypt(db.encdec.as_ref()))
264    }
265
266    #[handle_error(Error)]
267    pub fn add(&self, entry: LoginEntry) -> ApiResult<Login> {
268        let db = self.lock_db()?;
269        db.add(entry, db.encdec.as_ref())
270            .and_then(|enc_login| enc_login.decrypt(db.encdec.as_ref()))
271    }
272
273    #[handle_error(Error)]
274    pub fn add_many(&self, entries: Vec<LoginEntry>) -> ApiResult<Vec<BulkResultEntry>> {
275        let db = self.lock_db()?;
276        db.add_many(entries, db.encdec.as_ref()).map(|enc_logins| {
277            enc_logins
278                .into_iter()
279                .map(|enc_login| map_bulk_result_entry(enc_login, db.encdec.as_ref()))
280                .collect()
281        })
282    }
283
284    /// This method is intended to preserve metadata (LoginMeta) during a migration.
285    /// In normal operation, this method should not be used; instead,
286    /// use `add(entry)`, which manages the corresponding fields itself.
287    #[handle_error(Error)]
288    pub fn add_with_meta(&self, entry_with_meta: LoginEntryWithMeta) -> ApiResult<Login> {
289        let db = self.lock_db()?;
290        db.add_with_meta(entry_with_meta, db.encdec.as_ref())
291            .and_then(|enc_login| enc_login.decrypt(db.encdec.as_ref()))
292    }
293
294    #[handle_error(Error)]
295    pub fn add_many_with_meta(
296        &self,
297        entries_with_meta: Vec<LoginEntryWithMeta>,
298    ) -> ApiResult<Vec<BulkResultEntry>> {
299        let db = self.lock_db()?;
300        db.add_many_with_meta(entries_with_meta, db.encdec.as_ref())
301            .map(|enc_logins| {
302                enc_logins
303                    .into_iter()
304                    .map(|enc_login| map_bulk_result_entry(enc_login, db.encdec.as_ref()))
305                    .collect()
306            })
307    }
308
309    #[handle_error(Error)]
310    pub fn add_or_update(&self, entry: LoginEntry) -> ApiResult<Login> {
311        let db = self.lock_db()?;
312        db.add_or_update(entry, db.encdec.as_ref())
313            .and_then(|enc_login| enc_login.decrypt(db.encdec.as_ref()))
314    }
315
316    #[handle_error(Error)]
317    pub fn set_checkpoint(&self, checkpoint: &str) -> ApiResult<()> {
318        self.lock_db()?
319            .put_meta(schema::CHECKPOINT_KEY, &checkpoint)
320    }
321
322    #[handle_error(Error)]
323    pub fn get_checkpoint(&self) -> ApiResult<Option<String>> {
324        self.lock_db()?.get_meta(schema::CHECKPOINT_KEY)
325    }
326
327    #[handle_error(Error)]
328    pub fn run_maintenance(&self) -> ApiResult<()> {
329        let conn = self.lock_db()?;
330        run_maintenance(&conn)?;
331        Ok(())
332    }
333
334    pub fn shutdown(&self) {
335        if let Some(db) = self.db.lock().take() {
336            let _ = db.shutdown();
337        }
338    }
339
340    // This allows the embedding app to say "make this instance available to
341    // the sync manager". The implementation is more like "offer to sync mgr"
342    // (thereby avoiding us needing to link with the sync manager) but
343    // `register_with_sync_manager()` is logically what's happening so that's
344    // the name it gets.
345    pub fn register_with_sync_manager(self: Arc<Self>) {
346        let mut state = STORE_FOR_MANAGER.lock();
347        *state = Arc::downgrade(&self);
348    }
349
350    // this isn't exposed by uniffi - currently the
351    // only consumer of this is our "example" (and hence why they
352    // are `pub` and not `pub(crate)`).
353    // We could probably make the example work with the sync manager - but then
354    // our example would link with places and logins etc, and it's not a big
355    // deal really.
356    #[handle_error(Error)]
357    pub fn create_logins_sync_engine(self: Arc<Self>) -> ApiResult<Box<dyn SyncEngine>> {
358        Ok(Box::new(LoginsSyncEngine::new(self)?) as Box<dyn SyncEngine>)
359    }
360}
361
362#[cfg(not(feature = "keydb"))]
363#[cfg(test)]
364mod tests {
365    use super::*;
366    use crate::encryption::test_utils::TEST_ENCDEC;
367    use crate::util;
368    use nss::ensure_initialized;
369    use std::cmp::Reverse;
370    use std::time::SystemTime;
371
372    fn assert_logins_equiv(a: &LoginEntry, b: &Login) {
373        assert_eq!(a.origin, b.origin);
374        assert_eq!(a.form_action_origin, b.form_action_origin);
375        assert_eq!(a.http_realm, b.http_realm);
376        assert_eq!(a.username_field, b.username_field);
377        assert_eq!(a.password_field, b.password_field);
378        assert_eq!(b.username, a.username);
379        assert_eq!(b.password, a.password);
380    }
381
382    #[test]
383    fn test_general() {
384        ensure_initialized();
385
386        let store = LoginStore::new_in_memory();
387        let list = store.list().expect("Grabbing Empty list to work");
388        assert_eq!(list.len(), 0);
389        let start_us = util::system_time_ms_i64(SystemTime::now());
390
391        let a = LoginEntry {
392            origin: "https://www.example.com".into(),
393            form_action_origin: Some("https://www.example.com".into()),
394            username_field: "user_input".into(),
395            password_field: "pass_input".into(),
396            username: "coolperson21".into(),
397            password: "p4ssw0rd".into(),
398            ..Default::default()
399        };
400
401        let b = LoginEntry {
402            origin: "https://www.example2.com".into(),
403            http_realm: Some("Some String Here".into()),
404            username: "asdf".into(),
405            password: "fdsa".into(),
406            ..Default::default()
407        };
408        let a_id = store.add(a.clone()).expect("added a").id;
409        let b_id = store.add(b.clone()).expect("added b").id;
410
411        let a_from_db = store
412            .get(&a_id)
413            .expect("Not to error getting a")
414            .expect("a to exist");
415
416        assert_logins_equiv(&a, &a_from_db);
417        assert!(a_from_db.time_created >= start_us);
418        assert!(a_from_db.time_password_changed >= start_us);
419        assert!(a_from_db.time_last_used >= start_us);
420        assert_eq!(a_from_db.times_used, 1);
421
422        let b_from_db = store
423            .get(&b_id)
424            .expect("Not to error getting b")
425            .expect("b to exist");
426
427        assert_logins_equiv(&LoginEntry { ..b.clone() }, &b_from_db);
428        assert!(b_from_db.time_created >= start_us);
429        assert!(b_from_db.time_password_changed >= start_us);
430        assert!(b_from_db.time_last_used >= start_us);
431        assert_eq!(b_from_db.times_used, 1);
432
433        let mut list = store.list().expect("Grabbing list to work");
434        assert_eq!(list.len(), 2);
435
436        let mut expect = vec![a_from_db, b_from_db.clone()];
437
438        list.sort_by_key(|b| Reverse(b.guid()));
439        expect.sort_by_key(|b| Reverse(b.guid()));
440        assert_eq!(list, expect);
441
442        store.delete(&a_id).expect("Successful delete");
443        assert!(store
444            .get(&a_id)
445            .expect("get after delete should still work")
446            .is_none());
447
448        let list = store.list().expect("Grabbing list to work");
449        assert_eq!(list.len(), 1);
450        assert_eq!(list[0], b_from_db);
451
452        let has_logins = store
453            .has_logins_by_base_domain("example2.com")
454            .expect("Expect a result for this origin");
455        assert!(has_logins);
456
457        let list = store
458            .get_by_base_domain("example2.com")
459            .expect("Expect a list for this origin");
460        assert_eq!(list.len(), 1);
461        assert_eq!(list[0], b_from_db);
462
463        let has_logins = store
464            .has_logins_by_base_domain("www.example.com")
465            .expect("Expect a result for this origin");
466        assert!(!has_logins);
467
468        let list = store
469            .get_by_base_domain("www.example.com")
470            .expect("Expect an empty list");
471        assert_eq!(list.len(), 0);
472
473        let now_us = util::system_time_ms_i64(SystemTime::now());
474        let b2 = LoginEntry {
475            username: b.username.to_owned(),
476            password: "newpass".into(),
477            ..b
478        };
479
480        store
481            .update(&b_id, b2.clone())
482            .expect("update b should work");
483
484        let b_after_update = store
485            .get(&b_id)
486            .expect("Not to error getting b")
487            .expect("b to exist");
488
489        assert_logins_equiv(&b2, &b_after_update);
490        assert!(b_after_update.time_created >= start_us);
491        assert!(b_after_update.time_created <= now_us);
492        assert!(b_after_update.time_password_changed >= now_us);
493        assert!(b_after_update.time_last_used >= now_us);
494        // Should be two even though we updated twice
495        assert_eq!(b_after_update.times_used, 2);
496    }
497
498    #[test]
499    fn test_checkpoint() {
500        ensure_initialized();
501        let store = LoginStore::new_in_memory();
502        let checkpoint = "a-checkpoint";
503        store.set_checkpoint(checkpoint).ok();
504        assert_eq!(store.get_checkpoint().unwrap().unwrap(), checkpoint);
505    }
506
507    #[test]
508    fn test_sync_manager_registration() {
509        ensure_initialized();
510        let store = Arc::new(LoginStore::new_in_memory());
511        assert_eq!(Arc::strong_count(&store), 1);
512        assert_eq!(Arc::weak_count(&store), 0);
513        Arc::clone(&store).register_with_sync_manager();
514        assert_eq!(Arc::strong_count(&store), 1);
515        assert_eq!(Arc::weak_count(&store), 1);
516        let registered = STORE_FOR_MANAGER.lock().upgrade().expect("should upgrade");
517        assert!(Arc::ptr_eq(&store, &registered));
518        drop(registered);
519        // should be no new references
520        assert_eq!(Arc::strong_count(&store), 1);
521        assert_eq!(Arc::weak_count(&store), 1);
522        // dropping the registered object should drop the registration.
523        drop(store);
524        assert!(STORE_FOR_MANAGER.lock().upgrade().is_none());
525    }
526
527    #[test]
528    fn test_wipe_local_on_a_fresh_database_is_a_noop() {
529        ensure_initialized();
530        // If the database has data, then wipe_local() returns > 0 rows deleted
531        let db = LoginDb::open_in_memory();
532        db.add_or_update(
533            LoginEntry {
534                origin: "https://www.example.com".into(),
535                form_action_origin: Some("https://www.example.com".into()),
536                username_field: "user_input".into(),
537                password_field: "pass_input".into(),
538                username: "coolperson21".into(),
539                password: "p4ssw0rd".into(),
540                ..Default::default()
541            },
542            &TEST_ENCDEC.clone(),
543        )
544        .unwrap();
545        assert!(db.wipe_local().unwrap() > 0);
546
547        // If the database is empty, then wipe_local() returns 0 rows deleted
548        let db = LoginDb::open_in_memory();
549        assert_eq!(db.wipe_local().unwrap(), 0);
550    }
551
552    #[test]
553    fn test_shutdown() {
554        ensure_initialized();
555        let store = LoginStore::new_in_memory();
556        store.shutdown();
557        assert!(matches!(
558            store.list(),
559            Err(LoginsApiError::UnexpectedLoginsApiError { reason: _ })
560        ));
561        assert!(store.db.lock().is_none());
562    }
563
564    #[test]
565    fn test_delete_undecryptable_records_for_remote_replacement() {
566        ensure_initialized();
567        let store = Arc::new(LoginStore::new_in_memory());
568        // Not much of a test, but let's make sure this doesn't deadlock at least.
569        store
570            .delete_undecryptable_records_for_remote_replacement()
571            .unwrap();
572    }
573}
574
575#[test]
576fn test_send() {
577    fn ensure_send<T: Send>() {}
578    ensure_send::<LoginStore>();
579}
580
581#[cfg(feature = "keydb")]
582#[cfg(test)]
583mod tests_keydb {
584    use super::*;
585    use crate::{ManagedEncryptorDecryptor, NSSKeyManager, PrimaryPasswordAuthenticator};
586    use async_trait::async_trait;
587    use nss::ensure_initialized_with_profile_dir;
588    use std::path::PathBuf;
589
590    struct MockPrimaryPasswordAuthenticator {
591        password: String,
592    }
593
594    #[async_trait]
595    impl PrimaryPasswordAuthenticator for MockPrimaryPasswordAuthenticator {
596        async fn get_primary_password(&self) -> ApiResult<String> {
597            Ok(self.password.clone())
598        }
599        async fn on_authentication_success(&self) -> ApiResult<()> {
600            Ok(())
601        }
602        async fn on_authentication_failure(&self) -> ApiResult<()> {
603            Ok(())
604        }
605    }
606
607    fn profile_path() -> PathBuf {
608        std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
609            .join("../support/rc_crypto/nss/fixtures/profile")
610    }
611
612    #[test]
613    fn decrypting_logins_with_primary_password() {
614        ensure_initialized_with_profile_dir(profile_path());
615
616        // `password` is the primary password of the profile fixture
617        let primary_password_authenticator = MockPrimaryPasswordAuthenticator {
618            password: "password".to_string(),
619        };
620        let key_manager = NSSKeyManager::new(Arc::new(primary_password_authenticator));
621        let encdec = ManagedEncryptorDecryptor::new(Arc::new(key_manager));
622        let store = LoginStore::new(profile_path().join("logins.db"), Arc::new(encdec))
623            .expect("store from fixtures");
624        let list = store.list().expect("Grabbing list to work");
625
626        assert_eq!(list.len(), 1);
627
628        assert_eq!(list[0].origin, "https://www.example.com");
629        assert_eq!(list[0].username, "test");
630        assert_eq!(list[0].password, "test");
631    }
632}