Cope better with errors in child processes

If a test needs to run in a child process, make it easier to cope if
that child process encounters a failure along the way.

- Add a stringly-typed `Error` to the `run_as` module, which can:
  - be serialized and so emitted from child processes
  - be constructed from an `anyhow::Error`.
- Add helper macros that construct and `return` an `Error` rather than
  directly panicking.
- Add a `recv_or_die()` method that attempts to read a response message
  from the child process, but copes with the channel being gone. This
  happens if the child has already exited; in this case a final result
  message is hopefully available on the `result_reader`.
- Migrate the auth-bound tests to use `Result<(), run_as::Error>`.

Test: keystore2_client_tests auth_bound
Change-Id: Ic306bb272f740a44c0e1d06c948f11435ac3b211
diff --git a/keystore2/test_utils/key_generations.rs b/keystore2/test_utils/key_generations.rs
index c40e944..5e823c2 100644
--- a/keystore2/test_utils/key_generations.rs
+++ b/keystore2/test_utils/key_generations.rs
@@ -393,22 +393,27 @@
 }
 
 /// Check for a specific KeyMint error.
-pub fn assert_km_error<T: std::fmt::Debug>(result: &BinderResult<T>, want: ErrorCode) {
-    match result {
-        Ok(_) => panic!("Expected KeyMint error {want:?}, found success"),
-        Err(s) => {
-            assert_eq!(
-                s.exception_code(),
-                ExceptionCode::SERVICE_SPECIFIC,
-                "Expected KeyMint service-specific error {want:?}, got {result:?}"
-            );
-            assert_eq!(
-                s.service_specific_error(),
-                want.0,
-                "Expected KeyMint service-specific error {want:?}, got {result:?}"
-            );
+#[macro_export]
+macro_rules! expect_km_error {
+    { $result:expr, $want:expr } => {
+        match $result {
+            Ok(_) => return Err(format!(
+                "{}:{}: Expected KeyMint error {:?}, found success",
+                file!(),
+                line!(),
+                $want
+            ).into()),
+            Err(s) if s.exception_code() == ExceptionCode::SERVICE_SPECIFIC
+                    && s.service_specific_error() == $want.0 => {}
+            Err(e) => return Err(format!(
+                "{}:{}: Expected KeyMint service-specific error {:?}, got {e:?}",
+                file!(),
+                line!(),
+                $want
+            ).into()),
         }
-    }
+
+    };
 }
 
 /// Get the value of the given system property, if the given system property doesn't exist
diff --git a/keystore2/test_utils/run_as.rs b/keystore2/test_utils/run_as.rs
index 2cd9fec..14a72be 100644
--- a/keystore2/test_utils/run_as.rs
+++ b/keystore2/test_utils/run_as.rs
@@ -32,12 +32,104 @@
     fork, pipe as nix_pipe, read as nix_read, setgid, setuid, write as nix_write, ForkResult, Gid,
     Pid, Uid,
 };
-use serde::{de::DeserializeOwned, Serialize};
+use serde::{de::DeserializeOwned, Deserialize, Serialize};
 use std::io::{Read, Write};
 use std::marker::PhantomData;
 use std::os::fd::AsRawFd;
 use std::os::fd::OwnedFd;
 
+/// Newtype string error, which can be serialized and transferred out from a sub-process.
+#[derive(Debug, Deserialize, Serialize, PartialEq, Eq)]
+pub struct Error(pub String);
+
+/// Allow ergonomic use of [`anyhow::Error`].
+impl From<anyhow::Error> for Error {
+    fn from(err: anyhow::Error) -> Self {
+        // Use the debug format of [`anyhow::Error`] to include backtrace.
+        Self(format!("{:?}", err))
+    }
+}
+impl From<String> for Error {
+    fn from(val: String) -> Self {
+        Self(val)
+    }
+}
+impl From<&str> for Error {
+    fn from(val: &str) -> Self {
+        Self(val.to_string())
+    }
+}
+
+impl std::fmt::Display for Error {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        write!(f, "{}", self.0)
+    }
+}
+
+impl std::error::Error for Error {}
+
+/// Equivalent to the [`assert!`] macro which returns an [`Error`] rather than emitting a panic.
+/// This is useful for test code that is `run_as`, so failures are more accessible.
+#[macro_export]
+macro_rules! expect {
+    ($cond:expr $(,)?) => {{
+        let result = $cond;
+        if !result {
+            return Err($crate::run_as::Error(format!(
+                "{}:{}: check '{}' failed",
+                file!(),
+                line!(),
+                stringify!($cond)
+            )));
+        }
+    }};
+    ($cond:expr, $($arg:tt)+) => {{
+        let result = $cond;
+        if !result {
+            return Err($crate::run_as::Error(format!(
+                "{}:{}: check '{}' failed: {}",
+                file!(),
+                line!(),
+                stringify!($cond),
+                format_args!($($arg)+)
+            )));
+        }
+    }};
+}
+
+/// Equivalent to the [`assert_eq!`] macro which returns an [`Error`] rather than emitting a panic.
+/// This is useful for test code that is `run_as`, so failures are more accessible.
+#[macro_export]
+macro_rules! expect_eq {
+    ($left:expr, $right:expr $(,)?) => {{
+        let left = $left;
+        let right = $right;
+        if left != right {
+            return Err($crate::run_as::Error(format!(
+                "{}:{}: assertion {} == {} failed\n  left: {left:?}\n right: {right:?}\n",
+                file!(),
+                line!(),
+                stringify!($left),
+                stringify!($right),
+            )));
+        }
+    }};
+    ($left:expr, $right:expr, $($arg:tt)+) => {{
+        let left = $left;
+        let right = $right;
+        if left != right {
+            return Err($crate::run_as::Error(format!(
+                "{}:{}: assertion {} == {} failed: {}\n  left: {left:?}\n right: {right:?}\n",
+                file!(),
+                line!(),
+                stringify!($left),
+                stringify!($right),
+                format_args!($($arg)+)
+            )));
+        }
+    }};
+}
+
 fn transition(se_context: selinux::Context, uid: Uid, gid: Gid) {
     setgid(gid).expect("Failed to set GID. This test might need more privileges.");
     setuid(uid).expect("Failed to set UID. This test might need more privileges.");
@@ -119,31 +211,48 @@
     /// Receiving blocks until an object of type T has been read from the channel.
     /// Panics if an error occurs during io or deserialization.
     pub fn recv(&mut self) -> T {
+        match self.recv_err() {
+            Ok(val) => val,
+            Err(e) => panic!("{e}"),
+        }
+    }
+
+    /// Receives a serializable object from the corresponding ChannelWriter.
+    /// Receiving blocks until an object of type T has been read from the channel.
+    pub fn recv_err(&mut self) -> Result<T, Error> {
         let mut size_buffer = [0u8; std::mem::size_of::<usize>()];
         match self.0.read(&mut size_buffer).expect("In ChannelReader::recv: Failed to read size.") {
             r if r != size_buffer.len() => {
-                panic!("In ChannelReader::recv: Failed to read size. Insufficient data: {}", r);
+                return Err(format!(
+                    "In ChannelReader::recv: Failed to read size. Insufficient data: {}",
+                    r
+                )
+                .into());
             }
             _ => {}
         };
         let size = usize::from_be_bytes(size_buffer);
         let mut data_buffer = vec![0u8; size];
-        match self
-            .0
-            .read(&mut data_buffer)
-            .expect("In ChannelReader::recv: Failed to read serialized data.")
-        {
-            r if r != data_buffer.len() => {
-                panic!(
+        match self.0.read(&mut data_buffer) {
+            Ok(r) if r != data_buffer.len() => {
+                return Err(format!(
                     "In ChannelReader::recv: Failed to read serialized data. Insufficient data: {}",
                     r
-                );
+                )
+                .into());
             }
-            _ => {}
+            Ok(_) => {}
+            Err(e) => {
+                return Err(format!(
+                    "In ChannelReader::recv: Failed to read serialized data: {e:?}"
+                )
+                .into())
+            }
         };
 
-        serde_cbor::from_slice(&data_buffer)
-            .expect("In ChannelReader::recv: Failed to deserialize data.")
+        serde_cbor::from_slice(&data_buffer).map_err(|e| {
+            format!("In ChannelReader::recv: Failed to deserialize data: {e:?}").into()
+        })
     }
 }
 
@@ -186,6 +295,11 @@
     /// Get child result. Panics if the child did not exit with status 0 or if a serialization
     /// error occurred.
     pub fn get_result(mut self) -> R {
+        self.get_death_result()
+    }
+
+    /// Get child result via a mutable reference.
+    fn get_death_result(&mut self) -> R {
         let status =
             waitpid(self.pid, None).expect("ChildHandle::wait: Failed while waiting for child.");
         match status {
@@ -205,6 +319,31 @@
     }
 }
 
+impl<R, M> ChildHandle<Result<R, Error>, M>
+where
+    R: Serialize + DeserializeOwned,
+    M: Serialize + DeserializeOwned,
+{
+    /// Receive a response from the child.  If the child has closed the response
+    /// channel, assume it has terminated and read the final result.
+    /// Panics on child failure, but will display the child error value.
+    pub fn recv_or_die(&mut self) -> M {
+        match self.response_reader.recv_err() {
+            Ok(v) => v,
+            Err(_e) => {
+                // We have failed to read from the `response_reader` channel.
+                // Assume this is because the child completed early with an error.
+                match self.get_death_result() {
+                    Ok(_) => {
+                        panic!("Child completed OK despite failure to read a response!")
+                    }
+                    Err(e) => panic!("Child failed with:\n{e}"),
+                }
+            }
+        }
+    }
+}
+
 impl<R: Serialize + DeserializeOwned, M: Serialize + DeserializeOwned> Drop for ChildHandle<R, M> {
     fn drop(&mut self) {
         if self.exit_status.is_none() {
diff --git a/keystore2/tests/Android.bp b/keystore2/tests/Android.bp
index ff89493..0406a71 100644
--- a/keystore2/tests/Android.bp
+++ b/keystore2/tests/Android.bp
@@ -49,6 +49,7 @@
         "libaconfig_android_hardware_biometrics_rust",
         "libandroid_logger",
         "libandroid_security_flags_rust",
+        "libanyhow",
         "libbinder_rs",
         "libkeystore2_test_utils",
         "liblog_rust",
diff --git a/keystore2/tests/user_auth.rs b/keystore2/tests/user_auth.rs
index 301f9dc..336af4f 100644
--- a/keystore2/tests/user_auth.rs
+++ b/keystore2/tests/user_auth.rs
@@ -37,9 +37,10 @@
 use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
     Timestamp::Timestamp,
 };
+use anyhow::Context;
 use keystore2_test_utils::{
-    authorizations::AuthSetBuilder, get_keystore_service, run_as,
-    run_as::{ChannelReader, ChannelWriter}, key_generations::assert_km_error,
+    authorizations::AuthSetBuilder, expect, get_keystore_service, run_as,
+    run_as::{ChannelReader, ChannelWriter}, expect_km_error,
 };
 use log::{warn, info};
 use nix::unistd::{Gid, Uid};
@@ -182,7 +183,7 @@
 
     let child_fn = move |reader: &mut ChannelReader<Barrier>,
                          writer: &mut ChannelWriter<Barrier>|
-          -> Result<(), String> {
+          -> Result<(), run_as::Error> {
         // Now we're in a new process, wait to be notified before starting.
         let gk_sid: i64 = match reader.recv().0 {
             Some(sid) => sid,
@@ -197,7 +198,8 @@
         // Action A: create a new auth-bound key which requires auth in the last 3 seconds,
         // and fail to start an operation using it.
         let ks2 = get_keystore_service();
-        let sec_level = ks2.getSecurityLevel(SecurityLevel::TRUSTED_ENVIRONMENT).unwrap();
+        let sec_level =
+            ks2.getSecurityLevel(SecurityLevel::TRUSTED_ENVIRONMENT).context("no TEE")?;
         let params = AuthSetBuilder::new()
             .user_secure_id(gk_sid)
             .user_secure_id(BIO_FAKE_SID1)
@@ -223,13 +225,13 @@
                 0,
                 b"entropy",
             )
-            .expect("key generation failed");
+            .context("key generation failed")?;
         info!("A: created auth-timeout key {key:?}");
 
         // No HATs so cannot create an operation using the key.
         let params = AuthSetBuilder::new().purpose(KeyPurpose::SIGN).digest(Digest::SHA_2_256);
         let result = sec_level.createOperation(&key, &params, UNFORCED);
-        assert_km_error(&result, ErrorCode::KEY_USER_NOT_AUTHENTICATED);
+        expect_km_error!(&result, ErrorCode::KEY_USER_NOT_AUTHENTICATED);
         info!("A: failed auth-bound operation (no HAT) as expected {result:?}");
 
         writer.send(&Barrier::new(None)); // A done.
@@ -238,10 +240,10 @@
         reader.recv();
 
         let result = sec_level.createOperation(&key, &params, UNFORCED);
-        assert!(result.is_ok());
-        let op = result.unwrap().iOperation.expect("no operation in result");
+        expect!(result.is_ok());
+        let op = result.unwrap().iOperation.context("no operation in result")?;
         let result = op.finish(Some(b"data"), None);
-        assert!(result.is_ok());
+        expect!(result.is_ok());
         info!("B: performed auth-bound operation (with valid GK HAT) as expected");
 
         writer.send(&Barrier::new(None)); // B done.
@@ -286,7 +288,7 @@
 
     info!("trigger child process action A and wait for completion");
     child_handle.send(&Barrier::new(Some(user.gk_sid.unwrap())));
-    child_handle.recv();
+    child_handle.recv_or_die();
 
     // Unlock with GK password to get a genuine auth token.
     let real_hat = user.gk_verify(0).expect("failed to perform GK verify");
@@ -294,11 +296,11 @@
 
     info!("trigger child process action B and wait for completion");
     child_handle.send(&Barrier::new(None));
-    child_handle.recv();
+    child_handle.recv_or_die();
 
     info!("trigger child process action C and wait for completion");
     child_handle.send(&Barrier::new(None));
-    child_handle.recv();
+    child_handle.recv_or_die();
 
     assert_eq!(child_handle.get_result(), Ok(()), "child process failed");
 }
@@ -313,7 +315,7 @@
 
     let child_fn = move |reader: &mut ChannelReader<BarrierReached>,
                          writer: &mut ChannelWriter<BarrierReached>|
-          -> Result<(), String> {
+          -> Result<(), run_as::Error> {
         // Now we're in a new process, wait to be notified before starting.
         reader.recv();
 
@@ -321,7 +323,8 @@
         // and fail to start an operation using it.
         let ks2 = get_keystore_service();
 
-        let sec_level = ks2.getSecurityLevel(SecurityLevel::TRUSTED_ENVIRONMENT).unwrap();
+        let sec_level =
+            ks2.getSecurityLevel(SecurityLevel::TRUSTED_ENVIRONMENT).context("no TEE")?;
         let params = AuthSetBuilder::new()
             .user_secure_id(BIO_FAKE_SID1)
             .user_secure_id(BIO_FAKE_SID2)
@@ -346,13 +349,13 @@
                 0,
                 b"entropy",
             )
-            .expect("key generation failed");
+            .context("key generation failed")?;
         info!("A: created auth-timeout key {key:?}");
 
         // No HATs so cannot create an operation using the key.
         let params = AuthSetBuilder::new().purpose(KeyPurpose::SIGN).digest(Digest::SHA_2_256);
         let result = sec_level.createOperation(&key, &params, UNFORCED);
-        assert_km_error(&result, ErrorCode::KEY_USER_NOT_AUTHENTICATED);
+        expect_km_error!(&result, ErrorCode::KEY_USER_NOT_AUTHENTICATED);
         info!("A: failed auth-bound operation (no HAT) as expected {result:?}");
 
         writer.send(&BarrierReached {}); // A done.
@@ -361,7 +364,7 @@
         reader.recv();
 
         let result = sec_level.createOperation(&key, &params, UNFORCED);
-        assert_km_error(&result, ErrorCode::KEY_USER_NOT_AUTHENTICATED);
+        expect_km_error!(&result, ErrorCode::KEY_USER_NOT_AUTHENTICATED);
         info!("B: failed auth-bound operation (HAT is invalid) as expected {result:?}");
 
         writer.send(&BarrierReached {}); // B done.
@@ -371,7 +374,7 @@
         info!("C: wait so that any HAT times out");
         sleep(Duration::from_secs(4));
         let result = sec_level.createOperation(&key, &params, UNFORCED);
-        assert_km_error(&result, ErrorCode::KEY_USER_NOT_AUTHENTICATED);
+        expect_km_error!(&result, ErrorCode::KEY_USER_NOT_AUTHENTICATED);
         info!("C: failed auth-bound operation (HAT is too old) as expected {result:?}");
         writer.send(&BarrierReached {}); // C done.
 
@@ -402,7 +405,7 @@
 
     info!("trigger child process action A and wait for completion");
     child_handle.send(&BarrierReached {});
-    child_handle.recv();
+    child_handle.recv_or_die();
 
     // Unlock with password and a fake auth token that matches the key
     auth_service.onDeviceUnlocked(user_id, Some(SYNTHETIC_PASSWORD)).unwrap();
@@ -410,11 +413,11 @@
 
     info!("trigger child process action B and wait for completion");
     child_handle.send(&BarrierReached {});
-    child_handle.recv();
+    child_handle.recv_or_die();
 
     info!("trigger child process action C and wait for completion");
     child_handle.send(&BarrierReached {});
-    child_handle.recv();
+    child_handle.recv_or_die();
 
     assert_eq!(child_handle.get_result(), Ok(()), "child process failed");
 }
@@ -430,7 +433,7 @@
 
     let child_fn = move |reader: &mut ChannelReader<Barrier>,
                          writer: &mut ChannelWriter<Barrier>|
-          -> Result<(), String> {
+          -> Result<(), run_as::Error> {
         // Now we're in a new process, wait to be notified before starting.
         let gk_sid: i64 = match reader.recv().0 {
             Some(sid) => sid,
@@ -445,7 +448,8 @@
         // Action A: create a new auth-bound key which requires auth-per-operation (because
         // AUTH_TIMEOUT is not specified), and fail to finish an operation using it.
         let ks2 = get_keystore_service();
-        let sec_level = ks2.getSecurityLevel(SecurityLevel::TRUSTED_ENVIRONMENT).unwrap();
+        let sec_level =
+            ks2.getSecurityLevel(SecurityLevel::TRUSTED_ENVIRONMENT).context("no TEE")?;
         let params = AuthSetBuilder::new()
             .user_secure_id(gk_sid)
             .user_secure_id(BIO_FAKE_SID1)
@@ -469,7 +473,7 @@
                 0,
                 b"entropy",
             )
-            .expect("key generation failed");
+            .context("key generation failed")?;
         info!("A: created auth-per-op key {key:?}");
 
         // We can create an operation using the key...
@@ -477,12 +481,12 @@
         let result = sec_level
             .createOperation(&key, &params, UNFORCED)
             .expect("failed to create auth-per-op operation");
-        let op = result.iOperation.expect("no operation in result");
+        let op = result.iOperation.context("no operation in result")?;
         info!("A: created auth-per-op operation, got challenge {:?}", result.operationChallenge);
 
         // .. but attempting to finish the operation fails because Keystore can't find a HAT.
         let result = op.finish(Some(b"data"), None);
-        assert_km_error(&result, ErrorCode::KEY_USER_NOT_AUTHENTICATED);
+        expect_km_error!(&result, ErrorCode::KEY_USER_NOT_AUTHENTICATED);
         info!("A: failed auth-per-op op (no HAT) as expected {result:?}");
 
         writer.send(&Barrier::new(None)); // A done.
@@ -492,14 +496,14 @@
         let result = sec_level
             .createOperation(&key, &params, UNFORCED)
             .expect("failed to create auth-per-op operation");
-        let op = result.iOperation.expect("no operation in result");
+        let op = result.iOperation.context("no operation in result")?;
         info!("B: created auth-per-op operation, got challenge {:?}", result.operationChallenge);
         writer.send(&Barrier::new(Some(result.operationChallenge.unwrap().challenge))); // B done.
 
         // Action C: finishing the operation succeeds now there's a per-op HAT.
         reader.recv();
         let result = op.finish(Some(b"data"), None);
-        assert!(result.is_ok());
+        expect!(result.is_ok());
         info!("C: performed auth-per-op op expected");
         writer.send(&Barrier::new(None)); // D done.
 
@@ -535,11 +539,11 @@
 
     info!("trigger child process action A and wait for completion");
     child_handle.send(&Barrier::new(Some(user.gk_sid.unwrap())));
-    child_handle.recv();
+    child_handle.recv_or_die();
 
     info!("trigger child process action B and wait for completion");
     child_handle.send(&Barrier::new(None));
-    let challenge = child_handle.recv().0.expect("no challenge");
+    let challenge = child_handle.recv_or_die().0.expect("no challenge");
 
     // Unlock with GK and the challenge to get a genuine per-op auth token
     let real_hat = user.gk_verify(challenge).expect("failed to perform GK verify");
@@ -547,7 +551,7 @@
 
     info!("trigger child process action C and wait for completion");
     child_handle.send(&Barrier::new(None));
-    child_handle.recv();
+    child_handle.recv_or_die();
 
     assert_eq!(child_handle.get_result(), Ok(()), "child process failed");
 }
@@ -563,7 +567,7 @@
 
     let child_fn = move |reader: &mut ChannelReader<Barrier>,
                          writer: &mut ChannelWriter<Barrier>|
-          -> Result<(), String> {
+          -> Result<(), run_as::Error> {
         // Now we're in a new process, wait to be notified before starting.
         reader.recv();
 
@@ -571,7 +575,8 @@
         // AUTH_TIMEOUT is not specified), and fail to finish an operation using it.
         let ks2 = get_keystore_service();
 
-        let sec_level = ks2.getSecurityLevel(SecurityLevel::TRUSTED_ENVIRONMENT).unwrap();
+        let sec_level =
+            ks2.getSecurityLevel(SecurityLevel::TRUSTED_ENVIRONMENT).context("no TEE")?;
         let params = AuthSetBuilder::new()
             .user_secure_id(GK_FAKE_SID)
             .user_secure_id(BIO_FAKE_SID1)
@@ -595,7 +600,7 @@
                 0,
                 b"entropy",
             )
-            .expect("key generation failed");
+            .context("key generation failed")?;
         info!("A: created auth-per-op key {key:?}");
 
         // We can create an operation using the key...
@@ -603,12 +608,12 @@
         let result = sec_level
             .createOperation(&key, &params, UNFORCED)
             .expect("failed to create auth-per-op operation");
-        let op = result.iOperation.expect("no operation in result");
+        let op = result.iOperation.context("no operation in result")?;
         info!("A: created auth-per-op operation, got challenge {:?}", result.operationChallenge);
 
         // .. but attempting to finish the operation fails because Keystore can't find a HAT.
         let result = op.finish(Some(b"data"), None);
-        assert_km_error(&result, ErrorCode::KEY_USER_NOT_AUTHENTICATED);
+        expect_km_error!(&result, ErrorCode::KEY_USER_NOT_AUTHENTICATED);
         info!("A: failed auth-per-op op (no HAT) as expected {result:?}");
 
         writer.send(&Barrier::new(0)); // A done.
@@ -619,12 +624,12 @@
         let result = sec_level
             .createOperation(&key, &params, UNFORCED)
             .expect("failed to create auth-per-op operation");
-        let op = result.iOperation.expect("no operation in result");
+        let op = result.iOperation.context("no operation in result")?;
         info!("B: created auth-per-op operation, got challenge {:?}", result.operationChallenge);
         // The operation fails because the HAT that Keystore received is not related to the
         // challenge.
         let result = op.finish(Some(b"data"), None);
-        assert_km_error(&result, ErrorCode::KEY_USER_NOT_AUTHENTICATED);
+        expect_km_error!(&result, ErrorCode::KEY_USER_NOT_AUTHENTICATED);
         info!("B: failed auth-per-op op (HAT is not per-op) as expected {result:?}");
 
         writer.send(&Barrier::new(0)); // B done.
@@ -634,7 +639,7 @@
         let result = sec_level
             .createOperation(&key, &params, UNFORCED)
             .expect("failed to create auth-per-op operation");
-        let op = result.iOperation.expect("no operation in result");
+        let op = result.iOperation.context("no operation in result")?;
         info!("C: created auth-per-op operation, got challenge {:?}", result.operationChallenge);
         writer.send(&Barrier::new(result.operationChallenge.unwrap().challenge)); // C done.
 
@@ -643,7 +648,7 @@
         // rejects the HAT).
         reader.recv();
         let result = op.finish(Some(b"data"), None);
-        assert_km_error(&result, ErrorCode::KEY_USER_NOT_AUTHENTICATED);
+        expect_km_error!(&result, ErrorCode::KEY_USER_NOT_AUTHENTICATED);
         info!("D: failed auth-per-op op (HAT is per-op but invalid) as expected {result:?}");
         writer.send(&Barrier::new(0)); // D done.
 
@@ -674,7 +679,7 @@
 
     info!("trigger child process action A and wait for completion");
     child_handle.send(&Barrier::new(0));
-    child_handle.recv();
+    child_handle.recv_or_die();
 
     // Unlock with password and a fake auth token.
     auth_service.onDeviceUnlocked(user_id, Some(SYNTHETIC_PASSWORD)).unwrap();
@@ -682,18 +687,18 @@
 
     info!("trigger child process action B and wait for completion");
     child_handle.send(&Barrier::new(0));
-    child_handle.recv();
+    child_handle.recv_or_die();
 
     info!("trigger child process action C and wait for completion");
     child_handle.send(&Barrier::new(0));
-    let challenge = child_handle.recv().0;
+    let challenge = child_handle.recv_or_die().0;
 
     // Add a fake auth token with the challenge value.
     auth_service.addAuthToken(&fake_lskf_token_with_challenge(GK_FAKE_SID, challenge)).unwrap();
 
     info!("trigger child process action D and wait for completion");
     child_handle.send(&Barrier::new(0));
-    child_handle.recv();
+    child_handle.recv_or_die();
 
     assert_eq!(child_handle.get_result(), Ok(()), "child process failed");
 }
@@ -708,7 +713,7 @@
 
     let child_fn = move |reader: &mut ChannelReader<BarrierReached>,
                          writer: &mut ChannelWriter<BarrierReached>|
-          -> Result<(), String> {
+          -> Result<(), run_as::Error> {
         let ks2 = get_keystore_service();
         if ks2.getInterfaceVersion().unwrap() < 4 {
             // Assuming `IKeystoreAuthorization::onDeviceLocked` and
@@ -722,7 +727,8 @@
 
         // Action A: create a new unlocked-device-required key (which thus requires
         // super-encryption), while the device is unlocked.
-        let sec_level = ks2.getSecurityLevel(SecurityLevel::TRUSTED_ENVIRONMENT).unwrap();
+        let sec_level =
+            ks2.getSecurityLevel(SecurityLevel::TRUSTED_ENVIRONMENT).context("no TEE")?;
         let params = AuthSetBuilder::new()
             .no_auth_required()
             .unlocked_device_required()
@@ -745,7 +751,7 @@
                 0,
                 b"entropy",
             )
-            .expect("key generation failed");
+            .context("key generation failed")?;
         info!("A: created unlocked-device-required key while unlocked {key:?}");
         writer.send(&BarrierReached {}); // A done.
 
@@ -754,7 +760,7 @@
         let params = AuthSetBuilder::new().purpose(KeyPurpose::SIGN).digest(Digest::SHA_2_256);
         let result = sec_level.createOperation(&key, &params, UNFORCED);
         info!("B: use unlocked-device-required key while locked => {result:?}");
-        assert_km_error(&result, ErrorCode::DEVICE_LOCKED);
+        expect_km_error!(&result, ErrorCode::DEVICE_LOCKED);
         writer.send(&BarrierReached {}); // B done.
 
         // Action C: try to use the unlocked-device-required key while unlocked with a
@@ -762,7 +768,7 @@
         reader.recv();
         let result = sec_level.createOperation(&key, &params, UNFORCED);
         info!("C: use unlocked-device-required key while lskf-unlocked => {result:?}");
-        assert!(result.is_ok(), "failed with {result:?}");
+        expect!(result.is_ok(), "failed with {result:?}");
         abort_op(result);
         writer.send(&BarrierReached {}); // C done.
 
@@ -771,7 +777,7 @@
         reader.recv();
         let result = sec_level.createOperation(&key, &params, UNFORCED);
         info!("D: use unlocked-device-required key while weak-locked => {result:?}");
-        assert!(result.is_ok(), "createOperation failed: {result:?}");
+        expect!(result.is_ok(), "createOperation failed: {result:?}");
         abort_op(result);
         writer.send(&BarrierReached {}); // D done.
 
@@ -808,7 +814,7 @@
 
     info!("trigger child process action A while unlocked and wait for completion");
     child_handle.send(&BarrierReached {});
-    child_handle.recv();
+    child_handle.recv_or_die();
 
     // Move to locked and don't allow weak unlock, so super keys are wiped.
     auth_service
@@ -817,7 +823,7 @@
 
     info!("trigger child process action B while locked and wait for completion");
     child_handle.send(&BarrierReached {});
-    child_handle.recv();
+    child_handle.recv_or_die();
 
     // Unlock with password => loads super key from database.
     auth_service.onDeviceUnlocked(user_id, Some(SYNTHETIC_PASSWORD)).unwrap();
@@ -825,7 +831,7 @@
 
     info!("trigger child process action C while lskf-unlocked and wait for completion");
     child_handle.send(&BarrierReached {});
-    child_handle.recv();
+    child_handle.recv_or_die();
 
     // Move to locked and allow weak unlock, then do a weak unlock.
     auth_service
@@ -835,7 +841,7 @@
 
     info!("trigger child process action D while weak-unlocked and wait for completion");
     child_handle.send(&BarrierReached {});
-    child_handle.recv();
+    child_handle.recv_or_die();
 
     assert_eq!(child_handle.get_result(), Ok(()), "child process failed");
 }