David Drysdale | 79af266 | 2024-02-19 14:50:31 +0000 | [diff] [blame] | 1 | // 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 Drysdale | cf8875c | 2024-03-15 18:16:02 +0000 | [diff] [blame] | 17 | use anyhow::{anyhow, Context, Result}; |
David Drysdale | 79af266 | 2024-02-19 14:50:31 +0000 | [diff] [blame] | 18 | use log::{debug, error, info, warn}; |
| 19 | use rusqlite::{params, params_from_iter, Connection, OpenFlags, Rows}; |
| 20 | use std::path::PathBuf; |
| 21 | |
| 22 | /// Subdirectory to hold the database. |
| 23 | const DB_DIR: &str = "vmdb"; |
| 24 | |
| 25 | /// Name of the file that holds the database. |
| 26 | const 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) |
| 30 | const MAX_VARIABLES: usize = 999; |
| 31 | |
David Drysdale | cf8875c | 2024-03-15 18:16:02 +0000 | [diff] [blame] | 32 | /// Return the current time as milliseconds since epoch. |
| 33 | fn 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 Drysdale | 79af266 | 2024-02-19 14:50:31 +0000 | [diff] [blame] | 41 | /// Identifier for a VM and its corresponding secret. |
| 42 | pub type VmId = [u8; 64]; |
| 43 | |
| 44 | /// Representation of an on-disk database of VM IDs. |
| 45 | pub struct VmIdDb { |
| 46 | conn: Connection, |
| 47 | } |
| 48 | |
David Drysdale | cf8875c | 2024-03-15 18:16:02 +0000 | [diff] [blame] | 49 | struct RetryOnFailure(bool); |
| 50 | |
David Drysdale | 79af266 | 2024-02-19 14:50:31 +0000 | [diff] [blame] | 51 | impl 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 Drysdale | 79af266 | 2024-02-19 14:50:31 +0000 | [diff] [blame] | 63 | db_path.push(DB_FILENAME); |
David Drysdale | cf8875c | 2024-03-15 18:16:02 +0000 | [diff] [blame] | 64 | Self::new_at_path(db_path, RetryOnFailure(true)) |
| 65 | } |
| 66 | |
| 67 | fn new_at_path(db_path: PathBuf, retry: RetryOnFailure) -> Result<(Self, bool)> { |
David Drysdale | 79af266 | 2024-02-19 14:50:31 +0000 | [diff] [blame] | 68 | 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 Drysdale | cf8875c | 2024-03-15 18:16:02 +0000 | [diff] [blame] | 86 | let mut db = Self { |
| 87 | conn: Connection::open_with_flags(&db_path, flags) |
David Drysdale | 79af266 | 2024-02-19 14:50:31 +0000 | [diff] [blame] | 88 | .context(format!("failed to open/create DB with {flags:?}"))?, |
| 89 | }; |
| 90 | |
| 91 | if created { |
David Drysdale | cf8875c | 2024-03-15 18:16:02 +0000 | [diff] [blame] | 92 | 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 Drysdale | 79af266 | 2024-02-19 14:50:31 +0000 | [diff] [blame] | 120 | } |
David Drysdale | cf8875c | 2024-03-15 18:16:02 +0000 | [diff] [blame] | 121 | Ok((db, created)) |
David Drysdale | 79af266 | 2024-02-19 14:50:31 +0000 | [diff] [blame] | 122 | } |
| 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 Drysdale | cf8875c | 2024-03-15 18:16:02 +0000 | [diff] [blame] | 138 | 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 Drysdale | 79af266 | 2024-02-19 14:50:31 +0000 | [diff] [blame] | 147 | fn init_tables(&mut self) -> Result<()> { |
David Drysdale | cf8875c | 2024-03-15 18:16:02 +0000 | [diff] [blame] | 148 | 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 Drysdale | 79af266 | 2024-02-19 14:50:31 +0000 | [diff] [blame] | 195 | 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 Drysdale | 79af266 | 2024-02-19 14:50:31 +0000 | [diff] [blame] | 218 | pub fn add_vm_id(&mut self, vm_id: &VmId, user_id: i32, app_id: i32) -> Result<()> { |
David Drysdale | cf8875c | 2024-03-15 18:16:02 +0000 | [diff] [blame] | 219 | let now = db_now(); |
David Drysdale | 79af266 | 2024-02-19 14:50:31 +0000 | [diff] [blame] | 220 | let _rows = self |
| 221 | .conn |
| 222 | .execute( |
David Drysdale | cf8875c | 2024-03-15 18:16:02 +0000 | [diff] [blame] | 223 | "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 Drysdale | 79af266 | 2024-02-19 14:50:31 +0000 | [diff] [blame] | 225 | ) |
| 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), |
David Drysdale | 1138fa0 | 2024-03-19 13:06:23 +0000 | [diff] [blame] | 268 | Err(e) => error!("failed to parse row: {e:?}"), |
David Drysdale | 79af266 | 2024-02-19 14:50:31 +0000 | [diff] [blame] | 269 | } |
| 270 | } |
| 271 | |
| 272 | Ok(vm_ids) |
| 273 | } |
David Drysdale | 1138fa0 | 2024-03-19 13:06:23 +0000 | [diff] [blame] | 274 | |
David Drysdale | 825c90f | 2024-03-26 12:45:29 +0000 | [diff] [blame^] | 275 | /// Determine the number of VM IDs associated with `(user_id, app_id)`. |
| 276 | pub fn count_vm_ids_for_app(&mut self, user_id: i32, app_id: i32) -> Result<usize> { |
| 277 | let mut stmt = self |
| 278 | .conn |
| 279 | .prepare("SELECT COUNT(vm_id) FROM main.vmids WHERE user_id = ? AND app_id = ?;") |
| 280 | .context("failed to prepare SELECT stmt")?; |
| 281 | stmt.query_row(params![user_id, app_id], |row| row.get(0)).context("query failed") |
| 282 | } |
| 283 | |
| 284 | /// Return the `count` oldest VM IDs associated with `(user_id, app_id)`. |
| 285 | pub fn oldest_vm_ids_for_app( |
| 286 | &mut self, |
| 287 | user_id: i32, |
| 288 | app_id: i32, |
| 289 | count: usize, |
| 290 | ) -> Result<Vec<VmId>> { |
| 291 | // SQLite considers NULL columns to be smaller than values, so rows left over from a v0 |
| 292 | // database will be listed first. |
| 293 | let mut stmt = self |
| 294 | .conn |
| 295 | .prepare( |
| 296 | "SELECT vm_id FROM main.vmids WHERE user_id = ? AND app_id = ? ORDER BY created LIMIT ?;", |
| 297 | ) |
| 298 | .context("failed to prepare SELECT stmt")?; |
| 299 | let rows = stmt.query(params![user_id, app_id, count]).context("query failed")?; |
| 300 | Self::vm_ids_from_rows(rows) |
| 301 | } |
| 302 | |
David Drysdale | 1138fa0 | 2024-03-19 13:06:23 +0000 | [diff] [blame] | 303 | /// Return all of the `(user_id, app_id)` pairs present in the database. |
| 304 | pub fn get_all_owners(&mut self) -> Result<Vec<(i32, i32)>> { |
| 305 | let mut stmt = self |
| 306 | .conn |
| 307 | .prepare("SELECT DISTINCT user_id, app_id FROM main.vmids;") |
| 308 | .context("failed to prepare SELECT stmt")?; |
| 309 | let mut rows = stmt.query(()).context("query failed")?; |
| 310 | let mut owners: Vec<(i32, i32)> = Vec::new(); |
| 311 | while let Some(row) = rows.next().context("failed row unpack")? { |
| 312 | let user_id = match row.get(0) { |
| 313 | Ok(v) => v, |
| 314 | Err(e) => { |
| 315 | error!("failed to parse row: {e:?}"); |
| 316 | continue; |
| 317 | } |
| 318 | }; |
| 319 | let app_id = match row.get(1) { |
| 320 | Ok(v) => v, |
| 321 | Err(e) => { |
| 322 | error!("failed to parse row: {e:?}"); |
| 323 | continue; |
| 324 | } |
| 325 | }; |
| 326 | owners.push((user_id, app_id)); |
| 327 | } |
| 328 | |
| 329 | Ok(owners) |
| 330 | } |
David Drysdale | 79af266 | 2024-02-19 14:50:31 +0000 | [diff] [blame] | 331 | } |
| 332 | |
David Drysdale | cf8875c | 2024-03-15 18:16:02 +0000 | [diff] [blame] | 333 | /// Current schema version. |
| 334 | #[cfg(test)] |
| 335 | const SCHEMA_VERSION: usize = 1; |
| 336 | |
| 337 | /// Create a new in-memory database for testing. |
David Drysdale | 79af266 | 2024-02-19 14:50:31 +0000 | [diff] [blame] | 338 | #[cfg(test)] |
| 339 | pub fn new_test_db() -> VmIdDb { |
David Drysdale | cf8875c | 2024-03-15 18:16:02 +0000 | [diff] [blame] | 340 | tests::new_test_db_version(SCHEMA_VERSION) |
David Drysdale | 79af266 | 2024-02-19 14:50:31 +0000 | [diff] [blame] | 341 | } |
| 342 | |
| 343 | #[cfg(test)] |
| 344 | mod tests { |
| 345 | use super::*; |
David Drysdale | cf8875c | 2024-03-15 18:16:02 +0000 | [diff] [blame] | 346 | use std::io::Write; |
| 347 | |
David Drysdale | 79af266 | 2024-02-19 14:50:31 +0000 | [diff] [blame] | 348 | const VM_ID1: VmId = [1u8; 64]; |
| 349 | const VM_ID2: VmId = [2u8; 64]; |
| 350 | const VM_ID3: VmId = [3u8; 64]; |
| 351 | const VM_ID4: VmId = [4u8; 64]; |
| 352 | const VM_ID5: VmId = [5u8; 64]; |
| 353 | const USER1: i32 = 1; |
| 354 | const USER2: i32 = 2; |
| 355 | const USER3: i32 = 3; |
| 356 | const USER_UNKNOWN: i32 = 4; |
| 357 | const APP_A: i32 = 50; |
| 358 | const APP_B: i32 = 60; |
| 359 | const APP_C: i32 = 70; |
| 360 | const APP_UNKNOWN: i32 = 99; |
| 361 | |
David Drysdale | cf8875c | 2024-03-15 18:16:02 +0000 | [diff] [blame] | 362 | pub fn new_test_db_version(version: usize) -> VmIdDb { |
| 363 | let mut db = VmIdDb { conn: Connection::open_in_memory().unwrap() }; |
| 364 | match version { |
| 365 | 0 => db.init_tables_v0().unwrap(), |
| 366 | 1 => db.init_tables_v1().unwrap(), |
| 367 | _ => panic!("unexpected version {version}"), |
| 368 | } |
| 369 | db |
| 370 | } |
| 371 | |
| 372 | fn show_contents(db: &VmIdDb) { |
| 373 | let mut stmt = db.conn.prepare("SELECT * FROM main.vmids;").unwrap(); |
| 374 | let mut rows = stmt.query(()).unwrap(); |
David Drysdale | 825c90f | 2024-03-26 12:45:29 +0000 | [diff] [blame^] | 375 | println!("DB contents:"); |
| 376 | while let Some(row) = rows.next().unwrap() { |
| 377 | println!(" {row:?}"); |
| 378 | } |
| 379 | } |
| 380 | |
| 381 | fn show_contents_for_app(db: &VmIdDb, user_id: i32, app_id: i32, count: usize) { |
| 382 | let mut stmt = db |
| 383 | .conn |
| 384 | .prepare("SELECT vm_id, created FROM main.vmids WHERE user_id = ? AND app_id = ? ORDER BY created LIMIT ?;") |
| 385 | .unwrap(); |
| 386 | let mut rows = stmt.query(params![user_id, app_id, count]).unwrap(); |
| 387 | println!("First (by created) {count} rows for app_id={app_id}"); |
David Drysdale | cf8875c | 2024-03-15 18:16:02 +0000 | [diff] [blame] | 388 | while let Some(row) = rows.next().unwrap() { |
| 389 | println!(" {row:?}"); |
| 390 | } |
| 391 | } |
| 392 | |
| 393 | #[test] |
| 394 | fn test_schema_version0() { |
| 395 | let mut db0 = VmIdDb { conn: Connection::open_in_memory().unwrap() }; |
| 396 | db0.init_tables_v0().unwrap(); |
| 397 | let version = db0.schema_version().unwrap(); |
| 398 | assert_eq!(0, version); |
| 399 | } |
| 400 | |
| 401 | #[test] |
| 402 | fn test_schema_version1() { |
| 403 | let mut db1 = VmIdDb { conn: Connection::open_in_memory().unwrap() }; |
| 404 | db1.init_tables_v1().unwrap(); |
| 405 | let version = db1.schema_version().unwrap(); |
| 406 | assert_eq!(1, version); |
| 407 | } |
| 408 | |
| 409 | #[test] |
| 410 | fn test_schema_upgrade_v0_v1() { |
| 411 | let mut db = new_test_db_version(0); |
| 412 | let version = db.schema_version().unwrap(); |
| 413 | assert_eq!(0, version); |
| 414 | |
| 415 | // Manually insert a row before upgrade. |
| 416 | db.conn |
| 417 | .execute( |
| 418 | "REPLACE INTO main.vmids (vm_id, user_id, app_id) VALUES (?1, ?2, ?3);", |
| 419 | params![&VM_ID1, &USER1, APP_A], |
| 420 | ) |
| 421 | .unwrap(); |
| 422 | |
| 423 | db.upgrade_tables_v0_v1().unwrap(); |
| 424 | let version = db.schema_version().unwrap(); |
| 425 | assert_eq!(1, version); |
| 426 | |
| 427 | assert_eq!(vec![VM_ID1], db.vm_ids_for_user(USER1).unwrap()); |
| 428 | show_contents(&db); |
| 429 | } |
| 430 | |
| 431 | #[test] |
| 432 | fn test_corrupt_database_file() { |
| 433 | let db_dir = tempfile::Builder::new().prefix("vmdb-test-").tempdir().unwrap(); |
| 434 | let mut db_path = db_dir.path().to_owned(); |
| 435 | db_path.push(DB_FILENAME); |
| 436 | { |
| 437 | let mut file = std::fs::File::create(db_path).unwrap(); |
| 438 | let _ = file.write_all(b"This is not an SQLite file!"); |
| 439 | } |
| 440 | |
| 441 | // Non-DB file should be wiped and start over. |
| 442 | let (mut db, created) = |
| 443 | VmIdDb::new(&db_dir.path().to_string_lossy()).expect("failed to replace bogus DB"); |
| 444 | assert!(created); |
| 445 | db.add_vm_id(&VM_ID1, USER1, APP_A).unwrap(); |
| 446 | assert_eq!(vec![VM_ID1], db.vm_ids_for_user(USER1).unwrap()); |
| 447 | } |
| 448 | |
| 449 | #[test] |
| 450 | fn test_non_upgradable_database_file() { |
| 451 | let db_dir = tempfile::Builder::new().prefix("vmdb-test-").tempdir().unwrap(); |
| 452 | let mut db_path = db_dir.path().to_owned(); |
| 453 | db_path.push(DB_FILENAME); |
| 454 | { |
| 455 | // Create an unrelated database that happens to apparently have a schema version of 0. |
| 456 | let (db, created) = VmIdDb::new(&db_dir.path().to_string_lossy()).unwrap(); |
| 457 | assert!(created); |
| 458 | db.conn.execute("DROP TABLE main.vmids", ()).unwrap(); |
| 459 | db.conn.execute("PRAGMA main.user_version = 0;", ()).unwrap(); |
| 460 | } |
| 461 | |
| 462 | // Should fail to open a database because the upgrade fails. |
| 463 | let result = VmIdDb::new(&db_dir.path().to_string_lossy()); |
| 464 | assert!(result.is_err()); |
| 465 | } |
| 466 | |
| 467 | #[test] |
| 468 | fn test_database_from_the_future() { |
| 469 | let db_dir = tempfile::Builder::new().prefix("vmdb-test-").tempdir().unwrap(); |
| 470 | { |
| 471 | let (mut db, created) = VmIdDb::new(&db_dir.path().to_string_lossy()).unwrap(); |
| 472 | assert!(created); |
| 473 | db.add_vm_id(&VM_ID1, USER1, APP_A).unwrap(); |
| 474 | // Make the database look like it's from a future version. |
| 475 | db.conn.execute("PRAGMA main.user_version = 99;", ()).unwrap(); |
| 476 | } |
| 477 | // Should fail to open a database from the future. |
| 478 | let result = VmIdDb::new(&db_dir.path().to_string_lossy()); |
| 479 | assert!(result.is_err()); |
| 480 | } |
| 481 | |
David Drysdale | 79af266 | 2024-02-19 14:50:31 +0000 | [diff] [blame] | 482 | #[test] |
| 483 | fn test_add_remove() { |
| 484 | let mut db = new_test_db(); |
| 485 | db.add_vm_id(&VM_ID1, USER1, APP_A).unwrap(); |
| 486 | db.add_vm_id(&VM_ID2, USER1, APP_A).unwrap(); |
| 487 | db.add_vm_id(&VM_ID3, USER1, APP_A).unwrap(); |
| 488 | db.add_vm_id(&VM_ID4, USER2, APP_B).unwrap(); |
| 489 | db.add_vm_id(&VM_ID5, USER3, APP_A).unwrap(); |
David Drysdale | 1138fa0 | 2024-03-19 13:06:23 +0000 | [diff] [blame] | 490 | db.add_vm_id(&VM_ID5, USER3, APP_C).unwrap(); // Overwrites APP_A |
| 491 | |
| 492 | assert_eq!( |
| 493 | vec![(USER1, APP_A), (USER2, APP_B), (USER3, APP_C)], |
| 494 | db.get_all_owners().unwrap() |
| 495 | ); |
| 496 | |
David Drysdale | 79af266 | 2024-02-19 14:50:31 +0000 | [diff] [blame] | 497 | let empty: Vec<VmId> = Vec::new(); |
| 498 | |
| 499 | assert_eq!(vec![VM_ID1, VM_ID2, VM_ID3], db.vm_ids_for_user(USER1).unwrap()); |
| 500 | assert_eq!(vec![VM_ID1, VM_ID2, VM_ID3], db.vm_ids_for_app(USER1, APP_A).unwrap()); |
David Drysdale | 825c90f | 2024-03-26 12:45:29 +0000 | [diff] [blame^] | 501 | assert_eq!(3, db.count_vm_ids_for_app(USER1, APP_A).unwrap()); |
David Drysdale | 79af266 | 2024-02-19 14:50:31 +0000 | [diff] [blame] | 502 | assert_eq!(vec![VM_ID4], db.vm_ids_for_app(USER2, APP_B).unwrap()); |
David Drysdale | 825c90f | 2024-03-26 12:45:29 +0000 | [diff] [blame^] | 503 | assert_eq!(1, db.count_vm_ids_for_app(USER2, APP_B).unwrap()); |
David Drysdale | 79af266 | 2024-02-19 14:50:31 +0000 | [diff] [blame] | 504 | assert_eq!(vec![VM_ID5], db.vm_ids_for_user(USER3).unwrap()); |
| 505 | assert_eq!(empty, db.vm_ids_for_user(USER_UNKNOWN).unwrap()); |
| 506 | assert_eq!(empty, db.vm_ids_for_app(USER1, APP_UNKNOWN).unwrap()); |
David Drysdale | 825c90f | 2024-03-26 12:45:29 +0000 | [diff] [blame^] | 507 | assert_eq!(0, db.count_vm_ids_for_app(USER1, APP_UNKNOWN).unwrap()); |
David Drysdale | 79af266 | 2024-02-19 14:50:31 +0000 | [diff] [blame] | 508 | |
| 509 | db.delete_vm_ids(&[VM_ID2, VM_ID3]).unwrap(); |
| 510 | |
| 511 | assert_eq!(vec![VM_ID1], db.vm_ids_for_user(USER1).unwrap()); |
| 512 | assert_eq!(vec![VM_ID1], db.vm_ids_for_app(USER1, APP_A).unwrap()); |
David Drysdale | 825c90f | 2024-03-26 12:45:29 +0000 | [diff] [blame^] | 513 | assert_eq!(1, db.count_vm_ids_for_app(USER1, APP_A).unwrap()); |
David Drysdale | 79af266 | 2024-02-19 14:50:31 +0000 | [diff] [blame] | 514 | |
| 515 | // OK to delete things that don't exist. |
| 516 | db.delete_vm_ids(&[VM_ID2, VM_ID3]).unwrap(); |
| 517 | |
| 518 | assert_eq!(vec![VM_ID1], db.vm_ids_for_user(USER1).unwrap()); |
| 519 | assert_eq!(vec![VM_ID1], db.vm_ids_for_app(USER1, APP_A).unwrap()); |
David Drysdale | 825c90f | 2024-03-26 12:45:29 +0000 | [diff] [blame^] | 520 | assert_eq!(1, db.count_vm_ids_for_app(USER1, APP_A).unwrap()); |
David Drysdale | 79af266 | 2024-02-19 14:50:31 +0000 | [diff] [blame] | 521 | |
| 522 | db.add_vm_id(&VM_ID2, USER1, APP_A).unwrap(); |
| 523 | db.add_vm_id(&VM_ID3, USER1, APP_A).unwrap(); |
| 524 | |
| 525 | assert_eq!(vec![VM_ID1, VM_ID2, VM_ID3], db.vm_ids_for_user(USER1).unwrap()); |
| 526 | assert_eq!(vec![VM_ID1, VM_ID2, VM_ID3], db.vm_ids_for_app(USER1, APP_A).unwrap()); |
David Drysdale | 825c90f | 2024-03-26 12:45:29 +0000 | [diff] [blame^] | 527 | assert_eq!(3, db.count_vm_ids_for_app(USER1, APP_A).unwrap()); |
David Drysdale | 79af266 | 2024-02-19 14:50:31 +0000 | [diff] [blame] | 528 | assert_eq!(vec![VM_ID4], db.vm_ids_for_app(USER2, APP_B).unwrap()); |
David Drysdale | 825c90f | 2024-03-26 12:45:29 +0000 | [diff] [blame^] | 529 | assert_eq!(1, db.count_vm_ids_for_app(USER2, APP_B).unwrap()); |
David Drysdale | 79af266 | 2024-02-19 14:50:31 +0000 | [diff] [blame] | 530 | assert_eq!(vec![VM_ID5], db.vm_ids_for_user(USER3).unwrap()); |
| 531 | assert_eq!(empty, db.vm_ids_for_user(USER_UNKNOWN).unwrap()); |
| 532 | assert_eq!(empty, db.vm_ids_for_app(USER1, APP_UNKNOWN).unwrap()); |
David Drysdale | 825c90f | 2024-03-26 12:45:29 +0000 | [diff] [blame^] | 533 | assert_eq!(0, db.count_vm_ids_for_app(USER1, APP_UNKNOWN).unwrap()); |
David Drysdale | 1138fa0 | 2024-03-19 13:06:23 +0000 | [diff] [blame] | 534 | |
| 535 | assert_eq!( |
| 536 | vec![(USER1, APP_A), (USER2, APP_B), (USER3, APP_C)], |
| 537 | db.get_all_owners().unwrap() |
| 538 | ); |
| 539 | |
David Drysdale | cf8875c | 2024-03-15 18:16:02 +0000 | [diff] [blame] | 540 | show_contents(&db); |
David Drysdale | 79af266 | 2024-02-19 14:50:31 +0000 | [diff] [blame] | 541 | } |
| 542 | |
| 543 | #[test] |
| 544 | fn test_invalid_vm_id() { |
| 545 | let mut db = new_test_db(); |
| 546 | db.add_vm_id(&VM_ID3, USER1, APP_A).unwrap(); |
| 547 | db.add_vm_id(&VM_ID2, USER1, APP_A).unwrap(); |
| 548 | db.add_vm_id(&VM_ID1, USER1, APP_A).unwrap(); |
| 549 | |
| 550 | // Note that results are returned in `vm_id` order, because the table is `WITHOUT ROWID`. |
| 551 | assert_eq!(vec![VM_ID1, VM_ID2, VM_ID3], db.vm_ids_for_user(USER1).unwrap()); |
| 552 | |
| 553 | // Manually insert a row with a VM ID that's the wrong size. |
| 554 | db.conn |
| 555 | .execute( |
David Drysdale | cf8875c | 2024-03-15 18:16:02 +0000 | [diff] [blame] | 556 | "REPLACE INTO main.vmids (vm_id, user_id, app_id, created) VALUES (?1, ?2, ?3, ?4);", |
| 557 | params![&[99u8; 60], &USER1, APP_A, &db_now()], |
David Drysdale | 79af266 | 2024-02-19 14:50:31 +0000 | [diff] [blame] | 558 | ) |
| 559 | .unwrap(); |
| 560 | |
| 561 | // Invalid row is skipped and remainder returned. |
| 562 | assert_eq!(vec![VM_ID1, VM_ID2, VM_ID3], db.vm_ids_for_user(USER1).unwrap()); |
David Drysdale | cf8875c | 2024-03-15 18:16:02 +0000 | [diff] [blame] | 563 | show_contents(&db); |
David Drysdale | 79af266 | 2024-02-19 14:50:31 +0000 | [diff] [blame] | 564 | } |
David Drysdale | 825c90f | 2024-03-26 12:45:29 +0000 | [diff] [blame^] | 565 | |
| 566 | #[test] |
| 567 | fn test_remove_oldest_with_upgrade() { |
| 568 | let mut db = new_test_db_version(0); |
| 569 | let version = db.schema_version().unwrap(); |
| 570 | assert_eq!(0, version); |
| 571 | |
| 572 | let remove_count = 10; |
| 573 | let mut want = vec![]; |
| 574 | |
| 575 | // Manually insert rows before upgrade. |
| 576 | const V0_COUNT: usize = 5; |
| 577 | for idx in 0..V0_COUNT { |
| 578 | let mut vm_id = [0u8; 64]; |
| 579 | vm_id[0..8].copy_from_slice(&(idx as u64).to_be_bytes()); |
| 580 | if want.len() < remove_count { |
| 581 | want.push(vm_id); |
| 582 | } |
| 583 | db.conn |
| 584 | .execute( |
| 585 | "REPLACE INTO main.vmids (vm_id, user_id, app_id) VALUES (?1, ?2, ?3);", |
| 586 | params![&vm_id, &USER1, APP_A], |
| 587 | ) |
| 588 | .unwrap(); |
| 589 | } |
| 590 | |
| 591 | // Now move to v1. |
| 592 | db.upgrade_tables_v0_v1().unwrap(); |
| 593 | let version = db.schema_version().unwrap(); |
| 594 | assert_eq!(1, version); |
| 595 | |
| 596 | for idx in V0_COUNT..40 { |
| 597 | let mut vm_id = [0u8; 64]; |
| 598 | vm_id[0..8].copy_from_slice(&(idx as u64).to_be_bytes()); |
| 599 | if want.len() < remove_count { |
| 600 | want.push(vm_id); |
| 601 | } |
| 602 | db.add_vm_id(&vm_id, USER1, APP_A).unwrap(); |
| 603 | } |
| 604 | show_contents_for_app(&db, USER1, APP_A, 10); |
| 605 | let got = db.oldest_vm_ids_for_app(USER1, APP_A, 10).unwrap(); |
| 606 | assert_eq!(got, want); |
| 607 | } |
David Drysdale | 79af266 | 2024-02-19 14:50:31 +0000 | [diff] [blame] | 608 | } |