Merge "Skip CSR generation for AVF RKP HAL when it is not supported" into main
diff --git a/keystore2/legacykeystore/lib.rs b/keystore2/legacykeystore/lib.rs
index d407416..41b8685 100644
--- a/keystore2/legacykeystore/lib.rs
+++ b/keystore2/legacykeystore/lib.rs
@@ -210,41 +210,25 @@
     }
 }
 
-/// This function should be used by legacykeystore service calls to translate error conditions
-/// into service specific exceptions.
+/// Translate errors into service specific exceptions.
 ///
-/// All error conditions get logged by this function, except for ERROR_ENTRY_NOT_FOUND error.
-///
-/// `Error::Error(x)` variants get mapped onto a service specific error code of `x`.
-///
-/// All non `Error` error conditions get mapped onto `ERROR_SYSTEM_ERROR`.
-///
-/// `handle_ok` will be called if `result` is `Ok(value)` where `value` will be passed
-/// as argument to `handle_ok`. `handle_ok` must generate a `BinderResult<T>`, but it
-/// typically returns Ok(value).
-fn map_or_log_err<T, U, F>(result: Result<U>, handle_ok: F) -> BinderResult<T>
-where
-    F: FnOnce(U) -> BinderResult<T>,
-{
-    result.map_or_else(
-        |e| {
-            let root_cause = e.root_cause();
-            let (rc, log_error) = match root_cause.downcast_ref::<Error>() {
-                // Make the entry not found errors silent.
-                Some(Error::Error(ERROR_ENTRY_NOT_FOUND)) => (ERROR_ENTRY_NOT_FOUND, false),
-                Some(Error::Error(e)) => (*e, true),
-                Some(Error::Binder(_, _)) | None => (ERROR_SYSTEM_ERROR, true),
-            };
-            if log_error {
-                log::error!("{:?}", e);
-            }
-            Err(BinderStatus::new_service_specific_error(
-                rc,
-                anyhow_error_to_cstring(&e).as_deref(),
-            ))
-        },
-        handle_ok,
-    )
+/// All errors are logged, except for ERROR_ENTRY_NOT_FOUND error.  `Error::Error(x)` variants get
+/// mapped onto a service specific error code of `x`, other errors are mapped to
+/// `ERROR_SYSTEM_ERROR`.
+fn map_or_log_err<T>(result: Result<T>) -> BinderResult<T> {
+    result.map_err(|e| {
+        let root_cause = e.root_cause();
+        let (rc, log_error) = match root_cause.downcast_ref::<Error>() {
+            // Make the entry not found errors silent.
+            Some(Error::Error(ERROR_ENTRY_NOT_FOUND)) => (ERROR_ENTRY_NOT_FOUND, false),
+            Some(Error::Error(e)) => (*e, true),
+            Some(Error::Binder(_, _)) | None => (ERROR_SYSTEM_ERROR, true),
+        };
+        if log_error {
+            log::error!("{:?}", e);
+        }
+        BinderStatus::new_service_specific_error(rc, anyhow_error_to_cstring(&e).as_deref())
+    })
 }
 
 fn ensure_keystore_put_is_enabled() -> Result<()> {
@@ -552,19 +536,19 @@
 impl ILegacyKeystore for LegacyKeystoreService {
     fn get(&self, alias: &str, uid: i32) -> BinderResult<Vec<u8>> {
         let _wp = wd::watch("ILegacyKeystore::get");
-        map_or_log_err(self.legacy_keystore.get(alias, uid), Ok)
+        map_or_log_err(self.legacy_keystore.get(alias, uid))
     }
     fn put(&self, alias: &str, uid: i32, entry: &[u8]) -> BinderResult<()> {
         let _wp = wd::watch("ILegacyKeystore::put");
-        map_or_log_err(self.legacy_keystore.put(alias, uid, entry), Ok)
+        map_or_log_err(self.legacy_keystore.put(alias, uid, entry))
     }
     fn remove(&self, alias: &str, uid: i32) -> BinderResult<()> {
         let _wp = wd::watch("ILegacyKeystore::remove");
-        map_or_log_err(self.legacy_keystore.remove(alias, uid), Ok)
+        map_or_log_err(self.legacy_keystore.remove(alias, uid))
     }
     fn list(&self, prefix: &str, uid: i32) -> BinderResult<Vec<String>> {
         let _wp = wd::watch("ILegacyKeystore::list");
-        map_or_log_err(self.legacy_keystore.list(prefix, uid), Ok)
+        map_or_log_err(self.legacy_keystore.list(prefix, uid))
     }
 }
 
diff --git a/keystore2/src/apc.rs b/keystore2/src/apc.rs
index bdde5ae..8fda1f2 100644
--- a/keystore2/src/apc.rs
+++ b/keystore2/src/apc.rs
@@ -82,33 +82,20 @@
 /// `selinux::Error::perm()` is mapped on `ResponseCode::PERMISSION_DENIED`.
 ///
 /// All non `Error` error conditions get mapped onto ResponseCode::SYSTEM_ERROR`.
-///
-/// `handle_ok` will be called if `result` is `Ok(value)` where `value` will be passed
-/// as argument to `handle_ok`. `handle_ok` must generate a `BinderResult<T>`, but it
-/// typically returns Ok(value).
-pub fn map_or_log_err<T, U, F>(result: Result<U>, handle_ok: F) -> BinderResult<T>
-where
-    F: FnOnce(U) -> BinderResult<T>,
-{
-    result.map_or_else(
-        |e| {
-            log::error!("{:#?}", e);
-            let root_cause = e.root_cause();
-            let rc = match root_cause.downcast_ref::<Error>() {
-                Some(Error::Rc(rcode)) => rcode.0,
-                Some(Error::Binder(_, _)) => ResponseCode::SYSTEM_ERROR.0,
-                None => match root_cause.downcast_ref::<selinux::Error>() {
-                    Some(selinux::Error::PermissionDenied) => ResponseCode::PERMISSION_DENIED.0,
-                    _ => ResponseCode::SYSTEM_ERROR.0,
-                },
-            };
-            Err(BinderStatus::new_service_specific_error(
-                rc,
-                anyhow_error_to_cstring(&e).as_deref(),
-            ))
-        },
-        handle_ok,
-    )
+pub fn map_or_log_err<T>(result: Result<T>) -> BinderResult<T> {
+    result.map_err(|e| {
+        log::error!("{:#?}", e);
+        let root_cause = e.root_cause();
+        let rc = match root_cause.downcast_ref::<Error>() {
+            Some(Error::Rc(rcode)) => rcode.0,
+            Some(Error::Binder(_, _)) => ResponseCode::SYSTEM_ERROR.0,
+            None => match root_cause.downcast_ref::<selinux::Error>() {
+                Some(selinux::Error::PermissionDenied) => ResponseCode::PERMISSION_DENIED.0,
+                _ => ResponseCode::SYSTEM_ERROR.0,
+            },
+        };
+        BinderStatus::new_service_specific_error(rc, anyhow_error_to_cstring(&e).as_deref())
+    })
 }
 
 /// Rate info records how many failed attempts a client has made to display a protected
@@ -354,20 +341,23 @@
     ) -> BinderResult<()> {
         // presentPrompt can take more time than other operations.
         let _wp = wd::watch_millis("IProtectedConfirmation::presentPrompt", 3000);
-        map_or_log_err(
-            self.present_prompt(listener, prompt_text, extra_data, locale, ui_option_flags),
-            Ok,
-        )
+        map_or_log_err(self.present_prompt(
+            listener,
+            prompt_text,
+            extra_data,
+            locale,
+            ui_option_flags,
+        ))
     }
     fn cancelPrompt(
         &self,
         listener: &binder::Strong<dyn IConfirmationCallback>,
     ) -> BinderResult<()> {
         let _wp = wd::watch("IProtectedConfirmation::cancelPrompt");
-        map_or_log_err(self.cancel_prompt(listener), Ok)
+        map_or_log_err(self.cancel_prompt(listener))
     }
     fn isSupported(&self) -> BinderResult<bool> {
         let _wp = wd::watch("IProtectedConfirmation::isSupported");
-        map_or_log_err(Self::is_supported(), Ok)
+        map_or_log_err(Self::is_supported())
     }
 }
diff --git a/keystore2/src/authorization.rs b/keystore2/src/authorization.rs
index 5810c35..4636a66 100644
--- a/keystore2/src/authorization.rs
+++ b/keystore2/src/authorization.rs
@@ -64,38 +64,27 @@
 /// `selinux::Error::perm()` is mapped on `ResponseCode::PERMISSION_DENIED`.
 ///
 /// All non `Error` error conditions get mapped onto ResponseCode::SYSTEM_ERROR`.
-///
-/// `handle_ok` will be called if `result` is `Ok(value)` where `value` will be passed
-/// as argument to `handle_ok`. `handle_ok` must generate a `BinderResult<T>`, but it
-/// typically returns Ok(value).
-pub fn map_or_log_err<T, U, F>(result: Result<U>, handle_ok: F) -> BinderResult<T>
-where
-    F: FnOnce(U) -> BinderResult<T>,
-{
-    result.map_or_else(
-        |e| {
-            log::error!("{:#?}", e);
-            let root_cause = e.root_cause();
-            if let Some(KeystoreError::Rc(ks_rcode)) = root_cause.downcast_ref::<KeystoreError>() {
-                let rc = match *ks_rcode {
-                    // Although currently keystore2/ResponseCode.aidl and
-                    // authorization/ResponseCode.aidl share the same integer values for the
-                    // common response codes, this may deviate in the future, hence the
-                    // conversion here.
-                    KsResponseCode::SYSTEM_ERROR => ResponseCode::SYSTEM_ERROR.0,
-                    KsResponseCode::KEY_NOT_FOUND => ResponseCode::KEY_NOT_FOUND.0,
-                    KsResponseCode::VALUE_CORRUPTED => ResponseCode::VALUE_CORRUPTED.0,
-                    KsResponseCode::INVALID_ARGUMENT => ResponseCode::INVALID_ARGUMENT.0,
-                    // If the code paths of IKeystoreAuthorization aidl's methods happen to return
-                    // other error codes from KsResponseCode in the future, they should be converted
-                    // as well.
-                    _ => ResponseCode::SYSTEM_ERROR.0,
-                };
-                return Err(BinderStatus::new_service_specific_error(
-                    rc,
-                    anyhow_error_to_cstring(&e).as_deref(),
-                ));
-            }
+pub fn map_or_log_err<T>(result: Result<T>) -> BinderResult<T> {
+    result.map_err(|e| {
+        log::error!("{:#?}", e);
+        let root_cause = e.root_cause();
+        if let Some(KeystoreError::Rc(ks_rcode)) = root_cause.downcast_ref::<KeystoreError>() {
+            let rc = match *ks_rcode {
+                // Although currently keystore2/ResponseCode.aidl and
+                // authorization/ResponseCode.aidl share the same integer values for the
+                // common response codes, this may deviate in the future, hence the
+                // conversion here.
+                KsResponseCode::SYSTEM_ERROR => ResponseCode::SYSTEM_ERROR.0,
+                KsResponseCode::KEY_NOT_FOUND => ResponseCode::KEY_NOT_FOUND.0,
+                KsResponseCode::VALUE_CORRUPTED => ResponseCode::VALUE_CORRUPTED.0,
+                KsResponseCode::INVALID_ARGUMENT => ResponseCode::INVALID_ARGUMENT.0,
+                // If the code paths of IKeystoreAuthorization aidl's methods happen to return
+                // other error codes from KsResponseCode in the future, they should be converted
+                // as well.
+                _ => ResponseCode::SYSTEM_ERROR.0,
+            };
+            BinderStatus::new_service_specific_error(rc, anyhow_error_to_cstring(&e).as_deref())
+        } else {
             let rc = match root_cause.downcast_ref::<Error>() {
                 Some(Error::Rc(rcode)) => rcode.0,
                 Some(Error::Binder(_, _)) => ResponseCode::SYSTEM_ERROR.0,
@@ -104,13 +93,9 @@
                     _ => ResponseCode::SYSTEM_ERROR.0,
                 },
             };
-            Err(BinderStatus::new_service_specific_error(
-                rc,
-                anyhow_error_to_cstring(&e).as_deref(),
-            ))
-        },
-        handle_ok,
-    )
+            BinderStatus::new_service_specific_error(rc, anyhow_error_to_cstring(&e).as_deref())
+        }
+    })
 }
 
 /// This struct is defined to implement the aforementioned AIDL interface.
@@ -272,12 +257,12 @@
 impl IKeystoreAuthorization for AuthorizationManager {
     fn addAuthToken(&self, auth_token: &HardwareAuthToken) -> BinderResult<()> {
         let _wp = wd::watch("IKeystoreAuthorization::addAuthToken");
-        map_or_log_err(self.add_auth_token(auth_token), Ok)
+        map_or_log_err(self.add_auth_token(auth_token))
     }
 
     fn onDeviceUnlocked(&self, user_id: i32, password: Option<&[u8]>) -> BinderResult<()> {
         let _wp = wd::watch("IKeystoreAuthorization::onDeviceUnlocked");
-        map_or_log_err(self.on_device_unlocked(user_id, password.map(|pw| pw.into())), Ok)
+        map_or_log_err(self.on_device_unlocked(user_id, password.map(|pw| pw.into())))
     }
 
     fn onDeviceLocked(
@@ -287,17 +272,17 @@
         weak_unlock_enabled: bool,
     ) -> BinderResult<()> {
         let _wp = wd::watch("IKeystoreAuthorization::onDeviceLocked");
-        map_or_log_err(self.on_device_locked(user_id, unlocking_sids, weak_unlock_enabled), Ok)
+        map_or_log_err(self.on_device_locked(user_id, unlocking_sids, weak_unlock_enabled))
     }
 
     fn onWeakUnlockMethodsExpired(&self, user_id: i32) -> BinderResult<()> {
         let _wp = wd::watch("IKeystoreAuthorization::onWeakUnlockMethodsExpired");
-        map_or_log_err(self.on_weak_unlock_methods_expired(user_id), Ok)
+        map_or_log_err(self.on_weak_unlock_methods_expired(user_id))
     }
 
     fn onNonLskfUnlockMethodsExpired(&self, user_id: i32) -> BinderResult<()> {
         let _wp = wd::watch("IKeystoreAuthorization::onNonLskfUnlockMethodsExpired");
-        map_or_log_err(self.on_non_lskf_unlock_methods_expired(user_id), Ok)
+        map_or_log_err(self.on_non_lskf_unlock_methods_expired(user_id))
     }
 
     fn getAuthTokensForCredStore(
@@ -307,14 +292,11 @@
         auth_token_max_age_millis: i64,
     ) -> binder::Result<AuthorizationTokens> {
         let _wp = wd::watch("IKeystoreAuthorization::getAuthTokensForCredStore");
-        map_or_log_err(
-            self.get_auth_tokens_for_credstore(
-                challenge,
-                secure_user_id,
-                auth_token_max_age_millis,
-            ),
-            Ok,
-        )
+        map_or_log_err(self.get_auth_tokens_for_credstore(
+            challenge,
+            secure_user_id,
+            auth_token_max_age_millis,
+        ))
     }
 
     fn getLastAuthTime(
@@ -323,7 +305,7 @@
         auth_types: &[HardwareAuthenticatorType],
     ) -> binder::Result<i64> {
         if aconfig_android_hardware_biometrics_rust::last_authentication_time() {
-            map_or_log_err(self.get_last_auth_time(secure_user_id, auth_types), Ok)
+            map_or_log_err(self.get_last_auth_time(secure_user_id, auth_types))
         } else {
             Err(BinderStatus::new_service_specific_error(
                 ResponseCode::PERMISSION_DENIED.0,
diff --git a/keystore2/src/error.rs b/keystore2/src/error.rs
index f0d0d27..b9a2291 100644
--- a/keystore2/src/error.rs
+++ b/keystore2/src/error.rs
@@ -167,42 +167,17 @@
 /// into service specific exceptions.
 ///
 /// All error conditions get logged by this function, except for KEY_NOT_FOUND error.
-///
-/// `handle_ok` will be called if `result` is `Ok(value)` where `value` will be passed
-/// as argument to `handle_ok`. `handle_ok` must generate a `BinderResult<T>`, but it
-/// typically returns Ok(value).
-///
-/// # Examples
-///
-/// ```
-/// fn loadKey() -> anyhow::Result<Vec<u8>> {
-///     if (good_but_auth_required) {
-///         Ok(vec!['k', 'e', 'y'])
-///     } else {
-///         Err(anyhow!(Error::Rc(ResponseCode::KEY_NOT_FOUND)))
-///     }
-/// }
-///
-/// map_or_log_err(loadKey(), Ok)
-/// ```
-pub fn map_or_log_err<T, U, F>(result: anyhow::Result<U>, handle_ok: F) -> BinderResult<T>
-where
-    F: FnOnce(U) -> BinderResult<T>,
-{
-    map_err_with(
-        result,
-        |e| {
-            // Make the key not found errors silent.
-            if !matches!(
-                e.root_cause().downcast_ref::<Error>(),
-                Some(Error::Rc(ResponseCode::KEY_NOT_FOUND))
-            ) {
-                log::error!("{:?}", e);
-            }
-            e
-        },
-        handle_ok,
-    )
+pub fn map_or_log_err<T>(result: anyhow::Result<T>) -> BinderResult<T> {
+    map_err_with(result, |e| {
+        // Make the key not found errors silent.
+        if !matches!(
+            e.root_cause().downcast_ref::<Error>(),
+            Some(Error::Rc(ResponseCode::KEY_NOT_FOUND))
+        ) {
+            log::error!("{:?}", e);
+        }
+        e
+    })
 }
 
 /// This function turns an anyhow error into an optional CString.
@@ -222,26 +197,15 @@
 /// This function behaves similar to map_or_log_error, but it does not log the errors, instead
 /// it calls map_err on the error before mapping it to a binder result allowing callers to
 /// log or transform the error before mapping it.
-pub fn map_err_with<T, U, F1, F2>(
-    result: anyhow::Result<U>,
-    map_err: F1,
-    handle_ok: F2,
-) -> BinderResult<T>
+pub fn map_err_with<T, F1>(result: anyhow::Result<T>, map_err: F1) -> BinderResult<T>
 where
     F1: FnOnce(anyhow::Error) -> anyhow::Error,
-    F2: FnOnce(U) -> BinderResult<T>,
 {
-    result.map_or_else(
-        |e| {
-            let e = map_err(e);
-            let rc = anyhow_error_to_serialized_error(&e);
-            Err(BinderStatus::new_service_specific_error(
-                rc.0,
-                anyhow_error_to_cstring(&e).as_deref(),
-            ))
-        },
-        handle_ok,
-    )
+    result.map_err(|e| {
+        let e = map_err(e);
+        let rc = anyhow_error_to_serialized_error(&e);
+        BinderStatus::new_service_specific_error(rc.0, anyhow_error_to_cstring(&e).as_deref())
+    })
 }
 
 /// This type is used to send error codes on the wire.
@@ -359,8 +323,7 @@
         for rc in ResponseCode::LOCKED.0..ResponseCode::BACKEND_BUSY.0 {
             assert_eq!(
                 Result::<(), i32>::Err(rc),
-                map_or_log_err(nested_rc(ResponseCode(rc)), |_| Err(BinderStatus::ok()))
-                    .map_err(|s| s.service_specific_error())
+                map_or_log_err(nested_rc(ResponseCode(rc))).map_err(|s| s.service_specific_error())
             );
         }
 
@@ -369,8 +332,7 @@
         for ec in ErrorCode::UNKNOWN_ERROR.0..ErrorCode::ROOT_OF_TRUST_ALREADY_SET.0 {
             assert_eq!(
                 Result::<(), i32>::Err(ec),
-                map_or_log_err(nested_ec(ErrorCode(ec)), |_| Err(BinderStatus::ok()))
-                    .map_err(|s| s.service_specific_error())
+                map_or_log_err(nested_ec(ErrorCode(ec))).map_err(|s| s.service_specific_error())
             );
         }
 
@@ -381,8 +343,7 @@
                 Result::<(), i32>::Err(ec),
                 map_or_log_err(
                     map_km_error(binder_sse_error(ec))
-                        .with_context(|| format!("Km error code: {}.", ec)),
-                    |_| Err(BinderStatus::ok())
+                        .with_context(|| format!("Km error code: {}.", ec))
                 )
                 .map_err(|s| s.service_specific_error())
             );
@@ -396,10 +357,8 @@
         // map_or_log_err then maps it on a service specific error of ResponseCode::SYSTEM_ERROR.
         assert_eq!(
             Result::<(), ResponseCode>::Err(ResponseCode::SYSTEM_ERROR),
-            map_or_log_err(sse.context("Non negative service specific error."), |_| Err(
-                BinderStatus::ok()
-            ))
-            .map_err(|s| ResponseCode(s.service_specific_error()))
+            map_or_log_err(sse.context("Non negative service specific error."))
+                .map_err(|s| ResponseCode(s.service_specific_error()))
         );
 
         // map_km_error creates a Error::Binder variant storing the given exception code.
@@ -408,31 +367,29 @@
         // map_or_log_err then maps it on a service specific error of ResponseCode::SYSTEM_ERROR.
         assert_eq!(
             Result::<(), ResponseCode>::Err(ResponseCode::SYSTEM_ERROR),
-            map_or_log_err(binder_exception.context("Binder Exception."), |_| Err(
-                BinderStatus::ok()
-            ))
-            .map_err(|s| ResponseCode(s.service_specific_error()))
+            map_or_log_err(binder_exception.context("Binder Exception."))
+                .map_err(|s| ResponseCode(s.service_specific_error()))
         );
 
         // selinux::Error::Perm() needs to be mapped to ResponseCode::PERMISSION_DENIED
         assert_eq!(
             Result::<(), ResponseCode>::Err(ResponseCode::PERMISSION_DENIED),
-            map_or_log_err(nested_selinux_perm(), |_| Err(BinderStatus::ok()))
+            map_or_log_err(nested_selinux_perm())
                 .map_err(|s| ResponseCode(s.service_specific_error()))
         );
 
         // All other errors get mapped on System Error.
         assert_eq!(
             Result::<(), ResponseCode>::Err(ResponseCode::SYSTEM_ERROR),
-            map_or_log_err(nested_other_error(), |_| Err(BinderStatus::ok()))
+            map_or_log_err(nested_other_error())
                 .map_err(|s| ResponseCode(s.service_specific_error()))
         );
 
         // Result::Ok variants get passed to the ok handler.
-        assert_eq!(Ok(ResponseCode::LOCKED), map_or_log_err(nested_ok(ResponseCode::LOCKED), Ok));
+        assert_eq!(Ok(ResponseCode::LOCKED), map_or_log_err(nested_ok(ResponseCode::LOCKED)));
         assert_eq!(
             Ok(ResponseCode::SYSTEM_ERROR),
-            map_or_log_err(nested_ok(ResponseCode::SYSTEM_ERROR), Ok)
+            map_or_log_err(nested_ok(ResponseCode::SYSTEM_ERROR))
         );
 
         Ok(())
diff --git a/keystore2/src/globals.rs b/keystore2/src/globals.rs
index 2d5c20a..c7b495d 100644
--- a/keystore2/src/globals.rs
+++ b/keystore2/src/globals.rs
@@ -44,8 +44,8 @@
 };
 use android_security_compat::aidl::android::security::compat::IKeystoreCompatService::IKeystoreCompatService;
 use anyhow::{Context, Result};
-use binder::get_declared_instances;
 use binder::FromIBinder;
+use binder::{get_declared_instances, is_declared};
 use lazy_static::lazy_static;
 use std::sync::{Arc, Mutex, RwLock};
 use std::{cell::RefCell, sync::Once};
@@ -420,19 +420,20 @@
 pub fn get_remotely_provisioned_component_name(security_level: &SecurityLevel) -> Result<String> {
     let remote_prov_descriptor: &str =
         <BpRemotelyProvisionedComponent as IRemotelyProvisionedComponent>::get_descriptor();
-    let remotely_prov_instances = get_declared_instances(remote_prov_descriptor).unwrap();
 
     match *security_level {
         SecurityLevel::TRUSTED_ENVIRONMENT => {
-            if remotely_prov_instances.iter().any(|instance| *instance == "default") {
-                Some(format!("{}/default", remote_prov_descriptor))
+            let instance = format!("{}/default", remote_prov_descriptor);
+            if is_declared(&instance)? {
+                Some(instance)
             } else {
                 None
             }
         }
         SecurityLevel::STRONGBOX => {
-            if remotely_prov_instances.iter().any(|instance| *instance == "strongbox") {
-                Some(format!("{}/strongbox", remote_prov_descriptor))
+            let instance = format!("{}/strongbox", remote_prov_descriptor);
+            if is_declared(&instance)? {
+                Some(instance)
             } else {
                 None
             }
diff --git a/keystore2/src/km_compat.rs b/keystore2/src/km_compat.rs
index 03c9d02..02bcb1a 100644
--- a/keystore2/src/km_compat.rs
+++ b/keystore2/src/km_compat.rs
@@ -226,7 +226,7 @@
     ) -> binder::Result<KeyCreationResult> {
         if self.emu.emulation_required(key_params, &KeyImportData::None) {
             let mut result = self.soft.generateKey(key_params, attestation_key)?;
-            result.keyBlob = map_or_log_err(wrap_keyblob(&result.keyBlob), Ok)?;
+            result.keyBlob = map_or_log_err(wrap_keyblob(&result.keyBlob))?;
             Ok(result)
         } else {
             self.real.generateKey(key_params, attestation_key)
@@ -242,7 +242,7 @@
         if self.emu.emulation_required(key_params, &KeyImportData::new(key_format, key_data)?) {
             let mut result =
                 self.soft.importKey(key_params, key_format, key_data, attestation_key)?;
-            result.keyBlob = map_or_log_err(wrap_keyblob(&result.keyBlob), Ok)?;
+            result.keyBlob = map_or_log_err(wrap_keyblob(&result.keyBlob))?;
             Ok(result)
         } else {
             self.real.importKey(key_params, key_format, key_data, attestation_key)
@@ -281,7 +281,7 @@
             KeyBlob::Wrapped(keyblob) => {
                 // Re-wrap the upgraded keyblob.
                 let upgraded_keyblob = self.soft.upgradeKey(keyblob, upgrade_params)?;
-                map_or_log_err(wrap_keyblob(&upgraded_keyblob), Ok)
+                map_or_log_err(wrap_keyblob(&upgraded_keyblob))
             }
         }
     }
diff --git a/keystore2/src/maintenance.rs b/keystore2/src/maintenance.rs
index 644e7e5..c384a03 100644
--- a/keystore2/src/maintenance.rs
+++ b/keystore2/src/maintenance.rs
@@ -303,13 +303,13 @@
             password.is_some()
         );
         let _wp = wd::watch("IKeystoreMaintenance::onUserPasswordChanged");
-        map_or_log_err(Self::on_user_password_changed(user_id, password.map(|pw| pw.into())), Ok)
+        map_or_log_err(Self::on_user_password_changed(user_id, password.map(|pw| pw.into())))
     }
 
     fn onUserAdded(&self, user_id: i32) -> BinderResult<()> {
         log::info!("onUserAdded(user={user_id})");
         let _wp = wd::watch("IKeystoreMaintenance::onUserAdded");
-        map_or_log_err(self.add_or_remove_user(user_id), Ok)
+        map_or_log_err(self.add_or_remove_user(user_id))
     }
 
     fn initUserSuperKeys(
@@ -320,31 +320,31 @@
     ) -> BinderResult<()> {
         log::info!("initUserSuperKeys(user={user_id}, allow_existing={allow_existing})");
         let _wp = wd::watch("IKeystoreMaintenance::initUserSuperKeys");
-        map_or_log_err(self.init_user_super_keys(user_id, password.into(), allow_existing), Ok)
+        map_or_log_err(self.init_user_super_keys(user_id, password.into(), allow_existing))
     }
 
     fn onUserRemoved(&self, user_id: i32) -> BinderResult<()> {
         log::info!("onUserRemoved(user={user_id})");
         let _wp = wd::watch("IKeystoreMaintenance::onUserRemoved");
-        map_or_log_err(self.add_or_remove_user(user_id), Ok)
+        map_or_log_err(self.add_or_remove_user(user_id))
     }
 
     fn onUserLskfRemoved(&self, user_id: i32) -> BinderResult<()> {
         log::info!("onUserLskfRemoved(user={user_id})");
         let _wp = wd::watch("IKeystoreMaintenance::onUserLskfRemoved");
-        map_or_log_err(Self::on_user_lskf_removed(user_id), Ok)
+        map_or_log_err(Self::on_user_lskf_removed(user_id))
     }
 
     fn clearNamespace(&self, domain: Domain, nspace: i64) -> BinderResult<()> {
         log::info!("clearNamespace({domain:?}, nspace={nspace})");
         let _wp = wd::watch("IKeystoreMaintenance::clearNamespace");
-        map_or_log_err(self.clear_namespace(domain, nspace), Ok)
+        map_or_log_err(self.clear_namespace(domain, nspace))
     }
 
     fn earlyBootEnded(&self) -> BinderResult<()> {
         log::info!("earlyBootEnded()");
         let _wp = wd::watch("IKeystoreMaintenance::earlyBootEnded");
-        map_or_log_err(Self::early_boot_ended(), Ok)
+        map_or_log_err(Self::early_boot_ended())
     }
 
     fn migrateKeyNamespace(
@@ -354,13 +354,13 @@
     ) -> BinderResult<()> {
         log::info!("migrateKeyNamespace(src={source:?}, dest={destination:?})");
         let _wp = wd::watch("IKeystoreMaintenance::migrateKeyNamespace");
-        map_or_log_err(Self::migrate_key_namespace(source, destination), Ok)
+        map_or_log_err(Self::migrate_key_namespace(source, destination))
     }
 
     fn deleteAllKeys(&self) -> BinderResult<()> {
         log::warn!("deleteAllKeys()");
         let _wp = wd::watch("IKeystoreMaintenance::deleteAllKeys");
-        map_or_log_err(Self::delete_all_keys(), Ok)
+        map_or_log_err(Self::delete_all_keys())
     }
 
     fn getAppUidsAffectedBySid(
@@ -370,6 +370,6 @@
     ) -> BinderResult<std::vec::Vec<i64>> {
         log::info!("getAppUidsAffectedBySid(secure_user_id={secure_user_id:?})");
         let _wp = wd::watch("IKeystoreMaintenance::getAppUidsAffectedBySid");
-        map_or_log_err(Self::get_app_uids_affected_by_sid(user_id, secure_user_id), Ok)
+        map_or_log_err(Self::get_app_uids_affected_by_sid(user_id, secure_user_id))
     }
 }
diff --git a/keystore2/src/metrics.rs b/keystore2/src/metrics.rs
index c114c8b..bbe12aa 100644
--- a/keystore2/src/metrics.rs
+++ b/keystore2/src/metrics.rs
@@ -52,6 +52,6 @@
 impl IKeystoreMetrics for Metrics {
     fn pullMetrics(&self, atom_id: AtomID) -> BinderResult<Vec<KeystoreAtom>> {
         let _wp = wd::watch("IKeystoreMetrics::pullMetrics");
-        map_or_log_err(self.pull_metrics(atom_id), Ok)
+        map_or_log_err(self.pull_metrics(atom_id))
     }
 }
diff --git a/keystore2/src/operation.rs b/keystore2/src/operation.rs
index 290bc74..94bd7c3 100644
--- a/keystore2/src/operation.rs
+++ b/keystore2/src/operation.rs
@@ -822,24 +822,18 @@
 impl IKeystoreOperation for KeystoreOperation {
     fn updateAad(&self, aad_input: &[u8]) -> binder::Result<()> {
         let _wp = wd::watch("IKeystoreOperation::updateAad");
-        map_or_log_err(
-            self.with_locked_operation(
-                |op| op.update_aad(aad_input).context(ks_err!("KeystoreOperation::updateAad")),
-                false,
-            ),
-            Ok,
-        )
+        map_or_log_err(self.with_locked_operation(
+            |op| op.update_aad(aad_input).context(ks_err!("KeystoreOperation::updateAad")),
+            false,
+        ))
     }
 
     fn update(&self, input: &[u8]) -> binder::Result<Option<Vec<u8>>> {
         let _wp = wd::watch("IKeystoreOperation::update");
-        map_or_log_err(
-            self.with_locked_operation(
-                |op| op.update(input).context(ks_err!("KeystoreOperation::update")),
-                false,
-            ),
-            Ok,
-        )
+        map_or_log_err(self.with_locked_operation(
+            |op| op.update(input).context(ks_err!("KeystoreOperation::update")),
+            false,
+        ))
     }
     fn finish(
         &self,
@@ -847,13 +841,10 @@
         signature: Option<&[u8]>,
     ) -> binder::Result<Option<Vec<u8>>> {
         let _wp = wd::watch("IKeystoreOperation::finish");
-        map_or_log_err(
-            self.with_locked_operation(
-                |op| op.finish(input, signature).context(ks_err!("KeystoreOperation::finish")),
-                true,
-            ),
-            Ok,
-        )
+        map_or_log_err(self.with_locked_operation(
+            |op| op.finish(input, signature).context(ks_err!("KeystoreOperation::finish")),
+            true,
+        ))
     }
 
     fn abort(&self) -> binder::Result<()> {
@@ -873,7 +864,6 @@
                 };
                 e
             },
-            Ok,
         )
     }
 }
diff --git a/keystore2/src/security_level.rs b/keystore2/src/security_level.rs
index 59f2315..71d6dba 100644
--- a/keystore2/src/security_level.rs
+++ b/keystore2/src/security_level.rs
@@ -996,7 +996,7 @@
         forced: bool,
     ) -> binder::Result<CreateOperationResponse> {
         let _wp = self.watch("IKeystoreSecurityLevel::createOperation");
-        map_or_log_err(self.create_operation(key, operation_parameters, forced), Ok)
+        map_or_log_err(self.create_operation(key, operation_parameters, forced))
     }
     fn generateKey(
         &self,
@@ -1012,7 +1012,7 @@
         let result = self.generate_key(key, attestation_key, params, flags, entropy);
         log_key_creation_event_stats(self.security_level, params, &result);
         log_key_generated(key, ThreadState::get_calling_uid(), result.is_ok());
-        map_or_log_err(result, Ok)
+        map_or_log_err(result)
     }
     fn importKey(
         &self,
@@ -1026,7 +1026,7 @@
         let result = self.import_key(key, attestation_key, params, flags, key_data);
         log_key_creation_event_stats(self.security_level, params, &result);
         log_key_imported(key, ThreadState::get_calling_uid(), result.is_ok());
-        map_or_log_err(result, Ok)
+        map_or_log_err(result)
     }
     fn importWrappedKey(
         &self,
@@ -1041,20 +1041,20 @@
             self.import_wrapped_key(key, wrapping_key, masking_key, params, authenticators);
         log_key_creation_event_stats(self.security_level, params, &result);
         log_key_imported(key, ThreadState::get_calling_uid(), result.is_ok());
-        map_or_log_err(result, Ok)
+        map_or_log_err(result)
     }
     fn convertStorageKeyToEphemeral(
         &self,
         storage_key: &KeyDescriptor,
     ) -> binder::Result<EphemeralStorageKeyResponse> {
         let _wp = self.watch("IKeystoreSecurityLevel::convertStorageKeyToEphemeral");
-        map_or_log_err(self.convert_storage_key_to_ephemeral(storage_key), Ok)
+        map_or_log_err(self.convert_storage_key_to_ephemeral(storage_key))
     }
     fn deleteKey(&self, key: &KeyDescriptor) -> binder::Result<()> {
         let _wp = self.watch("IKeystoreSecurityLevel::deleteKey");
         let result = self.delete_key(key);
         log_key_deleted(key, ThreadState::get_calling_uid(), result.is_ok());
-        map_or_log_err(result, Ok)
+        map_or_log_err(result)
     }
 }
 
diff --git a/keystore2/src/service.rs b/keystore2/src/service.rs
index 1eab8a8..2ca9ccf 100644
--- a/keystore2/src/service.rs
+++ b/keystore2/src/service.rs
@@ -384,11 +384,11 @@
         let _wp = wd::watch_millis_with("IKeystoreService::getSecurityLevel", 500, move || {
             format!("security_level: {}", security_level.0)
         });
-        map_or_log_err(self.get_security_level(security_level), Ok)
+        map_or_log_err(self.get_security_level(security_level))
     }
     fn getKeyEntry(&self, key: &KeyDescriptor) -> binder::Result<KeyEntryResponse> {
         let _wp = wd::watch("IKeystoreService::get_key_entry");
-        map_or_log_err(self.get_key_entry(key), Ok)
+        map_or_log_err(self.get_key_entry(key))
     }
     fn updateSubcomponent(
         &self,
@@ -397,17 +397,17 @@
         certificate_chain: Option<&[u8]>,
     ) -> binder::Result<()> {
         let _wp = wd::watch("IKeystoreService::updateSubcomponent");
-        map_or_log_err(self.update_subcomponent(key, public_cert, certificate_chain), Ok)
+        map_or_log_err(self.update_subcomponent(key, public_cert, certificate_chain))
     }
     fn listEntries(&self, domain: Domain, namespace: i64) -> binder::Result<Vec<KeyDescriptor>> {
         let _wp = wd::watch("IKeystoreService::listEntries");
-        map_or_log_err(self.list_entries(domain, namespace), Ok)
+        map_or_log_err(self.list_entries(domain, namespace))
     }
     fn deleteKey(&self, key: &KeyDescriptor) -> binder::Result<()> {
         let _wp = wd::watch("IKeystoreService::deleteKey");
         let result = self.delete_key(key);
         log_key_deleted(key, ThreadState::get_calling_uid(), result.is_ok());
-        map_or_log_err(result, Ok)
+        map_or_log_err(result)
     }
     fn grant(
         &self,
@@ -416,11 +416,11 @@
         access_vector: i32,
     ) -> binder::Result<KeyDescriptor> {
         let _wp = wd::watch("IKeystoreService::grant");
-        map_or_log_err(self.grant(key, grantee_uid, access_vector.into()), Ok)
+        map_or_log_err(self.grant(key, grantee_uid, access_vector.into()))
     }
     fn ungrant(&self, key: &KeyDescriptor, grantee_uid: i32) -> binder::Result<()> {
         let _wp = wd::watch("IKeystoreService::ungrant");
-        map_or_log_err(self.ungrant(key, grantee_uid), Ok)
+        map_or_log_err(self.ungrant(key, grantee_uid))
     }
     fn listEntriesBatched(
         &self,
@@ -429,11 +429,11 @@
         start_past_alias: Option<&str>,
     ) -> binder::Result<Vec<KeyDescriptor>> {
         let _wp = wd::watch("IKeystoreService::listEntriesBatched");
-        map_or_log_err(self.list_entries_batched(domain, namespace, start_past_alias), Ok)
+        map_or_log_err(self.list_entries_batched(domain, namespace, start_past_alias))
     }
 
     fn getNumberOfEntries(&self, domain: Domain, namespace: i64) -> binder::Result<i32> {
         let _wp = wd::watch("IKeystoreService::getNumberOfEntries");
-        map_or_log_err(self.count_num_entries(domain, namespace), Ok)
+        map_or_log_err(self.count_num_entries(domain, namespace))
     }
 }
diff --git a/mls/mls-rs-crypto-boringssl/Android.bp b/mls/mls-rs-crypto-boringssl/Android.bp
index b363640..b7843c8 100644
--- a/mls/mls-rs-crypto-boringssl/Android.bp
+++ b/mls/mls-rs-crypto-boringssl/Android.bp
@@ -1,16 +1,7 @@
-// Copyright 2024, The Android Open Source Project
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//     http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
+// This file is generated by cargo_embargo.
+// Do not modify this file after the first "rust_*" or "genrule" module
+// because the changes will be overridden on upgrade.
+// Content before the first "rust_*" or "genrule" module is preserved.
 
 package {
     default_applicable_licenses: ["platform_system_security_mls_rs_crypto_boringssl_license"],
@@ -32,7 +23,10 @@
     name: "libmls_rs_crypto_boringssl",
     host_supported: true,
     crate_name: "mls_rs_crypto_boringssl",
-    srcs: ["src/lib.rs"],
+    cargo_env_compat: true,
+    cargo_pkg_version: "0.1.0",
+    crate_root: "src/lib.rs",
+    edition: "2021",
     cfgs: ["mls_build_async"],
     rustlibs: [
         "libbssl_crypto",
@@ -47,8 +41,8 @@
         "libmaybe_async",
     ],
     apex_available: [
-        "//apex_available:anyapex",
         "//apex_available:platform",
+        "//apex_available:anyapex",
     ],
     product_available: true,
     vendor_available: true,
diff --git a/mls/mls-rs-crypto-boringssl/Cargo.toml b/mls/mls-rs-crypto-boringssl/Cargo.toml
new file mode 100644
index 0000000..8468df5
--- /dev/null
+++ b/mls/mls-rs-crypto-boringssl/Cargo.toml
@@ -0,0 +1,17 @@
+[package]
+name = "mls-rs-crypto-boringssl"
+version = "0.1.0"
+edition = "2021"
+
+[dependencies]
+bssl-crypto = { path = "../../../../external/boringssl/src/rust/bssl-crypto" }
+mls-rs-codec = "0.5.3"
+mls-rs-core = "0.18.0"
+mls-rs-crypto-traits = "0.10.0"
+thiserror = "1.0.49"
+zeroize = { version = "1.6.0", features = ["zeroize_derive"] }
+maybe-async = "0.2.10"
+
+[target.'cfg(mls_build_async)'.dependencies]
+async-trait = "0.1.74"
+
diff --git a/mls/mls-rs-crypto-boringssl/cargo_embargo.json b/mls/mls-rs-crypto-boringssl/cargo_embargo.json
new file mode 100644
index 0000000..de66107
--- /dev/null
+++ b/mls/mls-rs-crypto-boringssl/cargo_embargo.json
@@ -0,0 +1,4 @@
+{
+    "extra_cfg": ["mls_build_async"],
+    "run_cargo": false
+}