blob: c4b06862b1c6be072bf1f2b437fc7c5cd3c42022 [file] [log] [blame]
Tri Voe8f04442022-12-21 08:53:56 -08001// Copyright 2022, 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//! Helper wrapper around RKPD interface.
Tri Vo437d0142023-01-18 16:43:49 -080016// TODO(b/264891956): Return RKP specific errors.
Tri Voe8f04442022-12-21 08:53:56 -080017
Tri Vo437d0142023-01-18 16:43:49 -080018use crate::error::{map_binder_status_code, Error};
Tri Voe8f04442022-12-21 08:53:56 -080019use crate::globals::get_remotely_provisioned_component_name;
20use crate::ks_err;
21use crate::utils::watchdog as wd;
22use android_hardware_security_keymint::aidl::android::hardware::security::keymint::SecurityLevel::SecurityLevel;
23use android_security_rkp_aidl::aidl::android::security::rkp::{
24 IGetKeyCallback::BnGetKeyCallback, IGetKeyCallback::IGetKeyCallback,
25 IGetRegistrationCallback::BnGetRegistrationCallback,
26 IGetRegistrationCallback::IGetRegistrationCallback, IRegistration::IRegistration,
Seth Moorea55428e2023-01-10 13:07:31 -080027 IRemoteProvisioning::IRemoteProvisioning,
28 IStoreUpgradedKeyCallback::BnStoreUpgradedKeyCallback,
29 IStoreUpgradedKeyCallback::IStoreUpgradedKeyCallback,
30 RemotelyProvisionedKey::RemotelyProvisionedKey,
Tri Voe8f04442022-12-21 08:53:56 -080031};
32use android_security_rkp_aidl::binder::{BinderFeatures, Interface, Strong};
Tri Vo437d0142023-01-18 16:43:49 -080033use android_system_keystore2::aidl::android::system::keystore2::ResponseCode::ResponseCode;
Tri Voe8f04442022-12-21 08:53:56 -080034use anyhow::{Context, Result};
Tri Voe8f04442022-12-21 08:53:56 -080035use std::sync::Mutex;
Tri Vo437d0142023-01-18 16:43:49 -080036use std::time::Duration;
37use tokio::sync::oneshot;
38use tokio::time::timeout;
39
40// Normally, we block indefinitely when making calls outside of keystore and rely on watchdog to
41// report deadlocks. However, RKPD is mainline updatable. Also, calls to RKPD may wait on network
42// for certificates. So, we err on the side of caution and timeout instead.
43static RKPD_TIMEOUT: Duration = Duration::from_secs(10);
44
45fn tokio_rt() -> tokio::runtime::Runtime {
46 tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap()
47}
Tri Voe8f04442022-12-21 08:53:56 -080048
Seth Moorea882c962023-01-09 16:55:10 -080049/// Thread-safe channel for sending a value once and only once. If a value has
50/// already been send, subsequent calls to send will noop.
51struct SafeSender<T> {
52 inner: Mutex<Option<oneshot::Sender<T>>>,
53}
54
55impl<T> SafeSender<T> {
56 fn new(sender: oneshot::Sender<T>) -> Self {
57 Self { inner: Mutex::new(Some(sender)) }
58 }
59
60 fn send(&self, value: T) {
61 if let Some(inner) = self.inner.lock().unwrap().take() {
62 // assert instead of unwrap, because on failure send returns Err(value)
63 assert!(inner.send(value).is_ok(), "thread state is terminally broken");
64 }
65 }
66}
Tri Voe8f04442022-12-21 08:53:56 -080067
68struct GetRegistrationCallback {
Seth Moorea882c962023-01-09 16:55:10 -080069 registration_tx: SafeSender<Result<binder::Strong<dyn IRegistration>>>,
Tri Voe8f04442022-12-21 08:53:56 -080070}
71
72impl GetRegistrationCallback {
73 pub fn new_native_binder(
Seth Moorea882c962023-01-09 16:55:10 -080074 registration_tx: oneshot::Sender<Result<binder::Strong<dyn IRegistration>>>,
Seth Moore613a1fd2023-01-11 10:42:26 -080075 ) -> Strong<dyn IGetRegistrationCallback> {
Tri Voe8f04442022-12-21 08:53:56 -080076 let result: Self =
Seth Moorea882c962023-01-09 16:55:10 -080077 GetRegistrationCallback { registration_tx: SafeSender::new(registration_tx) };
Seth Moore613a1fd2023-01-11 10:42:26 -080078 BnGetRegistrationCallback::new_binder(result, BinderFeatures::default())
Tri Voe8f04442022-12-21 08:53:56 -080079 }
80}
81
82impl Interface for GetRegistrationCallback {}
83
84impl IGetRegistrationCallback for GetRegistrationCallback {
85 fn onSuccess(&self, registration: &Strong<dyn IRegistration>) -> binder::Result<()> {
86 let _wp = wd::watch_millis("IGetRegistrationCallback::onSuccess", 500);
Seth Moore613a1fd2023-01-11 10:42:26 -080087 self.registration_tx.send(Ok(registration.clone()));
88 Ok(())
Tri Voe8f04442022-12-21 08:53:56 -080089 }
90 fn onCancel(&self) -> binder::Result<()> {
91 let _wp = wd::watch_millis("IGetRegistrationCallback::onCancel", 500);
Seth Moore613a1fd2023-01-11 10:42:26 -080092 log::warn!("IGetRegistrationCallback cancelled");
93 self.registration_tx.send(
Tri Vo437d0142023-01-18 16:43:49 -080094 Err(Error::Rc(ResponseCode::OUT_OF_KEYS))
Seth Moore613a1fd2023-01-11 10:42:26 -080095 .context(ks_err!("GetRegistrationCallback cancelled.")),
96 );
97 Ok(())
Tri Voe8f04442022-12-21 08:53:56 -080098 }
99 fn onError(&self, error: &str) -> binder::Result<()> {
100 let _wp = wd::watch_millis("IGetRegistrationCallback::onError", 500);
Seth Moore613a1fd2023-01-11 10:42:26 -0800101 log::error!("IGetRegistrationCallback failed: '{error}'");
102 self.registration_tx.send(
Tri Vo437d0142023-01-18 16:43:49 -0800103 Err(Error::Rc(ResponseCode::OUT_OF_KEYS))
Seth Moore613a1fd2023-01-11 10:42:26 -0800104 .context(ks_err!("GetRegistrationCallback failed: {:?}", error)),
105 );
106 Ok(())
Tri Voe8f04442022-12-21 08:53:56 -0800107 }
108}
109
110/// Make a new connection to a IRegistration service.
111async fn get_rkpd_registration(
112 security_level: &SecurityLevel,
113) -> Result<binder::Strong<dyn IRegistration>> {
114 let remote_provisioning: Strong<dyn IRemoteProvisioning> =
115 map_binder_status_code(binder::get_interface("remote_provisioning"))
116 .context(ks_err!("Trying to connect to IRemoteProvisioning service."))?;
117
118 let rpc_name = get_remotely_provisioned_component_name(security_level)
119 .context(ks_err!("Trying to get IRPC name."))?;
120
121 let (tx, rx) = oneshot::channel();
Seth Moore613a1fd2023-01-11 10:42:26 -0800122 let cb = GetRegistrationCallback::new_native_binder(tx);
Tri Voe8f04442022-12-21 08:53:56 -0800123
124 remote_provisioning
125 .getRegistration(&rpc_name, &cb)
126 .context(ks_err!("Trying to get registration."))?;
127
Tri Vo437d0142023-01-18 16:43:49 -0800128 match timeout(RKPD_TIMEOUT, rx).await {
129 Err(e) => {
130 Err(Error::Rc(ResponseCode::SYSTEM_ERROR)).context(ks_err!("Waiting for RKPD: {:?}", e))
131 }
132 Ok(v) => v.unwrap(),
133 }
Tri Voe8f04442022-12-21 08:53:56 -0800134}
135
Tri Voe8f04442022-12-21 08:53:56 -0800136struct GetKeyCallback {
Seth Moorea882c962023-01-09 16:55:10 -0800137 key_tx: SafeSender<Result<RemotelyProvisionedKey>>,
Tri Voe8f04442022-12-21 08:53:56 -0800138}
139
140impl GetKeyCallback {
Seth Moorea882c962023-01-09 16:55:10 -0800141 pub fn new_native_binder(
142 key_tx: oneshot::Sender<Result<RemotelyProvisionedKey>>,
Seth Moore613a1fd2023-01-11 10:42:26 -0800143 ) -> Strong<dyn IGetKeyCallback> {
Seth Moorea882c962023-01-09 16:55:10 -0800144 let result: Self = GetKeyCallback { key_tx: SafeSender::new(key_tx) };
Seth Moore613a1fd2023-01-11 10:42:26 -0800145 BnGetKeyCallback::new_binder(result, BinderFeatures::default())
Tri Voe8f04442022-12-21 08:53:56 -0800146 }
147}
148
149impl Interface for GetKeyCallback {}
150
151impl IGetKeyCallback for GetKeyCallback {
152 fn onSuccess(&self, key: &RemotelyProvisionedKey) -> binder::Result<()> {
153 let _wp = wd::watch_millis("IGetKeyCallback::onSuccess", 500);
Seth Moore613a1fd2023-01-11 10:42:26 -0800154 self.key_tx.send(Ok(RemotelyProvisionedKey {
155 keyBlob: key.keyBlob.clone(),
156 encodedCertChain: key.encodedCertChain.clone(),
157 }));
158 Ok(())
Tri Voe8f04442022-12-21 08:53:56 -0800159 }
160 fn onCancel(&self) -> binder::Result<()> {
161 let _wp = wd::watch_millis("IGetKeyCallback::onCancel", 500);
Seth Moore613a1fd2023-01-11 10:42:26 -0800162 log::warn!("IGetKeyCallback cancelled");
163 self.key_tx.send(
Tri Vo437d0142023-01-18 16:43:49 -0800164 Err(Error::Rc(ResponseCode::OUT_OF_KEYS)).context(ks_err!("GetKeyCallback cancelled.")),
Seth Moore613a1fd2023-01-11 10:42:26 -0800165 );
166 Ok(())
Tri Voe8f04442022-12-21 08:53:56 -0800167 }
168 fn onError(&self, error: &str) -> binder::Result<()> {
169 let _wp = wd::watch_millis("IGetKeyCallback::onError", 500);
Seth Moore613a1fd2023-01-11 10:42:26 -0800170 log::error!("IGetKeyCallback failed: {error}");
171 self.key_tx.send(
Tri Vo437d0142023-01-18 16:43:49 -0800172 Err(Error::Rc(ResponseCode::OUT_OF_KEYS))
Seth Moore613a1fd2023-01-11 10:42:26 -0800173 .context(ks_err!("GetKeyCallback failed: {:?}", error)),
174 );
175 Ok(())
Tri Voe8f04442022-12-21 08:53:56 -0800176 }
177}
178
Tri Vo437d0142023-01-18 16:43:49 -0800179async fn get_rkpd_attestation_key_from_registration_async(
180 registration: &Strong<dyn IRegistration>,
181 caller_uid: u32,
182) -> Result<RemotelyProvisionedKey> {
183 let (tx, rx) = oneshot::channel();
184 let cb = GetKeyCallback::new_native_binder(tx);
185
186 registration
187 .getKey(caller_uid.try_into().unwrap(), &cb)
188 .context(ks_err!("Trying to get key."))?;
189
190 match timeout(RKPD_TIMEOUT, rx).await {
191 Err(e) => Err(Error::Rc(ResponseCode::OUT_OF_KEYS))
192 .context(ks_err!("Waiting for RKPD key timed out: {:?}", e)),
193 Ok(v) => v.unwrap(),
194 }
195}
196
Tri Voe8f04442022-12-21 08:53:56 -0800197async fn get_rkpd_attestation_key_async(
198 security_level: &SecurityLevel,
199 caller_uid: u32,
200) -> Result<RemotelyProvisionedKey> {
201 let registration = get_rkpd_registration(security_level)
202 .await
203 .context(ks_err!("Trying to get to IRegistration service."))?;
Tri Vo437d0142023-01-18 16:43:49 -0800204 get_rkpd_attestation_key_from_registration_async(&registration, caller_uid).await
Tri Voe8f04442022-12-21 08:53:56 -0800205}
206
Seth Moorea55428e2023-01-10 13:07:31 -0800207struct StoreUpgradedKeyCallback {
208 completer: SafeSender<Result<()>>,
209}
210
211impl StoreUpgradedKeyCallback {
212 pub fn new_native_binder(
213 completer: oneshot::Sender<Result<()>>,
Seth Moore613a1fd2023-01-11 10:42:26 -0800214 ) -> Strong<dyn IStoreUpgradedKeyCallback> {
Seth Moorea55428e2023-01-10 13:07:31 -0800215 let result: Self = StoreUpgradedKeyCallback { completer: SafeSender::new(completer) };
Seth Moore613a1fd2023-01-11 10:42:26 -0800216 BnStoreUpgradedKeyCallback::new_binder(result, BinderFeatures::default())
Seth Moorea55428e2023-01-10 13:07:31 -0800217 }
218}
219
220impl Interface for StoreUpgradedKeyCallback {}
221
222impl IStoreUpgradedKeyCallback for StoreUpgradedKeyCallback {
223 fn onSuccess(&self) -> binder::Result<()> {
224 let _wp = wd::watch_millis("IGetRegistrationCallback::onSuccess", 500);
Seth Moore613a1fd2023-01-11 10:42:26 -0800225 self.completer.send(Ok(()));
226 Ok(())
Seth Moorea55428e2023-01-10 13:07:31 -0800227 }
228
229 fn onError(&self, error: &str) -> binder::Result<()> {
230 let _wp = wd::watch_millis("IGetRegistrationCallback::onError", 500);
Seth Moore613a1fd2023-01-11 10:42:26 -0800231 log::error!("IGetRegistrationCallback failed: {error}");
232 self.completer.send(
Tri Vo437d0142023-01-18 16:43:49 -0800233 Err(Error::Rc(ResponseCode::SYSTEM_ERROR))
Seth Moore613a1fd2023-01-11 10:42:26 -0800234 .context(ks_err!("Failed to store upgraded key: {:?}", error)),
235 );
236 Ok(())
Seth Moorea55428e2023-01-10 13:07:31 -0800237 }
238}
239
Tri Vo437d0142023-01-18 16:43:49 -0800240async fn store_rkpd_attestation_key_with_registration_async(
241 registration: &Strong<dyn IRegistration>,
242 key_blob: &[u8],
243 upgraded_blob: &[u8],
244) -> Result<()> {
245 let (tx, rx) = oneshot::channel();
246 let cb = StoreUpgradedKeyCallback::new_native_binder(tx);
247
248 registration
249 .storeUpgradedKeyAsync(key_blob, upgraded_blob, &cb)
250 .context(ks_err!("Failed to store upgraded blob with RKPD."))?;
251
252 match timeout(RKPD_TIMEOUT, rx).await {
253 Err(e) => Err(Error::Rc(ResponseCode::SYSTEM_ERROR))
254 .context(ks_err!("Waiting for RKPD to complete storing key: {:?}", e)),
255 Ok(v) => v.unwrap(),
256 }
257}
258
Tri Voe8f04442022-12-21 08:53:56 -0800259async fn store_rkpd_attestation_key_async(
260 security_level: &SecurityLevel,
261 key_blob: &[u8],
262 upgraded_blob: &[u8],
263) -> Result<()> {
264 let registration = get_rkpd_registration(security_level)
265 .await
266 .context(ks_err!("Trying to get to IRegistration service."))?;
Tri Vo437d0142023-01-18 16:43:49 -0800267 store_rkpd_attestation_key_with_registration_async(&registration, key_blob, upgraded_blob).await
Tri Voe8f04442022-12-21 08:53:56 -0800268}
269
270/// Get attestation key from RKPD.
271pub fn get_rkpd_attestation_key(
272 security_level: &SecurityLevel,
273 caller_uid: u32,
274) -> Result<RemotelyProvisionedKey> {
275 let _wp = wd::watch_millis("Calling get_rkpd_attestation_key()", 500);
Tri Vo437d0142023-01-18 16:43:49 -0800276 tokio_rt().block_on(get_rkpd_attestation_key_async(security_level, caller_uid))
Tri Voe8f04442022-12-21 08:53:56 -0800277}
278
279/// Store attestation key in RKPD.
280pub fn store_rkpd_attestation_key(
281 security_level: &SecurityLevel,
282 key_blob: &[u8],
283 upgraded_blob: &[u8],
284) -> Result<()> {
285 let _wp = wd::watch_millis("Calling store_rkpd_attestation_key()", 500);
Tri Vo437d0142023-01-18 16:43:49 -0800286 tokio_rt().block_on(store_rkpd_attestation_key_async(security_level, key_blob, upgraded_blob))
Tri Voe8f04442022-12-21 08:53:56 -0800287}
288
289#[cfg(test)]
290mod tests {
291 use super::*;
292 use android_security_rkp_aidl::aidl::android::security::rkp::IRegistration::BnRegistration;
Tri Vo4b1cd822023-01-23 13:05:35 -0800293 use std::sync::atomic::{AtomicU32, Ordering};
Tri Voe8f04442022-12-21 08:53:56 -0800294
295 #[derive(Default)]
Tri Vo437d0142023-01-18 16:43:49 -0800296 struct MockRegistration {
297 key: RemotelyProvisionedKey,
298 latency: Option<Duration>,
Tri Voe8f04442022-12-21 08:53:56 -0800299 }
300
Tri Voe8f04442022-12-21 08:53:56 -0800301 impl MockRegistration {
Tri Vo437d0142023-01-18 16:43:49 -0800302 pub fn new_native_binder(
303 key: &RemotelyProvisionedKey,
304 latency: Option<Duration>,
305 ) -> Strong<dyn IRegistration> {
306 let result = Self {
307 key: RemotelyProvisionedKey {
308 keyBlob: key.keyBlob.clone(),
309 encodedCertChain: key.encodedCertChain.clone(),
310 },
311 latency,
312 };
Tri Voe8f04442022-12-21 08:53:56 -0800313 BnRegistration::new_binder(result, BinderFeatures::default())
314 }
315 }
316
317 impl Interface for MockRegistration {}
318
319 impl IRegistration for MockRegistration {
Tri Vo437d0142023-01-18 16:43:49 -0800320 fn getKey(&self, _: i32, cb: &Strong<dyn IGetKeyCallback>) -> binder::Result<()> {
321 let key = RemotelyProvisionedKey {
322 keyBlob: self.key.keyBlob.clone(),
323 encodedCertChain: self.key.encodedCertChain.clone(),
324 };
325 let latency = self.latency;
326 let get_key_cb = cb.clone();
327
328 // Need a separate thread to trigger timeout in the caller.
329 std::thread::spawn(move || {
330 if let Some(duration) = latency {
331 std::thread::sleep(duration);
332 }
333 get_key_cb.onSuccess(&key).unwrap();
334 });
335 Ok(())
Tri Voe8f04442022-12-21 08:53:56 -0800336 }
337
338 fn cancelGetKey(&self, _: &Strong<dyn IGetKeyCallback>) -> binder::Result<()> {
339 todo!()
340 }
341
Seth Moorea55428e2023-01-10 13:07:31 -0800342 fn storeUpgradedKeyAsync(
343 &self,
344 _: &[u8],
345 _: &[u8],
Tri Vo437d0142023-01-18 16:43:49 -0800346 cb: &Strong<dyn IStoreUpgradedKeyCallback>,
Seth Moorea55428e2023-01-10 13:07:31 -0800347 ) -> binder::Result<()> {
Tri Vo437d0142023-01-18 16:43:49 -0800348 // We are primarily concerned with timing out correctly. Storing the key in this mock
349 // registration isn't particularly interesting, so skip that part.
350 let store_cb = cb.clone();
351 let latency = self.latency;
352
353 std::thread::spawn(move || {
354 if let Some(duration) = latency {
355 std::thread::sleep(duration);
356 }
357 store_cb.onSuccess().unwrap();
358 });
359 Ok(())
Tri Voe8f04442022-12-21 08:53:56 -0800360 }
361 }
362
Tri Vo437d0142023-01-18 16:43:49 -0800363 fn get_mock_registration(
364 key: &RemotelyProvisionedKey,
365 latency: Option<Duration>,
366 ) -> Result<binder::Strong<dyn IRegistration>> {
Tri Voe8f04442022-12-21 08:53:56 -0800367 let (tx, rx) = oneshot::channel();
Seth Moore613a1fd2023-01-11 10:42:26 -0800368 let cb = GetRegistrationCallback::new_native_binder(tx);
Tri Vo437d0142023-01-18 16:43:49 -0800369 let mock_registration = MockRegistration::new_native_binder(key, latency);
Tri Voe8f04442022-12-21 08:53:56 -0800370
371 assert!(cb.onSuccess(&mock_registration).is_ok());
Tri Vo437d0142023-01-18 16:43:49 -0800372 tokio_rt().block_on(rx).unwrap()
Tri Voe8f04442022-12-21 08:53:56 -0800373 }
374
Tri Vo4b1cd822023-01-23 13:05:35 -0800375 // Using the same key ID makes test cases race with each other. So, we use separate key IDs for
376 // different test cases.
377 fn get_next_key_id() -> u32 {
378 static ID: AtomicU32 = AtomicU32::new(0);
379 ID.fetch_add(1, Ordering::Relaxed)
380 }
381
Tri Voe8f04442022-12-21 08:53:56 -0800382 #[test]
383 fn test_get_registration_cb_success() {
Tri Vo437d0142023-01-18 16:43:49 -0800384 let key: RemotelyProvisionedKey = Default::default();
385 let registration = get_mock_registration(&key, /*latency=*/ None);
Tri Voe8f04442022-12-21 08:53:56 -0800386 assert!(registration.is_ok());
387 }
388
389 #[test]
390 fn test_get_registration_cb_cancel() {
391 let (tx, rx) = oneshot::channel();
Seth Moore613a1fd2023-01-11 10:42:26 -0800392 let cb = GetRegistrationCallback::new_native_binder(tx);
Tri Voe8f04442022-12-21 08:53:56 -0800393 assert!(cb.onCancel().is_ok());
394
Tri Vo437d0142023-01-18 16:43:49 -0800395 let result = tokio_rt().block_on(rx).unwrap();
Tri Voe8f04442022-12-21 08:53:56 -0800396 assert_eq!(
397 result.unwrap_err().downcast::<Error>().unwrap(),
Tri Vo437d0142023-01-18 16:43:49 -0800398 Error::Rc(ResponseCode::OUT_OF_KEYS)
Tri Voe8f04442022-12-21 08:53:56 -0800399 );
400 }
401
402 #[test]
403 fn test_get_registration_cb_error() {
404 let (tx, rx) = oneshot::channel();
Seth Moore613a1fd2023-01-11 10:42:26 -0800405 let cb = GetRegistrationCallback::new_native_binder(tx);
Tri Voe8f04442022-12-21 08:53:56 -0800406 assert!(cb.onError("error").is_ok());
407
Tri Vo437d0142023-01-18 16:43:49 -0800408 let result = tokio_rt().block_on(rx).unwrap();
Tri Voe8f04442022-12-21 08:53:56 -0800409 assert_eq!(
410 result.unwrap_err().downcast::<Error>().unwrap(),
Tri Vo437d0142023-01-18 16:43:49 -0800411 Error::Rc(ResponseCode::OUT_OF_KEYS)
Tri Voe8f04442022-12-21 08:53:56 -0800412 );
413 }
414
415 #[test]
416 fn test_get_key_cb_success() {
417 let mock_key =
418 RemotelyProvisionedKey { keyBlob: vec![1, 2, 3], encodedCertChain: vec![4, 5, 6] };
419 let (tx, rx) = oneshot::channel();
Seth Moore613a1fd2023-01-11 10:42:26 -0800420 let cb = GetKeyCallback::new_native_binder(tx);
Tri Voe8f04442022-12-21 08:53:56 -0800421 assert!(cb.onSuccess(&mock_key).is_ok());
422
Tri Vo437d0142023-01-18 16:43:49 -0800423 let key = tokio_rt().block_on(rx).unwrap().unwrap();
Tri Voe8f04442022-12-21 08:53:56 -0800424 assert_eq!(key, mock_key);
425 }
426
427 #[test]
428 fn test_get_key_cb_cancel() {
429 let (tx, rx) = oneshot::channel();
Seth Moore613a1fd2023-01-11 10:42:26 -0800430 let cb = GetKeyCallback::new_native_binder(tx);
Tri Voe8f04442022-12-21 08:53:56 -0800431 assert!(cb.onCancel().is_ok());
432
Tri Vo437d0142023-01-18 16:43:49 -0800433 let result = tokio_rt().block_on(rx).unwrap();
Tri Voe8f04442022-12-21 08:53:56 -0800434 assert_eq!(
435 result.unwrap_err().downcast::<Error>().unwrap(),
Tri Vo437d0142023-01-18 16:43:49 -0800436 Error::Rc(ResponseCode::OUT_OF_KEYS)
Tri Voe8f04442022-12-21 08:53:56 -0800437 );
438 }
439
440 #[test]
441 fn test_get_key_cb_error() {
442 let (tx, rx) = oneshot::channel();
Seth Moore613a1fd2023-01-11 10:42:26 -0800443 let cb = GetKeyCallback::new_native_binder(tx);
Tri Voe8f04442022-12-21 08:53:56 -0800444 assert!(cb.onError("error").is_ok());
445
Tri Vo437d0142023-01-18 16:43:49 -0800446 let result = tokio_rt().block_on(rx).unwrap();
Tri Voe8f04442022-12-21 08:53:56 -0800447 assert_eq!(
448 result.unwrap_err().downcast::<Error>().unwrap(),
Tri Vo437d0142023-01-18 16:43:49 -0800449 Error::Rc(ResponseCode::OUT_OF_KEYS)
Tri Voe8f04442022-12-21 08:53:56 -0800450 );
451 }
452
453 #[test]
Seth Moore613a1fd2023-01-11 10:42:26 -0800454 fn test_store_upgraded_cb_success() {
Seth Moorea55428e2023-01-10 13:07:31 -0800455 let (tx, rx) = oneshot::channel();
Seth Moore613a1fd2023-01-11 10:42:26 -0800456 let cb = StoreUpgradedKeyCallback::new_native_binder(tx);
Seth Moorea55428e2023-01-10 13:07:31 -0800457 assert!(cb.onSuccess().is_ok());
458
Tri Vo437d0142023-01-18 16:43:49 -0800459 tokio_rt().block_on(rx).unwrap().unwrap();
Seth Moorea55428e2023-01-10 13:07:31 -0800460 }
461
462 #[test]
463 fn test_store_upgraded_key_cb_error() {
464 let (tx, rx) = oneshot::channel();
Seth Moore613a1fd2023-01-11 10:42:26 -0800465 let cb = StoreUpgradedKeyCallback::new_native_binder(tx);
Seth Moorea55428e2023-01-10 13:07:31 -0800466 assert!(cb.onError("oh no! it failed").is_ok());
467
Tri Vo437d0142023-01-18 16:43:49 -0800468 let result = tokio_rt().block_on(rx).unwrap();
Seth Moorea55428e2023-01-10 13:07:31 -0800469 assert_eq!(
470 result.unwrap_err().downcast::<Error>().unwrap(),
Tri Vo437d0142023-01-18 16:43:49 -0800471 Error::Rc(ResponseCode::SYSTEM_ERROR)
472 );
473 }
474
475 #[test]
476 fn test_get_mock_key_success() {
477 let mock_key =
478 RemotelyProvisionedKey { keyBlob: vec![1, 2, 3], encodedCertChain: vec![4, 5, 6] };
479 let registration = get_mock_registration(&mock_key, /*latency=*/ None).unwrap();
480
481 let key = tokio_rt()
482 .block_on(get_rkpd_attestation_key_from_registration_async(&registration, 0))
483 .unwrap();
484 assert_eq!(key, mock_key);
485 }
486
487 #[test]
488 fn test_get_mock_key_timeout() {
489 let mock_key =
490 RemotelyProvisionedKey { keyBlob: vec![1, 2, 3], encodedCertChain: vec![4, 5, 6] };
491 let latency = RKPD_TIMEOUT + Duration::from_secs(10);
492 let registration = get_mock_registration(&mock_key, Some(latency)).unwrap();
493
494 let result =
495 tokio_rt().block_on(get_rkpd_attestation_key_from_registration_async(&registration, 0));
496 assert_eq!(
497 result.unwrap_err().downcast::<Error>().unwrap(),
498 Error::Rc(ResponseCode::OUT_OF_KEYS)
499 );
500 }
501
502 #[test]
503 fn test_store_mock_key_success() {
504 let mock_key =
505 RemotelyProvisionedKey { keyBlob: vec![1, 2, 3], encodedCertChain: vec![4, 5, 6] };
506 let registration = get_mock_registration(&mock_key, /*latency=*/ None).unwrap();
507 tokio_rt()
508 .block_on(store_rkpd_attestation_key_with_registration_async(&registration, &[], &[]))
509 .unwrap();
510 }
511
512 #[test]
513 fn test_store_mock_key_timeout() {
514 let mock_key =
515 RemotelyProvisionedKey { keyBlob: vec![1, 2, 3], encodedCertChain: vec![4, 5, 6] };
516 let latency = RKPD_TIMEOUT + Duration::from_secs(10);
517 let registration = get_mock_registration(&mock_key, Some(latency)).unwrap();
518
519 let result = tokio_rt().block_on(store_rkpd_attestation_key_with_registration_async(
520 &registration,
521 &[],
522 &[],
523 ));
524 assert_eq!(
525 result.unwrap_err().downcast::<Error>().unwrap(),
526 Error::Rc(ResponseCode::SYSTEM_ERROR)
Seth Moorea55428e2023-01-10 13:07:31 -0800527 );
528 }
529
530 #[test]
Tri Voe8f04442022-12-21 08:53:56 -0800531 fn test_get_rkpd_attestation_key() {
Seth Mooref896d362023-01-11 08:06:17 -0800532 binder::ProcessState::start_thread_pool();
Tri Vo437d0142023-01-18 16:43:49 -0800533 let key_id = get_next_key_id();
534 let key = get_rkpd_attestation_key(&SecurityLevel::TRUSTED_ENVIRONMENT, key_id).unwrap();
Tri Voe8f04442022-12-21 08:53:56 -0800535 assert!(!key.keyBlob.is_empty());
536 assert!(!key.encodedCertChain.is_empty());
537 }
538
539 #[test]
Tri Voe8f04442022-12-21 08:53:56 -0800540 fn test_get_rkpd_attestation_key_same_caller() {
Seth Mooref896d362023-01-11 08:06:17 -0800541 binder::ProcessState::start_thread_pool();
Tri Voe8f04442022-12-21 08:53:56 -0800542 let sec_level = SecurityLevel::TRUSTED_ENVIRONMENT;
Tri Vo4b1cd822023-01-23 13:05:35 -0800543 let key_id = get_next_key_id();
Tri Voe8f04442022-12-21 08:53:56 -0800544
545 // Multiple calls should return the same key.
Tri Vo4b1cd822023-01-23 13:05:35 -0800546 let first_key = get_rkpd_attestation_key(&sec_level, key_id).unwrap();
547 let second_key = get_rkpd_attestation_key(&sec_level, key_id).unwrap();
Tri Voe8f04442022-12-21 08:53:56 -0800548
549 assert_eq!(first_key.keyBlob, second_key.keyBlob);
550 assert_eq!(first_key.encodedCertChain, second_key.encodedCertChain);
551 }
552
553 #[test]
Tri Voe8f04442022-12-21 08:53:56 -0800554 fn test_get_rkpd_attestation_key_different_caller() {
Seth Mooref896d362023-01-11 08:06:17 -0800555 binder::ProcessState::start_thread_pool();
Tri Voe8f04442022-12-21 08:53:56 -0800556 let sec_level = SecurityLevel::TRUSTED_ENVIRONMENT;
Tri Vo4b1cd822023-01-23 13:05:35 -0800557 let first_key_id = get_next_key_id();
558 let second_key_id = get_next_key_id();
Tri Voe8f04442022-12-21 08:53:56 -0800559
560 // Different callers should be getting different keys.
Tri Vo4b1cd822023-01-23 13:05:35 -0800561 let first_key = get_rkpd_attestation_key(&sec_level, first_key_id).unwrap();
562 let second_key = get_rkpd_attestation_key(&sec_level, second_key_id).unwrap();
Tri Voe8f04442022-12-21 08:53:56 -0800563
564 assert_ne!(first_key.keyBlob, second_key.keyBlob);
565 assert_ne!(first_key.encodedCertChain, second_key.encodedCertChain);
566 }
567
568 #[test]
Tri Vobac3b522023-01-23 13:10:24 -0800569 // Couple of things to note:
570 // 1. This test must never run with UID of keystore. Otherwise, it can mess up keys stored by
571 // keystore.
572 // 2. Storing and reading the stored key is prone to race condition. So, we only do this in one
573 // test case.
Tri Voe8f04442022-12-21 08:53:56 -0800574 fn test_store_rkpd_attestation_key() {
Seth Mooref896d362023-01-11 08:06:17 -0800575 binder::ProcessState::start_thread_pool();
Tri Voe8f04442022-12-21 08:53:56 -0800576 let sec_level = SecurityLevel::TRUSTED_ENVIRONMENT;
Tri Vo4b1cd822023-01-23 13:05:35 -0800577 let key_id = get_next_key_id();
578 let key = get_rkpd_attestation_key(&SecurityLevel::TRUSTED_ENVIRONMENT, key_id).unwrap();
Tri Vobac3b522023-01-23 13:10:24 -0800579 let new_blob: [u8; 8] = rand::random();
Tri Voe8f04442022-12-21 08:53:56 -0800580
Tri Vobac3b522023-01-23 13:10:24 -0800581 assert!(store_rkpd_attestation_key(&sec_level, &key.keyBlob, &new_blob).is_ok());
582
583 let new_key =
584 get_rkpd_attestation_key(&SecurityLevel::TRUSTED_ENVIRONMENT, key_id).unwrap();
585 assert_eq!(new_key.keyBlob, new_blob);
Tri Voe8f04442022-12-21 08:53:56 -0800586 }
587}