autofill/db/
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/. */
4
5use crate::db::models::address::{Address, UpdatableAddressFields};
6use crate::db::models::credit_card::{CreditCard, UpdatableCreditCardFields};
7use crate::db::{addresses, credit_cards, credit_cards::CreditCardsDeletionMetrics, AutofillDb};
8use crate::error::*;
9use error_support::handle_error;
10use rusqlite::{
11    types::{FromSql, ToSql},
12    Connection,
13};
14use sql_support::{self, run_maintenance, ConnExt};
15use std::path::Path;
16use std::sync::{Arc, Mutex, Weak};
17use sync15::engine::{SyncEngine, SyncEngineId};
18use sync_guid::Guid;
19
20// Our "sync manager" will use whatever is stashed here.
21lazy_static::lazy_static! {
22    // Mutex: just taken long enough to update the contents - needed to wrap
23    //        the Weak as it isn't `Sync`
24    // [Arc/Weak]<Store>: What the sync manager actually needs.
25    static ref STORE_FOR_MANAGER: Mutex<Weak<Store>> = Mutex::new(Weak::new());
26}
27
28/// Called by the sync manager to get a sync engine via the store previously
29/// registered with the sync manager.
30pub fn get_registered_sync_engine(engine_id: &SyncEngineId) -> Option<Box<dyn SyncEngine>> {
31    let weak = STORE_FOR_MANAGER.lock().unwrap();
32    match weak.upgrade() {
33        None => None,
34        Some(store) => match engine_id {
35            SyncEngineId::Addresses => Some(Box::new(crate::sync::address::create_engine(store))),
36            SyncEngineId::CreditCards => {
37                Some(Box::new(crate::sync::credit_card::create_engine(store)))
38            }
39            // panicking here seems reasonable - it's a static error if this
40            // it hit, not something that runtime conditions can influence.
41            _ => unreachable!("can't provide unknown engine: {}", engine_id),
42        },
43    }
44}
45
46// This is the type that uniffi exposes.
47pub struct Store {
48    pub(crate) db: Mutex<AutofillDb>,
49}
50
51impl Store {
52    #[handle_error(Error)]
53    pub fn new(db_path: impl AsRef<Path>) -> ApiResult<Self> {
54        Ok(Self {
55            db: Mutex::new(AutofillDb::new(db_path)?),
56        })
57    }
58
59    /// Creates a store backed by an in-memory database with its own memory API (required for unit tests).
60    #[cfg(test)]
61    pub fn new_memory() -> Self {
62        Self {
63            db: Mutex::new(crate::db::test::new_mem_db()),
64        }
65    }
66
67    /// Creates a store backed by an in-memory database that shares its memory API (required for autofill sync tests).
68    #[handle_error(Error)]
69    pub fn new_shared_memory(db_name: &str) -> ApiResult<Self> {
70        Ok(Self {
71            db: Mutex::new(AutofillDb::new_memory(db_name)?),
72        })
73    }
74
75    #[handle_error(Error)]
76    pub fn add_credit_card(&self, fields: UpdatableCreditCardFields) -> ApiResult<CreditCard> {
77        let credit_card = credit_cards::add_credit_card(&self.db.lock().unwrap().writer, fields)?;
78        Ok(credit_card.into())
79    }
80
81    #[handle_error(Error)]
82    pub fn get_credit_card(&self, guid: String) -> ApiResult<CreditCard> {
83        let credit_card =
84            credit_cards::get_credit_card(&self.db.lock().unwrap().writer, &Guid::new(&guid))?;
85        Ok(credit_card.into())
86    }
87
88    #[handle_error(Error)]
89    pub fn get_all_credit_cards(&self) -> ApiResult<Vec<CreditCard>> {
90        let credit_cards = credit_cards::get_all_credit_cards(&self.db.lock().unwrap().writer)?
91            .into_iter()
92            .map(|x| x.into())
93            .collect();
94        Ok(credit_cards)
95    }
96
97    #[handle_error(Error)]
98    pub fn update_credit_card(
99        &self,
100        guid: String,
101        credit_card: UpdatableCreditCardFields,
102    ) -> ApiResult<()> {
103        credit_cards::update_credit_card(
104            &self.db.lock().unwrap().writer,
105            &Guid::new(&guid),
106            &credit_card,
107        )
108    }
109
110    #[handle_error(Error)]
111    pub fn delete_credit_card(&self, guid: String) -> ApiResult<bool> {
112        credit_cards::delete_credit_card(&self.db.lock().unwrap().writer, &Guid::new(&guid))
113    }
114
115    #[handle_error(Error)]
116    pub fn touch_credit_card(&self, guid: String) -> ApiResult<()> {
117        credit_cards::touch(&self.db.lock().unwrap().writer, &Guid::new(&guid))
118    }
119
120    #[handle_error(Error)]
121    pub fn add_address(&self, new_address: UpdatableAddressFields) -> ApiResult<Address> {
122        Ok(addresses::add_address(&self.db.lock().unwrap().writer, new_address)?.into())
123    }
124
125    #[handle_error(Error)]
126    pub fn get_address(&self, guid: String) -> ApiResult<Address> {
127        Ok(addresses::get_address(&self.db.lock().unwrap().writer, &Guid::new(&guid))?.into())
128    }
129
130    #[handle_error(Error)]
131    pub fn get_all_addresses(&self) -> ApiResult<Vec<Address>> {
132        let addresses = addresses::get_all_addresses(&self.db.lock().unwrap().writer)?
133            .into_iter()
134            .map(|x| x.into())
135            .collect();
136        Ok(addresses)
137    }
138
139    #[handle_error(Error)]
140    pub fn update_address(&self, guid: String, address: UpdatableAddressFields) -> ApiResult<()> {
141        addresses::update_address(&self.db.lock().unwrap().writer, &Guid::new(&guid), &address)
142    }
143
144    #[handle_error(Error)]
145    pub fn delete_address(&self, guid: String) -> ApiResult<bool> {
146        addresses::delete_address(&self.db.lock().unwrap().writer, &Guid::new(&guid))
147    }
148
149    #[handle_error(Error)]
150    pub fn touch_address(&self, guid: String) -> ApiResult<()> {
151        addresses::touch(&self.db.lock().unwrap().writer, &Guid::new(&guid))
152    }
153
154    #[handle_error(Error)]
155    pub fn scrub_encrypted_data(self: Arc<Self>) -> ApiResult<()> {
156        // scrub the data on disk
157        // Currently only credit cards have encrypted data
158        credit_cards::scrub_encrypted_credit_card_data(&self.db.lock().unwrap().writer)?;
159        // Force the sync engine to refetch data (only need to do this for the credit cards, since the
160        // addresses engine doesn't store encrypted data).
161        crate::sync::credit_card::create_engine(self).reset_local_sync_data()?;
162        Ok(())
163    }
164
165    #[handle_error(Error)]
166    pub fn scrub_undecryptable_credit_card_data_for_remote_replacement(
167        self: Arc<Self>,
168        local_encryption_key: String,
169    ) -> ApiResult<CreditCardsDeletionMetrics> {
170        let db = &self.db.lock().unwrap().writer;
171        let deletion_stats =
172            credit_cards::scrub_undecryptable_credit_card_data_for_remote_replacement(
173                db,
174                local_encryption_key,
175            )?;
176
177        // Here we reset the local sync data so that the credit card engine syncs as if
178        // it were the first sync. This will potentially allow a previous sync of the
179        // record that exists on the sync server to overwrite the local record and restore
180        // the scrubbed credit card number.
181        crate::sync::credit_card::create_engine(self.clone())
182            .reset_local_sync_data_for_verification(db)?;
183        Ok(deletion_stats)
184    }
185
186    #[handle_error(Error)]
187    pub fn run_maintenance(&self) -> ApiResult<()> {
188        let conn = self.db.lock().unwrap();
189        run_maintenance(&conn)?;
190        Ok(())
191    }
192
193    // This allows the embedding app to say "make this instance available to
194    // the sync manager". The implementation is more like "offer to sync mgr"
195    // (thereby avoiding us needing to link with the sync manager) but
196    // `register_with_sync_manager()` is logically what's happening so that's
197    // the name it gets.
198    pub fn register_with_sync_manager(self: Arc<Self>) {
199        let mut state = STORE_FOR_MANAGER.lock().unwrap();
200        *state = Arc::downgrade(&self);
201    }
202
203    // These 2 are a little odd - they aren't exposed by uniffi - currently the
204    // only consumer of this is our "example" (and hence why they
205    // are `pub` and not `pub(crate)`).
206    // We could probably make the example work with the sync manager - but then
207    // our example would link with places and logins etc, and it's not a big
208    // deal really.
209    pub fn create_credit_cards_sync_engine(self: Arc<Self>) -> Box<dyn SyncEngine> {
210        Box::new(crate::sync::credit_card::create_engine(self))
211    }
212
213    pub fn create_addresses_sync_engine(self: Arc<Self>) -> Box<dyn SyncEngine> {
214        Box::new(crate::sync::address::create_engine(self))
215    }
216}
217
218pub(crate) fn put_meta(conn: &Connection, key: &str, value: &dyn ToSql) -> Result<()> {
219    conn.execute_cached(
220        "REPLACE INTO moz_meta (key, value) VALUES (:key, :value)",
221        &[(":key", &key as &dyn ToSql), (":value", value)],
222    )?;
223    Ok(())
224}
225
226pub(crate) fn get_meta<T: FromSql>(conn: &Connection, key: &str) -> Result<Option<T>> {
227    let res = conn.try_query_one(
228        "SELECT value FROM moz_meta WHERE key = :key",
229        &[(":key", &key)],
230        true,
231    )?;
232    Ok(res)
233}
234
235pub(crate) fn delete_meta(conn: &Connection, key: &str) -> Result<()> {
236    conn.execute_cached("DELETE FROM moz_meta WHERE key = :key", &[(":key", &key)])?;
237    Ok(())
238}
239
240#[cfg(test)]
241mod tests {
242    use super::*;
243    use crate::db::test::new_mem_db;
244    use crate::encryption::EncryptorDecryptor;
245    use nss::ensure_initialized;
246
247    #[test]
248    fn test_autofill_meta() -> Result<()> {
249        let db = new_mem_db();
250        let test_key = "TEST KEY A";
251        let test_value = "TEST VALUE A";
252        let test_key2 = "TEST KEY B";
253        let test_value2 = "TEST VALUE B";
254
255        put_meta(&db, test_key, &test_value)?;
256        put_meta(&db, test_key2, &test_value2)?;
257
258        let retrieved_value: String = get_meta(&db, test_key)?.expect("test value");
259        let retrieved_value2: String = get_meta(&db, test_key2)?.expect("test value 2");
260
261        assert_eq!(retrieved_value, test_value);
262        assert_eq!(retrieved_value2, test_value2);
263
264        // check that the value of an existing key can be updated
265        let test_value3 = "TEST VALUE C";
266        put_meta(&db, test_key, &test_value3)?;
267
268        let retrieved_value3: String = get_meta(&db, test_key)?.expect("test value 3");
269
270        assert_eq!(retrieved_value3, test_value3);
271
272        // check that a deleted key is not retrieved
273        delete_meta(&db, test_key)?;
274        let retrieved_value4: Option<String> = get_meta(&db, test_key)?;
275        assert!(retrieved_value4.is_none());
276
277        db.writer.execute("DELETE FROM moz_meta", [])?;
278
279        Ok(())
280    }
281
282    #[test]
283    fn test_sync_manager_registration() {
284        let store = Arc::new(Store::new_shared_memory("sync-mgr-test").unwrap());
285        assert_eq!(Arc::strong_count(&store), 1);
286        assert_eq!(Arc::weak_count(&store), 0);
287        Arc::clone(&store).register_with_sync_manager();
288        assert_eq!(Arc::strong_count(&store), 1);
289        assert_eq!(Arc::weak_count(&store), 1);
290        let registered = STORE_FOR_MANAGER
291            .lock()
292            .unwrap()
293            .upgrade()
294            .expect("should upgrade");
295        assert!(Arc::ptr_eq(&store, &registered));
296        drop(registered);
297        // should be no new references
298        assert_eq!(Arc::strong_count(&store), 1);
299        assert_eq!(Arc::weak_count(&store), 1);
300        // dropping the registered object should drop the registration.
301        drop(store);
302        assert!(STORE_FOR_MANAGER.lock().unwrap().upgrade().is_none());
303    }
304
305    #[test]
306    fn test_scrub_undecryptable_credit_card_data_for_remote_replacement() {
307        ensure_initialized();
308        let store = Arc::new(Store::new_shared_memory("sync-mgr-test").expect("create store"));
309        let key = EncryptorDecryptor::create_key().expect("create key");
310        let encdec = EncryptorDecryptor::new(&key).expect("create EncryptorDecryptor");
311
312        store
313            .add_credit_card(UpdatableCreditCardFields {
314                cc_name: "john deer".to_string(),
315                cc_number_enc: encdec
316                    .encrypt("567812345678123456781")
317                    .expect("encrypt cc number"),
318                cc_number_last_4: "6781".to_string(),
319                cc_exp_month: 10,
320                cc_exp_year: 2025,
321                cc_type: "mastercard".to_string(),
322            })
323            .expect("add credit card to database");
324
325        store
326            .scrub_undecryptable_credit_card_data_for_remote_replacement(key)
327            .expect("scrub credit card record");
328    }
329}