blob: cea4d6becbc4edd877ef956ad8be1c4422e795ec [file] [log] [blame]
Janis Danisevskis7d77a762020-07-20 13:03:31 -07001// Copyright 2020, 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//! Keystore error provides convenience methods and types for Keystore error handling.
Janis Danisevskis7d77a762020-07-20 13:03:31 -070016//!
Tri Vocd6fc7a2023-08-31 11:46:32 -040017//! Here are some important types and helper functions:
Janis Danisevskis7d77a762020-07-20 13:03:31 -070018//!
Tri Vocd6fc7a2023-08-31 11:46:32 -040019//! `Error` type encapsulate Keystore, Keymint, and Binder errors. It is used internally by
20//! Keystore to diagnose error conditions that need to be reported to the client.
21//!
22//! `SerializedError` is used send error codes on the wire.
23//!
David Drysdaledb7ddde2024-06-07 16:22:49 +010024//! `into_[logged_]binder` is a convenience method used to convert `anyhow::Error` into
25//! `SerializedError` wire type.
Tri Vocd6fc7a2023-08-31 11:46:32 -040026//!
27//! Keystore functions should use `anyhow::Result` to return error conditions, and context should
28//! be added every time an error is forwarded.
Janis Danisevskis7d77a762020-07-20 13:03:31 -070029
Shawn Willden708744a2020-12-11 13:05:27 +000030pub use android_hardware_security_keymint::aidl::android::hardware::security::keymint::ErrorCode::ErrorCode;
Alice Wang849cfe42023-11-10 12:43:36 +000031use android_security_rkp_aidl::aidl::android::security::rkp::IGetKeyCallback::ErrorCode::ErrorCode as GetKeyErrorCode;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070032pub use android_system_keystore2::aidl::android::system::keystore2::ResponseCode::ResponseCode;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070033use android_system_keystore2::binder::{
Janis Danisevskisba998992020-12-29 16:08:40 -080034 ExceptionCode, Result as BinderResult, Status as BinderStatus, StatusCode,
Janis Danisevskis017d2092020-09-02 10:15:52 -070035};
Janis Danisevskis2ee014b2021-05-05 14:29:08 -070036use keystore2_selinux as selinux;
Alice Wang01c16b62023-11-07 14:27:49 +000037use rkpd_client::Error as RkpdError;
Janis Danisevskis2ee014b2021-05-05 14:29:08 -070038use std::cmp::PartialEq;
Janis Danisevskisea03cff2021-12-16 08:10:17 -080039use std::ffi::CString;
Janis Danisevskis7d77a762020-07-20 13:03:31 -070040
41/// This is the main Keystore error type. It wraps the Keystore `ResponseCode` generated
42/// from AIDL in the `Rc` variant and Keymint `ErrorCode` in the Km variant.
Chris Wailes263de9f2022-08-11 15:00:51 -070043#[derive(Debug, thiserror::Error, PartialEq, Eq)]
Janis Danisevskis7d77a762020-07-20 13:03:31 -070044pub enum Error {
45 /// Wraps a Keystore `ResponseCode` as defined by the Keystore AIDL interface specification.
46 #[error("Error::Rc({0:?})")]
Janis Danisevskise24f3472020-08-12 17:58:49 -070047 Rc(ResponseCode),
Janis Danisevskis7d77a762020-07-20 13:03:31 -070048 /// Wraps a Keymint `ErrorCode` as defined by the Keymint AIDL interface specification.
49 #[error("Error::Km({0:?})")]
Janis Danisevskise24f3472020-08-12 17:58:49 -070050 Km(ErrorCode),
Janis Danisevskis017d2092020-09-02 10:15:52 -070051 /// Wraps a Binder exception code other than a service specific exception.
52 #[error("Binder exception code {0:?}, {1:?}")]
53 Binder(ExceptionCode, i32),
Janis Danisevskisba998992020-12-29 16:08:40 -080054 /// Wraps a Binder status code.
55 #[error("Binder transaction error {0:?}")]
56 BinderTransaction(StatusCode),
Janis Danisevskis7d77a762020-07-20 13:03:31 -070057}
58
59impl Error {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070060 /// Short hand for `Error::Rc(ResponseCode::SYSTEM_ERROR)`
Janis Danisevskis7d77a762020-07-20 13:03:31 -070061 pub fn sys() -> Self {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070062 Error::Rc(ResponseCode::SYSTEM_ERROR)
Janis Danisevskis7d77a762020-07-20 13:03:31 -070063 }
64
Seth Moore7ee79f92021-12-07 11:42:49 -080065 /// Short hand for `Error::Rc(ResponseCode::PERMISSION_DENIED)`
Janis Danisevskis7d77a762020-07-20 13:03:31 -070066 pub fn perm() -> Self {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070067 Error::Rc(ResponseCode::PERMISSION_DENIED)
Janis Danisevskis7d77a762020-07-20 13:03:31 -070068 }
69}
70
Alice Wang849cfe42023-11-10 12:43:36 +000071impl From<RkpdError> for Error {
72 fn from(e: RkpdError) -> Self {
73 match e {
74 RkpdError::RequestCancelled | RkpdError::GetRegistrationFailed => {
75 Error::Rc(ResponseCode::OUT_OF_KEYS_TRANSIENT_ERROR)
76 }
77 RkpdError::GetKeyFailed(e) => {
78 let response_code = match e {
79 GetKeyErrorCode::ERROR_UNKNOWN => ResponseCode::OUT_OF_KEYS_TRANSIENT_ERROR,
80 GetKeyErrorCode::ERROR_PERMANENT => ResponseCode::OUT_OF_KEYS_PERMANENT_ERROR,
81 GetKeyErrorCode::ERROR_PENDING_INTERNET_CONNECTIVITY => {
82 ResponseCode::OUT_OF_KEYS_PENDING_INTERNET_CONNECTIVITY
83 }
84 GetKeyErrorCode::ERROR_REQUIRES_SECURITY_PATCH => {
85 ResponseCode::OUT_OF_KEYS_REQUIRES_SYSTEM_UPGRADE
86 }
87 _ => {
88 log::error!("Unexpected get key error from rkpd: {e:?}");
89 ResponseCode::OUT_OF_KEYS_TRANSIENT_ERROR
90 }
91 };
92 Error::Rc(response_code)
93 }
94 RkpdError::RetryableTimeout => Error::Rc(ResponseCode::OUT_OF_KEYS_TRANSIENT_ERROR),
95 RkpdError::StoreUpgradedKeyFailed | RkpdError::Timeout => {
96 Error::Rc(ResponseCode::SYSTEM_ERROR)
97 }
98 RkpdError::BinderTransaction(s) => Error::BinderTransaction(s),
99 }
100 }
101}
102
103/// Maps an `rkpd_client::Error` that is wrapped with an `anyhow::Error` to a keystore2 `Error`.
104pub fn wrapped_rkpd_error_to_ks_error(e: &anyhow::Error) -> Error {
105 match e.downcast_ref::<RkpdError>() {
106 Some(e) => Error::from(*e),
107 None => {
108 log::error!("Failed to downcast the anyhow::Error to rkpd_client::Error: {e:?}");
109 Error::Rc(ResponseCode::SYSTEM_ERROR)
110 }
111 }
112}
113
Janis Danisevskis017d2092020-09-02 10:15:52 -0700114/// Helper function to map the binder status we get from calls into KeyMint
115/// to a Keystore Error. We don't create an anyhow error here to make
116/// it easier to evaluate KeyMint errors, which we must do in some cases, e.g.,
117/// when diagnosing authentication requirements, update requirements, and running
118/// out of operation slots.
119pub fn map_km_error<T>(r: BinderResult<T>) -> Result<T, Error> {
120 r.map_err(|s| {
121 match s.exception_code() {
122 ExceptionCode::SERVICE_SPECIFIC => {
123 let se = s.service_specific_error();
124 if se < 0 {
125 // Negative service specific errors are KM error codes.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700126 Error::Km(ErrorCode(s.service_specific_error()))
Janis Danisevskis017d2092020-09-02 10:15:52 -0700127 } else {
128 // Non negative error codes cannot be KM error codes.
129 // So we create an `Error::Binder` variant to preserve
130 // the service specific error code for logging.
Janis Danisevskis017d2092020-09-02 10:15:52 -0700131 Error::Binder(ExceptionCode::SERVICE_SPECIFIC, se)
132 }
133 }
134 // We create `Error::Binder` to preserve the exception code
135 // for logging.
Janis Danisevskis017d2092020-09-02 10:15:52 -0700136 e_code => Error::Binder(e_code, 0),
137 }
138 })
139}
140
Janis Danisevskisba998992020-12-29 16:08:40 -0800141/// This function is similar to map_km_error only that we don't expect
142/// any KeyMint error codes, we simply preserve the exception code and optional
143/// service specific exception.
144pub fn map_binder_status<T>(r: BinderResult<T>) -> Result<T, Error> {
145 r.map_err(|s| match s.exception_code() {
146 ExceptionCode::SERVICE_SPECIFIC => {
147 let se = s.service_specific_error();
148 Error::Binder(ExceptionCode::SERVICE_SPECIFIC, se)
149 }
150 ExceptionCode::TRANSACTION_FAILED => {
151 let e = s.transaction_error();
152 Error::BinderTransaction(e)
153 }
154 e_code => Error::Binder(e_code, 0),
155 })
156}
157
158/// This function maps a status code onto a Keystore Error.
159pub fn map_binder_status_code<T>(r: Result<T, StatusCode>) -> Result<T, Error> {
160 r.map_err(Error::BinderTransaction)
161}
162
David Drysdaledb7ddde2024-06-07 16:22:49 +0100163/// Convert an [`anyhow::Error`] to a [`binder::Status`], logging the value
164/// along the way (except if it is `KEY_NOT_FOUND`).
165pub fn into_logged_binder(e: anyhow::Error) -> BinderStatus {
166 // Log everything except key not found.
167 if !matches!(
168 e.root_cause().downcast_ref::<Error>(),
169 Some(Error::Rc(ResponseCode::KEY_NOT_FOUND))
170 ) {
171 log::error!("{:?}", e);
172 }
173 into_binder(e)
Janis Danisevskis778245c2021-03-04 15:40:23 -0800174}
175
Janis Danisevskisea03cff2021-12-16 08:10:17 -0800176/// This function turns an anyhow error into an optional CString.
177/// This is especially useful to add a message string to a service specific error.
178/// If the formatted string was not convertible because it contained a nul byte,
179/// None is returned and a warning is logged.
180pub fn anyhow_error_to_cstring(e: &anyhow::Error) -> Option<CString> {
181 match CString::new(format!("{:?}", e)) {
182 Ok(msg) => Some(msg),
183 Err(_) => {
184 log::warn!("Cannot convert error message to CStr. It contained a nul byte.");
185 None
186 }
187 }
188}
189
David Drysdaledb7ddde2024-06-07 16:22:49 +0100190/// Convert an [`anyhow::Error`] to a [`binder::Status`].
191pub fn into_binder(e: anyhow::Error) -> binder::Status {
192 let rc = anyhow_error_to_serialized_error(&e);
193 BinderStatus::new_service_specific_error(rc.0, anyhow_error_to_cstring(&e).as_deref())
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700194}
195
Tri Vocd6fc7a2023-08-31 11:46:32 -0400196/// This type is used to send error codes on the wire.
197///
198/// Errors are squashed into one number space using following rules:
199/// - All Keystore and Keymint errors codes are identity mapped. It's possible because by
200/// convention Keystore `ResponseCode` errors are positive, and Keymint `ErrorCode` errors are
201/// negative.
202/// - `selinux::Error::PermissionDenied` is mapped to `ResponseCode::PERMISSION_DENIED`.
203/// - All other error conditions, e.g. Binder errors, are mapped to `ResponseCode::SYSTEM_ERROR`.
204///
205/// The type should be used to forward all error codes to clients of Keystore AIDL interface and to
206/// metrics events.
207#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
208pub struct SerializedError(pub i32);
209
210/// Returns a SerializedError given a reference to Error.
211pub fn error_to_serialized_error(e: &Error) -> SerializedError {
212 match e {
213 Error::Rc(rcode) => SerializedError(rcode.0),
214 Error::Km(ec) => SerializedError(ec.0),
215 // Binder errors are reported as system error.
216 Error::Binder(_, _) | Error::BinderTransaction(_) => {
217 SerializedError(ResponseCode::SYSTEM_ERROR.0)
218 }
219 }
220}
221
222/// Returns a SerializedError given a reference to anyhow::Error.
223pub fn anyhow_error_to_serialized_error(e: &anyhow::Error) -> SerializedError {
Hasini Gunasingheb7142972021-02-20 03:11:27 +0000224 let root_cause = e.root_cause();
225 match root_cause.downcast_ref::<Error>() {
Tri Vocd6fc7a2023-08-31 11:46:32 -0400226 Some(e) => error_to_serialized_error(e),
Hasini Gunasingheb7142972021-02-20 03:11:27 +0000227 None => match root_cause.downcast_ref::<selinux::Error>() {
Tri Vocd6fc7a2023-08-31 11:46:32 -0400228 Some(selinux::Error::PermissionDenied) => {
229 SerializedError(ResponseCode::PERMISSION_DENIED.0)
230 }
231 _ => SerializedError(ResponseCode::SYSTEM_ERROR.0),
Hasini Gunasingheb7142972021-02-20 03:11:27 +0000232 },
233 }
234}
235
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700236#[cfg(test)]
Hasini Gunasingheaf993662020-07-24 18:40:20 +0000237pub mod tests {
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700238
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700239 use super::*;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700240 use android_system_keystore2::binder::{
Janis Danisevskis017d2092020-09-02 10:15:52 -0700241 ExceptionCode, Result as BinderResult, Status as BinderStatus,
242 };
Janis Danisevskise24f3472020-08-12 17:58:49 -0700243 use anyhow::{anyhow, Context};
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700244
Janis Danisevskise24f3472020-08-12 17:58:49 -0700245 fn nested_nested_rc(rc: ResponseCode) -> anyhow::Result<()> {
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700246 Err(anyhow!(Error::Rc(rc))).context("nested nested rc")
247 }
248
Janis Danisevskise24f3472020-08-12 17:58:49 -0700249 fn nested_rc(rc: ResponseCode) -> anyhow::Result<()> {
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700250 nested_nested_rc(rc).context("nested rc")
251 }
252
253 fn nested_nested_ec(ec: ErrorCode) -> anyhow::Result<()> {
254 Err(anyhow!(Error::Km(ec))).context("nested nested ec")
255 }
256
257 fn nested_ec(ec: ErrorCode) -> anyhow::Result<()> {
258 nested_nested_ec(ec).context("nested ec")
259 }
260
Janis Danisevskise24f3472020-08-12 17:58:49 -0700261 fn nested_nested_ok(rc: ResponseCode) -> anyhow::Result<ResponseCode> {
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700262 Ok(rc)
263 }
264
Janis Danisevskise24f3472020-08-12 17:58:49 -0700265 fn nested_ok(rc: ResponseCode) -> anyhow::Result<ResponseCode> {
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700266 nested_nested_ok(rc).context("nested ok")
267 }
268
Janis Danisevskisce995432020-07-21 12:22:34 -0700269 fn nested_nested_selinux_perm() -> anyhow::Result<()> {
270 Err(anyhow!(selinux::Error::perm())).context("nested nexted selinux permission denied")
271 }
272
273 fn nested_selinux_perm() -> anyhow::Result<()> {
274 nested_nested_selinux_perm().context("nested selinux permission denied")
275 }
276
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700277 #[derive(Debug, thiserror::Error)]
278 enum TestError {
279 #[error("TestError::Fail")]
280 Fail = 0,
281 }
282
283 fn nested_nested_other_error() -> anyhow::Result<()> {
284 Err(anyhow!(TestError::Fail)).context("nested nested other error")
285 }
286
287 fn nested_other_error() -> anyhow::Result<()> {
288 nested_nested_other_error().context("nested other error")
289 }
290
Janis Danisevskis017d2092020-09-02 10:15:52 -0700291 fn binder_sse_error(sse: i32) -> BinderResult<()> {
292 Err(BinderStatus::new_service_specific_error(sse, None))
293 }
294
295 fn binder_exception(ex: ExceptionCode) -> BinderResult<()> {
296 Err(BinderStatus::new_exception(ex, None))
297 }
298
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700299 #[test]
300 fn keystore_error_test() -> anyhow::Result<(), String> {
301 android_logger::init_once(
302 android_logger::Config::default()
303 .with_tag("keystore_error_tests")
Jeff Vander Stoep153d1aa2024-02-07 14:33:36 +0100304 .with_max_level(log::LevelFilter::Debug),
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700305 );
Janis Danisevskise24f3472020-08-12 17:58:49 -0700306 // All Error::Rc(x) get mapped on a service specific error
307 // code of x.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700308 for rc in ResponseCode::LOCKED.0..ResponseCode::BACKEND_BUSY.0 {
Janis Danisevskise24f3472020-08-12 17:58:49 -0700309 assert_eq!(
310 Result::<(), i32>::Err(rc),
David Drysdaledb7ddde2024-06-07 16:22:49 +0100311 nested_rc(ResponseCode(rc))
312 .map_err(into_logged_binder)
313 .map_err(|s| s.service_specific_error())
Janis Danisevskise24f3472020-08-12 17:58:49 -0700314 );
315 }
316
Janis Danisevskis017d2092020-09-02 10:15:52 -0700317 // All Keystore Error::Km(x) get mapped on a service
Janis Danisevskise24f3472020-08-12 17:58:49 -0700318 // specific error of x.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700319 for ec in ErrorCode::UNKNOWN_ERROR.0..ErrorCode::ROOT_OF_TRUST_ALREADY_SET.0 {
Janis Danisevskise24f3472020-08-12 17:58:49 -0700320 assert_eq!(
321 Result::<(), i32>::Err(ec),
David Drysdaledb7ddde2024-06-07 16:22:49 +0100322 nested_ec(ErrorCode(ec))
323 .map_err(into_logged_binder)
324 .map_err(|s| s.service_specific_error())
Janis Danisevskise24f3472020-08-12 17:58:49 -0700325 );
326 }
327
Janis Danisevskis017d2092020-09-02 10:15:52 -0700328 // All Keymint errors x received through a Binder Result get mapped on
329 // a service specific error of x.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700330 for ec in ErrorCode::UNKNOWN_ERROR.0..ErrorCode::ROOT_OF_TRUST_ALREADY_SET.0 {
Janis Danisevskis017d2092020-09-02 10:15:52 -0700331 assert_eq!(
332 Result::<(), i32>::Err(ec),
David Drysdaledb7ddde2024-06-07 16:22:49 +0100333 map_km_error(binder_sse_error(ec))
334 .with_context(|| format!("Km error code: {}.", ec))
335 .map_err(into_logged_binder)
336 .map_err(|s| s.service_specific_error())
Janis Danisevskis017d2092020-09-02 10:15:52 -0700337 );
338 }
339
340 // map_km_error creates an Error::Binder variant storing
341 // ExceptionCode::SERVICE_SPECIFIC and the given
342 // service specific error.
343 let sse = map_km_error(binder_sse_error(1));
344 assert_eq!(Err(Error::Binder(ExceptionCode::SERVICE_SPECIFIC, 1)), sse);
David Drysdaledb7ddde2024-06-07 16:22:49 +0100345 // into_binder then maps it on a service specific error of ResponseCode::SYSTEM_ERROR.
Janis Danisevskis017d2092020-09-02 10:15:52 -0700346 assert_eq!(
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700347 Result::<(), ResponseCode>::Err(ResponseCode::SYSTEM_ERROR),
David Drysdaledb7ddde2024-06-07 16:22:49 +0100348 sse.context("Non negative service specific error.")
349 .map_err(into_logged_binder)
David Drysdale5238d772024-06-07 15:12:10 +0100350 .map_err(|s| ResponseCode(s.service_specific_error()))
Janis Danisevskis017d2092020-09-02 10:15:52 -0700351 );
352
353 // map_km_error creates a Error::Binder variant storing the given exception code.
354 let binder_exception = map_km_error(binder_exception(ExceptionCode::TRANSACTION_FAILED));
355 assert_eq!(Err(Error::Binder(ExceptionCode::TRANSACTION_FAILED, 0)), binder_exception);
David Drysdaledb7ddde2024-06-07 16:22:49 +0100356 // into_binder then maps it on a service specific error of ResponseCode::SYSTEM_ERROR.
Janis Danisevskis017d2092020-09-02 10:15:52 -0700357 assert_eq!(
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700358 Result::<(), ResponseCode>::Err(ResponseCode::SYSTEM_ERROR),
David Drysdaledb7ddde2024-06-07 16:22:49 +0100359 binder_exception
360 .context("Binder Exception.")
361 .map_err(into_logged_binder)
David Drysdale5238d772024-06-07 15:12:10 +0100362 .map_err(|s| ResponseCode(s.service_specific_error()))
Janis Danisevskis017d2092020-09-02 10:15:52 -0700363 );
364
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700365 // selinux::Error::Perm() needs to be mapped to ResponseCode::PERMISSION_DENIED
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700366 assert_eq!(
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700367 Result::<(), ResponseCode>::Err(ResponseCode::PERMISSION_DENIED),
David Drysdaledb7ddde2024-06-07 16:22:49 +0100368 nested_selinux_perm()
369 .map_err(into_logged_binder)
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700370 .map_err(|s| ResponseCode(s.service_specific_error()))
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700371 );
372
Janis Danisevskise24f3472020-08-12 17:58:49 -0700373 // All other errors get mapped on System Error.
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700374 assert_eq!(
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700375 Result::<(), ResponseCode>::Err(ResponseCode::SYSTEM_ERROR),
David Drysdaledb7ddde2024-06-07 16:22:49 +0100376 nested_other_error()
377 .map_err(into_logged_binder)
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700378 .map_err(|s| ResponseCode(s.service_specific_error()))
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700379 );
380
381 // Result::Ok variants get passed to the ok handler.
David Drysdaledb7ddde2024-06-07 16:22:49 +0100382 assert_eq!(
383 Ok(ResponseCode::LOCKED),
384 nested_ok(ResponseCode::LOCKED).map_err(into_logged_binder)
385 );
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700386 assert_eq!(
387 Ok(ResponseCode::SYSTEM_ERROR),
David Drysdaledb7ddde2024-06-07 16:22:49 +0100388 nested_ok(ResponseCode::SYSTEM_ERROR).map_err(into_logged_binder)
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700389 );
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700390
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700391 Ok(())
392 }
Hasini Gunasingheaf993662020-07-24 18:40:20 +0000393
394 //Helper function to test whether error cases are handled as expected.
Janis Danisevskise24f3472020-08-12 17:58:49 -0700395 pub fn check_result_contains_error_string<T>(
396 result: anyhow::Result<T>,
397 expected_error_string: &str,
398 ) {
Hasini Gunasingheaf993662020-07-24 18:40:20 +0000399 let error_str = format!(
400 "{:#?}",
401 result.err().unwrap_or_else(|| panic!("Expected the error: {}", expected_error_string))
402 );
403 assert!(
404 error_str.contains(expected_error_string),
405 "The string \"{}\" should contain \"{}\"",
406 error_str,
407 expected_error_string
408 );
409 }
Alice Wang849cfe42023-11-10 12:43:36 +0000410
411 #[test]
412 fn rkpd_error_is_in_sync_with_response_code() {
413 let error_mapping = [
414 (RkpdError::RequestCancelled, ResponseCode::OUT_OF_KEYS_TRANSIENT_ERROR),
415 (RkpdError::GetRegistrationFailed, ResponseCode::OUT_OF_KEYS_TRANSIENT_ERROR),
416 (
417 RkpdError::GetKeyFailed(GetKeyErrorCode::ERROR_UNKNOWN),
418 ResponseCode::OUT_OF_KEYS_TRANSIENT_ERROR,
419 ),
420 (
421 RkpdError::GetKeyFailed(GetKeyErrorCode::ERROR_PERMANENT),
422 ResponseCode::OUT_OF_KEYS_PERMANENT_ERROR,
423 ),
424 (
425 RkpdError::GetKeyFailed(GetKeyErrorCode::ERROR_PENDING_INTERNET_CONNECTIVITY),
426 ResponseCode::OUT_OF_KEYS_PENDING_INTERNET_CONNECTIVITY,
427 ),
428 (
429 RkpdError::GetKeyFailed(GetKeyErrorCode::ERROR_REQUIRES_SECURITY_PATCH),
430 ResponseCode::OUT_OF_KEYS_REQUIRES_SYSTEM_UPGRADE,
431 ),
432 (RkpdError::StoreUpgradedKeyFailed, ResponseCode::SYSTEM_ERROR),
433 (RkpdError::RetryableTimeout, ResponseCode::OUT_OF_KEYS_TRANSIENT_ERROR),
434 (RkpdError::Timeout, ResponseCode::SYSTEM_ERROR),
435 ];
436 for (rkpd_error, expected_response_code) in error_mapping {
437 let e: Error = rkpd_error.into();
438 assert_eq!(e, Error::Rc(expected_response_code));
439 }
440 }
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700441} // mod tests