blob: d8a5276cf1d96417059e37ef2ad7b578105d38aa [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.
16
Tri Voe8f04442022-12-21 08:53:56 -080017use android_security_rkp_aidl::aidl::android::security::rkp::{
Seth Moore484010a2023-01-31 11:22:26 -080018 IGetKeyCallback::BnGetKeyCallback, IGetKeyCallback::ErrorCode::ErrorCode as GetKeyErrorCode,
19 IGetKeyCallback::IGetKeyCallback, IGetRegistrationCallback::BnGetRegistrationCallback,
Tri Voe8f04442022-12-21 08:53:56 -080020 IGetRegistrationCallback::IGetRegistrationCallback, IRegistration::IRegistration,
Seth Moorea55428e2023-01-10 13:07:31 -080021 IRemoteProvisioning::IRemoteProvisioning,
22 IStoreUpgradedKeyCallback::BnStoreUpgradedKeyCallback,
23 IStoreUpgradedKeyCallback::IStoreUpgradedKeyCallback,
24 RemotelyProvisionedKey::RemotelyProvisionedKey,
Tri Voe8f04442022-12-21 08:53:56 -080025};
Tri Voe8f04442022-12-21 08:53:56 -080026use anyhow::{Context, Result};
Alice Wang849cfe42023-11-10 12:43:36 +000027use binder::{BinderFeatures, Interface, StatusCode, Strong};
Alice Wange66c3312023-11-07 12:41:42 +000028use message_macro::source_location_msg;
Tri Voe8f04442022-12-21 08:53:56 -080029use std::sync::Mutex;
Tri Vo437d0142023-01-18 16:43:49 -080030use std::time::Duration;
31use tokio::sync::oneshot;
32use tokio::time::timeout;
33
34// Normally, we block indefinitely when making calls outside of keystore and rely on watchdog to
35// report deadlocks. However, RKPD is mainline updatable. Also, calls to RKPD may wait on network
36// for certificates. So, we err on the side of caution and timeout instead.
37static RKPD_TIMEOUT: Duration = Duration::from_secs(10);
38
39fn tokio_rt() -> tokio::runtime::Runtime {
40 tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap()
41}
Tri Voe8f04442022-12-21 08:53:56 -080042
Alice Wang849cfe42023-11-10 12:43:36 +000043/// Errors occurred during the interaction with RKPD.
44#[derive(Debug, Clone, Copy, thiserror::Error, PartialEq, Eq)]
45pub enum Error {
46 /// An RKPD request gets cancelled.
47 #[error("An RKPD request gets cancelled")]
48 RequestCancelled,
49
50 /// Failed to get registration.
51 #[error("Failed to get registration")]
52 GetRegistrationFailed,
53
54 /// Failed to get key.
55 #[error("Failed to get key: {0:?}")]
56 GetKeyFailed(GetKeyErrorCode),
57
58 /// Failed to store upgraded key.
59 #[error("Failed to store upgraded key")]
60 StoreUpgradedKeyFailed,
61
62 /// Retryable timeout when waiting for a callback.
63 #[error("Retryable timeout when waiting for a callback")]
64 RetryableTimeout,
65
66 /// Timeout when waiting for a callback.
67 #[error("Timeout when waiting for a callback")]
68 Timeout,
69
70 /// Wraps a Binder status code.
71 #[error("Binder transaction error {0:?}")]
72 BinderTransaction(StatusCode),
73}
74
75impl From<StatusCode> for Error {
76 fn from(s: StatusCode) -> Self {
77 Self::BinderTransaction(s)
78 }
79}
80
Seth Moorea882c962023-01-09 16:55:10 -080081/// Thread-safe channel for sending a value once and only once. If a value has
82/// already been send, subsequent calls to send will noop.
83struct SafeSender<T> {
84 inner: Mutex<Option<oneshot::Sender<T>>>,
85}
86
87impl<T> SafeSender<T> {
88 fn new(sender: oneshot::Sender<T>) -> Self {
89 Self { inner: Mutex::new(Some(sender)) }
90 }
91
92 fn send(&self, value: T) {
93 if let Some(inner) = self.inner.lock().unwrap().take() {
Tri Vo0e5fe2c2023-02-15 17:02:06 -080094 // It's possible for the corresponding receiver to time out and be dropped. In this
95 // case send() will fail. This error is not actionable though, so only log the error.
96 if inner.send(value).is_err() {
97 log::error!("SafeSender::send() failed");
98 }
Seth Moorea882c962023-01-09 16:55:10 -080099 }
100 }
101}
Tri Voe8f04442022-12-21 08:53:56 -0800102
103struct GetRegistrationCallback {
Seth Moorea882c962023-01-09 16:55:10 -0800104 registration_tx: SafeSender<Result<binder::Strong<dyn IRegistration>>>,
Tri Voe8f04442022-12-21 08:53:56 -0800105}
106
107impl GetRegistrationCallback {
108 pub fn new_native_binder(
Seth Moorea882c962023-01-09 16:55:10 -0800109 registration_tx: oneshot::Sender<Result<binder::Strong<dyn IRegistration>>>,
Seth Moore613a1fd2023-01-11 10:42:26 -0800110 ) -> Strong<dyn IGetRegistrationCallback> {
Tri Voe8f04442022-12-21 08:53:56 -0800111 let result: Self =
Seth Moorea882c962023-01-09 16:55:10 -0800112 GetRegistrationCallback { registration_tx: SafeSender::new(registration_tx) };
Seth Moore613a1fd2023-01-11 10:42:26 -0800113 BnGetRegistrationCallback::new_binder(result, BinderFeatures::default())
Tri Voe8f04442022-12-21 08:53:56 -0800114 }
115}
116
117impl Interface for GetRegistrationCallback {}
118
119impl IGetRegistrationCallback for GetRegistrationCallback {
120 fn onSuccess(&self, registration: &Strong<dyn IRegistration>) -> binder::Result<()> {
Seth Moore613a1fd2023-01-11 10:42:26 -0800121 self.registration_tx.send(Ok(registration.clone()));
122 Ok(())
Tri Voe8f04442022-12-21 08:53:56 -0800123 }
124 fn onCancel(&self) -> binder::Result<()> {
Seth Moore613a1fd2023-01-11 10:42:26 -0800125 log::warn!("IGetRegistrationCallback cancelled");
126 self.registration_tx.send(
Alice Wang849cfe42023-11-10 12:43:36 +0000127 Err(Error::RequestCancelled)
Alice Wange66c3312023-11-07 12:41:42 +0000128 .context(source_location_msg!("GetRegistrationCallback cancelled.")),
Seth Moore613a1fd2023-01-11 10:42:26 -0800129 );
130 Ok(())
Tri Voe8f04442022-12-21 08:53:56 -0800131 }
Seth Moore484010a2023-01-31 11:22:26 -0800132 fn onError(&self, description: &str) -> binder::Result<()> {
Seth Moore484010a2023-01-31 11:22:26 -0800133 log::error!("IGetRegistrationCallback failed: '{description}'");
Alice Wang849cfe42023-11-10 12:43:36 +0000134 self.registration_tx.send(
135 Err(Error::GetRegistrationFailed)
136 .context(source_location_msg!("GetRegistrationCallback failed: {:?}", description)),
137 );
Seth Moore613a1fd2023-01-11 10:42:26 -0800138 Ok(())
Tri Voe8f04442022-12-21 08:53:56 -0800139 }
140}
141
142/// Make a new connection to a IRegistration service.
Alice Wangbf6a6932023-11-07 11:47:12 +0000143async fn get_rkpd_registration(rpc_name: &str) -> Result<binder::Strong<dyn IRegistration>> {
Tri Voe8f04442022-12-21 08:53:56 -0800144 let remote_provisioning: Strong<dyn IRemoteProvisioning> =
Alice Wang849cfe42023-11-10 12:43:36 +0000145 binder::get_interface("remote_provisioning")
146 .map_err(Error::from)
Alice Wange66c3312023-11-07 12:41:42 +0000147 .context(source_location_msg!("Trying to connect to IRemoteProvisioning service."))?;
Tri Voe8f04442022-12-21 08:53:56 -0800148
Tri Voe8f04442022-12-21 08:53:56 -0800149 let (tx, rx) = oneshot::channel();
Seth Moore613a1fd2023-01-11 10:42:26 -0800150 let cb = GetRegistrationCallback::new_native_binder(tx);
Tri Voe8f04442022-12-21 08:53:56 -0800151
152 remote_provisioning
Alice Wangbf6a6932023-11-07 11:47:12 +0000153 .getRegistration(rpc_name, &cb)
Alice Wange66c3312023-11-07 12:41:42 +0000154 .context(source_location_msg!("Trying to get registration."))?;
Tri Voe8f04442022-12-21 08:53:56 -0800155
Tri Vo437d0142023-01-18 16:43:49 -0800156 match timeout(RKPD_TIMEOUT, rx).await {
Alice Wang849cfe42023-11-10 12:43:36 +0000157 Err(e) => Err(Error::Timeout).context(source_location_msg!("Waiting for RKPD: {:?}", e)),
Tri Vo437d0142023-01-18 16:43:49 -0800158 Ok(v) => v.unwrap(),
159 }
Tri Voe8f04442022-12-21 08:53:56 -0800160}
161
Tri Voe8f04442022-12-21 08:53:56 -0800162struct GetKeyCallback {
Seth Moorea882c962023-01-09 16:55:10 -0800163 key_tx: SafeSender<Result<RemotelyProvisionedKey>>,
Tri Voe8f04442022-12-21 08:53:56 -0800164}
165
166impl GetKeyCallback {
Seth Moorea882c962023-01-09 16:55:10 -0800167 pub fn new_native_binder(
168 key_tx: oneshot::Sender<Result<RemotelyProvisionedKey>>,
Seth Moore613a1fd2023-01-11 10:42:26 -0800169 ) -> Strong<dyn IGetKeyCallback> {
Seth Moorea882c962023-01-09 16:55:10 -0800170 let result: Self = GetKeyCallback { key_tx: SafeSender::new(key_tx) };
Seth Moore613a1fd2023-01-11 10:42:26 -0800171 BnGetKeyCallback::new_binder(result, BinderFeatures::default())
Tri Voe8f04442022-12-21 08:53:56 -0800172 }
173}
174
175impl Interface for GetKeyCallback {}
176
177impl IGetKeyCallback for GetKeyCallback {
178 fn onSuccess(&self, key: &RemotelyProvisionedKey) -> binder::Result<()> {
Seth Moore613a1fd2023-01-11 10:42:26 -0800179 self.key_tx.send(Ok(RemotelyProvisionedKey {
180 keyBlob: key.keyBlob.clone(),
181 encodedCertChain: key.encodedCertChain.clone(),
182 }));
183 Ok(())
Tri Voe8f04442022-12-21 08:53:56 -0800184 }
185 fn onCancel(&self) -> binder::Result<()> {
Seth Moore613a1fd2023-01-11 10:42:26 -0800186 log::warn!("IGetKeyCallback cancelled");
187 self.key_tx.send(
Alice Wang849cfe42023-11-10 12:43:36 +0000188 Err(Error::RequestCancelled).context(source_location_msg!("GetKeyCallback cancelled.")),
Seth Moore613a1fd2023-01-11 10:42:26 -0800189 );
190 Ok(())
Tri Voe8f04442022-12-21 08:53:56 -0800191 }
Seth Moore484010a2023-01-31 11:22:26 -0800192 fn onError(&self, error: GetKeyErrorCode, description: &str) -> binder::Result<()> {
Seth Moore484010a2023-01-31 11:22:26 -0800193 log::error!("IGetKeyCallback failed: {description}");
Alice Wang849cfe42023-11-10 12:43:36 +0000194 self.key_tx.send(Err(Error::GetKeyFailed(error)).context(source_location_msg!(
Seth Moore484010a2023-01-31 11:22:26 -0800195 "GetKeyCallback failed: {:?} {:?}",
196 error,
197 description
198 )));
Seth Moore613a1fd2023-01-11 10:42:26 -0800199 Ok(())
Tri Voe8f04442022-12-21 08:53:56 -0800200 }
201}
202
Tri Vo437d0142023-01-18 16:43:49 -0800203async fn get_rkpd_attestation_key_from_registration_async(
204 registration: &Strong<dyn IRegistration>,
205 caller_uid: u32,
206) -> Result<RemotelyProvisionedKey> {
207 let (tx, rx) = oneshot::channel();
208 let cb = GetKeyCallback::new_native_binder(tx);
209
210 registration
211 .getKey(caller_uid.try_into().unwrap(), &cb)
Alice Wange66c3312023-11-07 12:41:42 +0000212 .context(source_location_msg!("Trying to get key."))?;
Tri Vo437d0142023-01-18 16:43:49 -0800213
214 match timeout(RKPD_TIMEOUT, rx).await {
Tri Vo0e5fe2c2023-02-15 17:02:06 -0800215 Err(e) => {
216 // Make a best effort attempt to cancel the timed out request.
217 if let Err(e) = registration.cancelGetKey(&cb) {
218 log::error!("IRegistration::cancelGetKey failed: {:?}", e);
219 }
Alice Wang849cfe42023-11-10 12:43:36 +0000220 Err(Error::RetryableTimeout)
Alice Wange66c3312023-11-07 12:41:42 +0000221 .context(source_location_msg!("Waiting for RKPD key timed out: {:?}", e))
Tri Vo0e5fe2c2023-02-15 17:02:06 -0800222 }
Tri Vo437d0142023-01-18 16:43:49 -0800223 Ok(v) => v.unwrap(),
224 }
225}
226
Tri Voe8f04442022-12-21 08:53:56 -0800227async fn get_rkpd_attestation_key_async(
Alice Wangbf6a6932023-11-07 11:47:12 +0000228 rpc_name: &str,
Tri Voe8f04442022-12-21 08:53:56 -0800229 caller_uid: u32,
230) -> Result<RemotelyProvisionedKey> {
Alice Wangbf6a6932023-11-07 11:47:12 +0000231 let registration = get_rkpd_registration(rpc_name)
Tri Voe8f04442022-12-21 08:53:56 -0800232 .await
Alice Wange66c3312023-11-07 12:41:42 +0000233 .context(source_location_msg!("Trying to get to IRegistration service."))?;
Tri Vo437d0142023-01-18 16:43:49 -0800234 get_rkpd_attestation_key_from_registration_async(&registration, caller_uid).await
Tri Voe8f04442022-12-21 08:53:56 -0800235}
236
Seth Moorea55428e2023-01-10 13:07:31 -0800237struct StoreUpgradedKeyCallback {
238 completer: SafeSender<Result<()>>,
239}
240
241impl StoreUpgradedKeyCallback {
242 pub fn new_native_binder(
243 completer: oneshot::Sender<Result<()>>,
Seth Moore613a1fd2023-01-11 10:42:26 -0800244 ) -> Strong<dyn IStoreUpgradedKeyCallback> {
Seth Moorea55428e2023-01-10 13:07:31 -0800245 let result: Self = StoreUpgradedKeyCallback { completer: SafeSender::new(completer) };
Seth Moore613a1fd2023-01-11 10:42:26 -0800246 BnStoreUpgradedKeyCallback::new_binder(result, BinderFeatures::default())
Seth Moorea55428e2023-01-10 13:07:31 -0800247 }
248}
249
250impl Interface for StoreUpgradedKeyCallback {}
251
252impl IStoreUpgradedKeyCallback for StoreUpgradedKeyCallback {
253 fn onSuccess(&self) -> binder::Result<()> {
Seth Moore613a1fd2023-01-11 10:42:26 -0800254 self.completer.send(Ok(()));
255 Ok(())
Seth Moorea55428e2023-01-10 13:07:31 -0800256 }
257
258 fn onError(&self, error: &str) -> binder::Result<()> {
Alice Wang849cfe42023-11-10 12:43:36 +0000259 log::error!("IStoreUpgradedKeyCallback failed: {error}");
Seth Moore613a1fd2023-01-11 10:42:26 -0800260 self.completer.send(
Alice Wang849cfe42023-11-10 12:43:36 +0000261 Err(Error::StoreUpgradedKeyFailed)
Alice Wange66c3312023-11-07 12:41:42 +0000262 .context(source_location_msg!("Failed to store upgraded key: {:?}", error)),
Seth Moore613a1fd2023-01-11 10:42:26 -0800263 );
264 Ok(())
Seth Moorea55428e2023-01-10 13:07:31 -0800265 }
266}
267
Tri Vo437d0142023-01-18 16:43:49 -0800268async fn store_rkpd_attestation_key_with_registration_async(
269 registration: &Strong<dyn IRegistration>,
270 key_blob: &[u8],
271 upgraded_blob: &[u8],
272) -> Result<()> {
273 let (tx, rx) = oneshot::channel();
274 let cb = StoreUpgradedKeyCallback::new_native_binder(tx);
275
276 registration
277 .storeUpgradedKeyAsync(key_blob, upgraded_blob, &cb)
Alice Wange66c3312023-11-07 12:41:42 +0000278 .context(source_location_msg!("Failed to store upgraded blob with RKPD."))?;
Tri Vo437d0142023-01-18 16:43:49 -0800279
280 match timeout(RKPD_TIMEOUT, rx).await {
Alice Wang849cfe42023-11-10 12:43:36 +0000281 Err(e) => Err(Error::Timeout)
Alice Wange66c3312023-11-07 12:41:42 +0000282 .context(source_location_msg!("Waiting for RKPD to complete storing key: {:?}", e)),
Tri Vo437d0142023-01-18 16:43:49 -0800283 Ok(v) => v.unwrap(),
284 }
285}
286
Tri Voe8f04442022-12-21 08:53:56 -0800287async fn store_rkpd_attestation_key_async(
Alice Wangbf6a6932023-11-07 11:47:12 +0000288 rpc_name: &str,
Tri Voe8f04442022-12-21 08:53:56 -0800289 key_blob: &[u8],
290 upgraded_blob: &[u8],
291) -> Result<()> {
Alice Wangbf6a6932023-11-07 11:47:12 +0000292 let registration = get_rkpd_registration(rpc_name)
Tri Voe8f04442022-12-21 08:53:56 -0800293 .await
Alice Wange66c3312023-11-07 12:41:42 +0000294 .context(source_location_msg!("Trying to get to IRegistration service."))?;
Tri Vo437d0142023-01-18 16:43:49 -0800295 store_rkpd_attestation_key_with_registration_async(&registration, key_blob, upgraded_blob).await
Tri Voe8f04442022-12-21 08:53:56 -0800296}
297
298/// Get attestation key from RKPD.
Alice Wangbf6a6932023-11-07 11:47:12 +0000299pub fn get_rkpd_attestation_key(rpc_name: &str, caller_uid: u32) -> Result<RemotelyProvisionedKey> {
Alice Wangbf6a6932023-11-07 11:47:12 +0000300 tokio_rt().block_on(get_rkpd_attestation_key_async(rpc_name, caller_uid))
Tri Voe8f04442022-12-21 08:53:56 -0800301}
302
303/// Store attestation key in RKPD.
304pub fn store_rkpd_attestation_key(
Alice Wangbf6a6932023-11-07 11:47:12 +0000305 rpc_name: &str,
Tri Voe8f04442022-12-21 08:53:56 -0800306 key_blob: &[u8],
307 upgraded_blob: &[u8],
308) -> Result<()> {
Alice Wangbf6a6932023-11-07 11:47:12 +0000309 tokio_rt().block_on(store_rkpd_attestation_key_async(rpc_name, key_blob, upgraded_blob))
Tri Voe8f04442022-12-21 08:53:56 -0800310}
311
312#[cfg(test)]
313mod tests {
314 use super::*;
315 use android_security_rkp_aidl::aidl::android::security::rkp::IRegistration::BnRegistration;
Tri Vo4b1cd822023-01-23 13:05:35 -0800316 use std::sync::atomic::{AtomicU32, Ordering};
Tri Vo215f12e2023-02-15 16:23:39 -0800317 use std::sync::{Arc, Mutex};
Tri Voe8f04442022-12-21 08:53:56 -0800318
Alice Wangbf6a6932023-11-07 11:47:12 +0000319 const DEFAULT_RPC_SERVICE_NAME: &str =
320 "android.hardware.security.keymint.IRemotelyProvisionedComponent/default";
321
Tri Vo215f12e2023-02-15 16:23:39 -0800322 struct MockRegistrationValues {
Tri Vo437d0142023-01-18 16:43:49 -0800323 key: RemotelyProvisionedKey,
324 latency: Option<Duration>,
Tri Vo215f12e2023-02-15 16:23:39 -0800325 thread_join_handles: Vec<Option<std::thread::JoinHandle<()>>>,
Tri Voe8f04442022-12-21 08:53:56 -0800326 }
327
Tri Vo215f12e2023-02-15 16:23:39 -0800328 struct MockRegistration(Arc<Mutex<MockRegistrationValues>>);
329
Tri Voe8f04442022-12-21 08:53:56 -0800330 impl MockRegistration {
Tri Vo437d0142023-01-18 16:43:49 -0800331 pub fn new_native_binder(
332 key: &RemotelyProvisionedKey,
333 latency: Option<Duration>,
334 ) -> Strong<dyn IRegistration> {
Tri Vo215f12e2023-02-15 16:23:39 -0800335 let result = Self(Arc::new(Mutex::new(MockRegistrationValues {
Tri Vo437d0142023-01-18 16:43:49 -0800336 key: RemotelyProvisionedKey {
337 keyBlob: key.keyBlob.clone(),
338 encodedCertChain: key.encodedCertChain.clone(),
339 },
340 latency,
Tri Vo215f12e2023-02-15 16:23:39 -0800341 thread_join_handles: Vec::new(),
342 })));
Tri Voe8f04442022-12-21 08:53:56 -0800343 BnRegistration::new_binder(result, BinderFeatures::default())
344 }
345 }
346
Tri Vo215f12e2023-02-15 16:23:39 -0800347 impl Drop for MockRegistration {
348 fn drop(&mut self) {
349 let mut values = self.0.lock().unwrap();
350 for handle in values.thread_join_handles.iter_mut() {
351 // These are test threads. So, no need to worry too much about error handling.
352 handle.take().unwrap().join().unwrap();
353 }
354 }
355 }
356
Tri Voe8f04442022-12-21 08:53:56 -0800357 impl Interface for MockRegistration {}
358
359 impl IRegistration for MockRegistration {
Tri Vo437d0142023-01-18 16:43:49 -0800360 fn getKey(&self, _: i32, cb: &Strong<dyn IGetKeyCallback>) -> binder::Result<()> {
Tri Vo215f12e2023-02-15 16:23:39 -0800361 let mut values = self.0.lock().unwrap();
Tri Vo437d0142023-01-18 16:43:49 -0800362 let key = RemotelyProvisionedKey {
Tri Vo215f12e2023-02-15 16:23:39 -0800363 keyBlob: values.key.keyBlob.clone(),
364 encodedCertChain: values.key.encodedCertChain.clone(),
Tri Vo437d0142023-01-18 16:43:49 -0800365 };
Tri Vo215f12e2023-02-15 16:23:39 -0800366 let latency = values.latency;
Tri Vo437d0142023-01-18 16:43:49 -0800367 let get_key_cb = cb.clone();
368
369 // Need a separate thread to trigger timeout in the caller.
Tri Vo215f12e2023-02-15 16:23:39 -0800370 let join_handle = std::thread::spawn(move || {
Tri Vo437d0142023-01-18 16:43:49 -0800371 if let Some(duration) = latency {
372 std::thread::sleep(duration);
373 }
374 get_key_cb.onSuccess(&key).unwrap();
375 });
Tri Vo215f12e2023-02-15 16:23:39 -0800376 values.thread_join_handles.push(Some(join_handle));
Tri Vo437d0142023-01-18 16:43:49 -0800377 Ok(())
Tri Voe8f04442022-12-21 08:53:56 -0800378 }
379
380 fn cancelGetKey(&self, _: &Strong<dyn IGetKeyCallback>) -> binder::Result<()> {
Tri Vo0e5fe2c2023-02-15 17:02:06 -0800381 Ok(())
Tri Voe8f04442022-12-21 08:53:56 -0800382 }
383
Seth Moorea55428e2023-01-10 13:07:31 -0800384 fn storeUpgradedKeyAsync(
385 &self,
386 _: &[u8],
387 _: &[u8],
Tri Vo437d0142023-01-18 16:43:49 -0800388 cb: &Strong<dyn IStoreUpgradedKeyCallback>,
Seth Moorea55428e2023-01-10 13:07:31 -0800389 ) -> binder::Result<()> {
Tri Vo437d0142023-01-18 16:43:49 -0800390 // We are primarily concerned with timing out correctly. Storing the key in this mock
391 // registration isn't particularly interesting, so skip that part.
Tri Vo215f12e2023-02-15 16:23:39 -0800392 let values = self.0.lock().unwrap();
Tri Vo437d0142023-01-18 16:43:49 -0800393 let store_cb = cb.clone();
Tri Vo215f12e2023-02-15 16:23:39 -0800394 let latency = values.latency;
Tri Vo437d0142023-01-18 16:43:49 -0800395
396 std::thread::spawn(move || {
397 if let Some(duration) = latency {
398 std::thread::sleep(duration);
399 }
400 store_cb.onSuccess().unwrap();
401 });
402 Ok(())
Tri Voe8f04442022-12-21 08:53:56 -0800403 }
404 }
405
Tri Vo437d0142023-01-18 16:43:49 -0800406 fn get_mock_registration(
407 key: &RemotelyProvisionedKey,
408 latency: Option<Duration>,
409 ) -> Result<binder::Strong<dyn IRegistration>> {
Tri Voe8f04442022-12-21 08:53:56 -0800410 let (tx, rx) = oneshot::channel();
Seth Moore613a1fd2023-01-11 10:42:26 -0800411 let cb = GetRegistrationCallback::new_native_binder(tx);
Tri Vo437d0142023-01-18 16:43:49 -0800412 let mock_registration = MockRegistration::new_native_binder(key, latency);
Tri Voe8f04442022-12-21 08:53:56 -0800413
414 assert!(cb.onSuccess(&mock_registration).is_ok());
Tri Vo437d0142023-01-18 16:43:49 -0800415 tokio_rt().block_on(rx).unwrap()
Tri Voe8f04442022-12-21 08:53:56 -0800416 }
417
Tri Vo4b1cd822023-01-23 13:05:35 -0800418 // Using the same key ID makes test cases race with each other. So, we use separate key IDs for
419 // different test cases.
420 fn get_next_key_id() -> u32 {
421 static ID: AtomicU32 = AtomicU32::new(0);
422 ID.fetch_add(1, Ordering::Relaxed)
423 }
424
Tri Voe8f04442022-12-21 08:53:56 -0800425 #[test]
426 fn test_get_registration_cb_success() {
Tri Vo437d0142023-01-18 16:43:49 -0800427 let key: RemotelyProvisionedKey = Default::default();
428 let registration = get_mock_registration(&key, /*latency=*/ None);
Tri Voe8f04442022-12-21 08:53:56 -0800429 assert!(registration.is_ok());
430 }
431
432 #[test]
433 fn test_get_registration_cb_cancel() {
434 let (tx, rx) = oneshot::channel();
Seth Moore613a1fd2023-01-11 10:42:26 -0800435 let cb = GetRegistrationCallback::new_native_binder(tx);
Tri Voe8f04442022-12-21 08:53:56 -0800436 assert!(cb.onCancel().is_ok());
437
Tri Vo437d0142023-01-18 16:43:49 -0800438 let result = tokio_rt().block_on(rx).unwrap();
Alice Wang849cfe42023-11-10 12:43:36 +0000439 assert_eq!(result.unwrap_err().downcast::<Error>().unwrap(), Error::RequestCancelled);
Tri Voe8f04442022-12-21 08:53:56 -0800440 }
441
442 #[test]
443 fn test_get_registration_cb_error() {
444 let (tx, rx) = oneshot::channel();
Seth Moore613a1fd2023-01-11 10:42:26 -0800445 let cb = GetRegistrationCallback::new_native_binder(tx);
Tri Voe8f04442022-12-21 08:53:56 -0800446 assert!(cb.onError("error").is_ok());
447
Tri Vo437d0142023-01-18 16:43:49 -0800448 let result = tokio_rt().block_on(rx).unwrap();
Alice Wang849cfe42023-11-10 12:43:36 +0000449 assert_eq!(result.unwrap_err().downcast::<Error>().unwrap(), Error::GetRegistrationFailed);
Tri Voe8f04442022-12-21 08:53:56 -0800450 }
451
452 #[test]
453 fn test_get_key_cb_success() {
454 let mock_key =
455 RemotelyProvisionedKey { keyBlob: vec![1, 2, 3], encodedCertChain: vec![4, 5, 6] };
456 let (tx, rx) = oneshot::channel();
Seth Moore613a1fd2023-01-11 10:42:26 -0800457 let cb = GetKeyCallback::new_native_binder(tx);
Tri Voe8f04442022-12-21 08:53:56 -0800458 assert!(cb.onSuccess(&mock_key).is_ok());
459
Tri Vo437d0142023-01-18 16:43:49 -0800460 let key = tokio_rt().block_on(rx).unwrap().unwrap();
Tri Voe8f04442022-12-21 08:53:56 -0800461 assert_eq!(key, mock_key);
462 }
463
464 #[test]
465 fn test_get_key_cb_cancel() {
466 let (tx, rx) = oneshot::channel();
Seth Moore613a1fd2023-01-11 10:42:26 -0800467 let cb = GetKeyCallback::new_native_binder(tx);
Tri Voe8f04442022-12-21 08:53:56 -0800468 assert!(cb.onCancel().is_ok());
469
Tri Vo437d0142023-01-18 16:43:49 -0800470 let result = tokio_rt().block_on(rx).unwrap();
Alice Wang849cfe42023-11-10 12:43:36 +0000471 assert_eq!(result.unwrap_err().downcast::<Error>().unwrap(), Error::RequestCancelled);
Tri Voe8f04442022-12-21 08:53:56 -0800472 }
473
474 #[test]
475 fn test_get_key_cb_error() {
Seth Moore484010a2023-01-31 11:22:26 -0800476 for get_key_error in GetKeyErrorCode::enum_values() {
477 let (tx, rx) = oneshot::channel();
478 let cb = GetKeyCallback::new_native_binder(tx);
479 assert!(cb.onError(get_key_error, "error").is_ok());
480
481 let result = tokio_rt().block_on(rx).unwrap();
482 assert_eq!(
483 result.unwrap_err().downcast::<Error>().unwrap(),
Alice Wang849cfe42023-11-10 12:43:36 +0000484 Error::GetKeyFailed(get_key_error),
Seth Moore484010a2023-01-31 11:22:26 -0800485 );
486 }
Tri Voe8f04442022-12-21 08:53:56 -0800487 }
488
489 #[test]
Seth Moore613a1fd2023-01-11 10:42:26 -0800490 fn test_store_upgraded_cb_success() {
Seth Moorea55428e2023-01-10 13:07:31 -0800491 let (tx, rx) = oneshot::channel();
Seth Moore613a1fd2023-01-11 10:42:26 -0800492 let cb = StoreUpgradedKeyCallback::new_native_binder(tx);
Seth Moorea55428e2023-01-10 13:07:31 -0800493 assert!(cb.onSuccess().is_ok());
494
Tri Vo437d0142023-01-18 16:43:49 -0800495 tokio_rt().block_on(rx).unwrap().unwrap();
Seth Moorea55428e2023-01-10 13:07:31 -0800496 }
497
498 #[test]
499 fn test_store_upgraded_key_cb_error() {
500 let (tx, rx) = oneshot::channel();
Seth Moore613a1fd2023-01-11 10:42:26 -0800501 let cb = StoreUpgradedKeyCallback::new_native_binder(tx);
Seth Moorea55428e2023-01-10 13:07:31 -0800502 assert!(cb.onError("oh no! it failed").is_ok());
503
Tri Vo437d0142023-01-18 16:43:49 -0800504 let result = tokio_rt().block_on(rx).unwrap();
Alice Wang849cfe42023-11-10 12:43:36 +0000505 assert_eq!(result.unwrap_err().downcast::<Error>().unwrap(), Error::StoreUpgradedKeyFailed);
Tri Vo437d0142023-01-18 16:43:49 -0800506 }
507
508 #[test]
509 fn test_get_mock_key_success() {
510 let mock_key =
511 RemotelyProvisionedKey { keyBlob: vec![1, 2, 3], encodedCertChain: vec![4, 5, 6] };
512 let registration = get_mock_registration(&mock_key, /*latency=*/ None).unwrap();
513
514 let key = tokio_rt()
515 .block_on(get_rkpd_attestation_key_from_registration_async(&registration, 0))
516 .unwrap();
517 assert_eq!(key, mock_key);
518 }
519
520 #[test]
521 fn test_get_mock_key_timeout() {
522 let mock_key =
523 RemotelyProvisionedKey { keyBlob: vec![1, 2, 3], encodedCertChain: vec![4, 5, 6] };
Tri Vo215f12e2023-02-15 16:23:39 -0800524 let latency = RKPD_TIMEOUT + Duration::from_secs(1);
Tri Vo437d0142023-01-18 16:43:49 -0800525 let registration = get_mock_registration(&mock_key, Some(latency)).unwrap();
526
527 let result =
528 tokio_rt().block_on(get_rkpd_attestation_key_from_registration_async(&registration, 0));
Alice Wang849cfe42023-11-10 12:43:36 +0000529 assert_eq!(result.unwrap_err().downcast::<Error>().unwrap(), Error::RetryableTimeout);
Tri Vo437d0142023-01-18 16:43:49 -0800530 }
531
532 #[test]
533 fn test_store_mock_key_success() {
534 let mock_key =
535 RemotelyProvisionedKey { keyBlob: vec![1, 2, 3], encodedCertChain: vec![4, 5, 6] };
536 let registration = get_mock_registration(&mock_key, /*latency=*/ None).unwrap();
537 tokio_rt()
538 .block_on(store_rkpd_attestation_key_with_registration_async(&registration, &[], &[]))
539 .unwrap();
540 }
541
542 #[test]
543 fn test_store_mock_key_timeout() {
544 let mock_key =
545 RemotelyProvisionedKey { keyBlob: vec![1, 2, 3], encodedCertChain: vec![4, 5, 6] };
Tri Vo215f12e2023-02-15 16:23:39 -0800546 let latency = RKPD_TIMEOUT + Duration::from_secs(1);
Tri Vo437d0142023-01-18 16:43:49 -0800547 let registration = get_mock_registration(&mock_key, Some(latency)).unwrap();
548
549 let result = tokio_rt().block_on(store_rkpd_attestation_key_with_registration_async(
550 &registration,
551 &[],
552 &[],
553 ));
Alice Wang849cfe42023-11-10 12:43:36 +0000554 assert_eq!(result.unwrap_err().downcast::<Error>().unwrap(), Error::Timeout);
Seth Moorea55428e2023-01-10 13:07:31 -0800555 }
556
557 #[test]
Tri Voe8f04442022-12-21 08:53:56 -0800558 fn test_get_rkpd_attestation_key() {
Seth Mooref896d362023-01-11 08:06:17 -0800559 binder::ProcessState::start_thread_pool();
Tri Vo437d0142023-01-18 16:43:49 -0800560 let key_id = get_next_key_id();
Alice Wangbf6a6932023-11-07 11:47:12 +0000561 let key = get_rkpd_attestation_key(DEFAULT_RPC_SERVICE_NAME, key_id).unwrap();
Tri Voe8f04442022-12-21 08:53:56 -0800562 assert!(!key.keyBlob.is_empty());
563 assert!(!key.encodedCertChain.is_empty());
564 }
565
566 #[test]
Tri Voe8f04442022-12-21 08:53:56 -0800567 fn test_get_rkpd_attestation_key_same_caller() {
Seth Mooref896d362023-01-11 08:06:17 -0800568 binder::ProcessState::start_thread_pool();
Tri Vo4b1cd822023-01-23 13:05:35 -0800569 let key_id = get_next_key_id();
Tri Voe8f04442022-12-21 08:53:56 -0800570
571 // Multiple calls should return the same key.
Alice Wangbf6a6932023-11-07 11:47:12 +0000572 let first_key = get_rkpd_attestation_key(DEFAULT_RPC_SERVICE_NAME, key_id).unwrap();
573 let second_key = get_rkpd_attestation_key(DEFAULT_RPC_SERVICE_NAME, key_id).unwrap();
Tri Voe8f04442022-12-21 08:53:56 -0800574
575 assert_eq!(first_key.keyBlob, second_key.keyBlob);
576 assert_eq!(first_key.encodedCertChain, second_key.encodedCertChain);
577 }
578
579 #[test]
Tri Voe8f04442022-12-21 08:53:56 -0800580 fn test_get_rkpd_attestation_key_different_caller() {
Seth Mooref896d362023-01-11 08:06:17 -0800581 binder::ProcessState::start_thread_pool();
Tri Vo4b1cd822023-01-23 13:05:35 -0800582 let first_key_id = get_next_key_id();
583 let second_key_id = get_next_key_id();
Tri Voe8f04442022-12-21 08:53:56 -0800584
585 // Different callers should be getting different keys.
Alice Wangbf6a6932023-11-07 11:47:12 +0000586 let first_key = get_rkpd_attestation_key(DEFAULT_RPC_SERVICE_NAME, first_key_id).unwrap();
587 let second_key = get_rkpd_attestation_key(DEFAULT_RPC_SERVICE_NAME, second_key_id).unwrap();
Tri Voe8f04442022-12-21 08:53:56 -0800588
589 assert_ne!(first_key.keyBlob, second_key.keyBlob);
590 assert_ne!(first_key.encodedCertChain, second_key.encodedCertChain);
591 }
592
593 #[test]
Tri Vobac3b522023-01-23 13:10:24 -0800594 // Couple of things to note:
595 // 1. This test must never run with UID of keystore. Otherwise, it can mess up keys stored by
596 // keystore.
597 // 2. Storing and reading the stored key is prone to race condition. So, we only do this in one
598 // test case.
Tri Voe8f04442022-12-21 08:53:56 -0800599 fn test_store_rkpd_attestation_key() {
Seth Mooref896d362023-01-11 08:06:17 -0800600 binder::ProcessState::start_thread_pool();
Tri Vo4b1cd822023-01-23 13:05:35 -0800601 let key_id = get_next_key_id();
Alice Wangbf6a6932023-11-07 11:47:12 +0000602 let key = get_rkpd_attestation_key(DEFAULT_RPC_SERVICE_NAME, key_id).unwrap();
Tri Vobac3b522023-01-23 13:10:24 -0800603 let new_blob: [u8; 8] = rand::random();
Tri Voe8f04442022-12-21 08:53:56 -0800604
Alice Wangbf6a6932023-11-07 11:47:12 +0000605 assert!(
606 store_rkpd_attestation_key(DEFAULT_RPC_SERVICE_NAME, &key.keyBlob, &new_blob).is_ok()
607 );
Tri Vobac3b522023-01-23 13:10:24 -0800608
Alice Wangbf6a6932023-11-07 11:47:12 +0000609 let new_key = get_rkpd_attestation_key(DEFAULT_RPC_SERVICE_NAME, key_id).unwrap();
Tri Vofc179492023-02-01 14:18:18 -0800610
611 // Restore original key so that we don't leave RKPD with invalid blobs.
Alice Wangbf6a6932023-11-07 11:47:12 +0000612 assert!(
613 store_rkpd_attestation_key(DEFAULT_RPC_SERVICE_NAME, &new_blob, &key.keyBlob).is_ok()
614 );
Tri Vobac3b522023-01-23 13:10:24 -0800615 assert_eq!(new_key.keyBlob, new_blob);
Tri Voe8f04442022-12-21 08:53:56 -0800616 }
Tri Vo30268da2023-01-24 15:35:45 -0800617
618 #[test]
Tri Vo02f0fa42023-01-24 12:32:08 -0800619 fn test_stress_get_rkpd_attestation_key() {
620 binder::ProcessState::start_thread_pool();
621 let key_id = get_next_key_id();
622 let mut threads = vec![];
623 const NTHREADS: u32 = 10;
624 const NCALLS: u32 = 1000;
625
626 for _ in 0..NTHREADS {
627 threads.push(std::thread::spawn(move || {
628 for _ in 0..NCALLS {
Alice Wangbf6a6932023-11-07 11:47:12 +0000629 let key = get_rkpd_attestation_key(DEFAULT_RPC_SERVICE_NAME, key_id).unwrap();
Tri Vo02f0fa42023-01-24 12:32:08 -0800630 assert!(!key.keyBlob.is_empty());
631 assert!(!key.encodedCertChain.is_empty());
632 }
633 }));
634 }
635
636 for t in threads {
637 assert!(t.join().is_ok());
638 }
639 }
Tri Voe8f04442022-12-21 08:53:56 -0800640}