aKode fase 5: rinomina interna (crate akode-*, akode-rs/, akode-cli/, binario akode, AKODE_*, ~/.akode, snapshot)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-11 11:06:46 +01:00
parent df99318392
commit 86e7c72e5f
10383 changed files with 749164 additions and 749170 deletions

View File

@@ -0,0 +1,6 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "user-verification",
crate_name = "akode_user_verification",
)

View File

@@ -0,0 +1,33 @@
[package]
name = "akode-user-verification"
version.workspace = true
edition.workspace = true
license.workspace = true
[lints]
workspace = true
[dependencies]
base64 = { workspace = true }
p256 = { version = "0.13", default-features = false, features = ["arithmetic", "pkcs8", "std"] }
sha2 = { workspace = true }
thiserror = { workspace = true }
tracing = { workspace = true }
[target.'cfg(target_os = "macos")'.dependencies]
block2 = "0.6.2"
core-foundation = "0.10"
dirs = { workspace = true }
objc2 = "0.6.3"
objc2-foundation = { version = "0.3.2", default-features = false, features = ["std", "NSString"] }
objc2-local-authentication = { version = "0.3.2", default-features = false, features = ["std", "LAContext", "LABiometryType", "block2", "objc2-security"] }
security-framework = { version = "3.5", features = ["OSX_10_15"] }
security-framework-sys = "2.15"
[dev-dependencies]
p256 = { version = "0.13", features = ["ecdsa"] }
pretty_assertions = { workspace = true }
tempfile = { workspace = true }
[lib]
doctest = false

View File

@@ -0,0 +1,59 @@
# Native hardware test
`tests/hardware.rs` exercises the macOS provider with a real persisted Secure
Enclave key: create and reload it, verify a signature, cancel an authentication
request, and sign a new challenge with the same key. It is ignored by default.
Run on a physical Touch ID Mac with fingerprints enrolled and the lid open. Use
an existing **isolated development app** with a valid provisioning profile and
Keychain Sharing entitlements, plus its Apple Development signing identity.
The test does not use a Wallet account or submit a purchase. Run only one copy at
a time; it reserves the `codex-user-verification-hardware-test` key namespace and
removes that namespace's key before and after the test.
From the repository root, set `TEMPLATE_APP` to that signed development `.app`
and `SIGNING_IDENTITY` to its signing identity, then run in Bash. Signing the
runner is insufficient: the test executable itself needs the profile and
entitlements.
```bash
set -euo pipefail
: "${TEMPLATE_APP:?Set the path to the isolated signed development app}"
: "${SIGNING_IDENTITY:?Set its Apple Development identity}"
run_dir=$(mktemp -d)
app="$run_dir/HardwareTest.app"
(cd akode-rs && cargo build --locked -p akode-user-verification --test hardware \
--message-format=json) > "$run_dir/build.jsonl"
binary=$(jq -r 'select(.reason == "compiler-artifact" and .target.name == "hardware" and .executable != null) | .executable' "$run_dir/build.jsonl")
mkdir -p "$app/Contents/MacOS"
cp "$binary" "$app/Contents/MacOS/hardware"
cp "$TEMPLATE_APP/Contents/Info.plist" "$app/Contents/Info.plist"
cp "$TEMPLATE_APP/Contents/embedded.provisionprofile" "$app/Contents/embedded.provisionprofile"
/usr/libexec/PlistBuddy -c 'Set :CFBundleExecutable hardware' "$app/Contents/Info.plist"
codesign -d --xml --entitlements - "$TEMPLATE_APP" > "$run_dir/entitlements.plist"
codesign --force --options runtime --entitlements "$run_dir/entitlements.plist" \
--sign "$SIGNING_IDENTITY" "$app"
codesign --verify --strict "$app"
echo "Test bundle: $app"
"$app/Contents/MacOS/hardware" --ignored --exact \
persisted_key_signing_cancellation_and_retry --nocapture --test-threads=1
```
Use Touch ID for the first prompt, then remove your finger. Leave the
**cancellation** prompt untouched and observe that it appears and closes on its
own. Authenticate the **retry signing** prompt once. Passing assertions verify
both signatures, the cancellation result, and key removal; confirming visible
prompt dismissal is the operator's part of the test. An early interruption fails
the test rather than counting as cancellation.
If cancellation has not returned ten seconds after it is issued, the watchdog
exits with a failure instead of hanging. After a forced exit, stop any remaining
test process and remove the reserved key with the same signed bundle:
```bash
AKODE_HARDWARE_TEST_CLEANUP=1 "$app/Contents/MacOS/hardware" --ignored --exact \
persisted_key_signing_cancellation_and_retry --nocapture --test-threads=1
```
This test covers the native provider. It does not exercise app-server routing,
UI state, closed-lid recovery, or hosted Wallet completion.

View File

@@ -0,0 +1,86 @@
//! Public credential encoding and results; private keys never cross this boundary.
use crate::UserVerificationError;
use crate::UserVerificationFailureReason;
use crate::UserVerificationUnavailableReason;
use base64::Engine as _;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use p256::pkcs8::EncodePublicKey as _;
use sha2::Digest as _;
use sha2::Sha256;
/// Validated display text and exact challenge bytes supplied by the trusted calling UI.
#[derive(Clone)]
pub struct UserVerificationRequest {
pub challenge: Vec<u8>,
pub title: String,
pub description: String,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct UserVerificationKeyInfo {
pub credential_id: String,
pub algorithm: String,
/// Unpadded base64url of the P-256 SubjectPublicKeyInfo DER encoding.
pub public_key: String,
}
impl UserVerificationKeyInfo {
pub fn from_sec1_public_key(bytes: &[u8]) -> Result<Self, UserVerificationError> {
let public_key = p256::PublicKey::from_sec1_bytes(bytes)
.map_err(|_| invalid_public_key())?
.to_public_key_der()
.map_err(|_| invalid_public_key())?;
let bytes = public_key.as_bytes();
Ok(Self {
credential_id: URL_SAFE_NO_PAD.encode(Sha256::digest(bytes)),
algorithm: "ecdsaP256Sha256X962".to_string(),
public_key: URL_SAFE_NO_PAD.encode(bytes),
})
}
}
fn invalid_public_key() -> UserVerificationError {
UserVerificationError::Failed {
reason: UserVerificationFailureReason::ProviderError,
message: "could not encode the user-verification public key".to_string(),
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct UserVerificationKeyCreation {
pub created: bool,
pub credential: UserVerificationKeyInfo,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct UserVerificationKeyDeletion {
pub deleted_credential_id: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct UserVerificationStatus {
pub credential: Option<UserVerificationKeyInfo>,
pub unavailable_reason: Option<UserVerificationUnavailableReason>,
pub unavailable_message: Option<String>,
}
#[derive(Clone, PartialEq, Eq)]
pub struct UserVerificationProof {
pub credential_id: String,
/// Unpadded base64url of an ASN.1 DER ECDSA signature over the challenge, hashed once.
pub signature: String,
}
impl std::fmt::Debug for UserVerificationProof {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("UserVerificationProof")
.field("credential_id", &"[REDACTED]")
.field("signature", &"[REDACTED]")
.finish()
}
}
#[cfg(test)]
#[path = "credential_tests.rs"]
mod tests;

View File

@@ -0,0 +1,43 @@
//! Checks that the exported credential interoperates with DER-based service verification.
use super::*;
use p256::ecdsa::Signature;
use p256::ecdsa::SigningKey;
use p256::ecdsa::VerifyingKey;
use p256::ecdsa::signature::Signer as _;
use p256::ecdsa::signature::Verifier as _;
use p256::pkcs8::DecodePublicKey as _;
use pretty_assertions::assert_eq;
#[test]
fn exported_spki_verifies_the_exact_challenge_signature() {
let key = SigningKey::from_bytes((&[7_u8; 32]).into()).expect("valid signing key");
let info = UserVerificationKeyInfo::from_sec1_public_key(
key.verifying_key()
.to_encoded_point(/*compress*/ false)
.as_bytes(),
)
.expect("encode public key");
let der = URL_SAFE_NO_PAD.decode(&info.public_key).expect("base64url");
let verifier = VerifyingKey::from_public_key_der(&der).expect("valid SPKI DER");
let challenge = b"the exact server-issued challenge";
let signature: Signature = key.sign(challenge);
let signature = Signature::from_der(signature.to_der().as_bytes()).expect("DER signature");
verifier
.verify(challenge, &signature)
.expect("valid signature");
assert!(verifier.verify(b"different challenge", &signature).is_err());
assert_eq!(
info,
UserVerificationKeyInfo {
credential_id: URL_SAFE_NO_PAD.encode(Sha256::digest(&der)),
algorithm: "ecdsaP256Sha256X962".to_string(),
public_key: URL_SAFE_NO_PAD.encode(der),
}
);
}
#[test]
fn invalid_curve_point_is_rejected() {
assert!(UserVerificationKeyInfo::from_sec1_public_key(&[4_u8; 65]).is_err());
}

View File

@@ -0,0 +1,42 @@
//! Stable error categories, with provider diagnostics kept outside public error messages.
use thiserror::Error;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum UserVerificationUnavailableReason {
CredentialMissing,
BiometricsUnavailable,
ProviderUnavailable,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum UserVerificationCancellationReason {
UserCancelled,
Interrupted,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum UserVerificationFailureReason {
AuthenticationFailed,
Timeout,
ProviderError,
}
#[derive(Clone, Debug, Error, PartialEq, Eq)]
pub enum UserVerificationError {
#[error("user verification is unavailable: {message}")]
Unavailable {
reason: UserVerificationUnavailableReason,
message: String,
},
#[error("user verification was cancelled: {message}")]
Cancelled {
reason: UserVerificationCancellationReason,
message: String,
},
#[error("user verification failed: {message}")]
Failed {
reason: UserVerificationFailureReason,
message: String,
},
}

View File

@@ -0,0 +1,51 @@
//! Cancellation and caller-owned identity checks for queued native operations.
use crate::UserVerificationCancellationReason;
use crate::UserVerificationError;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
/// Invalidates queued work and suppresses late results. Native providers observe cancellation
/// during authentication and request dismissal of their active OS prompt.
#[derive(Clone, Default)]
pub struct UserVerificationRequestGuard {
cancelled: Arc<AtomicBool>,
activity_check: Option<Arc<dyn Fn() -> bool + Send + Sync>>,
}
impl UserVerificationRequestGuard {
/// The callback checks a captured identity; it must be nonblocking and must not prompt.
pub fn with_activity_check(activity_check: impl Fn() -> bool + Send + Sync + 'static) -> Self {
Self {
cancelled: Arc::default(),
activity_check: Some(Arc::new(activity_check)),
}
}
pub fn cancel(&self) {
self.cancelled.store(/*val*/ true, Ordering::Release);
}
pub fn is_active(&self) -> bool {
if self.activity_check.as_ref().is_some_and(|check| !check()) {
self.cancel();
}
!self.cancelled.load(Ordering::Acquire)
}
pub fn check(&self) -> Result<(), UserVerificationError> {
if self.is_active() {
Ok(())
} else {
Err(UserVerificationError::Cancelled {
reason: UserVerificationCancellationReason::Interrupted,
message: "the verification operation is no longer active".to_string(),
})
}
}
}
#[cfg(test)]
#[path = "guard_tests.rs"]
mod tests;

View File

@@ -0,0 +1,32 @@
//! Checks cancellation shared across queued operations and captured-identity callbacks.
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn identity_change_permanently_cancels_all_guard_clones() {
let identity_matches = Arc::new(AtomicBool::new(/*v*/ true));
let activity = Arc::clone(&identity_matches);
let guard =
UserVerificationRequestGuard::with_activity_check(move || activity.load(Ordering::Acquire));
let queued = guard.clone();
assert!(queued.check().is_ok());
identity_matches.store(/*val*/ false, Ordering::Release);
assert_eq!(
queued.check(),
Err(UserVerificationError::Cancelled {
reason: UserVerificationCancellationReason::Interrupted,
message: "the verification operation is no longer active".to_string(),
})
);
identity_matches.store(/*val*/ true, Ordering::Release);
assert!(!guard.is_active());
}
#[test]
fn cancelling_one_clone_invalidates_queued_work() {
let guard = UserVerificationRequestGuard::default();
let queued = guard.clone();
guard.cancel();
assert!(!queued.is_active());
}

View File

@@ -0,0 +1,25 @@
//! Keychain labels isolate account-user identities within the fixed plugin-service scope.
use base64::Engine as _;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use sha2::Digest as _;
use sha2::Sha256;
/// An opaque account-user namespace. App-server authenticates and selects the identity.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct UserVerificationKeyNamespace {
pub(crate) label: String,
}
impl UserVerificationKeyNamespace {
pub fn new(account_user_id: &str) -> Self {
let identity = URL_SAFE_NO_PAD.encode(Sha256::digest(account_user_id.as_bytes()));
Self {
label: format!("com.openai.codex.user-verification.plugin-service.v1.{identity}"),
}
}
}
#[cfg(test)]
#[path = "key_namespace_tests.rs"]
mod tests;

View File

@@ -0,0 +1,12 @@
//! Account-user identities share one service scope without exposing raw identifiers.
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn namespaces_are_stable_and_separate_accounts() {
let first = UserVerificationKeyNamespace::new("account-user-one");
assert_eq!(first, UserVerificationKeyNamespace::new("account-user-one"));
assert_ne!(first, UserVerificationKeyNamespace::new("account-user-two"));
assert!(!first.label.contains("account-user-one"));
}

View File

@@ -0,0 +1,91 @@
//! Device credentials and signing, independent of RPC routing, UI, and backend registration.
mod credential;
mod error;
mod guard;
mod key_namespace;
#[cfg(any(target_os = "macos", test))]
mod lifecycle_lock;
#[cfg(any(target_os = "macos", test))]
mod native_operation;
#[cfg(any(target_os = "macos", test))]
mod platform_macos;
#[cfg(not(target_os = "macos"))]
mod unsupported;
pub use credential::UserVerificationKeyCreation;
pub use credential::UserVerificationKeyDeletion;
pub use credential::UserVerificationKeyInfo;
pub use credential::UserVerificationProof;
pub use credential::UserVerificationRequest;
pub use credential::UserVerificationStatus;
pub use error::UserVerificationCancellationReason;
pub use error::UserVerificationError;
pub use error::UserVerificationFailureReason;
pub use error::UserVerificationUnavailableReason;
pub use guard::UserVerificationRequestGuard;
pub use key_namespace::UserVerificationKeyNamespace;
use std::sync::Arc;
/// Performs local credential operations for one captured account-user identity.
/// Implementations never perform network registration. Blocking implementations must run off
/// the async executor and check the guard after waiting, before effects, and before returning.
pub trait UserVerificationProvider: Send + Sync {
/// Reads local readiness without creating credentials or prompting for authentication.
fn status(
&self,
guard: &UserVerificationRequestGuard,
) -> Result<UserVerificationStatus, UserVerificationError>;
/// Creates a protected key only if none exists. Success does not mean server enrollment.
fn ensure_key(
&self,
guard: &UserVerificationRequestGuard,
) -> Result<UserVerificationKeyCreation, UserVerificationError>;
/// Removes the local key idempotently. Backend revocation belongs to the caller.
fn delete(
&self,
guard: &UserVerificationRequestGuard,
) -> Result<UserVerificationKeyDeletion, UserVerificationError>;
/// Authenticates and signs 1–4096 challenge bytes without interpreting an elicitation.
/// The caller owns approval UI, request correlation, and the captured identity check.
fn verify(
&self,
request: &UserVerificationRequest,
guard: &UserVerificationRequestGuard,
) -> Result<UserVerificationProof, UserVerificationError>;
}
/// Reports whether this build contains a native provider, independently of local readiness.
pub fn platform_supported() -> bool {
cfg!(target_os = "macos")
}
/// Probes biometric hardware without reading credentials, prompting, or checking enrollment.
/// This performs local OS work; async callers should run it off their executor during setup.
pub fn device_supported() -> bool {
#[cfg(target_os = "macos")]
{
platform_macos::device_supported()
}
#[cfg(not(target_os = "macos"))]
{
false
}
}
pub fn platform_provider(
namespace: UserVerificationKeyNamespace,
) -> Arc<dyn UserVerificationProvider> {
#[cfg(target_os = "macos")]
{
Arc::new(platform_macos::NativeProvider { namespace })
}
#[cfg(not(target_os = "macos"))]
{
let _ = namespace.label;
Arc::new(unsupported::UnsupportedProvider)
}
}

View File

@@ -0,0 +1,86 @@
//! Serializes operations for one account across local processes, with cancellable lock waits.
use crate::UserVerificationError;
use crate::UserVerificationFailureReason;
use crate::UserVerificationRequestGuard;
use std::fs;
use std::fs::File;
use std::fs::OpenOptions;
use std::path::Path;
use std::time::Duration;
use std::time::Instant;
pub(crate) struct LifecycleLock {
_file: File,
}
impl LifecycleLock {
#[cfg(target_os = "macos")]
pub(crate) fn acquire(
namespace: &crate::UserVerificationKeyNamespace,
guard: &UserVerificationRequestGuard,
) -> Result<Self, UserVerificationError> {
let directory = dirs::data_local_dir().ok_or_else(|| UserVerificationError::Failed {
reason: UserVerificationFailureReason::ProviderError,
message: "could not locate the credential lock directory".to_string(),
})?;
Self::acquire_at(
&directory
.join("com.openai.codex")
.join("user-verification")
.join(format!("{}.lock", namespace.label)),
Duration::from_secs(/*secs*/ 60),
guard,
)
}
fn acquire_at(
path: &Path,
timeout: Duration,
guard: &UserVerificationRequestGuard,
) -> Result<Self, UserVerificationError> {
guard.check()?;
if let Some(parent) = path.parent() {
fs::create_dir_all(parent).map_err(lock_error)?;
}
let file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(path)
.map_err(lock_error)?;
let started = Instant::now();
loop {
guard.check()?;
match file.try_lock() {
Ok(()) => {
guard.check()?;
return Ok(Self { _file: file });
}
Err(std::fs::TryLockError::WouldBlock) if started.elapsed() >= timeout => {
return Err(UserVerificationError::Failed {
reason: UserVerificationFailureReason::Timeout,
message: "timed out waiting for another credential operation".to_string(),
});
}
Err(std::fs::TryLockError::WouldBlock) => {
std::thread::sleep(Duration::from_millis(/*millis*/ 50).min(timeout));
}
Err(std::fs::TryLockError::Error(error)) => return Err(lock_error(error)),
}
}
}
}
fn lock_error(error: std::io::Error) -> UserVerificationError {
tracing::warn!(%error, "user-verification lifecycle lock failed");
UserVerificationError::Failed {
reason: UserVerificationFailureReason::ProviderError,
message: "could not acquire the credential lock".to_string(),
}
}
#[cfg(test)]
#[path = "lifecycle_lock_tests.rs"]
mod tests;

View File

@@ -0,0 +1,60 @@
//! Exercises real file-lock contention and cancellation without releasing the held lock.
use super::*;
use crate::UserVerificationCancellationReason;
use pretty_assertions::assert_eq;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
#[test]
fn lock_serializes_operations_and_releases_on_drop() {
let directory = tempfile::tempdir().expect("temporary directory");
let path = directory.path().join("credential.lock");
let guard = UserVerificationRequestGuard::default();
let first = LifecycleLock::acquire_at(&path, Duration::ZERO, &guard).expect("first lock");
assert_eq!(
LifecycleLock::acquire_at(&path, Duration::ZERO, &guard).err(),
Some(UserVerificationError::Failed {
reason: UserVerificationFailureReason::Timeout,
message: "timed out waiting for another credential operation".to_string(),
})
);
drop(first);
LifecycleLock::acquire_at(&path, Duration::ZERO, &guard).expect("lock after release");
}
#[test]
fn cancelled_waiter_stops_while_another_operation_still_holds_lock() {
let directory = tempfile::tempdir().expect("temporary directory");
let path = directory.path().join("credential.lock");
let holder = LifecycleLock::acquire_at(
&path,
Duration::ZERO,
&UserVerificationRequestGuard::default(),
)
.expect("held lock");
let (ready_tx, ready_rx) = std::sync::mpsc::channel();
let checks = AtomicUsize::new(/*v*/ 0);
let guard = UserVerificationRequestGuard::with_activity_check(move || {
if checks.fetch_add(/*val*/ 1, Ordering::Relaxed) == 1 {
ready_tx.send(()).expect("notify lock wait");
}
true
});
let queued = guard.clone();
let worker = std::thread::spawn(move || {
LifecycleLock::acquire_at(&path, Duration::from_secs(/*secs*/ 5), &queued).err()
});
ready_rx
.recv_timeout(Duration::from_secs(/*secs*/ 5))
.expect("waiter entered lock loop");
guard.cancel();
assert_eq!(
worker.join().expect("waiter stopped"),
Some(UserVerificationError::Cancelled {
reason: UserVerificationCancellationReason::Interrupted,
message: "the verification operation is no longer active".to_string(),
})
);
drop(holder);
}

View File

@@ -0,0 +1,43 @@
//! Drains asynchronous authentication before releasing its context and lifecycle lock.
use crate::UserVerificationError;
use crate::UserVerificationFailureReason;
use crate::UserVerificationRequestGuard;
use std::sync::mpsc;
use std::time::Duration;
pub(crate) fn wait_with_cancellation<T>(
guard: &UserVerificationRequestGuard,
completion: mpsc::Receiver<Result<T, UserVerificationError>>,
cancel: impl FnOnce(),
) -> Result<T, UserVerificationError> {
let result = loop {
match completion.recv_timeout(Duration::from_millis(/*millis*/ 50)) {
Ok(result) => break result,
Err(mpsc::RecvTimeoutError::Timeout) => {
if !guard.is_active() {
cancel();
// Invalidation is asynchronous. Keep the lifecycle lock until the
// authentication callback completes, then reject any late success.
break completion
.recv()
.unwrap_or_else(|_| Err(completion_error()));
}
}
Err(mpsc::RecvTimeoutError::Disconnected) => break Err(completion_error()),
}
};
guard.check()?;
result
}
fn completion_error() -> UserVerificationError {
UserVerificationError::Failed {
reason: UserVerificationFailureReason::ProviderError,
message: "the user-verification authorization could not complete".to_string(),
}
}
#[cfg(test)]
#[path = "native_operation_tests.rs"]
mod tests;

View File

@@ -0,0 +1,70 @@
//! Exercises cancellation completion and late-result rejection without biometric hardware.
use super::*;
use crate::UserVerificationCancellationReason;
use pretty_assertions::assert_eq;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
#[test]
fn cancellation_waits_for_completion_on_the_context_owner_thread() {
let guard = UserVerificationRequestGuard::default();
let queued = guard.clone();
let (done_tx, done_rx) = mpsc::sync_channel(0);
let (cancelled_tx, cancelled_rx) = mpsc::channel();
let owner = std::thread::spawn(move || {
let owner_thread = std::thread::current().id();
wait_with_cancellation(&queued, done_rx, || {
assert_eq!(std::thread::current().id(), owner_thread);
cancelled_tx.send(()).expect("dismiss authentication");
})
});
guard.cancel();
cancelled_rx
.recv_timeout(Duration::from_secs(/*secs*/ 5))
.expect("authentication invalidated");
assert!(!owner.is_finished());
done_tx
.send(Ok("late authorization"))
.expect("complete authentication");
assert_eq!(
owner.join().expect("owner returned"),
Err(UserVerificationError::Cancelled {
reason: UserVerificationCancellationReason::Interrupted,
message: "the verification operation is no longer active".to_string(),
})
);
}
#[test]
fn completed_operation_does_not_cancel_its_context() {
let cancelled = AtomicBool::new(/*v*/ false);
let (done_tx, done_rx) = mpsc::channel();
done_tx
.send(Ok("authorization"))
.expect("complete authentication");
assert_eq!(
wait_with_cancellation(&UserVerificationRequestGuard::default(), done_rx, || {
cancelled.store(/*val*/ true, Ordering::Release)
},),
Ok("authorization")
);
assert!(!cancelled.load(Ordering::Acquire));
}
#[test]
fn cancellation_rejects_already_completed_authorization() {
let guard = UserVerificationRequestGuard::default();
let (done_tx, done_rx) = mpsc::channel();
done_tx.send(Ok(())).expect("complete authentication");
guard.cancel();
assert_eq!(
wait_with_cancellation(&guard, done_rx, || panic!(
"authentication already completed"
)),
Err(UserVerificationError::Cancelled {
reason: UserVerificationCancellationReason::Interrupted,
message: "the verification operation is no longer active".to_string(),
})
);
}

View File

@@ -0,0 +1,12 @@
//! macOS Security and LocalAuthentication integration.
mod error;
#[cfg(target_os = "macos")]
mod key_protection;
#[cfg(target_os = "macos")]
mod provider;
#[cfg(target_os = "macos")]
pub(crate) use provider::NativeProvider;
#[cfg(target_os = "macos")]
pub(crate) use provider::device_supported;

View File

@@ -0,0 +1,54 @@
//! Maps macOS Security and LocalAuthentication failures to stable errors without exposing localized OS diagnostics.
use crate::UserVerificationCancellationReason;
use crate::UserVerificationError;
use crate::UserVerificationFailureReason;
use crate::UserVerificationUnavailableReason;
pub(crate) fn classify(domain: &str, code: i64) -> UserVerificationError {
tracing::debug!(domain, code, "native user-verification operation failed");
match (domain, code) {
("NSOSStatusErrorDomain", -128) | ("com.apple.LocalAuthentication", -2 | -3) => {
UserVerificationError::Cancelled {
reason: UserVerificationCancellationReason::UserCancelled,
message: "authentication was cancelled".to_string(),
}
}
("com.apple.LocalAuthentication", -4 | -9) => UserVerificationError::Cancelled {
reason: UserVerificationCancellationReason::Interrupted,
message: "authentication was interrupted".to_string(),
},
("NSOSStatusErrorDomain", -25293) | ("com.apple.LocalAuthentication", -1) => {
UserVerificationError::Failed {
reason: UserVerificationFailureReason::AuthenticationFailed,
message: "biometric authentication failed".to_string(),
}
}
("com.apple.LocalAuthentication", -5 | -6 | -7 | -8 | -12 | -13) => {
UserVerificationError::Unavailable {
reason: UserVerificationUnavailableReason::BiometricsUnavailable,
message: "biometric authentication is not available right now".to_string(),
}
}
("com.apple.LocalAuthentication", -1004) => UserVerificationError::Unavailable {
reason: UserVerificationUnavailableReason::ProviderUnavailable,
message: "authentication UI is not permitted in this process".to_string(),
},
("NSOSStatusErrorDomain", -34018) => UserVerificationError::Unavailable {
reason: UserVerificationUnavailableReason::ProviderUnavailable,
message: "this binary is missing the required keychain entitlements".to_string(),
},
("NSOSStatusErrorDomain", -25291 | -25308) => UserVerificationError::Unavailable {
reason: UserVerificationUnavailableReason::ProviderUnavailable,
message: "the platform keychain is not available right now".to_string(),
},
_ => UserVerificationError::Failed {
reason: UserVerificationFailureReason::ProviderError,
message: "the platform could not complete user verification".to_string(),
},
}
}
#[cfg(test)]
#[path = "error_tests.rs"]
mod tests;

View File

@@ -0,0 +1,51 @@
//! Native failure classification is based on the domain and code, never localized text.
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn cancellation_is_distinct_from_authentication_failure() {
assert_eq!(
classify("com.apple.LocalAuthentication", /*code*/ -2),
UserVerificationError::Cancelled {
reason: UserVerificationCancellationReason::UserCancelled,
message: "authentication was cancelled".to_string(),
}
);
assert_eq!(
classify("NSOSStatusErrorDomain", /*code*/ -25293),
UserVerificationError::Failed {
reason: UserVerificationFailureReason::AuthenticationFailed,
message: "biometric authentication failed".to_string(),
}
);
}
#[test]
fn biometric_lockout_and_missing_entitlements_report_distinct_unavailability() {
assert_eq!(
classify("com.apple.LocalAuthentication", /*code*/ -8),
UserVerificationError::Unavailable {
reason: UserVerificationUnavailableReason::BiometricsUnavailable,
message: "biometric authentication is not available right now".to_string(),
}
);
assert_eq!(
classify("NSOSStatusErrorDomain", /*code*/ -34018),
UserVerificationError::Unavailable {
reason: UserVerificationUnavailableReason::ProviderUnavailable,
message: "this binary is missing the required keychain entitlements".to_string(),
}
);
}
#[test]
fn unknown_error_domain_cannot_impersonate_cancellation() {
assert_eq!(
classify("unknown", /*code*/ -2),
UserVerificationError::Failed {
reason: UserVerificationFailureReason::ProviderError,
message: "the platform could not complete user verification".to_string(),
}
);
}

View File

@@ -0,0 +1,66 @@
//! Create biometric signing policies and validate Secure Enclave key attributes.
use super::error;
use crate::UserVerificationError;
use crate::UserVerificationUnavailableReason;
use core_foundation::base::CFEqual;
use core_foundation::base::TCFType as _;
use core_foundation::dictionary::CFDictionary;
use core_foundation::number::CFNumber;
use security_framework::access_control::ProtectionMode;
use security_framework::access_control::SecAccessControl;
use security_framework::key::SecKey;
use security_framework_sys::access_control::kSecAccessControlBiometryAny;
use security_framework_sys::access_control::kSecAccessControlPrivateKeyUsage;
use security_framework_sys::item::kSecAttrKeyClass;
use security_framework_sys::item::kSecAttrKeyClassPrivate;
use security_framework_sys::item::kSecAttrKeySizeInBits;
use security_framework_sys::item::kSecAttrKeyType;
use security_framework_sys::item::kSecAttrKeyTypeECSECPrimeRandom;
use security_framework_sys::item::kSecAttrTokenID;
use security_framework_sys::item::kSecAttrTokenIDSecureEnclave;
pub(super) fn access_control() -> Result<SecAccessControl, UserVerificationError> {
SecAccessControl::create_with_protection(
Some(ProtectionMode::AccessibleWhenUnlockedThisDeviceOnly),
kSecAccessControlBiometryAny | kSecAccessControlPrivateKeyUsage,
)
.map_err(|err| error::classify("NSOSStatusErrorDomain", i64::from(err.code())))
}
pub(super) fn validate(key: &SecKey) -> Result<(), UserVerificationError> {
validate_attributes(&key.attributes())
}
fn validate_attributes(attributes: &CFDictionary) -> Result<(), UserVerificationError> {
let size = CFNumber::from(/*value*/ 256);
// Do not compare opaque SecAccessControl objects: macOS can change their persisted
// representation. Biometric signing is enforced by the policy set at key creation.
// Reuse trusts that keys in this namespace, within the process's entitled keychain
// access groups, were created with that policy; these checks do not revalidate it.
let expected = unsafe {
[
(kSecAttrTokenID, kSecAttrTokenIDSecureEnclave.cast()),
(kSecAttrKeyClass, kSecAttrKeyClassPrivate.cast()),
(kSecAttrKeyType, kSecAttrKeyTypeECSECPrimeRandom.cast()),
(kSecAttrKeySizeInBits, size.as_CFTypeRef()),
]
};
if expected.into_iter().all(|(name, expected)| {
attributes
.find(name.cast())
.is_some_and(|value| unsafe { CFEqual(*value, expected) != 0 })
}) {
Ok(())
} else {
Err(UserVerificationError::Unavailable {
reason: UserVerificationUnavailableReason::ProviderUnavailable,
message: "the local credential has incompatible key protection; delete it before enrolling again"
.to_string(),
})
}
}
#[cfg(test)]
#[path = "key_protection_tests.rs"]
mod tests;

View File

@@ -0,0 +1,62 @@
//! Reject keys without the required Secure Enclave key attributes.
use super::*;
use core_foundation::base::CFType;
use core_foundation::dictionary::CFMutableDictionary;
use core_foundation::string::CFString;
use pretty_assertions::assert_eq;
fn protected_attributes() -> CFMutableDictionary<CFString, CFType> {
unsafe {
CFMutableDictionary::from_CFType_pairs(&[
(
CFString::wrap_under_get_rule(kSecAttrTokenID),
CFString::wrap_under_get_rule(kSecAttrTokenIDSecureEnclave).as_CFType(),
),
(
CFString::wrap_under_get_rule(kSecAttrKeyClass),
CFString::wrap_under_get_rule(kSecAttrKeyClassPrivate).as_CFType(),
),
(
CFString::wrap_under_get_rule(kSecAttrKeyType),
CFString::wrap_under_get_rule(kSecAttrKeyTypeECSECPrimeRandom).as_CFType(),
),
(
CFString::wrap_under_get_rule(kSecAttrKeySizeInBits),
CFNumber::from(/*value*/ 256).as_CFType(),
),
])
}
}
#[test]
fn reuse_requires_secure_enclave_key_attributes() {
let attributes = protected_attributes();
assert_eq!(
validate_attributes(&attributes.to_immutable().to_untyped()),
Ok(())
);
let alternatives = unsafe {
[
(kSecAttrTokenID, CFString::new("software").as_CFType()),
(kSecAttrKeyClass, CFString::new("public").as_CFType()),
(kSecAttrKeyType, CFString::new("RSA").as_CFType()),
(
kSecAttrKeySizeInBits,
CFNumber::from(/*value*/ 384).as_CFType(),
),
]
};
for (attribute, value) in alternatives {
let mut attributes = protected_attributes();
attributes.set(unsafe { CFString::wrap_under_get_rule(attribute) }, value);
assert_eq!(
validate_attributes(&attributes.to_immutable().to_untyped()),
Err(UserVerificationError::Unavailable {
reason: UserVerificationUnavailableReason::ProviderUnavailable,
message: "the local credential has incompatible key protection; delete it before enrolling again"
.to_string(),
})
);
}
}

View File

@@ -0,0 +1,367 @@
//! Secure Enclave keys; biometric access is enforced by the key, not a separate UI check.
use super::error;
use super::key_protection;
use crate::UserVerificationError;
use crate::UserVerificationFailureReason;
use crate::UserVerificationKeyCreation;
use crate::UserVerificationKeyDeletion;
use crate::UserVerificationKeyInfo;
use crate::UserVerificationKeyNamespace;
use crate::UserVerificationProof;
use crate::UserVerificationProvider;
use crate::UserVerificationRequest;
use crate::UserVerificationRequestGuard;
use crate::UserVerificationStatus;
use crate::UserVerificationUnavailableReason;
use crate::lifecycle_lock::LifecycleLock;
use crate::native_operation::wait_with_cancellation;
use base64::Engine as _;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use block2::RcBlock;
use core_foundation::base::CFType;
use core_foundation::base::TCFType as _;
use objc2::rc::Retained;
use objc2::runtime::Bool;
use objc2_foundation::NSError;
use objc2_foundation::NSString;
use objc2_local_authentication::LAAccessControlOperation;
use objc2_local_authentication::LABiometryType;
use objc2_local_authentication::LAContext;
use objc2_local_authentication::LAPolicy;
use security_framework::access_control::SecAccessControl;
use security_framework::base::Error as SecurityError;
use security_framework::item::ItemClass;
use security_framework::item::ItemSearchOptions;
use security_framework::item::KeyClass;
use security_framework::item::Limit;
use security_framework::item::Location;
use security_framework::item::Reference;
use security_framework::item::SearchResult;
use security_framework::key::Algorithm;
use security_framework::key::GenerateKeyOptions;
use security_framework::key::KeyType;
use security_framework::key::SecKey;
use security_framework::key::Token;
use security_framework_sys::base::errSecItemNotFound;
use security_framework_sys::item::kSecAttrAccessControl;
use security_framework_sys::item::kSecValueRef;
use std::sync::mpsc;
pub(crate) struct NativeProvider {
pub(crate) namespace: UserVerificationKeyNamespace,
}
pub(crate) fn device_supported() -> bool {
let context = noninteractive_context();
// canEvaluatePolicy populates biometryType even when enrollment or temporary lockout
// prevents authentication. Advertise hardware support independently of current readiness.
unsafe {
let _ = context.canEvaluatePolicy_error(LAPolicy::DeviceOwnerAuthenticationWithBiometrics);
context.biometryType() == LABiometryType::TouchID
}
}
impl UserVerificationProvider for NativeProvider {
fn status(
&self,
guard: &UserVerificationRequestGuard,
) -> Result<UserVerificationStatus, UserVerificationError> {
let _lock = LifecycleLock::acquire(&self.namespace, guard)?;
let context = noninteractive_context();
let credential = find_key(&self.namespace.label, &context, KeyUse::Protected)?
.as_ref()
.map(key_info)
.transpose()?;
let unavailable = if credential.is_none() {
Some((
UserVerificationUnavailableReason::CredentialMissing,
"no user-verification credential has been created".to_string(),
))
} else {
match check_biometrics(&context) {
Ok(()) => None,
Err(UserVerificationError::Unavailable { reason, message }) => {
Some((reason, message))
}
Err(error) => return Err(error),
}
};
let (unavailable_reason, unavailable_message) = match unavailable {
Some((reason, message)) => (Some(reason), Some(message)),
None => (None, None),
};
guard.check()?;
Ok(UserVerificationStatus {
credential,
unavailable_reason,
unavailable_message,
})
}
fn ensure_key(
&self,
guard: &UserVerificationRequestGuard,
) -> Result<UserVerificationKeyCreation, UserVerificationError> {
let _lock = LifecycleLock::acquire(&self.namespace, guard)?;
let context = noninteractive_context();
let existing = find_key(&self.namespace.label, &context, KeyUse::Protected)?;
guard.check()?;
let (key, created) = match existing {
Some(key) => (key, false),
None => (create_key(&self.namespace.label)?, true),
};
let credential = key_info(&key)?;
guard.check()?;
Ok(UserVerificationKeyCreation {
created,
credential,
})
}
fn delete(
&self,
guard: &UserVerificationRequestGuard,
) -> Result<UserVerificationKeyDeletion, UserVerificationError> {
let _lock = LifecycleLock::acquire(&self.namespace, guard)?;
let context = noninteractive_context();
// The credential ID is optional information for the caller. A colliding key may
// have no P-256 public key, or its lookup may fail because authentication is
// unavailable; neither should prevent removing this namespace's key items.
let credential = find_key(&self.namespace.label, &context, KeyUse::Deletion)
.ok()
.flatten()
.and_then(|key| key_info(&key).ok());
guard.check()?;
let mut options = ItemSearchOptions::new();
// GenerateKeyOptions persists both halves on macOS. Remove all key items under
// this exact namespace, including public keys left by an interrupted deletion.
options
.ignore_legacy_keychains()
.class(ItemClass::key())
.label(&self.namespace.label);
match options.delete() {
Ok(()) => {}
Err(error) if error.code() == errSecItemNotFound => {}
Err(error) => return Err(keychain_error(error)),
}
guard.check()?;
Ok(UserVerificationKeyDeletion {
deleted_credential_id: credential.map(|key| key.credential_id),
})
}
fn verify(
&self,
request: &UserVerificationRequest,
guard: &UserVerificationRequestGuard,
) -> Result<UserVerificationProof, UserVerificationError> {
guard.check()?;
if request.challenge.is_empty()
|| request.challenge.len() > 4096
|| request.title.is_empty()
|| request.title.len() > 256
|| request.description.len() > 4096
{
return Err(UserVerificationError::Failed {
reason: UserVerificationFailureReason::ProviderError,
message: "invalid user-verification challenge or display text".to_string(),
});
}
let _lock = LifecycleLock::acquire(&self.namespace, guard)?;
// A fresh context for every signature prevents authentication reuse between actions.
let context = unsafe { LAContext::new() };
let reason = if request.description.is_empty() {
request.title.clone()
} else {
format!("{}\n\n{}", request.title, request.description)
};
unsafe {
context.setLocalizedFallbackTitle(Some(&NSString::from_str("")));
context.setLocalizedReason(&NSString::from_str(&reason));
}
check_biometrics(&context)?;
guard.check()?;
// SecKeyCopyAttributes does not guarantee the stored item's access-control attribute.
let attributes = match key_query(&self.namespace.label, &noninteractive_context())
.load_refs(true)
.load_attributes(true)
.search()
{
Ok(results) => results.into_iter().find_map(|result| match result {
SearchResult::Dict(attributes) => Some(attributes),
_ => None,
}),
Err(error) if error.code() == errSecItemNotFound => {
return Err(UserVerificationError::Unavailable {
reason: UserVerificationUnavailableReason::CredentialMissing,
message: "no user-verification credential has been created".to_string(),
});
}
Err(error) => return Err(keychain_error(error)),
}
.ok_or_else(|| UserVerificationError::Failed {
reason: UserVerificationFailureReason::ProviderError,
message: "the user-verification key has no attributes".to_string(),
})?;
let key = attributes
.find(unsafe { kSecValueRef.cast() })
.and_then(|value| unsafe { CFType::wrap_under_get_rule(*value) }.downcast::<SecKey>())
.ok_or_else(|| UserVerificationError::Failed {
reason: UserVerificationFailureReason::ProviderError,
message: "the user-verification item has no key reference".to_string(),
})?;
key_protection::validate(&key)?;
let access = attributes
.find(unsafe { kSecAttrAccessControl.cast() })
.and_then(|value| {
unsafe { CFType::wrap_under_get_rule(*value) }.downcast::<SecAccessControl>()
})
.ok_or_else(|| UserVerificationError::Failed {
reason: UserVerificationFailureReason::ProviderError,
message: "the user-verification key has no access control".to_string(),
})?;
let (done_tx, done_rx) = mpsc::sync_channel(1);
let reply = RcBlock::new(move |success: Bool, error: *mut NSError| {
let result = if success.as_bool() {
Ok(())
} else if let Some(error) = unsafe { error.as_ref() } {
Err(error::classify(
&error.domain().to_string(),
error.code() as i64,
))
} else {
Err(UserVerificationError::Failed {
reason: UserVerificationFailureReason::ProviderError,
message: "biometric authorization did not complete".to_string(),
})
};
let _ = done_tx.send(result);
});
guard.check()?;
// Keychain signing reconstructs its own context. Evaluate the key's policy here
// so cancellation invalidates the context that actually owns the prompt.
unsafe {
context.evaluateAccessControl_operation_localizedReason_reply(
&*access.as_concrete_TypeRef().cast(),
LAAccessControlOperation::UseKeySign,
&NSString::from_str(&reason),
&reply,
);
}
wait_with_cancellation(guard, done_rx, || unsafe { context.invalidate() })?;
// Fetch a new key reference with the authorized, noninteractive context. Signing
// must fail instead of opening another prompt if that authorization is unusable.
unsafe {
context.setInteractionNotAllowed(/*interaction_not_allowed*/ true)
};
let key =
find_key(&self.namespace.label, &context, KeyUse::Protected)?.ok_or_else(|| {
UserVerificationError::Unavailable {
reason: UserVerificationUnavailableReason::CredentialMissing,
message: "no user-verification credential has been created".to_string(),
}
})?;
let credential = key_info(&key)?;
guard.check()?;
let signature = key
.create_signature(
Algorithm::ECDSASignatureMessageX962SHA256,
&request.challenge,
)
.map_err(|error| error::classify(&error.domain().to_string(), error.code() as i64));
guard.check()?;
Ok(UserVerificationProof {
credential_id: credential.credential_id,
signature: URL_SAFE_NO_PAD.encode(signature?),
})
}
}
fn noninteractive_context() -> Retained<LAContext> {
// Each context is confined to this blocking operation and never shared across threads.
unsafe {
let context = LAContext::new();
context.setInteractionNotAllowed(/*interaction_not_allowed*/ true);
context
}
}
fn check_biometrics(context: &LAContext) -> Result<(), UserVerificationError> {
// canEvaluatePolicy only checks availability; evaluating the key's policy authenticates.
unsafe { context.canEvaluatePolicy_error(LAPolicy::DeviceOwnerAuthenticationWithBiometrics) }
.map_err(|error| error::classify(&error.domain().to_string(), error.code() as i64))
}
enum KeyUse {
Protected,
Deletion,
}
fn find_key(
label: &str,
context: &LAContext,
key_use: KeyUse,
) -> Result<Option<SecKey>, UserVerificationError> {
match key_query(label, context).load_refs(true).search() {
Ok(results) => {
let key = results.into_iter().find_map(|result| match result {
SearchResult::Ref(Reference::Key(key)) => Some(key),
_ => None,
});
if let Some(key) = &key
&& matches!(key_use, KeyUse::Protected)
{
key_protection::validate(key)?;
}
Ok(key)
}
Err(error) if error.code() == errSecItemNotFound => Ok(None),
Err(error) => Err(keychain_error(error)),
}
}
fn key_query(label: &str, context: &LAContext) -> ItemSearchOptions {
// Security accepts an LAContext object as kSecUseAuthenticationContext. Wrapping under
// the get rule retains it, and ItemSearchOptions owns that retain for the query lifetime.
let authentication = unsafe { CFType::wrap_under_get_rule(std::ptr::from_ref(context).cast()) };
let mut options = ItemSearchOptions::new();
options
.ignore_legacy_keychains()
.key_class(KeyClass::private())
.label(label)
.local_authentication_context(Some(authentication))
.limit(Limit::Max(1));
options
}
fn create_key(label: &str) -> Result<SecKey, UserVerificationError> {
let access = key_protection::access_control()?;
let mut options = GenerateKeyOptions::default();
options
.set_key_type(KeyType::ec_sec_prime_random())
.set_size_in_bits(256)
.set_label(label)
.set_token(Token::SecureEnclave)
.set_location(Location::DataProtectionKeychain)
.set_access_control(access);
let key = SecKey::new(&options)
.map_err(|error| error::classify(&error.domain().to_string(), error.code() as i64))?;
key_protection::validate(&key)?;
Ok(key)
}
fn key_info(key: &SecKey) -> Result<UserVerificationKeyInfo, UserVerificationError> {
let bytes = key
.public_key()
.and_then(|key| key.external_representation())
.ok_or_else(|| UserVerificationError::Failed {
reason: UserVerificationFailureReason::ProviderError,
message: "could not export the user-verification public key".to_string(),
})?;
UserVerificationKeyInfo::from_sec1_public_key(&bytes)
}
fn keychain_error(error: SecurityError) -> UserVerificationError {
error::classify("NSOSStatusErrorDomain", i64::from(error.code()))
}

View File

@@ -0,0 +1,53 @@
//! Typed unavailable behavior until a native provider is available for this platform.
use crate::*;
pub(crate) struct UnsupportedProvider;
fn unavailable() -> UserVerificationError {
UserVerificationError::Unavailable {
reason: UserVerificationUnavailableReason::ProviderUnavailable,
message: "this platform does not support user verification".to_string(),
}
}
impl UserVerificationProvider for UnsupportedProvider {
fn status(
&self,
guard: &UserVerificationRequestGuard,
) -> Result<UserVerificationStatus, UserVerificationError> {
guard.check()?;
Ok(UserVerificationStatus {
credential: None,
unavailable_reason: Some(UserVerificationUnavailableReason::ProviderUnavailable),
unavailable_message: Some(
"this platform does not support user verification".to_string(),
),
})
}
fn ensure_key(
&self,
guard: &UserVerificationRequestGuard,
) -> Result<UserVerificationKeyCreation, UserVerificationError> {
guard.check()?;
Err(unavailable())
}
fn delete(
&self,
guard: &UserVerificationRequestGuard,
) -> Result<UserVerificationKeyDeletion, UserVerificationError> {
guard.check()?;
Err(unavailable())
}
fn verify(
&self,
_request: &UserVerificationRequest,
guard: &UserVerificationRequestGuard,
) -> Result<UserVerificationProof, UserVerificationError> {
guard.check()?;
Err(unavailable())
}
}

View File

@@ -0,0 +1,134 @@
//! Opt-in checks of the persisted Secure Enclave signing and cancellation path.
#![cfg(target_os = "macos")]
use base64::Engine as _;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use akode_user_verification::UserVerificationCancellationReason;
use akode_user_verification::UserVerificationError;
use akode_user_verification::UserVerificationKeyNamespace;
use akode_user_verification::UserVerificationProvider;
use akode_user_verification::UserVerificationRequest;
use akode_user_verification::UserVerificationRequestGuard;
use akode_user_verification::platform_provider;
use p256::ecdsa::Signature;
use p256::ecdsa::VerifyingKey;
use p256::ecdsa::signature::Verifier as _;
use p256::pkcs8::DecodePublicKey as _;
use pretty_assertions::assert_eq;
use std::sync::Arc;
use std::sync::mpsc;
use std::time::Duration;
const TEST_IDENTITY: &str = "codex-user-verification-hardware-test";
struct TestKey(Arc<dyn UserVerificationProvider>);
impl Drop for TestKey {
fn drop(&mut self) {
let deleted = self.0.delete(&UserVerificationRequestGuard::default());
if !std::thread::panicking() {
assert!(deleted.is_ok(), "delete the test credential: {deleted:?}");
}
}
}
#[test]
#[ignore = "requires a signed test app, a physical Touch ID Mac, and user interaction; see README.md"]
fn persisted_key_signing_cancellation_and_retry() {
let provider = platform_provider(UserVerificationKeyNamespace::new(TEST_IDENTITY));
// This namespace is reserved for this test, including cleanup after a killed run.
provider
.delete(&UserVerificationRequestGuard::default())
.expect("clear any previous test credential");
if std::env::var_os("AKODE_HARDWARE_TEST_CLEANUP").is_some() {
return;
}
let cleanup = TestKey(Arc::clone(&provider));
let created = provider
.ensure_key(&UserVerificationRequestGuard::default())
.expect("create a persisted Secure Enclave key");
assert!(created.created);
let reloaded = platform_provider(UserVerificationKeyNamespace::new(TEST_IDENTITY))
.ensure_key(&UserVerificationRequestGuard::default())
.expect("reload the persisted key");
assert!(!reloaded.created);
assert_eq!(reloaded.credential, created.credential);
let public_key = VerifyingKey::from_public_key_der(
&URL_SAFE_NO_PAD
.decode(&created.credential.public_key)
.unwrap(),
)
.unwrap();
let sign = |request: &UserVerificationRequest| {
let proof = provider
.verify(request, &UserVerificationRequestGuard::default())
.expect("sign with the persisted key");
assert_eq!(proof.credential_id, created.credential.credential_id);
let signature =
Signature::from_der(&URL_SAFE_NO_PAD.decode(proof.signature).unwrap()).unwrap();
public_key.verify(&request.challenge, &signature).unwrap();
};
let mut request = UserVerificationRequest {
challenge: b"Local hardware test. No purchase.".to_vec(),
title: "Hardware test: authenticate".into(),
description: "Use Touch ID once, then remove your finger.".into(),
};
eprintln!("Use Touch ID for the first signature.");
sign(&request);
request.title = "Hardware test: cancellation".into();
request.description =
"Leave Touch ID untouched; this prompt should close automatically.".into();
eprintln!("Leave the next prompt untouched; cancellation follows in three seconds.");
let guard = UserVerificationRequestGuard::default();
let cancellation = guard.clone();
let (finished, completion) = mpsc::channel();
let timer = std::thread::spawn(move || {
if completion.recv_timeout(Duration::from_secs(/* secs */ 3))
== Err(mpsc::RecvTimeoutError::Timeout)
{
cancellation.cancel();
if completion.recv_timeout(Duration::from_secs(/* secs */ 10))
== Err(mpsc::RecvTimeoutError::Timeout)
{
eprintln!(
"Cancellation did not finish. Run with AKODE_HARDWARE_TEST_CLEANUP=1 to remove the test key."
);
std::process::exit(/* code */ 1);
}
true
} else {
false
}
});
let result = provider.verify(&request, &guard);
finished.send(()).unwrap();
assert!(
timer.join().unwrap(),
"verification finished before cancellation"
);
assert!(
matches!(
result,
Err(UserVerificationError::Cancelled {
reason: UserVerificationCancellationReason::Interrupted,
..
})
),
"unexpected cancellation result: {result:?}"
);
request.challenge = b"Retry signing after cancellation.".to_vec();
request.title = "Hardware test: retry signing".into();
request.description = "Use Touch ID to sign again with the same stored key.".into();
eprintln!("Use Touch ID for the retry.");
sign(&request);
drop(cleanup);
assert!(
provider
.status(&UserVerificationRequestGuard::default())
.unwrap()
.credential
.is_none()
);
}