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,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()))
}