blob: ce1e1e7ac4cbfbc0faae53983f9eee660b69587a [file] [log] [blame]
David Drysdale79af2662024-02-19 14:50:31 +00001// Copyright 2024, 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
15//! Database of VM IDs.
16
David Drysdalecf8875c2024-03-15 18:16:02 +000017use anyhow::{anyhow, Context, Result};
David Drysdale79af2662024-02-19 14:50:31 +000018use log::{debug, error, info, warn};
19use rusqlite::{params, params_from_iter, Connection, OpenFlags, Rows};
20use std::path::PathBuf;
21
22/// Subdirectory to hold the database.
23const DB_DIR: &str = "vmdb";
24
25/// Name of the file that holds the database.
26const DB_FILENAME: &str = "vmids.sqlite";
27
28/// Maximum number of host parameters in a single SQL statement.
29/// (Default value of `SQLITE_LIMIT_VARIABLE_NUMBER` for <= 3.32.0)
30const MAX_VARIABLES: usize = 999;
31
David Drysdalecf8875c2024-03-15 18:16:02 +000032/// Return the current time as milliseconds since epoch.
33fn db_now() -> u64 {
34 let now = std::time::SystemTime::now()
35 .duration_since(std::time::UNIX_EPOCH)
36 .unwrap_or(std::time::Duration::ZERO)
37 .as_millis();
38 now.try_into().unwrap_or(u64::MAX)
39}
40
David Drysdale79af2662024-02-19 14:50:31 +000041/// Identifier for a VM and its corresponding secret.
42pub type VmId = [u8; 64];
43
44/// Representation of an on-disk database of VM IDs.
45pub struct VmIdDb {
46 conn: Connection,
47}
48
David Drysdalecf8875c2024-03-15 18:16:02 +000049struct RetryOnFailure(bool);
50
David Drysdale79af2662024-02-19 14:50:31 +000051impl VmIdDb {
52 /// Connect to the VM ID database file held in the given directory, creating it if necessary.
53 /// The second return value indicates whether a new database file was created.
54 ///
55 /// This function assumes no other threads/processes are attempting to connect concurrently.
56 pub fn new(db_dir: &str) -> Result<(Self, bool)> {
57 let mut db_path = PathBuf::from(db_dir);
58 db_path.push(DB_DIR);
59 if !db_path.exists() {
60 std::fs::create_dir(&db_path).context("failed to create {db_path:?}")?;
61 info!("created persistent db dir {db_path:?}");
62 }
David Drysdale79af2662024-02-19 14:50:31 +000063 db_path.push(DB_FILENAME);
David Drysdalecf8875c2024-03-15 18:16:02 +000064 Self::new_at_path(db_path, RetryOnFailure(true))
65 }
66
67 fn new_at_path(db_path: PathBuf, retry: RetryOnFailure) -> Result<(Self, bool)> {
David Drysdale79af2662024-02-19 14:50:31 +000068 let (flags, created) = if db_path.exists() {
69 debug!("connecting to existing database {db_path:?}");
70 (
71 OpenFlags::SQLITE_OPEN_READ_WRITE
72 | OpenFlags::SQLITE_OPEN_URI
73 | OpenFlags::SQLITE_OPEN_NO_MUTEX,
74 false,
75 )
76 } else {
77 info!("creating fresh database {db_path:?}");
78 (
79 OpenFlags::SQLITE_OPEN_READ_WRITE
80 | OpenFlags::SQLITE_OPEN_CREATE
81 | OpenFlags::SQLITE_OPEN_URI
82 | OpenFlags::SQLITE_OPEN_NO_MUTEX,
83 true,
84 )
85 };
David Drysdalecf8875c2024-03-15 18:16:02 +000086 let mut db = Self {
87 conn: Connection::open_with_flags(&db_path, flags)
David Drysdale79af2662024-02-19 14:50:31 +000088 .context(format!("failed to open/create DB with {flags:?}"))?,
89 };
90
91 if created {
David Drysdalecf8875c2024-03-15 18:16:02 +000092 db.init_tables().context("failed to create tables")?;
93 } else {
94 // An existing .sqlite file may have an earlier schema.
95 match db.schema_version() {
96 Err(e) => {
97 // Couldn't determine a schema version, so wipe and try again.
98 error!("failed to determine VM DB schema: {e:?}");
99 if retry.0 {
100 // This is the first attempt, so wipe and retry.
101 error!("resetting database file {db_path:?}");
102 let _ = std::fs::remove_file(&db_path);
103 return Self::new_at_path(db_path, RetryOnFailure(false));
104 } else {
105 // An earlier attempt at wiping/retrying has failed, so give up.
106 return Err(anyhow!("failed to reset database file {db_path:?}"));
107 }
108 }
109 Ok(0) => db.upgrade_tables_v0_v1().context("failed to upgrade schema v0 -> v1")?,
110 Ok(1) => {
111 // Current version, no action needed.
112 }
113 Ok(version) => {
114 // If the database looks like it's from a future version, leave it alone and
115 // fail to connect to it.
116 error!("database from the future (v{version})");
117 return Err(anyhow!("database from the future (v{version})"));
118 }
119 }
David Drysdale79af2662024-02-19 14:50:31 +0000120 }
David Drysdalecf8875c2024-03-15 18:16:02 +0000121 Ok((db, created))
David Drysdale79af2662024-02-19 14:50:31 +0000122 }
123
124 /// Delete the associated database file.
125 pub fn delete_db_file(self, db_dir: &str) {
126 let mut db_path = PathBuf::from(db_dir);
127 db_path.push(DB_DIR);
128 db_path.push(DB_FILENAME);
129
130 // Drop the connection before removing the backing file.
131 drop(self);
132 warn!("removing database file {db_path:?}");
133 if let Err(e) = std::fs::remove_file(&db_path) {
134 error!("failed to remove database file {db_path:?}: {e:?}");
135 }
136 }
137
David Drysdalecf8875c2024-03-15 18:16:02 +0000138 fn schema_version(&mut self) -> Result<i32> {
139 let version: i32 = self
140 .conn
141 .query_row("PRAGMA main.user_version", (), |row| row.get(0))
142 .context("failed to read pragma")?;
143 Ok(version)
144 }
145
146 /// Create the database table and indices using the current schema.
David Drysdale79af2662024-02-19 14:50:31 +0000147 fn init_tables(&mut self) -> Result<()> {
David Drysdalecf8875c2024-03-15 18:16:02 +0000148 self.init_tables_v1()
149 }
150
151 /// Create the database table and indices using the v1 schema.
152 fn init_tables_v1(&mut self) -> Result<()> {
153 info!("creating v1 database schema");
154 self.conn
155 .execute(
156 "CREATE TABLE IF NOT EXISTS main.vmids (
157 vm_id BLOB PRIMARY KEY,
158 user_id INTEGER,
159 app_id INTEGER,
160 created INTEGER
161 ) WITHOUT ROWID;",
162 (),
163 )
164 .context("failed to create table")?;
165 self.conn
166 .execute("CREATE INDEX IF NOT EXISTS main.vmids_user_index ON vmids(user_id);", [])
167 .context("Failed to create user index")?;
168 self.conn
169 .execute(
170 "CREATE INDEX IF NOT EXISTS main.vmids_app_index ON vmids(user_id, app_id);",
171 [],
172 )
173 .context("Failed to create app index")?;
174 self.conn
175 .execute("PRAGMA main.user_version = 1;", ())
176 .context("failed to declare version")?;
177 Ok(())
178 }
179
180 fn upgrade_tables_v0_v1(&mut self) -> Result<()> {
181 let _rows = self
182 .conn
183 .execute("ALTER TABLE main.vmids ADD COLUMN created INTEGER;", ())
184 .context("failed to alter table v0->v1")?;
185 self.conn
186 .execute("PRAGMA main.user_version = 1;", ())
187 .context("failed to set schema version")?;
188 Ok(())
189 }
190
191 /// Create the database table and indices using the v0 schema.
192 #[cfg(test)]
193 fn init_tables_v0(&mut self) -> Result<()> {
194 info!("creating v0 database schema");
David Drysdale79af2662024-02-19 14:50:31 +0000195 self.conn
196 .execute(
197 "CREATE TABLE IF NOT EXISTS main.vmids (
198 vm_id BLOB PRIMARY KEY,
199 user_id INTEGER,
200 app_id INTEGER
201 ) WITHOUT ROWID;",
202 (),
203 )
204 .context("failed to create table")?;
205 self.conn
206 .execute("CREATE INDEX IF NOT EXISTS main.vmids_user_index ON vmids(user_id);", [])
207 .context("Failed to create user index")?;
208 self.conn
209 .execute(
210 "CREATE INDEX IF NOT EXISTS main.vmids_app_index ON vmids(user_id, app_id);",
211 [],
212 )
213 .context("Failed to create app index")?;
214 Ok(())
215 }
216
217 /// Add the given VM ID into the database.
David Drysdale79af2662024-02-19 14:50:31 +0000218 pub fn add_vm_id(&mut self, vm_id: &VmId, user_id: i32, app_id: i32) -> Result<()> {
David Drysdalecf8875c2024-03-15 18:16:02 +0000219 let now = db_now();
David Drysdale79af2662024-02-19 14:50:31 +0000220 let _rows = self
221 .conn
222 .execute(
David Drysdalecf8875c2024-03-15 18:16:02 +0000223 "REPLACE INTO main.vmids (vm_id, user_id, app_id, created) VALUES (?1, ?2, ?3, ?4);",
224 params![vm_id, &user_id, &app_id, &now],
David Drysdale79af2662024-02-19 14:50:31 +0000225 )
226 .context("failed to add VM ID")?;
227 Ok(())
228 }
229
230 /// Remove the given VM IDs from the database. The collection of IDs is assumed to be smaller
231 /// than the maximum number of SQLite parameters.
232 pub fn delete_vm_ids(&mut self, vm_ids: &[VmId]) -> Result<()> {
233 assert!(vm_ids.len() < MAX_VARIABLES);
234 let mut vars = "?,".repeat(vm_ids.len());
235 vars.pop(); // remove trailing comma
236 let sql = format!("DELETE FROM main.vmids WHERE vm_id IN ({});", vars);
237 let mut stmt = self.conn.prepare(&sql).context("failed to prepare DELETE stmt")?;
238 let _rows = stmt.execute(params_from_iter(vm_ids)).context("failed to delete VM IDs")?;
239 Ok(())
240 }
241
242 /// Return the VM IDs associated with Android user ID `user_id`.
243 pub fn vm_ids_for_user(&mut self, user_id: i32) -> Result<Vec<VmId>> {
244 let mut stmt = self
245 .conn
246 .prepare("SELECT vm_id FROM main.vmids WHERE user_id = ?;")
247 .context("failed to prepare SELECT stmt")?;
248 let rows = stmt.query(params![user_id]).context("query failed")?;
249 Self::vm_ids_from_rows(rows)
250 }
251
252 /// Return the VM IDs associated with `(user_id, app_id)`.
253 pub fn vm_ids_for_app(&mut self, user_id: i32, app_id: i32) -> Result<Vec<VmId>> {
254 let mut stmt = self
255 .conn
256 .prepare("SELECT vm_id FROM main.vmids WHERE user_id = ? AND app_id = ?;")
257 .context("failed to prepare SELECT stmt")?;
258 let rows = stmt.query(params![user_id, app_id]).context("query failed")?;
259 Self::vm_ids_from_rows(rows)
260 }
261
262 /// Retrieve a collection of VM IDs from database rows.
263 fn vm_ids_from_rows(mut rows: Rows) -> Result<Vec<VmId>> {
264 let mut vm_ids: Vec<VmId> = Vec::new();
265 while let Some(row) = rows.next().context("failed row unpack")? {
266 match row.get(0) {
267 Ok(vm_id) => vm_ids.push(vm_id),
268 Err(e) => log::error!("failed to parse row: {e:?}"),
269 }
270 }
271
272 Ok(vm_ids)
273 }
274}
275
David Drysdalecf8875c2024-03-15 18:16:02 +0000276/// Current schema version.
277#[cfg(test)]
278const SCHEMA_VERSION: usize = 1;
279
280/// Create a new in-memory database for testing.
David Drysdale79af2662024-02-19 14:50:31 +0000281#[cfg(test)]
282pub fn new_test_db() -> VmIdDb {
David Drysdalecf8875c2024-03-15 18:16:02 +0000283 tests::new_test_db_version(SCHEMA_VERSION)
David Drysdale79af2662024-02-19 14:50:31 +0000284}
285
286#[cfg(test)]
287mod tests {
288 use super::*;
David Drysdalecf8875c2024-03-15 18:16:02 +0000289 use std::io::Write;
290
David Drysdale79af2662024-02-19 14:50:31 +0000291 const VM_ID1: VmId = [1u8; 64];
292 const VM_ID2: VmId = [2u8; 64];
293 const VM_ID3: VmId = [3u8; 64];
294 const VM_ID4: VmId = [4u8; 64];
295 const VM_ID5: VmId = [5u8; 64];
296 const USER1: i32 = 1;
297 const USER2: i32 = 2;
298 const USER3: i32 = 3;
299 const USER_UNKNOWN: i32 = 4;
300 const APP_A: i32 = 50;
301 const APP_B: i32 = 60;
302 const APP_C: i32 = 70;
303 const APP_UNKNOWN: i32 = 99;
304
David Drysdalecf8875c2024-03-15 18:16:02 +0000305 pub fn new_test_db_version(version: usize) -> VmIdDb {
306 let mut db = VmIdDb { conn: Connection::open_in_memory().unwrap() };
307 match version {
308 0 => db.init_tables_v0().unwrap(),
309 1 => db.init_tables_v1().unwrap(),
310 _ => panic!("unexpected version {version}"),
311 }
312 db
313 }
314
315 fn show_contents(db: &VmIdDb) {
316 let mut stmt = db.conn.prepare("SELECT * FROM main.vmids;").unwrap();
317 let mut rows = stmt.query(()).unwrap();
318 while let Some(row) = rows.next().unwrap() {
319 println!(" {row:?}");
320 }
321 }
322
323 #[test]
324 fn test_schema_version0() {
325 let mut db0 = VmIdDb { conn: Connection::open_in_memory().unwrap() };
326 db0.init_tables_v0().unwrap();
327 let version = db0.schema_version().unwrap();
328 assert_eq!(0, version);
329 }
330
331 #[test]
332 fn test_schema_version1() {
333 let mut db1 = VmIdDb { conn: Connection::open_in_memory().unwrap() };
334 db1.init_tables_v1().unwrap();
335 let version = db1.schema_version().unwrap();
336 assert_eq!(1, version);
337 }
338
339 #[test]
340 fn test_schema_upgrade_v0_v1() {
341 let mut db = new_test_db_version(0);
342 let version = db.schema_version().unwrap();
343 assert_eq!(0, version);
344
345 // Manually insert a row before upgrade.
346 db.conn
347 .execute(
348 "REPLACE INTO main.vmids (vm_id, user_id, app_id) VALUES (?1, ?2, ?3);",
349 params![&VM_ID1, &USER1, APP_A],
350 )
351 .unwrap();
352
353 db.upgrade_tables_v0_v1().unwrap();
354 let version = db.schema_version().unwrap();
355 assert_eq!(1, version);
356
357 assert_eq!(vec![VM_ID1], db.vm_ids_for_user(USER1).unwrap());
358 show_contents(&db);
359 }
360
361 #[test]
362 fn test_corrupt_database_file() {
363 let db_dir = tempfile::Builder::new().prefix("vmdb-test-").tempdir().unwrap();
364 let mut db_path = db_dir.path().to_owned();
365 db_path.push(DB_FILENAME);
366 {
367 let mut file = std::fs::File::create(db_path).unwrap();
368 let _ = file.write_all(b"This is not an SQLite file!");
369 }
370
371 // Non-DB file should be wiped and start over.
372 let (mut db, created) =
373 VmIdDb::new(&db_dir.path().to_string_lossy()).expect("failed to replace bogus DB");
374 assert!(created);
375 db.add_vm_id(&VM_ID1, USER1, APP_A).unwrap();
376 assert_eq!(vec![VM_ID1], db.vm_ids_for_user(USER1).unwrap());
377 }
378
379 #[test]
380 fn test_non_upgradable_database_file() {
381 let db_dir = tempfile::Builder::new().prefix("vmdb-test-").tempdir().unwrap();
382 let mut db_path = db_dir.path().to_owned();
383 db_path.push(DB_FILENAME);
384 {
385 // Create an unrelated database that happens to apparently have a schema version of 0.
386 let (db, created) = VmIdDb::new(&db_dir.path().to_string_lossy()).unwrap();
387 assert!(created);
388 db.conn.execute("DROP TABLE main.vmids", ()).unwrap();
389 db.conn.execute("PRAGMA main.user_version = 0;", ()).unwrap();
390 }
391
392 // Should fail to open a database because the upgrade fails.
393 let result = VmIdDb::new(&db_dir.path().to_string_lossy());
394 assert!(result.is_err());
395 }
396
397 #[test]
398 fn test_database_from_the_future() {
399 let db_dir = tempfile::Builder::new().prefix("vmdb-test-").tempdir().unwrap();
400 {
401 let (mut db, created) = VmIdDb::new(&db_dir.path().to_string_lossy()).unwrap();
402 assert!(created);
403 db.add_vm_id(&VM_ID1, USER1, APP_A).unwrap();
404 // Make the database look like it's from a future version.
405 db.conn.execute("PRAGMA main.user_version = 99;", ()).unwrap();
406 }
407 // Should fail to open a database from the future.
408 let result = VmIdDb::new(&db_dir.path().to_string_lossy());
409 assert!(result.is_err());
410 }
411
David Drysdale79af2662024-02-19 14:50:31 +0000412 #[test]
413 fn test_add_remove() {
414 let mut db = new_test_db();
415 db.add_vm_id(&VM_ID1, USER1, APP_A).unwrap();
416 db.add_vm_id(&VM_ID2, USER1, APP_A).unwrap();
417 db.add_vm_id(&VM_ID3, USER1, APP_A).unwrap();
418 db.add_vm_id(&VM_ID4, USER2, APP_B).unwrap();
419 db.add_vm_id(&VM_ID5, USER3, APP_A).unwrap();
420 db.add_vm_id(&VM_ID5, USER3, APP_C).unwrap();
421 let empty: Vec<VmId> = Vec::new();
422
423 assert_eq!(vec![VM_ID1, VM_ID2, VM_ID3], db.vm_ids_for_user(USER1).unwrap());
424 assert_eq!(vec![VM_ID1, VM_ID2, VM_ID3], db.vm_ids_for_app(USER1, APP_A).unwrap());
425 assert_eq!(vec![VM_ID4], db.vm_ids_for_app(USER2, APP_B).unwrap());
426 assert_eq!(vec![VM_ID5], db.vm_ids_for_user(USER3).unwrap());
427 assert_eq!(empty, db.vm_ids_for_user(USER_UNKNOWN).unwrap());
428 assert_eq!(empty, db.vm_ids_for_app(USER1, APP_UNKNOWN).unwrap());
429
430 db.delete_vm_ids(&[VM_ID2, VM_ID3]).unwrap();
431
432 assert_eq!(vec![VM_ID1], db.vm_ids_for_user(USER1).unwrap());
433 assert_eq!(vec![VM_ID1], db.vm_ids_for_app(USER1, APP_A).unwrap());
434
435 // OK to delete things that don't exist.
436 db.delete_vm_ids(&[VM_ID2, VM_ID3]).unwrap();
437
438 assert_eq!(vec![VM_ID1], db.vm_ids_for_user(USER1).unwrap());
439 assert_eq!(vec![VM_ID1], db.vm_ids_for_app(USER1, APP_A).unwrap());
440
441 db.add_vm_id(&VM_ID2, USER1, APP_A).unwrap();
442 db.add_vm_id(&VM_ID3, USER1, APP_A).unwrap();
443
444 assert_eq!(vec![VM_ID1, VM_ID2, VM_ID3], db.vm_ids_for_user(USER1).unwrap());
445 assert_eq!(vec![VM_ID1, VM_ID2, VM_ID3], db.vm_ids_for_app(USER1, APP_A).unwrap());
446 assert_eq!(vec![VM_ID4], db.vm_ids_for_app(USER2, APP_B).unwrap());
447 assert_eq!(vec![VM_ID5], db.vm_ids_for_user(USER3).unwrap());
448 assert_eq!(empty, db.vm_ids_for_user(USER_UNKNOWN).unwrap());
449 assert_eq!(empty, db.vm_ids_for_app(USER1, APP_UNKNOWN).unwrap());
David Drysdalecf8875c2024-03-15 18:16:02 +0000450 show_contents(&db);
David Drysdale79af2662024-02-19 14:50:31 +0000451 }
452
453 #[test]
454 fn test_invalid_vm_id() {
455 let mut db = new_test_db();
456 db.add_vm_id(&VM_ID3, USER1, APP_A).unwrap();
457 db.add_vm_id(&VM_ID2, USER1, APP_A).unwrap();
458 db.add_vm_id(&VM_ID1, USER1, APP_A).unwrap();
459
460 // Note that results are returned in `vm_id` order, because the table is `WITHOUT ROWID`.
461 assert_eq!(vec![VM_ID1, VM_ID2, VM_ID3], db.vm_ids_for_user(USER1).unwrap());
462
463 // Manually insert a row with a VM ID that's the wrong size.
464 db.conn
465 .execute(
David Drysdalecf8875c2024-03-15 18:16:02 +0000466 "REPLACE INTO main.vmids (vm_id, user_id, app_id, created) VALUES (?1, ?2, ?3, ?4);",
467 params![&[99u8; 60], &USER1, APP_A, &db_now()],
David Drysdale79af2662024-02-19 14:50:31 +0000468 )
469 .unwrap();
470
471 // Invalid row is skipped and remainder returned.
472 assert_eq!(vec![VM_ID1, VM_ID2, VM_ID3], db.vm_ids_for_user(USER1).unwrap());
David Drysdalecf8875c2024-03-15 18:16:02 +0000473 show_contents(&db);
David Drysdale79af2662024-02-19 14:50:31 +0000474 }
475}