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, 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 run_maintenance(&self) -> ApiResult<()> {
167        let conn = self.db.lock().unwrap();
168        run_maintenance(&conn)?;
169        Ok(())
170    }
171
172    // This allows the embedding app to say "make this instance available to
173    // the sync manager". The implementation is more like "offer to sync mgr"
174    // (thereby avoiding us needing to link with the sync manager) but
175    // `register_with_sync_manager()` is logically what's happening so that's
176    // the name it gets.
177    pub fn register_with_sync_manager(self: Arc<Self>) {
178        let mut state = STORE_FOR_MANAGER.lock().unwrap();
179        *state = Arc::downgrade(&self);
180    }
181
182    // These 2 are a little odd - they aren't exposed by uniffi - currently the
183    // only consumer of this is our "example" (and hence why they
184    // are `pub` and not `pub(crate)`).
185    // We could probably make the example work with the sync manager - but then
186    // our example would link with places and logins etc, and it's not a big
187    // deal really.
188    pub fn create_credit_cards_sync_engine(self: Arc<Self>) -> Box<dyn SyncEngine> {
189        Box::new(crate::sync::credit_card::create_engine(self))
190    }
191
192    pub fn create_addresses_sync_engine(self: Arc<Self>) -> Box<dyn SyncEngine> {
193        Box::new(crate::sync::address::create_engine(self))
194    }
195}
196
197pub(crate) fn put_meta(conn: &Connection, key: &str, value: &dyn ToSql) -> Result<()> {
198    conn.execute_cached(
199        "REPLACE INTO moz_meta (key, value) VALUES (:key, :value)",
200        &[(":key", &key as &dyn ToSql), (":value", value)],
201    )?;
202    Ok(())
203}
204
205pub(crate) fn get_meta<T: FromSql>(conn: &Connection, key: &str) -> Result<Option<T>> {
206    let res = conn.try_query_one(
207        "SELECT value FROM moz_meta WHERE key = :key",
208        &[(":key", &key)],
209        true,
210    )?;
211    Ok(res)
212}
213
214pub(crate) fn delete_meta(conn: &Connection, key: &str) -> Result<()> {
215    conn.execute_cached("DELETE FROM moz_meta WHERE key = :key", &[(":key", &key)])?;
216    Ok(())
217}
218
219#[cfg(test)]
220mod tests {
221    use super::*;
222    use crate::db::test::new_mem_db;
223
224    #[test]
225    fn test_autofill_meta() -> Result<()> {
226        let db = new_mem_db();
227        let test_key = "TEST KEY A";
228        let test_value = "TEST VALUE A";
229        let test_key2 = "TEST KEY B";
230        let test_value2 = "TEST VALUE B";
231
232        put_meta(&db, test_key, &test_value)?;
233        put_meta(&db, test_key2, &test_value2)?;
234
235        let retrieved_value: String = get_meta(&db, test_key)?.expect("test value");
236        let retrieved_value2: String = get_meta(&db, test_key2)?.expect("test value 2");
237
238        assert_eq!(retrieved_value, test_value);
239        assert_eq!(retrieved_value2, test_value2);
240
241        // check that the value of an existing key can be updated
242        let test_value3 = "TEST VALUE C";
243        put_meta(&db, test_key, &test_value3)?;
244
245        let retrieved_value3: String = get_meta(&db, test_key)?.expect("test value 3");
246
247        assert_eq!(retrieved_value3, test_value3);
248
249        // check that a deleted key is not retrieved
250        delete_meta(&db, test_key)?;
251        let retrieved_value4: Option<String> = get_meta(&db, test_key)?;
252        assert!(retrieved_value4.is_none());
253
254        db.writer.execute("DELETE FROM moz_meta", [])?;
255
256        Ok(())
257    }
258
259    #[test]
260    fn test_sync_manager_registration() {
261        let store = Arc::new(Store::new_shared_memory("sync-mgr-test").unwrap());
262        assert_eq!(Arc::strong_count(&store), 1);
263        assert_eq!(Arc::weak_count(&store), 0);
264        Arc::clone(&store).register_with_sync_manager();
265        assert_eq!(Arc::strong_count(&store), 1);
266        assert_eq!(Arc::weak_count(&store), 1);
267        let registered = STORE_FOR_MANAGER
268            .lock()
269            .unwrap()
270            .upgrade()
271            .expect("should upgrade");
272        assert!(Arc::ptr_eq(&store, &registered));
273        drop(registered);
274        // should be no new references
275        assert_eq!(Arc::strong_count(&store), 1);
276        assert_eq!(Arc::weak_count(&store), 1);
277        // dropping the registered object should drop the registration.
278        drop(store);
279        assert!(STORE_FOR_MANAGER.lock().unwrap().upgrade().is_none());
280    }
281}