use core::fmt;
use apple_cf::CFError;
use crate::ffi;
pub type Result<T, E = SecurityError> = std::result::Result<T, E>;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StatusError {
pub operation: &'static str,
pub status: ffi::OSStatus,
pub message: String,
}
impl fmt::Display for StatusError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{} failed with OSStatus {}: {}",
self.operation, self.status, self.message
)
}
}
impl std::error::Error for StatusError {}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum SecurityError {
InvalidArgument(String),
ItemNotFound(String),
DuplicateItem(String),
InteractionNotAllowed(String),
TrustEvaluationFailed(String),
CoreFoundation(CFError),
UnexpectedType {
operation: &'static str,
expected: &'static str,
},
Status(StatusError),
}
impl SecurityError {
#[must_use]
pub const fn code(&self) -> Option<ffi::OSStatus> {
match self {
Self::ItemNotFound(_) => Some(ffi::status::ITEM_NOT_FOUND),
Self::DuplicateItem(_) => Some(ffi::status::DUPLICATE_ITEM),
Self::InteractionNotAllowed(_) => Some(ffi::status::INTERACTION_NOT_ALLOWED),
Self::Status(error) => Some(error.status),
_ => None,
}
}
pub(crate) const fn from_status(
operation: &'static str,
status: ffi::OSStatus,
message: String,
) -> Self {
match status {
ffi::status::ITEM_NOT_FOUND => Self::ItemNotFound(message),
ffi::status::DUPLICATE_ITEM => Self::DuplicateItem(message),
ffi::status::INTERACTION_NOT_ALLOWED => Self::InteractionNotAllowed(message),
_ => Self::Status(StatusError {
operation,
status,
message,
}),
}
}
}
impl fmt::Display for SecurityError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::InvalidArgument(message) => write!(f, "invalid argument: {message}"),
Self::ItemNotFound(message) => write!(f, "item not found: {message}"),
Self::DuplicateItem(message) => write!(f, "duplicate item: {message}"),
Self::InteractionNotAllowed(message) => write!(f, "interaction not allowed: {message}"),
Self::TrustEvaluationFailed(message) => write!(f, "trust evaluation failed: {message}"),
Self::CoreFoundation(error) => write!(f, "{error}"),
Self::UnexpectedType {
operation,
expected,
} => write!(
f,
"{operation} returned an unexpected Core Foundation type (expected {expected})"
),
Self::Status(error) => write!(f, "{error}"),
}
}
}
impl std::error::Error for SecurityError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::CoreFoundation(error) => Some(error),
Self::Status(error) => Some(error),
_ => None,
}
}
}