blob: 8a4d7d82d54556caea324c1160c40d7ae8dc0acf [file] [log] [blame]
Janis Danisevskis77d72042021-01-20 15:36:30 -08001// Copyright 2020, The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
Janis Danisevskis3eb829d2021-06-14 14:18:20 -070015//! Implements the android.security.legacykeystore interface.
Janis Danisevskis77d72042021-01-20 15:36:30 -080016
Janis Danisevskis3eb829d2021-06-14 14:18:20 -070017use android_security_legacykeystore::aidl::android::security::legacykeystore::{
18 ILegacyKeystore::BnLegacyKeystore, ILegacyKeystore::ILegacyKeystore,
19 ILegacyKeystore::ERROR_ENTRY_NOT_FOUND, ILegacyKeystore::ERROR_PERMISSION_DENIED,
20 ILegacyKeystore::ERROR_SYSTEM_ERROR, ILegacyKeystore::UID_SELF,
Janis Danisevskis77d72042021-01-20 15:36:30 -080021};
Janis Danisevskis3eb829d2021-06-14 14:18:20 -070022use android_security_legacykeystore::binder::{
Andrew Walbrande45c8b2021-04-13 14:42:38 +000023 BinderFeatures, ExceptionCode, Result as BinderResult, Status as BinderStatus, Strong,
24 ThreadState,
25};
Seth Moorefbe5cf52021-06-09 15:59:00 -070026use anyhow::{Context, Result};
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +000027use keystore2::{async_task::AsyncTask, legacy_blob::LegacyBlobLoader, utils::watchdog as wd};
Janis Danisevskis77d72042021-01-20 15:36:30 -080028use rusqlite::{
29 params, Connection, OptionalExtension, Transaction, TransactionBehavior, NO_PARAMS,
30};
Janis Danisevskis06891072021-02-11 10:28:17 -080031use std::{
32 collections::HashSet,
33 path::{Path, PathBuf},
34};
Janis Danisevskis77d72042021-01-20 15:36:30 -080035
36struct DB {
37 conn: Connection,
38}
39
40impl DB {
41 fn new(db_file: &Path) -> Result<Self> {
42 let mut db = Self {
43 conn: Connection::open(db_file).context("Failed to initialize SQLite connection.")?,
44 };
Janis Danisevskis1be7e182021-04-12 14:31:12 -070045
Janis Danisevskis3eb829d2021-06-14 14:18:20 -070046 db.init_tables().context("Trying to initialize legacy keystore db.")?;
Janis Danisevskis77d72042021-01-20 15:36:30 -080047 Ok(db)
48 }
49
50 fn with_transaction<T, F>(&mut self, behavior: TransactionBehavior, f: F) -> Result<T>
51 where
52 F: Fn(&Transaction) -> Result<T>,
53 {
54 loop {
55 match self
56 .conn
57 .transaction_with_behavior(behavior)
58 .context("In with_transaction.")
59 .and_then(|tx| f(&tx).map(|result| (result, tx)))
60 .and_then(|(result, tx)| {
61 tx.commit().context("In with_transaction: Failed to commit transaction.")?;
62 Ok(result)
63 }) {
64 Ok(result) => break Ok(result),
65 Err(e) => {
66 if Self::is_locked_error(&e) {
67 std::thread::sleep(std::time::Duration::from_micros(500));
68 continue;
69 } else {
70 return Err(e).context("In with_transaction.");
71 }
72 }
73 }
74 }
75 }
76
77 fn is_locked_error(e: &anyhow::Error) -> bool {
Janis Danisevskis13f09152021-04-19 09:55:15 -070078 matches!(
79 e.root_cause().downcast_ref::<rusqlite::ffi::Error>(),
80 Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. })
81 | Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseLocked, .. })
82 )
Janis Danisevskis77d72042021-01-20 15:36:30 -080083 }
84
85 fn init_tables(&mut self) -> Result<()> {
86 self.with_transaction(TransactionBehavior::Immediate, |tx| {
87 tx.execute(
88 "CREATE TABLE IF NOT EXISTS profiles (
89 owner INTEGER,
90 alias BLOB,
91 profile BLOB,
92 UNIQUE(owner, alias));",
93 NO_PARAMS,
94 )
95 .context("Failed to initialize \"profiles\" table.")?;
96 Ok(())
97 })
98 }
99
100 fn list(&mut self, caller_uid: u32) -> Result<Vec<String>> {
101 self.with_transaction(TransactionBehavior::Deferred, |tx| {
102 let mut stmt = tx
103 .prepare("SELECT alias FROM profiles WHERE owner = ? ORDER BY alias ASC;")
104 .context("In list: Failed to prepare statement.")?;
105
106 let aliases = stmt
107 .query_map(params![caller_uid], |row| row.get(0))?
108 .collect::<rusqlite::Result<Vec<String>>>()
109 .context("In list: query_map failed.");
110 aliases
111 })
112 }
113
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700114 fn put(&mut self, caller_uid: u32, alias: &str, entry: &[u8]) -> Result<()> {
Janis Danisevskis77d72042021-01-20 15:36:30 -0800115 self.with_transaction(TransactionBehavior::Immediate, |tx| {
116 tx.execute(
117 "INSERT OR REPLACE INTO profiles (owner, alias, profile) values (?, ?, ?)",
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700118 params![caller_uid, alias, entry,],
Janis Danisevskis77d72042021-01-20 15:36:30 -0800119 )
120 .context("In put: Failed to insert or replace.")?;
121 Ok(())
122 })
123 }
124
125 fn get(&mut self, caller_uid: u32, alias: &str) -> Result<Option<Vec<u8>>> {
126 self.with_transaction(TransactionBehavior::Deferred, |tx| {
127 tx.query_row(
128 "SELECT profile FROM profiles WHERE owner = ? AND alias = ?;",
129 params![caller_uid, alias],
130 |row| row.get(0),
131 )
132 .optional()
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700133 .context("In get: failed loading entry.")
Janis Danisevskis77d72042021-01-20 15:36:30 -0800134 })
135 }
136
137 fn remove(&mut self, caller_uid: u32, alias: &str) -> Result<bool> {
138 let removed = self.with_transaction(TransactionBehavior::Immediate, |tx| {
139 tx.execute(
140 "DELETE FROM profiles WHERE owner = ? AND alias = ?;",
141 params![caller_uid, alias],
142 )
143 .context("In remove: Failed to delete row.")
144 })?;
145 Ok(removed == 1)
146 }
147}
148
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700149/// This is the main LegacyKeystore error type, it wraps binder exceptions and the
150/// LegacyKeystore errors.
Janis Danisevskis77d72042021-01-20 15:36:30 -0800151#[derive(Debug, thiserror::Error, PartialEq)]
152pub enum Error {
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700153 /// Wraps a LegacyKeystore error code.
Janis Danisevskis77d72042021-01-20 15:36:30 -0800154 #[error("Error::Error({0:?})")]
155 Error(i32),
156 /// Wraps a Binder exception code other than a service specific exception.
157 #[error("Binder exception code {0:?}, {1:?}")]
158 Binder(ExceptionCode, i32),
159}
160
161impl Error {
162 /// Short hand for `Error::Error(ERROR_SYSTEM_ERROR)`
163 pub fn sys() -> Self {
164 Error::Error(ERROR_SYSTEM_ERROR)
165 }
166
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700167 /// Short hand for `Error::Error(ERROR_ENTRY_NOT_FOUND)`
Janis Danisevskis77d72042021-01-20 15:36:30 -0800168 pub fn not_found() -> Self {
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700169 Error::Error(ERROR_ENTRY_NOT_FOUND)
170 }
171
172 /// Short hand for `Error::Error(ERROR_PERMISSION_DENIED)`
173 pub fn perm() -> Self {
174 Error::Error(ERROR_PERMISSION_DENIED)
Janis Danisevskis77d72042021-01-20 15:36:30 -0800175 }
176}
177
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700178/// This function should be used by legacykeystore service calls to translate error conditions
Janis Danisevskis77d72042021-01-20 15:36:30 -0800179/// into service specific exceptions.
180///
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700181/// All error conditions get logged by this function, except for ERROR_ENTRY_NOT_FOUND error.
Janis Danisevskis77d72042021-01-20 15:36:30 -0800182///
183/// `Error::Error(x)` variants get mapped onto a service specific error code of `x`.
184///
185/// All non `Error` error conditions get mapped onto `ERROR_SYSTEM_ERROR`.
186///
187/// `handle_ok` will be called if `result` is `Ok(value)` where `value` will be passed
188/// as argument to `handle_ok`. `handle_ok` must generate a `BinderResult<T>`, but it
189/// typically returns Ok(value).
190fn map_or_log_err<T, U, F>(result: Result<U>, handle_ok: F) -> BinderResult<T>
191where
192 F: FnOnce(U) -> BinderResult<T>,
193{
194 result.map_or_else(
195 |e| {
Janis Danisevskis77d72042021-01-20 15:36:30 -0800196 let root_cause = e.root_cause();
Hasini Gunasinghee1d1bbd2021-04-20 18:13:25 +0000197 let (rc, log_error) = match root_cause.downcast_ref::<Error>() {
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700198 // Make the entry not found errors silent.
199 Some(Error::Error(ERROR_ENTRY_NOT_FOUND)) => (ERROR_ENTRY_NOT_FOUND, false),
Hasini Gunasinghee1d1bbd2021-04-20 18:13:25 +0000200 Some(Error::Error(e)) => (*e, true),
201 Some(Error::Binder(_, _)) | None => (ERROR_SYSTEM_ERROR, true),
Janis Danisevskis77d72042021-01-20 15:36:30 -0800202 };
Hasini Gunasinghee1d1bbd2021-04-20 18:13:25 +0000203 if log_error {
204 log::error!("{:?}", e);
205 }
Janis Danisevskis77d72042021-01-20 15:36:30 -0800206 Err(BinderStatus::new_service_specific_error(rc, None))
207 },
208 handle_ok,
209 )
210}
211
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700212/// Implements ILegacyKeystore AIDL interface.
213pub struct LegacyKeystore {
Janis Danisevskis77d72042021-01-20 15:36:30 -0800214 db_path: PathBuf,
Janis Danisevskis06891072021-02-11 10:28:17 -0800215 async_task: AsyncTask,
216}
217
218struct AsyncState {
219 recently_imported: HashSet<(u32, String)>,
220 legacy_loader: LegacyBlobLoader,
221 db_path: PathBuf,
Janis Danisevskis77d72042021-01-20 15:36:30 -0800222}
223
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700224impl LegacyKeystore {
225 /// Note: The filename was chosen before the purpose of this module was extended.
226 /// It is kept for backward compatibility with early adopters.
227 const LEGACY_KEYSTORE_FILE_NAME: &'static str = "vpnprofilestore.sqlite";
228
229 /// Creates a new LegacyKeystore instance.
230 pub fn new_native_binder(path: &Path) -> Strong<dyn ILegacyKeystore> {
Janis Danisevskis77d72042021-01-20 15:36:30 -0800231 let mut db_path = path.to_path_buf();
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700232 db_path.push(Self::LEGACY_KEYSTORE_FILE_NAME);
Janis Danisevskis06891072021-02-11 10:28:17 -0800233
234 let result = Self { db_path, async_task: Default::default() };
235 result.init_shelf(path);
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700236 BnLegacyKeystore::new_binder(result, BinderFeatures::default())
Janis Danisevskis77d72042021-01-20 15:36:30 -0800237 }
238
239 fn open_db(&self) -> Result<DB> {
240 DB::new(&self.db_path).context("In open_db: Failed to open db.")
241 }
242
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700243 fn get_effective_uid(uid: i32) -> Result<u32> {
244 const AID_SYSTEM: u32 = 1000;
245 const AID_WIFI: u32 = 1010;
Janis Danisevskis77d72042021-01-20 15:36:30 -0800246 let calling_uid = ThreadState::get_calling_uid();
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700247 let uid = uid as u32;
Janis Danisevskis06891072021-02-11 10:28:17 -0800248
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700249 if uid == UID_SELF as u32 || uid == calling_uid {
250 Ok(calling_uid)
251 } else if calling_uid == AID_SYSTEM && uid == AID_WIFI {
252 // The only exception for legacy reasons is allowing SYSTEM to access
253 // the WIFI namespace.
254 // IMPORTANT: If you attempt to add more exceptions, it means you are adding
255 // more callers to this deprecated feature. DON'T!
256 Ok(AID_WIFI)
257 } else {
258 Err(Error::perm()).with_context(|| {
259 format!("In get_effective_uid: caller: {}, requested uid: {}.", calling_uid, uid)
260 })
Janis Danisevskis06891072021-02-11 10:28:17 -0800261 }
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700262 }
263
264 fn get(&self, alias: &str, uid: i32) -> Result<Vec<u8>> {
265 let mut db = self.open_db().context("In get.")?;
266 let uid = Self::get_effective_uid(uid).context("In get.")?;
267
268 if let Some(entry) = db.get(uid, alias).context("In get: Trying to load entry from DB.")? {
269 return Ok(entry);
270 }
271 if self.get_legacy(uid, alias).context("In get: Trying to migrate legacy blob.")? {
Janis Danisevskis06891072021-02-11 10:28:17 -0800272 // If we were able to migrate a legacy blob try again.
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700273 if let Some(entry) =
274 db.get(uid, alias).context("In get: Trying to load entry from DB.")?
Janis Danisevskis06891072021-02-11 10:28:17 -0800275 {
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700276 return Ok(entry);
Janis Danisevskis06891072021-02-11 10:28:17 -0800277 }
278 }
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700279 Err(Error::not_found()).context("In get: No such entry.")
Janis Danisevskis77d72042021-01-20 15:36:30 -0800280 }
281
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700282 fn put(&self, alias: &str, uid: i32, entry: &[u8]) -> Result<()> {
283 let uid = Self::get_effective_uid(uid).context("In put.")?;
284 // In order to make sure that we don't have stale legacy entries, make sure they are
Janis Danisevskis06891072021-02-11 10:28:17 -0800285 // migrated before replacing them.
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700286 let _ = self.get_legacy(uid, alias);
Janis Danisevskis06891072021-02-11 10:28:17 -0800287 let mut db = self.open_db().context("In put.")?;
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700288 db.put(uid, alias, entry).context("In put: Trying to insert entry into DB.")
Janis Danisevskis77d72042021-01-20 15:36:30 -0800289 }
290
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700291 fn remove(&self, alias: &str, uid: i32) -> Result<()> {
292 let uid = Self::get_effective_uid(uid).context("In remove.")?;
Janis Danisevskis06891072021-02-11 10:28:17 -0800293 let mut db = self.open_db().context("In remove.")?;
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700294 // In order to make sure that we don't have stale legacy entries, make sure they are
Janis Danisevskis06891072021-02-11 10:28:17 -0800295 // migrated before removing them.
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700296 let _ = self.get_legacy(uid, alias);
297 let removed =
298 db.remove(uid, alias).context("In remove: Trying to remove entry from DB.")?;
Janis Danisevskis77d72042021-01-20 15:36:30 -0800299 if removed {
300 Ok(())
301 } else {
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700302 Err(Error::not_found()).context("In remove: No such entry.")
Janis Danisevskis77d72042021-01-20 15:36:30 -0800303 }
304 }
305
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700306 fn list(&self, prefix: &str, uid: i32) -> Result<Vec<String>> {
Janis Danisevskis77d72042021-01-20 15:36:30 -0800307 let mut db = self.open_db().context("In list.")?;
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700308 let uid = Self::get_effective_uid(uid).context("In list.")?;
309 let mut result = self.list_legacy(uid).context("In list.")?;
310 result.append(&mut db.list(uid).context("In list: Trying to get list of entries.")?);
Janis Danisevskis06891072021-02-11 10:28:17 -0800311 result = result.into_iter().filter(|s| s.starts_with(prefix)).collect();
312 result.sort_unstable();
313 result.dedup();
314 Ok(result)
315 }
316
317 fn init_shelf(&self, path: &Path) {
318 let mut db_path = path.to_path_buf();
319 self.async_task.queue_hi(move |shelf| {
320 let legacy_loader = LegacyBlobLoader::new(&db_path);
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700321 db_path.push(Self::LEGACY_KEYSTORE_FILE_NAME);
Janis Danisevskis06891072021-02-11 10:28:17 -0800322
323 shelf.put(AsyncState { legacy_loader, db_path, recently_imported: Default::default() });
324 })
325 }
326
327 fn do_serialized<F, T: Send + 'static>(&self, f: F) -> Result<T>
328 where
329 F: FnOnce(&mut AsyncState) -> Result<T> + Send + 'static,
330 {
331 let (sender, receiver) = std::sync::mpsc::channel::<Result<T>>();
332 self.async_task.queue_hi(move |shelf| {
333 let state = shelf.get_downcast_mut::<AsyncState>().expect("Failed to get shelf.");
334 sender.send(f(state)).expect("Failed to send result.");
335 });
336 receiver.recv().context("In do_serialized: Failed to receive result.")?
337 }
338
339 fn list_legacy(&self, uid: u32) -> Result<Vec<String>> {
340 self.do_serialized(move |state| {
341 state
342 .legacy_loader
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700343 .list_legacy_keystore_entries(uid)
344 .context("Trying to list legacy keystore entries.")
Janis Danisevskis06891072021-02-11 10:28:17 -0800345 })
346 .context("In list_legacy.")
347 }
348
349 fn get_legacy(&self, uid: u32, alias: &str) -> Result<bool> {
350 let alias = alias.to_string();
351 self.do_serialized(move |state| {
352 if state.recently_imported.contains(&(uid, alias.clone())) {
353 return Ok(true);
354 }
355 let mut db = DB::new(&state.db_path).context("In open_db: Failed to open db.")?;
356 let migrated =
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700357 Self::migrate_one_legacy_entry(uid, &alias, &state.legacy_loader, &mut db)
358 .context("Trying to migrate legacy keystore entries.")?;
Janis Danisevskis06891072021-02-11 10:28:17 -0800359 if migrated {
360 state.recently_imported.insert((uid, alias));
361 }
362 Ok(migrated)
363 })
364 .context("In get_legacy.")
365 }
366
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700367 fn migrate_one_legacy_entry(
Janis Danisevskis06891072021-02-11 10:28:17 -0800368 uid: u32,
369 alias: &str,
370 legacy_loader: &LegacyBlobLoader,
371 db: &mut DB,
372 ) -> Result<bool> {
373 let blob = legacy_loader
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700374 .read_legacy_keystore_entry(uid, alias)
375 .context("In migrate_one_legacy_entry: Trying to read legacy keystore entry.")?;
376 if let Some(entry) = blob {
377 db.put(uid, alias, &entry)
378 .context("In migrate_one_legacy_entry: Trying to insert entry into DB.")?;
Janis Danisevskis06891072021-02-11 10:28:17 -0800379 legacy_loader
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700380 .remove_legacy_keystore_entry(uid, alias)
381 .context("In migrate_one_legacy_entry: Trying to delete legacy keystore entry.")?;
Janis Danisevskis06891072021-02-11 10:28:17 -0800382 Ok(true)
383 } else {
384 Ok(false)
385 }
Janis Danisevskis77d72042021-01-20 15:36:30 -0800386 }
387}
388
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700389impl binder::Interface for LegacyKeystore {}
Janis Danisevskis77d72042021-01-20 15:36:30 -0800390
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700391impl ILegacyKeystore for LegacyKeystore {
392 fn get(&self, alias: &str, uid: i32) -> BinderResult<Vec<u8>> {
393 let _wp = wd::watch_millis("ILegacyKeystore::get", 500);
394 map_or_log_err(self.get(alias, uid), Ok)
Janis Danisevskis77d72042021-01-20 15:36:30 -0800395 }
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700396 fn put(&self, alias: &str, uid: i32, entry: &[u8]) -> BinderResult<()> {
397 let _wp = wd::watch_millis("ILegacyKeystore::put", 500);
398 map_or_log_err(self.put(alias, uid, entry), Ok)
Janis Danisevskis77d72042021-01-20 15:36:30 -0800399 }
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700400 fn remove(&self, alias: &str, uid: i32) -> BinderResult<()> {
401 let _wp = wd::watch_millis("ILegacyKeystore::remove", 500);
402 map_or_log_err(self.remove(alias, uid), Ok)
Janis Danisevskis77d72042021-01-20 15:36:30 -0800403 }
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700404 fn list(&self, prefix: &str, uid: i32) -> BinderResult<Vec<String>> {
405 let _wp = wd::watch_millis("ILegacyKeystore::list", 500);
406 map_or_log_err(self.list(prefix, uid), Ok)
Janis Danisevskis77d72042021-01-20 15:36:30 -0800407 }
408}
409
410#[cfg(test)]
411mod db_test {
412 use super::*;
413 use keystore2_test_utils::TempDir;
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700414 use std::sync::Arc;
415 use std::thread;
416 use std::time::Duration;
417 use std::time::Instant;
Janis Danisevskis77d72042021-01-20 15:36:30 -0800418
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700419 static TEST_ALIAS: &str = &"test_alias";
Janis Danisevskis77d72042021-01-20 15:36:30 -0800420 static TEST_BLOB1: &[u8] = &[1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
421 static TEST_BLOB2: &[u8] = &[2, 2, 3, 4, 5, 6, 7, 8, 9, 0];
422 static TEST_BLOB3: &[u8] = &[3, 2, 3, 4, 5, 6, 7, 8, 9, 0];
423 static TEST_BLOB4: &[u8] = &[3, 2, 3, 4, 5, 6, 7, 8, 9, 0];
424
425 #[test]
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700426 fn test_entry_db() {
427 let test_dir = TempDir::new("entrydb_test_").expect("Failed to create temp dir.");
428 let mut db = DB::new(&test_dir.build().push(LegacyKeystore::LEGACY_KEYSTORE_FILE_NAME))
429 .expect("Failed to open database.");
Janis Danisevskis77d72042021-01-20 15:36:30 -0800430
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700431 // Insert three entries for owner 2.
Janis Danisevskis77d72042021-01-20 15:36:30 -0800432 db.put(2, "test1", TEST_BLOB1).expect("Failed to insert test1.");
433 db.put(2, "test2", TEST_BLOB2).expect("Failed to insert test2.");
434 db.put(2, "test3", TEST_BLOB3).expect("Failed to insert test3.");
435
436 // Check list returns all inserted aliases.
437 assert_eq!(
438 vec!["test1".to_string(), "test2".to_string(), "test3".to_string(),],
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700439 db.list(2).expect("Failed to list entries.")
Janis Danisevskis77d72042021-01-20 15:36:30 -0800440 );
441
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700442 // There should be no entries for owner 1.
443 assert_eq!(Vec::<String>::new(), db.list(1).expect("Failed to list entries."));
Janis Danisevskis77d72042021-01-20 15:36:30 -0800444
445 // Check the content of the three entries.
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700446 assert_eq!(Some(TEST_BLOB1), db.get(2, "test1").expect("Failed to get entry.").as_deref());
447 assert_eq!(Some(TEST_BLOB2), db.get(2, "test2").expect("Failed to get entry.").as_deref());
448 assert_eq!(Some(TEST_BLOB3), db.get(2, "test3").expect("Failed to get entry.").as_deref());
Janis Danisevskis77d72042021-01-20 15:36:30 -0800449
450 // Remove test2 and check and check that it is no longer retrievable.
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700451 assert!(db.remove(2, "test2").expect("Failed to remove entry."));
452 assert!(db.get(2, "test2").expect("Failed to get entry.").is_none());
Janis Danisevskis77d72042021-01-20 15:36:30 -0800453
454 // test2 should now no longer be in the list.
455 assert_eq!(
456 vec!["test1".to_string(), "test3".to_string(),],
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700457 db.list(2).expect("Failed to list entries.")
Janis Danisevskis77d72042021-01-20 15:36:30 -0800458 );
459
460 // Put on existing alias replaces it.
461 // Verify test1 is TEST_BLOB1.
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700462 assert_eq!(Some(TEST_BLOB1), db.get(2, "test1").expect("Failed to get entry.").as_deref());
Janis Danisevskis77d72042021-01-20 15:36:30 -0800463 db.put(2, "test1", TEST_BLOB4).expect("Failed to replace test1.");
464 // Verify test1 is TEST_BLOB4.
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700465 assert_eq!(Some(TEST_BLOB4), db.get(2, "test1").expect("Failed to get entry.").as_deref());
Janis Danisevskis77d72042021-01-20 15:36:30 -0800466 }
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700467
468 #[test]
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700469 fn concurrent_legacy_keystore_entry_test() -> Result<()> {
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700470 let temp_dir = Arc::new(
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700471 TempDir::new("concurrent_legacy_keystore_entry_test_")
472 .expect("Failed to create temp dir."),
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700473 );
474
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700475 let db_path = temp_dir.build().push(LegacyKeystore::LEGACY_KEYSTORE_FILE_NAME).to_owned();
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700476
477 let test_begin = Instant::now();
478
479 let mut db = DB::new(&db_path).expect("Failed to open database.");
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700480 const ENTRY_COUNT: u32 = 5000u32;
481 const ENTRY_DB_COUNT: u32 = 5000u32;
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700482
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700483 let mut actual_entry_count = ENTRY_COUNT;
484 // First insert ENTRY_COUNT entries.
485 for count in 0..ENTRY_COUNT {
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700486 if Instant::now().duration_since(test_begin) >= Duration::from_secs(15) {
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700487 actual_entry_count = count;
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700488 break;
489 }
490 let alias = format!("test_alias_{}", count);
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700491 db.put(1, &alias, TEST_BLOB1).expect("Failed to add entry (1).");
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700492 }
493
494 // Insert more keys from a different thread and into a different namespace.
495 let db_path1 = db_path.clone();
496 let handle1 = thread::spawn(move || {
497 let mut db = DB::new(&db_path1).expect("Failed to open database.");
498
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700499 for count in 0..actual_entry_count {
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700500 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
501 return;
502 }
503 let alias = format!("test_alias_{}", count);
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700504 db.put(2, &alias, TEST_BLOB2).expect("Failed to add entry (2).");
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700505 }
506
507 // Then delete them again.
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700508 for count in 0..actual_entry_count {
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700509 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
510 return;
511 }
512 let alias = format!("test_alias_{}", count);
513 db.remove(2, &alias).expect("Remove Failed (2).");
514 }
515 });
516
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700517 // And start deleting the first set of entries.
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700518 let db_path2 = db_path.clone();
519 let handle2 = thread::spawn(move || {
520 let mut db = DB::new(&db_path2).expect("Failed to open database.");
521
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700522 for count in 0..actual_entry_count {
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700523 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
524 return;
525 }
526 let alias = format!("test_alias_{}", count);
527 db.remove(1, &alias).expect("Remove Failed (1)).");
528 }
529 });
530
531 // While a lot of inserting and deleting is going on we have to open database connections
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700532 // successfully and then insert and delete a specific entry.
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700533 let db_path3 = db_path.clone();
534 let handle3 = thread::spawn(move || {
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700535 for _count in 0..ENTRY_DB_COUNT {
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700536 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
537 return;
538 }
539 let mut db = DB::new(&db_path3).expect("Failed to open database.");
540
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700541 db.put(3, &TEST_ALIAS, TEST_BLOB3).expect("Failed to add entry (3).");
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700542
543 db.remove(3, &TEST_ALIAS).expect("Remove failed (3).");
544 }
545 });
546
547 // While thread 3 is inserting and deleting TEST_ALIAS, we try to get the alias.
548 // This may yield an entry or none, but it must not fail.
549 let handle4 = thread::spawn(move || {
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700550 for _count in 0..ENTRY_DB_COUNT {
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700551 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
552 return;
553 }
554 let mut db = DB::new(&db_path).expect("Failed to open database.");
555
556 // This may return Some or None but it must not fail.
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700557 db.get(3, &TEST_ALIAS).expect("Failed to get entry (4).");
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700558 }
559 });
560
561 handle1.join().expect("Thread 1 panicked.");
562 handle2.join().expect("Thread 2 panicked.");
563 handle3.join().expect("Thread 3 panicked.");
564 handle4.join().expect("Thread 4 panicked.");
565
566 Ok(())
567 }
Janis Danisevskis77d72042021-01-20 15:36:30 -0800568}