apple-localauthentication 0.5.2

Safe Rust bindings for Apple's LocalAuthentication framework — contexts, rights, persisted secrets, keys, and credentials on macOS
Documentation
//! Async API for `LocalAuthentication`
//!
//! This module provides async versions of authentication operations when the `async` feature is enabled.
//! The async API is **executor-agnostic** and works with any async runtime (Tokio, async-std, smol, etc.).

use crate::la_context::LAContext;
use crate::la_error::{LAError, Result};
use crate::la_policy::LAPolicy;
use doom_fish_utils::completion::{error_from_cstr, AsyncCompletion, AsyncCompletionFuture};
use doom_fish_utils::panic_safe::catch_user_panic;
use security::AccessControl;
use std::ffi::{c_char, c_void};
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};

// ============================================================================
// Callbacks for async operations
// ============================================================================

type EvaluationResult = Result<bool>;

extern "C" fn evaluation_callback(
    success: u8,
    status: i32,
    error: *const c_char,
    user_data: *mut c_void,
) {
    catch_user_panic("evaluation_callback", || {
        let result = if status == crate::ffi::status::OK {
            Ok(success != 0)
        } else {
            let message = if error.is_null() {
                String::new()
            } else {
                // SAFETY: error is a valid C string from Swift bridge
                unsafe { error_from_cstr(error) }
            };
            Err(LAError::from_code_message(status, message))
        };
        // SAFETY: user_data points to a valid AsyncCompletion<EvaluationResult> created by AsyncCompletion::create()
        unsafe { AsyncCompletion::<EvaluationResult>::complete_ok(user_data, result) };
    });
}

// ============================================================================
// Future types
// ============================================================================

/// Future for async policy evaluation
pub struct AsyncPolicyEvaluation {
    inner: AsyncCompletionFuture<EvaluationResult>,
}

impl std::fmt::Debug for AsyncPolicyEvaluation {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AsyncPolicyEvaluation")
            .finish_non_exhaustive()
    }
}

impl Future for AsyncPolicyEvaluation {
    type Output = Result<bool>;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        Pin::new(&mut self.inner).poll(cx).map(|result| {
            result
                .map_err(LAError::BridgeFailed)
                .and_then(|result| result)
        })
    }
}

/// Future for async access control evaluation
pub struct AsyncAccessControlEvaluation {
    inner: AsyncCompletionFuture<EvaluationResult>,
}

impl std::fmt::Debug for AsyncAccessControlEvaluation {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AsyncAccessControlEvaluation")
            .finish_non_exhaustive()
    }
}

impl Future for AsyncAccessControlEvaluation {
    type Output = Result<bool>;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        Pin::new(&mut self.inner).poll(cx).map(|result| {
            result
                .map_err(LAError::BridgeFailed)
                .and_then(|result| result)
        })
    }
}

// ============================================================================
// Async operations extension trait
// ============================================================================

/// Extension trait adding async methods to `LAContext`
pub trait AsyncContextExt {
    /// Asynchronously evaluate a policy
    ///
    /// # Errors
    ///
    /// Returns an error if the localized reason is empty or contains a null byte.
    fn evaluate_policy_async(
        &self,
        policy: LAPolicy,
        localized_reason: &str,
    ) -> Result<AsyncPolicyEvaluation>;

    /// Asynchronously evaluate an access control
    ///
    /// # Errors
    ///
    /// Returns an error if the localized reason is empty or contains a null byte.
    fn evaluate_access_control_async(
        &self,
        access_control: &AccessControl,
        operation: crate::la_context::LAAccessControlOperation,
        localized_reason: &str,
    ) -> Result<AsyncAccessControlEvaluation>;
}

impl AsyncContextExt for LAContext {
    /// Asynchronously evaluate a policy
    ///
    /// Uses callback-based Swift FFI for true async operation.
    ///
    /// # Arguments
    ///
    /// * `policy` - The authentication policy to evaluate
    /// * `localized_reason` - A localized reason shown to the user
    fn evaluate_policy_async(
        &self,
        policy: LAPolicy,
        localized_reason: &str,
    ) -> Result<AsyncPolicyEvaluation> {
        if localized_reason.is_empty() {
            return Err(crate::la_error::LAError::InvalidArgument(
                "localized reason must not be empty".to_owned(),
            ));
        }

        let reason_cstring = std::ffi::CString::new(localized_reason).map_err(|_| {
            LAError::InvalidArgument("localized reason contains null byte".to_owned())
        })?;
        let (future, ctx) = AsyncCompletion::create();

        let context_ptr = self.as_ptr();

        unsafe {
            crate::ffi::la_context::la_context_evaluate_policy_async(
                context_ptr,
                policy.as_ffi(),
                reason_cstring.as_ptr(),
                evaluation_callback,
                ctx,
            );
        }

        Ok(AsyncPolicyEvaluation { inner: future })
    }

    /// Asynchronously evaluate an access control
    ///
    /// Uses callback-based Swift FFI for true async operation.
    ///
    /// # Arguments
    ///
    /// * `access_control` - The `SecAccessControl` to evaluate
    /// * `operation` - The access control operation to evaluate
    /// * `localized_reason` - A localized reason shown to the user
    fn evaluate_access_control_async(
        &self,
        access_control: &AccessControl,
        operation: crate::la_context::LAAccessControlOperation,
        localized_reason: &str,
    ) -> Result<AsyncAccessControlEvaluation> {
        if localized_reason.is_empty() {
            return Err(crate::la_error::LAError::InvalidArgument(
                "localized reason must not be empty".to_owned(),
            ));
        }

        let reason_cstring = std::ffi::CString::new(localized_reason).map_err(|_| {
            LAError::InvalidArgument("localized reason contains null byte".to_owned())
        })?;
        let (future, ctx) = AsyncCompletion::create();

        let context_ptr = self.as_ptr();

        unsafe {
            crate::ffi::la_context::la_context_evaluate_access_control_async(
                context_ptr,
                access_control.as_ptr().cast_const(),
                operation.raw_value(),
                reason_cstring.as_ptr(),
                evaluation_callback,
                ctx,
            );
        }

        Ok(AsyncAccessControlEvaluation { inner: future })
    }
}