blob: b9a229166855e6a1c52366fe49987dde1f8fde23 [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//!
24//! `map_or_log_err` is a convenience method used to convert `anyhow::Error` into `SerializedError`
25//! wire type.
26//!
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.
131 // `map_or_log_err` will map this on a system error,
132 // but not before logging the details to logcat.
133 Error::Binder(ExceptionCode::SERVICE_SPECIFIC, se)
134 }
135 }
136 // We create `Error::Binder` to preserve the exception code
137 // for logging.
138 // `map_or_log_err` will map this on a system error.
139 e_code => Error::Binder(e_code, 0),
140 }
141 })
142}
143
Janis Danisevskisba998992020-12-29 16:08:40 -0800144/// This function is similar to map_km_error only that we don't expect
145/// any KeyMint error codes, we simply preserve the exception code and optional
146/// service specific exception.
147pub fn map_binder_status<T>(r: BinderResult<T>) -> Result<T, Error> {
148 r.map_err(|s| match s.exception_code() {
149 ExceptionCode::SERVICE_SPECIFIC => {
150 let se = s.service_specific_error();
151 Error::Binder(ExceptionCode::SERVICE_SPECIFIC, se)
152 }
153 ExceptionCode::TRANSACTION_FAILED => {
154 let e = s.transaction_error();
155 Error::BinderTransaction(e)
156 }
157 e_code => Error::Binder(e_code, 0),
158 })
159}
160
161/// This function maps a status code onto a Keystore Error.
162pub fn map_binder_status_code<T>(r: Result<T, StatusCode>) -> Result<T, Error> {
163 r.map_err(Error::BinderTransaction)
164}
165
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700166/// This function should be used by Keystore service calls to translate error conditions
Janis Danisevskis8ea5f552020-11-20 11:22:59 -0800167/// into service specific exceptions.
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700168///
Hasini Gunasinghee1d1bbd2021-04-20 18:13:25 +0000169/// All error conditions get logged by this function, except for KEY_NOT_FOUND error.
David Drysdale5238d772024-06-07 15:12:10 +0100170pub fn map_or_log_err<T>(result: anyhow::Result<T>) -> BinderResult<T> {
171 map_err_with(result, |e| {
172 // Make the key not found errors silent.
173 if !matches!(
174 e.root_cause().downcast_ref::<Error>(),
175 Some(Error::Rc(ResponseCode::KEY_NOT_FOUND))
176 ) {
177 log::error!("{:?}", e);
178 }
179 e
180 })
Janis Danisevskis778245c2021-03-04 15:40:23 -0800181}
182
Janis Danisevskisea03cff2021-12-16 08:10:17 -0800183/// This function turns an anyhow error into an optional CString.
184/// This is especially useful to add a message string to a service specific error.
185/// If the formatted string was not convertible because it contained a nul byte,
186/// None is returned and a warning is logged.
187pub fn anyhow_error_to_cstring(e: &anyhow::Error) -> Option<CString> {
188 match CString::new(format!("{:?}", e)) {
189 Ok(msg) => Some(msg),
190 Err(_) => {
191 log::warn!("Cannot convert error message to CStr. It contained a nul byte.");
192 None
193 }
194 }
195}
196
Janis Danisevskis778245c2021-03-04 15:40:23 -0800197/// This function behaves similar to map_or_log_error, but it does not log the errors, instead
198/// it calls map_err on the error before mapping it to a binder result allowing callers to
199/// log or transform the error before mapping it.
David Drysdale5238d772024-06-07 15:12:10 +0100200pub fn map_err_with<T, F1>(result: anyhow::Result<T>, map_err: F1) -> BinderResult<T>
Janis Danisevskis778245c2021-03-04 15:40:23 -0800201where
202 F1: FnOnce(anyhow::Error) -> anyhow::Error,
Janis Danisevskis778245c2021-03-04 15:40:23 -0800203{
David Drysdale5238d772024-06-07 15:12:10 +0100204 result.map_err(|e| {
205 let e = map_err(e);
206 let rc = anyhow_error_to_serialized_error(&e);
207 BinderStatus::new_service_specific_error(rc.0, anyhow_error_to_cstring(&e).as_deref())
208 })
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700209}
210
Tri Vocd6fc7a2023-08-31 11:46:32 -0400211/// This type is used to send error codes on the wire.
212///
213/// Errors are squashed into one number space using following rules:
214/// - All Keystore and Keymint errors codes are identity mapped. It's possible because by
215/// convention Keystore `ResponseCode` errors are positive, and Keymint `ErrorCode` errors are
216/// negative.
217/// - `selinux::Error::PermissionDenied` is mapped to `ResponseCode::PERMISSION_DENIED`.
218/// - All other error conditions, e.g. Binder errors, are mapped to `ResponseCode::SYSTEM_ERROR`.
219///
220/// The type should be used to forward all error codes to clients of Keystore AIDL interface and to
221/// metrics events.
222#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
223pub struct SerializedError(pub i32);
224
225/// Returns a SerializedError given a reference to Error.
226pub fn error_to_serialized_error(e: &Error) -> SerializedError {
227 match e {
228 Error::Rc(rcode) => SerializedError(rcode.0),
229 Error::Km(ec) => SerializedError(ec.0),
230 // Binder errors are reported as system error.
231 Error::Binder(_, _) | Error::BinderTransaction(_) => {
232 SerializedError(ResponseCode::SYSTEM_ERROR.0)
233 }
234 }
235}
236
237/// Returns a SerializedError given a reference to anyhow::Error.
238pub fn anyhow_error_to_serialized_error(e: &anyhow::Error) -> SerializedError {
Hasini Gunasingheb7142972021-02-20 03:11:27 +0000239 let root_cause = e.root_cause();
240 match root_cause.downcast_ref::<Error>() {
Tri Vocd6fc7a2023-08-31 11:46:32 -0400241 Some(e) => error_to_serialized_error(e),
Hasini Gunasingheb7142972021-02-20 03:11:27 +0000242 None => match root_cause.downcast_ref::<selinux::Error>() {
Tri Vocd6fc7a2023-08-31 11:46:32 -0400243 Some(selinux::Error::PermissionDenied) => {
244 SerializedError(ResponseCode::PERMISSION_DENIED.0)
245 }
246 _ => SerializedError(ResponseCode::SYSTEM_ERROR.0),
Hasini Gunasingheb7142972021-02-20 03:11:27 +0000247 },
248 }
249}
250
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700251#[cfg(test)]
Hasini Gunasingheaf993662020-07-24 18:40:20 +0000252pub mod tests {
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700253
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700254 use super::*;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700255 use android_system_keystore2::binder::{
Janis Danisevskis017d2092020-09-02 10:15:52 -0700256 ExceptionCode, Result as BinderResult, Status as BinderStatus,
257 };
Janis Danisevskise24f3472020-08-12 17:58:49 -0700258 use anyhow::{anyhow, Context};
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700259
Janis Danisevskise24f3472020-08-12 17:58:49 -0700260 fn nested_nested_rc(rc: ResponseCode) -> anyhow::Result<()> {
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700261 Err(anyhow!(Error::Rc(rc))).context("nested nested rc")
262 }
263
Janis Danisevskise24f3472020-08-12 17:58:49 -0700264 fn nested_rc(rc: ResponseCode) -> anyhow::Result<()> {
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700265 nested_nested_rc(rc).context("nested rc")
266 }
267
268 fn nested_nested_ec(ec: ErrorCode) -> anyhow::Result<()> {
269 Err(anyhow!(Error::Km(ec))).context("nested nested ec")
270 }
271
272 fn nested_ec(ec: ErrorCode) -> anyhow::Result<()> {
273 nested_nested_ec(ec).context("nested ec")
274 }
275
Janis Danisevskise24f3472020-08-12 17:58:49 -0700276 fn nested_nested_ok(rc: ResponseCode) -> anyhow::Result<ResponseCode> {
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700277 Ok(rc)
278 }
279
Janis Danisevskise24f3472020-08-12 17:58:49 -0700280 fn nested_ok(rc: ResponseCode) -> anyhow::Result<ResponseCode> {
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700281 nested_nested_ok(rc).context("nested ok")
282 }
283
Janis Danisevskisce995432020-07-21 12:22:34 -0700284 fn nested_nested_selinux_perm() -> anyhow::Result<()> {
285 Err(anyhow!(selinux::Error::perm())).context("nested nexted selinux permission denied")
286 }
287
288 fn nested_selinux_perm() -> anyhow::Result<()> {
289 nested_nested_selinux_perm().context("nested selinux permission denied")
290 }
291
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700292 #[derive(Debug, thiserror::Error)]
293 enum TestError {
294 #[error("TestError::Fail")]
295 Fail = 0,
296 }
297
298 fn nested_nested_other_error() -> anyhow::Result<()> {
299 Err(anyhow!(TestError::Fail)).context("nested nested other error")
300 }
301
302 fn nested_other_error() -> anyhow::Result<()> {
303 nested_nested_other_error().context("nested other error")
304 }
305
Janis Danisevskis017d2092020-09-02 10:15:52 -0700306 fn binder_sse_error(sse: i32) -> BinderResult<()> {
307 Err(BinderStatus::new_service_specific_error(sse, None))
308 }
309
310 fn binder_exception(ex: ExceptionCode) -> BinderResult<()> {
311 Err(BinderStatus::new_exception(ex, None))
312 }
313
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700314 #[test]
315 fn keystore_error_test() -> anyhow::Result<(), String> {
316 android_logger::init_once(
317 android_logger::Config::default()
318 .with_tag("keystore_error_tests")
Jeff Vander Stoep153d1aa2024-02-07 14:33:36 +0100319 .with_max_level(log::LevelFilter::Debug),
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700320 );
Janis Danisevskise24f3472020-08-12 17:58:49 -0700321 // All Error::Rc(x) get mapped on a service specific error
322 // code of x.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700323 for rc in ResponseCode::LOCKED.0..ResponseCode::BACKEND_BUSY.0 {
Janis Danisevskise24f3472020-08-12 17:58:49 -0700324 assert_eq!(
325 Result::<(), i32>::Err(rc),
David Drysdale5238d772024-06-07 15:12:10 +0100326 map_or_log_err(nested_rc(ResponseCode(rc))).map_err(|s| s.service_specific_error())
Janis Danisevskise24f3472020-08-12 17:58:49 -0700327 );
328 }
329
Janis Danisevskis017d2092020-09-02 10:15:52 -0700330 // All Keystore Error::Km(x) get mapped on a service
Janis Danisevskise24f3472020-08-12 17:58:49 -0700331 // specific error of x.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700332 for ec in ErrorCode::UNKNOWN_ERROR.0..ErrorCode::ROOT_OF_TRUST_ALREADY_SET.0 {
Janis Danisevskise24f3472020-08-12 17:58:49 -0700333 assert_eq!(
334 Result::<(), i32>::Err(ec),
David Drysdale5238d772024-06-07 15:12:10 +0100335 map_or_log_err(nested_ec(ErrorCode(ec))).map_err(|s| s.service_specific_error())
Janis Danisevskise24f3472020-08-12 17:58:49 -0700336 );
337 }
338
Janis Danisevskis017d2092020-09-02 10:15:52 -0700339 // All Keymint errors x received through a Binder Result get mapped on
340 // a service specific error of x.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700341 for ec in ErrorCode::UNKNOWN_ERROR.0..ErrorCode::ROOT_OF_TRUST_ALREADY_SET.0 {
Janis Danisevskis017d2092020-09-02 10:15:52 -0700342 assert_eq!(
343 Result::<(), i32>::Err(ec),
344 map_or_log_err(
345 map_km_error(binder_sse_error(ec))
David Drysdale5238d772024-06-07 15:12:10 +0100346 .with_context(|| format!("Km error code: {}.", ec))
Janis Danisevskis017d2092020-09-02 10:15:52 -0700347 )
348 .map_err(|s| s.service_specific_error())
349 );
350 }
351
352 // map_km_error creates an Error::Binder variant storing
353 // ExceptionCode::SERVICE_SPECIFIC and the given
354 // service specific error.
355 let sse = map_km_error(binder_sse_error(1));
356 assert_eq!(Err(Error::Binder(ExceptionCode::SERVICE_SPECIFIC, 1)), sse);
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700357 // map_or_log_err then maps it on a service specific error of ResponseCode::SYSTEM_ERROR.
Janis Danisevskis017d2092020-09-02 10:15:52 -0700358 assert_eq!(
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700359 Result::<(), ResponseCode>::Err(ResponseCode::SYSTEM_ERROR),
David Drysdale5238d772024-06-07 15:12:10 +0100360 map_or_log_err(sse.context("Non negative service specific error."))
361 .map_err(|s| ResponseCode(s.service_specific_error()))
Janis Danisevskis017d2092020-09-02 10:15:52 -0700362 );
363
364 // map_km_error creates a Error::Binder variant storing the given exception code.
365 let binder_exception = map_km_error(binder_exception(ExceptionCode::TRANSACTION_FAILED));
366 assert_eq!(Err(Error::Binder(ExceptionCode::TRANSACTION_FAILED, 0)), binder_exception);
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700367 // map_or_log_err then maps it on a service specific error of ResponseCode::SYSTEM_ERROR.
Janis Danisevskis017d2092020-09-02 10:15:52 -0700368 assert_eq!(
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700369 Result::<(), ResponseCode>::Err(ResponseCode::SYSTEM_ERROR),
David Drysdale5238d772024-06-07 15:12:10 +0100370 map_or_log_err(binder_exception.context("Binder Exception."))
371 .map_err(|s| ResponseCode(s.service_specific_error()))
Janis Danisevskis017d2092020-09-02 10:15:52 -0700372 );
373
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700374 // selinux::Error::Perm() needs to be mapped to ResponseCode::PERMISSION_DENIED
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700375 assert_eq!(
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700376 Result::<(), ResponseCode>::Err(ResponseCode::PERMISSION_DENIED),
David Drysdale5238d772024-06-07 15:12:10 +0100377 map_or_log_err(nested_selinux_perm())
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
Janis Danisevskise24f3472020-08-12 17:58:49 -0700381 // All other errors get mapped on System Error.
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700382 assert_eq!(
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700383 Result::<(), ResponseCode>::Err(ResponseCode::SYSTEM_ERROR),
David Drysdale5238d772024-06-07 15:12:10 +0100384 map_or_log_err(nested_other_error())
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700385 .map_err(|s| ResponseCode(s.service_specific_error()))
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700386 );
387
388 // Result::Ok variants get passed to the ok handler.
David Drysdale5238d772024-06-07 15:12:10 +0100389 assert_eq!(Ok(ResponseCode::LOCKED), map_or_log_err(nested_ok(ResponseCode::LOCKED)));
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700390 assert_eq!(
391 Ok(ResponseCode::SYSTEM_ERROR),
David Drysdale5238d772024-06-07 15:12:10 +0100392 map_or_log_err(nested_ok(ResponseCode::SYSTEM_ERROR))
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700393 );
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700394
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700395 Ok(())
396 }
Hasini Gunasingheaf993662020-07-24 18:40:20 +0000397
398 //Helper function to test whether error cases are handled as expected.
Janis Danisevskise24f3472020-08-12 17:58:49 -0700399 pub fn check_result_contains_error_string<T>(
400 result: anyhow::Result<T>,
401 expected_error_string: &str,
402 ) {
Hasini Gunasingheaf993662020-07-24 18:40:20 +0000403 let error_str = format!(
404 "{:#?}",
405 result.err().unwrap_or_else(|| panic!("Expected the error: {}", expected_error_string))
406 );
407 assert!(
408 error_str.contains(expected_error_string),
409 "The string \"{}\" should contain \"{}\"",
410 error_str,
411 expected_error_string
412 );
413 }
Alice Wang849cfe42023-11-10 12:43:36 +0000414
415 #[test]
416 fn rkpd_error_is_in_sync_with_response_code() {
417 let error_mapping = [
418 (RkpdError::RequestCancelled, ResponseCode::OUT_OF_KEYS_TRANSIENT_ERROR),
419 (RkpdError::GetRegistrationFailed, ResponseCode::OUT_OF_KEYS_TRANSIENT_ERROR),
420 (
421 RkpdError::GetKeyFailed(GetKeyErrorCode::ERROR_UNKNOWN),
422 ResponseCode::OUT_OF_KEYS_TRANSIENT_ERROR,
423 ),
424 (
425 RkpdError::GetKeyFailed(GetKeyErrorCode::ERROR_PERMANENT),
426 ResponseCode::OUT_OF_KEYS_PERMANENT_ERROR,
427 ),
428 (
429 RkpdError::GetKeyFailed(GetKeyErrorCode::ERROR_PENDING_INTERNET_CONNECTIVITY),
430 ResponseCode::OUT_OF_KEYS_PENDING_INTERNET_CONNECTIVITY,
431 ),
432 (
433 RkpdError::GetKeyFailed(GetKeyErrorCode::ERROR_REQUIRES_SECURITY_PATCH),
434 ResponseCode::OUT_OF_KEYS_REQUIRES_SYSTEM_UPGRADE,
435 ),
436 (RkpdError::StoreUpgradedKeyFailed, ResponseCode::SYSTEM_ERROR),
437 (RkpdError::RetryableTimeout, ResponseCode::OUT_OF_KEYS_TRANSIENT_ERROR),
438 (RkpdError::Timeout, ResponseCode::SYSTEM_ERROR),
439 ];
440 for (rkpd_error, expected_response_code) in error_mapping {
441 let e: Error = rkpd_error.into();
442 assert_eq!(e, Error::Rc(expected_response_code));
443 }
444 }
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700445} // mod tests