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