blob: 87ba412228fbac769bff65773fffec5eced6ae02 [file] [log] [blame]
Alan Stokesea1f0462024-02-19 16:25:47 +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
David Drysdale79af2662024-02-19 14:50:31 +000015use android_hardware_security_secretkeeper::aidl::android::hardware::security::secretkeeper::{
16 ISecretkeeper::ISecretkeeper, SecretId::SecretId,
Alan Stokesea1f0462024-02-19 16:25:47 +000017};
David Drysdale1138fa02024-03-19 13:06:23 +000018use android_system_virtualizationmaintenance::aidl::android::system::virtualizationmaintenance;
19use anyhow::{anyhow, Context, Result};
20use binder::Strong;
David Drysdale79af2662024-02-19 14:50:31 +000021use log::{error, info, warn};
David Drysdale1138fa02024-03-19 13:06:23 +000022use virtualizationmaintenance::IVirtualizationReconciliationCallback::IVirtualizationReconciliationCallback;
Alan Stokesea1f0462024-02-19 16:25:47 +000023
David Drysdale79af2662024-02-19 14:50:31 +000024mod vmdb;
25use vmdb::{VmId, VmIdDb};
26
27/// Interface name for the Secretkeeper HAL.
28const SECRETKEEPER_SERVICE: &str = "android.hardware.security.secretkeeper.ISecretkeeper/default";
29
30/// Directory in which to write persistent state.
31const PERSISTENT_DIRECTORY: &str = "/data/misc/apexdata/com.android.virt";
32
33/// Maximum number of VM IDs to delete at once. Needs to be smaller than both the maximum
34/// number of SQLite parameters (999) and also small enough that an ISecretkeeper::deleteIds
35/// parcel fits within max AIDL message size.
36const DELETE_MAX_BATCH_SIZE: usize = 100;
37
David Drysdale825c90f2024-03-26 12:45:29 +000038/// Maximum number of VM IDs that a single app can have.
39const MAX_VM_IDS_PER_APP: usize = 400;
40
David Drysdale79af2662024-02-19 14:50:31 +000041/// State related to VM secrets.
42pub struct State {
Alan Stokes72820a92024-05-13 13:38:50 +010043 /// The real state, lazily created when we first need it.
44 inner: Option<InnerState>,
45}
46
47struct InnerState {
David Drysdale79af2662024-02-19 14:50:31 +000048 sk: binder::Strong<dyn ISecretkeeper>,
49 /// Database of VM IDs,
50 vm_id_db: VmIdDb,
51 batch_size: usize,
Alan Stokesea1f0462024-02-19 16:25:47 +000052}
53
David Drysdale79af2662024-02-19 14:50:31 +000054impl State {
55 pub fn new() -> Option<Self> {
Alan Stokes72820a92024-05-13 13:38:50 +010056 if is_sk_present() {
57 // Don't instantiate the inner state yet, that will happen when it is needed.
58 Some(Self { inner: None })
59 } else {
60 // If the Secretkeeper HAL doesn't exist, there's never any point in trying to
61 // handle maintenance for it.
62 info!("Failed to find a Secretkeeper instance; skipping secret management");
63 None
64 }
65 }
66
67 /// Return the existing inner state, or create one if there isn't one.
68 /// This is done on demand as in early boot (before we need Secretkeeper) it may not be
69 /// available to connect to. See b/331417880.
70 fn get_inner(&mut self) -> Result<&mut InnerState> {
71 if self.inner.is_none() {
72 self.inner = Some(InnerState::new()?);
73 }
74 Ok(self.inner.as_mut().unwrap())
75 }
76
77 /// Record a new VM ID. If there is an existing owner (user_id, app_id) for the VM ID,
78 /// it will be replaced.
79 pub fn add_id(&mut self, vm_id: &VmId, user_id: u32, app_id: u32) -> Result<()> {
80 self.get_inner()?.add_id(vm_id, user_id, app_id)
81 }
82
83 /// Delete the VM IDs associated with Android user ID `user_id`.
84 pub fn delete_ids_for_user(&mut self, user_id: i32) -> Result<()> {
85 self.get_inner()?.delete_ids_for_user(user_id)
86 }
87
88 /// Delete the VM IDs associated with `(user_id, app_id)`.
89 pub fn delete_ids_for_app(&mut self, user_id: i32, app_id: i32) -> Result<()> {
90 self.get_inner()?.delete_ids_for_app(user_id, app_id)
91 }
92
Alan Stokesde40e642024-06-04 13:36:05 +010093 /// Delete the provided VM ID associated with `(user_id, app_id)` from both Secretkeeper and
94 /// the database.
95 pub fn delete_id(&mut self, vm_id: &VmId, user_id: u32, app_id: u32) {
Alan Stokes72820a92024-05-13 13:38:50 +010096 let Ok(inner) = self.get_inner() else {
97 warn!("No Secretkeeper available, not deleting secrets");
98 return;
David Drysdale79af2662024-02-19 14:50:31 +000099 };
Alan Stokes72820a92024-05-13 13:38:50 +0100100
Alan Stokesde40e642024-06-04 13:36:05 +0100101 inner.delete_id_for_app(vm_id, user_id, app_id)
Alan Stokes72820a92024-05-13 13:38:50 +0100102 }
103
104 /// Perform reconciliation to allow for possibly missed notifications of user or app removal.
105 pub fn reconcile(
106 &mut self,
107 callback: &Strong<dyn IVirtualizationReconciliationCallback>,
108 ) -> Result<()> {
109 self.get_inner()?.reconcile(callback)
110 }
111}
112
113impl InnerState {
114 fn new() -> Result<Self> {
115 info!("Connecting to {SECRETKEEPER_SERVICE}");
116 let sk = binder::wait_for_interface::<dyn ISecretkeeper>(SECRETKEEPER_SERVICE)
117 .context("Connecting to {SECRETKEEPER_SERVICE}")?;
118 let (vm_id_db, created) = VmIdDb::new(PERSISTENT_DIRECTORY)
119 .context("Connecting to secret management database")?;
David Drysdale79af2662024-02-19 14:50:31 +0000120 if created {
121 // If the database did not previously exist, then this appears to be the first run of
122 // `virtualizationservice` since device setup or factory reset. In case of the latter,
123 // delete any secrets that may be left over from before reset, thus ensuring that the
124 // local database state matches that of the TA (i.e. empty).
125 warn!("no existing VM ID DB; clearing any previous secrets to match fresh DB");
126 if let Err(e) = sk.deleteAll() {
127 error!("failed to delete previous secrets, dropping database: {e:?}");
128 vm_id_db.delete_db_file(PERSISTENT_DIRECTORY);
Alan Stokes72820a92024-05-13 13:38:50 +0100129 return Err(e.into());
David Drysdale79af2662024-02-19 14:50:31 +0000130 }
131 } else {
132 info!("re-using existing VM ID DB");
133 }
Alan Stokes72820a92024-05-13 13:38:50 +0100134 Ok(Self { sk, vm_id_db, batch_size: DELETE_MAX_BATCH_SIZE })
Alan Stokesea1f0462024-02-19 16:25:47 +0000135 }
136
Alan Stokes72820a92024-05-13 13:38:50 +0100137 fn add_id(&mut self, vm_id: &VmId, user_id: u32, app_id: u32) -> Result<()> {
David Drysdalee64de8e2024-02-29 11:54:29 +0000138 let user_id: i32 = user_id.try_into().context(format!("user_id {user_id} out of range"))?;
139 let app_id: i32 = app_id.try_into().context(format!("app_id {app_id} out of range"))?;
David Drysdale825c90f2024-03-26 12:45:29 +0000140
141 // To prevent unbounded growth of VM IDs (and the associated state) for an app, limit the
142 // number of VM IDs per app.
143 let count = self
144 .vm_id_db
145 .count_vm_ids_for_app(user_id, app_id)
146 .context("failed to determine VM count")?;
147 if count >= MAX_VM_IDS_PER_APP {
148 // The owner has too many VM IDs, so delete the oldest IDs so that the new VM ID
149 // creation can progress/succeed.
150 let purge = 1 + count - MAX_VM_IDS_PER_APP;
151 let old_vm_ids = self
152 .vm_id_db
153 .oldest_vm_ids_for_app(user_id, app_id, purge)
154 .context("failed to find oldest VM IDs")?;
155 error!("Deleting {purge} of {count} VM IDs for user_id={user_id}, app_id={app_id}");
156 self.delete_ids(&old_vm_ids);
157 }
David Drysdalee64de8e2024-02-29 11:54:29 +0000158 self.vm_id_db.add_vm_id(vm_id, user_id, app_id)
159 }
160
Alan Stokesde40e642024-06-04 13:36:05 +0100161 fn delete_id_for_app(&mut self, vm_id: &VmId, user_id: u32, app_id: u32) {
162 if !self.vm_id_db.is_vm_id_for_app(vm_id, user_id, app_id).unwrap_or(false) {
163 info!(
164 "delete_id_for_app - VM id not associated with user_id={user_id}, app_id={app_id}"
165 );
166 return;
167 }
168 self.delete_ids(&[*vm_id])
169 }
170
Alan Stokes72820a92024-05-13 13:38:50 +0100171 fn delete_ids_for_user(&mut self, user_id: i32) -> Result<()> {
David Drysdale79af2662024-02-19 14:50:31 +0000172 let vm_ids = self.vm_id_db.vm_ids_for_user(user_id)?;
173 info!(
174 "delete_ids_for_user(user_id={user_id}) triggers deletion of {} secrets",
175 vm_ids.len()
176 );
177 self.delete_ids(&vm_ids);
178 Ok(())
179 }
180
Alan Stokes72820a92024-05-13 13:38:50 +0100181 fn delete_ids_for_app(&mut self, user_id: i32, app_id: i32) -> Result<()> {
David Drysdale79af2662024-02-19 14:50:31 +0000182 let vm_ids = self.vm_id_db.vm_ids_for_app(user_id, app_id)?;
183 info!(
184 "delete_ids_for_app(user_id={user_id}, app_id={app_id}) removes {} secrets",
185 vm_ids.len()
186 );
187 self.delete_ids(&vm_ids);
188 Ok(())
189 }
190
Alan Stokes72820a92024-05-13 13:38:50 +0100191 fn delete_ids(&mut self, mut vm_ids: &[VmId]) {
David Drysdale79af2662024-02-19 14:50:31 +0000192 while !vm_ids.is_empty() {
193 let len = std::cmp::min(vm_ids.len(), self.batch_size);
194 let batch = &vm_ids[..len];
195 self.delete_ids_batch(batch);
196 vm_ids = &vm_ids[len..];
197 }
198 }
199
200 /// Delete a batch of VM IDs from both Secretkeeper and the database. The batch is assumed
201 /// to be smaller than both:
202 /// - the corresponding limit for number of database parameters
203 /// - the corresponding limit for maximum size of a single AIDL message for `ISecretkeeper`.
204 fn delete_ids_batch(&mut self, vm_ids: &[VmId]) {
205 let secret_ids: Vec<SecretId> = vm_ids.iter().map(|id| SecretId { id: *id }).collect();
206 if let Err(e) = self.sk.deleteIds(&secret_ids) {
207 error!("failed to delete all secrets from Secretkeeper: {e:?}");
208 }
209 if let Err(e) = self.vm_id_db.delete_vm_ids(vm_ids) {
210 error!("failed to remove secret IDs from database: {e:?}");
211 }
212 }
David Drysdale1138fa02024-03-19 13:06:23 +0000213
Alan Stokes72820a92024-05-13 13:38:50 +0100214 fn reconcile(
David Drysdale1138fa02024-03-19 13:06:23 +0000215 &mut self,
216 callback: &Strong<dyn IVirtualizationReconciliationCallback>,
217 ) -> Result<()> {
218 // First, retrieve all (user_id, app_id) pairs that own a VM.
219 let owners = self.vm_id_db.get_all_owners().context("failed to retrieve owners from DB")?;
220 if owners.is_empty() {
221 info!("no VM owners, nothing to do");
222 return Ok(());
223 }
224
225 // Look for absent users.
226 let mut users: Vec<i32> = owners.iter().map(|(u, _a)| *u).collect();
227 users.sort();
228 users.dedup();
229 let users_exist = callback
230 .doUsersExist(&users)
231 .context(format!("failed to determine if {} users exist", users.len()))?;
232 if users_exist.len() != users.len() {
233 error!("callback returned {} bools for {} inputs!", users_exist.len(), users.len());
234 return Err(anyhow!("unexpected number of results from callback"));
235 }
236
237 for (user_id, present) in users.into_iter().zip(users_exist.into_iter()) {
238 if present {
239 // User is still present, but are all of the associated apps?
240 let mut apps: Vec<i32> = owners
241 .iter()
242 .filter_map(|(u, a)| if *u == user_id { Some(*a) } else { None })
243 .collect();
244 apps.sort();
245 apps.dedup();
246
247 let apps_exist = callback
248 .doAppsExist(user_id, &apps)
249 .context(format!("failed to check apps for user {user_id}"))?;
250 if apps_exist.len() != apps.len() {
251 error!(
252 "callback returned {} bools for {} inputs!",
253 apps_exist.len(),
254 apps.len()
255 );
256 return Err(anyhow!("unexpected number of results from callback"));
257 }
258
259 let missing_apps: Vec<i32> = apps
260 .iter()
261 .zip(apps_exist.into_iter())
262 .filter_map(|(app_id, present)| if present { None } else { Some(*app_id) })
263 .collect();
264
265 for app_id in missing_apps {
266 if core_app_id(app_id) {
267 info!("Skipping deletion for core app {app_id} for user {user_id}");
268 continue;
269 }
270 info!("App {app_id} for user {user_id} absent, deleting associated VM IDs");
271 if let Err(err) = self.delete_ids_for_app(user_id, app_id) {
272 error!("Failed to delete VM ID for user {user_id} app {app_id}: {err:?}");
273 }
274 }
275 } else {
276 info!("user {user_id} no longer present, deleting associated VM IDs");
277 if let Err(err) = self.delete_ids_for_user(user_id) {
278 error!("Failed to delete VM IDs for user {user_id} : {err:?}");
279 }
280 }
281 }
282
283 Ok(())
284 }
David Drysdale79af2662024-02-19 14:50:31 +0000285}
286
Alan Stokes72820a92024-05-13 13:38:50 +0100287/// Indicate whether an app ID belongs to a system core component.
288fn core_app_id(app_id: i32) -> bool {
289 app_id < 10000
290}
291
292fn is_sk_present() -> bool {
293 matches!(binder::is_declared(SECRETKEEPER_SERVICE), Ok(true))
294}
295
David Drysdale79af2662024-02-19 14:50:31 +0000296#[cfg(test)]
297mod tests {
298 use super::*;
Alan Stokes72820a92024-05-13 13:38:50 +0100299 use android_hardware_security_authgraph::aidl::android::hardware::security::authgraph;
Matt Gilbrideb57abcc2024-10-12 15:26:45 +0000300 use android_hardware_security_secretkeeper::aidl::android::hardware::security::secretkeeper::{
301 self, PublicKey::PublicKey,
302 };
Alan Stokes72820a92024-05-13 13:38:50 +0100303 use authgraph::IAuthGraphKeyExchange::IAuthGraphKeyExchange;
304 use secretkeeper::ISecretkeeper::BnSecretkeeper;
David Drysdale79af2662024-02-19 14:50:31 +0000305 use std::sync::{Arc, Mutex};
Alan Stokes72820a92024-05-13 13:38:50 +0100306 use virtualizationmaintenance::IVirtualizationReconciliationCallback::BnVirtualizationReconciliationCallback;
David Drysdale79af2662024-02-19 14:50:31 +0000307
308 /// Fake implementation of Secretkeeper that keeps a history of what operations were invoked.
309 #[derive(Default)]
310 struct FakeSk {
311 history: Arc<Mutex<Vec<SkOp>>>,
312 }
313
314 #[derive(Clone, PartialEq, Eq, Debug)]
315 enum SkOp {
316 Management,
317 DeleteIds(Vec<VmId>),
318 DeleteAll,
319 }
320
321 impl ISecretkeeper for FakeSk {
322 fn processSecretManagementRequest(&self, _req: &[u8]) -> binder::Result<Vec<u8>> {
323 self.history.lock().unwrap().push(SkOp::Management);
324 Ok(vec![])
325 }
326
327 fn getAuthGraphKe(&self) -> binder::Result<binder::Strong<dyn IAuthGraphKeyExchange>> {
328 unimplemented!()
329 }
330
331 fn deleteIds(&self, ids: &[SecretId]) -> binder::Result<()> {
332 self.history.lock().unwrap().push(SkOp::DeleteIds(ids.iter().map(|s| s.id).collect()));
333 Ok(())
334 }
335
336 fn deleteAll(&self) -> binder::Result<()> {
337 self.history.lock().unwrap().push(SkOp::DeleteAll);
338 Ok(())
339 }
Matt Gilbrideb57abcc2024-10-12 15:26:45 +0000340
341 fn getSecretkeeperIdentity(&self) -> binder::Result<PublicKey> {
342 unimplemented!()
343 }
David Drysdale79af2662024-02-19 14:50:31 +0000344 }
345 impl binder::Interface for FakeSk {}
346
347 fn new_test_state(history: Arc<Mutex<Vec<SkOp>>>, batch_size: usize) -> State {
348 let vm_id_db = vmdb::new_test_db();
349 let sk = FakeSk { history };
350 let sk = BnSecretkeeper::new_binder(sk, binder::BinderFeatures::default());
Alan Stokes72820a92024-05-13 13:38:50 +0100351 let inner = InnerState { sk, vm_id_db, batch_size };
352 State { inner: Some(inner) }
353 }
354
355 fn get_db(state: &mut State) -> &mut VmIdDb {
356 &mut state.inner.as_mut().unwrap().vm_id_db
David Drysdale79af2662024-02-19 14:50:31 +0000357 }
358
David Drysdale1138fa02024-03-19 13:06:23 +0000359 struct Reconciliation {
360 gone_users: Vec<i32>,
361 gone_apps: Vec<i32>,
362 }
363
364 impl IVirtualizationReconciliationCallback for Reconciliation {
365 fn doUsersExist(&self, user_ids: &[i32]) -> binder::Result<Vec<bool>> {
366 Ok(user_ids.iter().map(|user_id| !self.gone_users.contains(user_id)).collect())
367 }
368 fn doAppsExist(&self, _user_id: i32, app_ids: &[i32]) -> binder::Result<Vec<bool>> {
369 Ok(app_ids.iter().map(|app_id| !self.gone_apps.contains(app_id)).collect())
370 }
371 }
372 impl binder::Interface for Reconciliation {}
373
David Drysdale79af2662024-02-19 14:50:31 +0000374 const VM_ID1: VmId = [1u8; 64];
375 const VM_ID2: VmId = [2u8; 64];
376 const VM_ID3: VmId = [3u8; 64];
377 const VM_ID4: VmId = [4u8; 64];
378 const VM_ID5: VmId = [5u8; 64];
379
David Drysdale1138fa02024-03-19 13:06:23 +0000380 const USER1: i32 = 1;
381 const USER2: i32 = 2;
382 const USER3: i32 = 3;
383 const APP_A: i32 = 10050;
384 const APP_B: i32 = 10060;
385 const APP_C: i32 = 10070;
386 const CORE_APP_A: i32 = 45;
387
David Drysdale79af2662024-02-19 14:50:31 +0000388 #[test]
389 fn test_sk_state_batching() {
390 let history = Arc::new(Mutex::new(Vec::new()));
Alan Stokesde40e642024-06-04 13:36:05 +0100391 let sk_state = new_test_state(history.clone(), 2);
392 sk_state.inner.unwrap().delete_ids(&[VM_ID1, VM_ID2, VM_ID3, VM_ID4, VM_ID5]);
David Drysdale79af2662024-02-19 14:50:31 +0000393 let got = (*history.lock().unwrap()).clone();
394 assert_eq!(
395 got,
396 vec![
397 SkOp::DeleteIds(vec![VM_ID1, VM_ID2]),
398 SkOp::DeleteIds(vec![VM_ID3, VM_ID4]),
399 SkOp::DeleteIds(vec![VM_ID5]),
400 ]
401 );
402 }
403
404 #[test]
405 fn test_sk_state_no_batching() {
406 let history = Arc::new(Mutex::new(Vec::new()));
Alan Stokesde40e642024-06-04 13:36:05 +0100407 let sk_state = new_test_state(history.clone(), 6);
408 sk_state.inner.unwrap().delete_ids(&[VM_ID1, VM_ID2, VM_ID3, VM_ID4, VM_ID5]);
David Drysdale79af2662024-02-19 14:50:31 +0000409 let got = (*history.lock().unwrap()).clone();
410 assert_eq!(got, vec![SkOp::DeleteIds(vec![VM_ID1, VM_ID2, VM_ID3, VM_ID4, VM_ID5])]);
411 }
412
413 #[test]
414 fn test_sk_state() {
David Drysdale79af2662024-02-19 14:50:31 +0000415 let history = Arc::new(Mutex::new(Vec::new()));
416 let mut sk_state = new_test_state(history.clone(), 2);
417
Alan Stokes72820a92024-05-13 13:38:50 +0100418 get_db(&mut sk_state).add_vm_id(&VM_ID1, USER1, APP_A).unwrap();
419 get_db(&mut sk_state).add_vm_id(&VM_ID2, USER1, APP_A).unwrap();
420 get_db(&mut sk_state).add_vm_id(&VM_ID3, USER2, APP_B).unwrap();
421 get_db(&mut sk_state).add_vm_id(&VM_ID4, USER3, APP_A).unwrap();
Alan Stokesde40e642024-06-04 13:36:05 +0100422 get_db(&mut sk_state).add_vm_id(&VM_ID5, USER3, APP_C).unwrap();
David Drysdale79af2662024-02-19 14:50:31 +0000423 assert_eq!((*history.lock().unwrap()).clone(), vec![]);
424
425 sk_state.delete_ids_for_app(USER2, APP_B).unwrap();
426 assert_eq!((*history.lock().unwrap()).clone(), vec![SkOp::DeleteIds(vec![VM_ID3])]);
427
428 sk_state.delete_ids_for_user(USER3).unwrap();
429 assert_eq!(
430 (*history.lock().unwrap()).clone(),
431 vec![SkOp::DeleteIds(vec![VM_ID3]), SkOp::DeleteIds(vec![VM_ID4, VM_ID5]),]
432 );
433
Alan Stokes72820a92024-05-13 13:38:50 +0100434 assert_eq!(vec![VM_ID1, VM_ID2], get_db(&mut sk_state).vm_ids_for_user(USER1).unwrap());
435 assert_eq!(
436 vec![VM_ID1, VM_ID2],
437 get_db(&mut sk_state).vm_ids_for_app(USER1, APP_A).unwrap()
438 );
David Drysdale79af2662024-02-19 14:50:31 +0000439 let empty: Vec<VmId> = Vec::new();
Alan Stokes72820a92024-05-13 13:38:50 +0100440 assert_eq!(empty, get_db(&mut sk_state).vm_ids_for_app(USER2, APP_B).unwrap());
441 assert_eq!(empty, get_db(&mut sk_state).vm_ids_for_user(USER3).unwrap());
Alan Stokesea1f0462024-02-19 16:25:47 +0000442 }
David Drysdale1138fa02024-03-19 13:06:23 +0000443
444 #[test]
Alan Stokesde40e642024-06-04 13:36:05 +0100445 fn test_sk_state_delete_id() {
446 let history = Arc::new(Mutex::new(Vec::new()));
447 let mut sk_state = new_test_state(history.clone(), 2);
448
449 get_db(&mut sk_state).add_vm_id(&VM_ID1, USER1, APP_A).unwrap();
450 get_db(&mut sk_state).add_vm_id(&VM_ID2, USER1, APP_A).unwrap();
451 get_db(&mut sk_state).add_vm_id(&VM_ID3, USER2, APP_B).unwrap();
452 assert_eq!((*history.lock().unwrap()).clone(), vec![]);
453
454 // A VM ID that doesn't exist anywhere - no delete
455 sk_state.delete_id(&VM_ID4, USER1 as u32, APP_A as u32);
456 assert_eq!((*history.lock().unwrap()).clone(), vec![]);
457
458 // Wrong app ID - no delete
459 sk_state.delete_id(&VM_ID1, USER1 as u32, APP_B as u32);
460 assert_eq!((*history.lock().unwrap()).clone(), vec![]);
461
462 // Wrong user ID - no delete
463 sk_state.delete_id(&VM_ID1, USER2 as u32, APP_A as u32);
464 assert_eq!((*history.lock().unwrap()).clone(), vec![]);
465
466 // This porridge is just right.
467 sk_state.delete_id(&VM_ID1, USER1 as u32, APP_A as u32);
468 assert_eq!((*history.lock().unwrap()).clone(), vec![SkOp::DeleteIds(vec![VM_ID1])]);
469
470 assert_eq!(vec![VM_ID2], get_db(&mut sk_state).vm_ids_for_user(USER1).unwrap());
471 assert_eq!(vec![VM_ID3], get_db(&mut sk_state).vm_ids_for_user(USER2).unwrap());
472 }
473
474 #[test]
David Drysdale1138fa02024-03-19 13:06:23 +0000475 fn test_sk_state_reconcile() {
476 let history = Arc::new(Mutex::new(Vec::new()));
477 let mut sk_state = new_test_state(history.clone(), 20);
478
Alan Stokes72820a92024-05-13 13:38:50 +0100479 get_db(&mut sk_state).add_vm_id(&VM_ID1, USER1, APP_A).unwrap();
480 get_db(&mut sk_state).add_vm_id(&VM_ID2, USER1, APP_A).unwrap();
481 get_db(&mut sk_state).add_vm_id(&VM_ID3, USER2, APP_B).unwrap();
482 get_db(&mut sk_state).add_vm_id(&VM_ID4, USER2, CORE_APP_A).unwrap();
483 get_db(&mut sk_state).add_vm_id(&VM_ID5, USER3, APP_C).unwrap();
David Drysdale1138fa02024-03-19 13:06:23 +0000484
Alan Stokes72820a92024-05-13 13:38:50 +0100485 assert_eq!(vec![VM_ID1, VM_ID2], get_db(&mut sk_state).vm_ids_for_user(USER1).unwrap());
486 assert_eq!(
487 vec![VM_ID1, VM_ID2],
488 get_db(&mut sk_state).vm_ids_for_app(USER1, APP_A).unwrap()
489 );
490 assert_eq!(vec![VM_ID3], get_db(&mut sk_state).vm_ids_for_app(USER2, APP_B).unwrap());
491 assert_eq!(vec![VM_ID5], get_db(&mut sk_state).vm_ids_for_user(USER3).unwrap());
David Drysdale1138fa02024-03-19 13:06:23 +0000492
493 // Perform a reconciliation and pretend that USER1 and [CORE_APP_A, APP_B] are gone.
494 let reconciliation =
495 Reconciliation { gone_users: vec![USER1], gone_apps: vec![CORE_APP_A, APP_B] };
496 let callback = BnVirtualizationReconciliationCallback::new_binder(
497 reconciliation,
498 binder::BinderFeatures::default(),
499 );
500 sk_state.reconcile(&callback).unwrap();
501
502 let empty: Vec<VmId> = Vec::new();
Alan Stokes72820a92024-05-13 13:38:50 +0100503 assert_eq!(empty, get_db(&mut sk_state).vm_ids_for_user(USER1).unwrap());
504 assert_eq!(empty, get_db(&mut sk_state).vm_ids_for_app(USER1, APP_A).unwrap());
David Drysdale1138fa02024-03-19 13:06:23 +0000505 // VM for core app stays even though it's reported as absent.
Alan Stokes72820a92024-05-13 13:38:50 +0100506 assert_eq!(vec![VM_ID4], get_db(&mut sk_state).vm_ids_for_user(USER2).unwrap());
507 assert_eq!(empty, get_db(&mut sk_state).vm_ids_for_app(USER2, APP_B).unwrap());
508 assert_eq!(vec![VM_ID5], get_db(&mut sk_state).vm_ids_for_user(USER3).unwrap());
David Drysdale1138fa02024-03-19 13:06:23 +0000509 }
510
David Drysdale825c90f2024-03-26 12:45:29 +0000511 #[test]
512 fn test_sk_state_too_many_vms() {
513 let history = Arc::new(Mutex::new(Vec::new()));
514 let mut sk_state = new_test_state(history.clone(), 20);
515
516 // Every VM ID added up to the limit is kept.
517 for idx in 0..MAX_VM_IDS_PER_APP {
518 let mut vm_id = [0u8; 64];
519 vm_id[0..8].copy_from_slice(&(idx as u64).to_be_bytes());
520 sk_state.add_id(&vm_id, USER1 as u32, APP_A as u32).unwrap();
Alan Stokes72820a92024-05-13 13:38:50 +0100521 assert_eq!(idx + 1, get_db(&mut sk_state).count_vm_ids_for_app(USER1, APP_A).unwrap());
David Drysdale825c90f2024-03-26 12:45:29 +0000522 }
523 assert_eq!(
524 MAX_VM_IDS_PER_APP,
Alan Stokes72820a92024-05-13 13:38:50 +0100525 get_db(&mut sk_state).count_vm_ids_for_app(USER1, APP_A).unwrap()
David Drysdale825c90f2024-03-26 12:45:29 +0000526 );
527
528 // Beyond the limit it's one in, one out.
529 for idx in MAX_VM_IDS_PER_APP..MAX_VM_IDS_PER_APP + 10 {
530 let mut vm_id = [0u8; 64];
531 vm_id[0..8].copy_from_slice(&(idx as u64).to_be_bytes());
532 sk_state.add_id(&vm_id, USER1 as u32, APP_A as u32).unwrap();
533 assert_eq!(
534 MAX_VM_IDS_PER_APP,
Alan Stokes72820a92024-05-13 13:38:50 +0100535 get_db(&mut sk_state).count_vm_ids_for_app(USER1, APP_A).unwrap()
David Drysdale825c90f2024-03-26 12:45:29 +0000536 );
537 }
538 assert_eq!(
539 MAX_VM_IDS_PER_APP,
Alan Stokes72820a92024-05-13 13:38:50 +0100540 get_db(&mut sk_state).count_vm_ids_for_app(USER1, APP_A).unwrap()
David Drysdale825c90f2024-03-26 12:45:29 +0000541 );
542 }
543
David Drysdale1138fa02024-03-19 13:06:23 +0000544 struct Irreconcilable;
545
546 impl IVirtualizationReconciliationCallback for Irreconcilable {
547 fn doUsersExist(&self, user_ids: &[i32]) -> binder::Result<Vec<bool>> {
548 panic!("doUsersExist called with {user_ids:?}");
549 }
550 fn doAppsExist(&self, user_id: i32, app_ids: &[i32]) -> binder::Result<Vec<bool>> {
551 panic!("doAppsExist called with {user_id:?}, {app_ids:?}");
552 }
553 }
554 impl binder::Interface for Irreconcilable {}
555
556 #[test]
557 fn test_sk_state_reconcile_not_needed() {
558 let history = Arc::new(Mutex::new(Vec::new()));
559 let mut sk_state = new_test_state(history.clone(), 20);
560
Alan Stokes72820a92024-05-13 13:38:50 +0100561 get_db(&mut sk_state).add_vm_id(&VM_ID1, USER1, APP_A).unwrap();
562 get_db(&mut sk_state).add_vm_id(&VM_ID2, USER1, APP_A).unwrap();
563 get_db(&mut sk_state).add_vm_id(&VM_ID3, USER2, APP_B).unwrap();
564 get_db(&mut sk_state).add_vm_id(&VM_ID5, USER3, APP_C).unwrap();
David Drysdale1138fa02024-03-19 13:06:23 +0000565 sk_state.delete_ids_for_user(USER1).unwrap();
566 sk_state.delete_ids_for_user(USER2).unwrap();
567 sk_state.delete_ids_for_user(USER3).unwrap();
568
569 // No extant secrets, so reconciliation should not trigger the callback.
570 let callback = BnVirtualizationReconciliationCallback::new_binder(
571 Irreconcilable,
572 binder::BinderFeatures::default(),
573 );
574 sk_state.reconcile(&callback).unwrap();
575 }
Alan Stokesea1f0462024-02-19 16:25:47 +0000576}