Log macOS user verification enrollment failure diagnostics (#62107)

## What changed

Add structured warnings for enrollment failures during key lookup, access control creation, key creation, key validation, and public key export. Include available native and underlying error codes and allowlisted error domains, without logging error descriptions or other error metadata.

After a failure, check biometric readiness using a fresh, noninteractive context and include the result in the warning. Preserve the original error classification.

GitOrigin-RevId: 697e1a69dc5c8e457b61aff9a674e7aca77f86f2
This commit is contained in:
ben zhang
2026-11-17 20:05:26 +00:00
committed by copyberry
parent 6c0cee502d
commit 8011b92bc8
4 changed files with 121 additions and 13 deletions
@@ -1,5 +1,7 @@
//! macOS Security and LocalAuthentication integration.
#[cfg(target_os = "macos")]
mod enrollment_diagnostics;
mod error;
#[cfg(target_os = "macos")]
mod key_protection;
@@ -0,0 +1,81 @@
//! Collects content-free Apple error and biometric readiness details after local enrollment fails.
use super::provider::noninteractive_context;
use core_foundation::base::CFType;
use core_foundation::base::TCFType as _;
use core_foundation::dictionary::CFDictionary;
use core_foundation::error::CFError;
use core_foundation::error::CFErrorCopyUserInfo;
use core_foundation::error::kCFErrorUnderlyingErrorKey;
use core_foundation::string::CFString;
use objc2_local_authentication::LAPolicy;
use security_framework::base::Error as SecurityError;
pub(super) enum EnrollmentError<'a> {
Status(SecurityError),
Creation(&'a CFError),
}
pub(super) fn log_enrollment_failure(stage: &'static str, error: Option<EnrollmentError<'_>>) {
let (native_error, underlying) = match error {
Some(EnrollmentError::Status(error)) => (
Some(("NSOSStatusErrorDomain", i64::from(error.code()))),
None,
),
Some(EnrollmentError::Creation(error)) => {
(Some(diagnostic_code(error)), underlying_error(error))
}
None => (None, None),
};
// Query a fresh, noninteractive context only after failure. Readiness is
// evidence at that instant and must not replace the original Keychain result.
let context = noninteractive_context();
let readiness_error = unsafe {
context.canEvaluatePolicy_error(LAPolicy::DeviceOwnerAuthenticationWithBiometrics)
}
.err();
let readiness_domain = readiness_error
.as_ref()
.map(|error| error.domain().to_string());
tracing::warn!(
target: "codex_user_verification::enrollment",
stage,
native_domain = native_error.map(|(domain, _)| domain),
native_code = native_error.map(|(_, code)| code),
underlying_domain = underlying.map(|(domain, _)| domain),
underlying_code = underlying.map(|(_, code)| code),
biometrics_ready = readiness_error.is_none(),
readiness_domain = readiness_domain.as_deref().map(diagnostic_domain),
readiness_code = readiness_error.as_ref().map(|error| error.code() as i64),
"macos_user_verification_enrollment_failed"
);
}
fn diagnostic_code(error: &CFError) -> (&'static str, i64) {
(
diagnostic_domain(&error.domain().to_string()),
error.code() as i64,
)
}
fn underlying_error(error: &CFError) -> Option<(&'static str, i64)> {
// Security may wrap a more specific error. Read only the underlying error's
// domain and code; the rest of userInfo can contain private descriptions.
let info = unsafe { CFErrorCopyUserInfo(error.as_concrete_TypeRef()) };
if info.is_null() {
return None;
}
let info = unsafe { CFDictionary::<CFString, CFType>::wrap_under_create_rule(info) };
let key = unsafe { CFString::wrap_under_get_rule(kCFErrorUnderlyingErrorKey) };
let cause = info.find(&key)?.downcast::<CFError>()?;
Some(diagnostic_code(&cause))
}
fn diagnostic_domain(domain: &str) -> &'static str {
match domain {
"NSOSStatusErrorDomain" => "NSOSStatusErrorDomain",
"com.apple.LocalAuthentication" => "com.apple.LocalAuthentication",
"CryptoTokenKit" => "CryptoTokenKit",
_ => "other",
}
}
@@ -1,6 +1,5 @@
//! Create biometric signing policies and validate Secure Enclave key attributes.
use super::error;
use crate::UserVerificationError;
use crate::UserVerificationUnavailableReason;
use core_foundation::base::CFEqual;
@@ -9,6 +8,7 @@ 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::base::Error as SecurityError;
use security_framework::key::SecKey;
use security_framework_sys::access_control::kSecAccessControlBiometryAny;
use security_framework_sys::access_control::kSecAccessControlPrivateKeyUsage;
@@ -20,12 +20,11 @@ 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> {
pub(super) fn access_control() -> Result<SecAccessControl, SecurityError> {
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> {
@@ -1,5 +1,7 @@
//! Secure Enclave keys; biometric access is enforced by the key, not a separate UI check.
use super::enrollment_diagnostics::EnrollmentError;
use super::enrollment_diagnostics::log_enrollment_failure;
use super::error;
use super::key_protection;
use crate::UserVerificationBiometricType;
@@ -106,13 +108,15 @@ impl UserVerificationProvider for NativeProvider {
) -> Result<UserVerificationKeyCreation, UserVerificationError> {
let _lock = LifecycleLock::acquire(&self.namespace, guard)?;
let context = noninteractive_context();
let existing = find_key(&self.namespace.label, &context, KeyUse::Protected)?;
let existing = find_key(&self.namespace.label, &context, KeyUse::Enrollment)?;
guard.check()?;
let (key, created) = match existing {
Some(key) => (key, false),
None => (create_key(&self.namespace.label)?, true),
};
let credential = key_info(&key)?;
let credential = key_info(&key).inspect_err(|_| {
log_enrollment_failure("export_public_key", /*error*/ None);
})?;
guard.check()?;
Ok(UserVerificationKeyCreation {
created,
@@ -283,7 +287,7 @@ impl UserVerificationProvider for NativeProvider {
}
}
fn noninteractive_context() -> Retained<LAContext> {
pub(super) fn noninteractive_context() -> Retained<LAContext> {
// Each context is confined to this blocking operation and never shared across threads.
unsafe {
let context = LAContext::new();
@@ -300,6 +304,7 @@ fn check_biometrics(context: &LAContext) -> Result<(), UserVerificationError> {
enum KeyUse {
Protected,
Enrollment,
Deletion,
}
@@ -315,14 +320,23 @@ fn find_key(
_ => None,
});
if let Some(key) = &key
&& matches!(key_use, KeyUse::Protected)
&& !matches!(key_use, KeyUse::Deletion)
{
key_protection::validate(key)?;
key_protection::validate(key).inspect_err(|_| {
if matches!(key_use, KeyUse::Enrollment) {
log_enrollment_failure("validate_existing_key", /*error*/ None);
}
})?;
}
Ok(key)
}
Err(error) if error.code() == errSecItemNotFound => Ok(None),
Err(error) => Err(keychain_error(error)),
Err(error) => {
if matches!(key_use, KeyUse::Enrollment) {
log_enrollment_failure("lookup_key", Some(EnrollmentError::Status(error)));
}
Err(keychain_error(error))
}
}
}
@@ -341,7 +355,13 @@ fn key_query(label: &str, context: &LAContext) -> ItemSearchOptions {
}
fn create_key(label: &str) -> Result<SecKey, UserVerificationError> {
let access = key_protection::access_control()?;
let access = key_protection::access_control().map_err(|error| {
log_enrollment_failure(
"create_access_control",
Some(EnrollmentError::Status(error)),
);
keychain_error(error)
})?;
let mut options = GenerateKeyOptions::default();
options
.set_key_type(KeyType::ec_sec_prime_random())
@@ -350,9 +370,15 @@ fn create_key(label: &str) -> Result<SecKey, UserVerificationError> {
.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)?;
let key = SecKey::new(&options).map_err(|error| {
let domain = error.domain().to_string();
let code = error.code() as i64;
log_enrollment_failure("create_key", Some(EnrollmentError::Creation(&error)));
error::classify(&domain, code)
})?;
key_protection::validate(&key).inspect_err(|_| {
log_enrollment_failure("validate_created_key", /*error*/ None);
})?;
Ok(key)
}