localauthentication-rs
Safe Rust bindings for Apple's LocalAuthentication framework on macOS.
Installation
[]
= "0.5"
The library is imported as localauthentication. The optional async feature adds executor-agnostic futures for policy and access-control evaluation.
A successful evaluation is not a secure gate
LAContext::evaluate_policy returns Ok(true) when the user authenticated, but that boolean lives in your process: a debugger or a patched binary can flip it, so gating a secret on if evaluate_policy(..)? { .. } does not protect the secret. Let the system enforce the check instead:
- Keep the secret in a persisted right:
LARightStore::save_right_with_secretstores it, andLAPersistedRight::secret()/LASecret::load_dataonly return it after the right's authorization requirement has been met.LAPrivateKeyoperations are bound to the right in the same way. - Or store it as a keychain item protected by an access control, and let the keychain check it. With
security-rs, create anAccessControl(for exampleAccessControlFlags::USER_PRESENCEorBIOMETRY_CURRENT_SET, re-exported by this crate), attach it withKeychainOptions::access_control, and pass the context to the query withKeychainOptions::authentication_context(context.as_raw_la_context())(anunsafe fn: the pointer must be a liveLAContext), which setskSecUseAuthenticationContext.LAContext::evaluate_access_controlevaluates the sameAccessControlahead of time, so the keychain query does not prompt again. Keep the RustLAContextalive for as long as the query uses it: dropping it invalidates the context.
use *;
Platform notes
- The Rust crate is macOS-focused and links the system
LocalAuthentication.framework. - Requires macOS 13 or newer (the Swift bridge's deployment target).
LAContext::domain_state()plus theLAEnvironment::{current_user, state, add_observer}surface are macOS 15+ APIs.- Persisted-right and key APIs can require signing or entitlements; the examples and tests treat
OSStatus -34018as an expected environment limitation. LAPrivateKey::exchange_keys_with_public_keyusesSecKeyExchangeParametersfor the requested derived-key length and optional shared-info KDF context.
Build a macOS binary that uses this crate with a deployment target of macOS 13.0 or later. The
Swift bridge uses Swift concurrency. Rust builds binaries for macOS 11.0 on Apple silicon and for
macOS 10.12 on x86_64 by default. With these targets, the binary loads the Swift runtime
through @rpath and stops at launch with an error such as
Library not loaded: @rpath/libswift_Concurrency.dylib. Set MACOSX_DEPLOYMENT_TARGET=13.0 in
the environment, or set it for the project in .cargo/config.toml:
[]
= "13.0"
Cargo does not link the binary again when only this variable changes, so run cargo clean
after you set it.
Timeouts, cancellation and dropping
- The synchronous calls that wait for the framework (
LAContext::evaluate_policy,evaluate_access_control,LARight/LAPersistedRightauthorization, theLARightStoreoperations, and the key and secret operations) wait at mostsync_timeout(), 30 seconds by default. Change it for the whole process withset_sync_timeout(Some(duration)), or passNoneto wait indefinitely. The async API never times out. - A timed-out call returns
LAError::TimedOutand is cancelled: an evaluation invalidates itsLAContext(which dismisses the prompt), an authorization that completes later is deauthorized again, and a right that is saved after the timeout is removed again. Removals cannot be undone and may still complete after a timeout. - Dropping an
LAContextinvalidates it, so a prompt that is still on screen is dismissed and any pending evaluation (including an async one) fails withLAError::AppCancel.
Secrets and errors
LACredentialkeeps its bytes inzeroize::Zeroizing, prints them as<redacted>inDebug, and compares them in constant time.LASecret::load_data,LAPrivateKey::decryptandLAPrivateKey::exchange_keys_with_public_keyreturnZeroizing<Vec<u8>>, and the bridge wipes its copy. Copies held by the framework cannot be wiped from Rust.- Errors from
LAErrorDomainmap to the typedLAErrorvariants, from both the synchronous and the async API. Errors from other domains (for exampleNSOSStatusErrorDomain -34018when an entitlement is missing) becomeLAError::Other, with the domain and code in the message.
Quick start
use *;
Highlights
LAContextlifecycle, policy preflight/evaluation, credential injection, domain-state snapshots, and access-control evaluation withsecurity-rs'sAccessControl(re-exported withAccessControlFlagsandAccessControlProtection)LAPolicy,LAError,LA_ERROR_DOMAIN,BiometryType, andLACompanionTypeLAAuthenticationRequirementandLABiometryFallbackRequirementbuilders for rightsLARightandLARightStorefor in-memory and persisted authorization flowsLAPersistedRight,LASecret,LAPrivateKey,LAPublicKey,SecKeyAlgorithm, andSecKeyExchangeParametershelpers for persisted secrets and asymmetric-key operationsLAEnvironment,LAEnvironmentObserver,LAEnvironmentState, and the environment mechanism subclasses for macOS 15 environment snapshots and change notifications- Backward-compatible aliases for the v0.1.x surface (
Policy,LocalAuthenticationError,context, anderror) - Async API (gated behind
asyncfeature): executor-agnostic async wrappers for policy and access control evaluation viaAsyncContextExttrait
Async API
When the async feature is enabled, the async_api module provides executor-agnostic async methods for authentication:
use *;
use AsyncContextExt;
The async API:
- Works with any async runtime (Tokio, async-std, smol, pollster, etc.)
- Uses callback-based Swift FFI for true async operations
- Provides
AsyncContextExttrait with async variants ofevaluate_policy_asyncandevaluate_access_control_async - Returns futures that resolve to
Result<bool, LAError>with the same error variants as the synchronous API
See examples/02_async_policy.rs for a complete example.
Examples
The crate ships numbered examples for every logical area:
01_smoke—LAContext, policies, credentials, and domain state02_async_policy— async policy evaluation usingAsyncContextExt(requires theasyncfeature; shows an authentication prompt)02_policy_catalog— policy availability across biometric and companion modes03_error_codes—LAErrorand domain/code mapping04_credentials—LACredentialhelpers05_authentication_requirements— requirement builders andLARightconstruction06_rights— right state/tag/preflight/deauthorize flow07_right_store— sharedLARightStorepersistence entry points08_persisted_right—LAPersistedRight,LASecret, andLAPrivateKey09_public_key—LAPublicKeyexport plusLAPrivateKeyverify/encrypt/key-exchange capability checks10_environment—LAEnvironment, observer registration, and mechanism snapshots
Run the full verification matrix with:
for; do name=""; [ || ; done
For the header-by-header audit, see COVERAGE.md.
License
Licensed under either of Apache-2.0 or MIT at your option.