Skip to main content

security/
error.rs

1//! Errors returned by the `security-rs` bindings.
2
3use core::fmt;
4
5use apple_cf::NullPointerError;
6
7/// Convenient result alias used throughout this crate.
8pub type Result<T, E = SecurityError> = std::result::Result<T, E>;
9
10/// Raw `OSStatus` code returned by Security.framework.
11pub type OsStatus = i32;
12
13/// Common status-code constants surfaced by the safe bridge.
14pub mod status {
15    use super::OsStatus;
16
17    /// Mirrors a common `OSStatus` value from Security.framework.
18    pub const SUCCESS: OsStatus = 0;
19    /// Mirrors a common `OSStatus` value from Security.framework.
20    pub const DUPLICATE_ITEM: OsStatus = -25_299;
21    /// Mirrors a common `OSStatus` value from Security.framework.
22    pub const ITEM_NOT_FOUND: OsStatus = -25_300;
23    /// Mirrors a common `OSStatus` value from Security.framework.
24    pub const INTERACTION_NOT_ALLOWED: OsStatus = -25_308;
25    pub const USER_CANCELED: OsStatus = -128;
26    pub const AUTH_FAILED: OsStatus = -25_293;
27    pub const MISSING_ENTITLEMENT: OsStatus = -34_018;
28    pub const UNIMPLEMENTED: OsStatus = -4;
29}
30
31/// Structured `OSStatus` error returned by `Security.framework`.
32#[derive(Debug, Clone, PartialEq, Eq)]
33pub struct StatusError {
34    /// API name that returned the status code.
35    pub operation: &'static str,
36    /// Raw `OSStatus` numeric code.
37    pub status: OsStatus,
38    /// Human-readable description when available.
39    pub message: String,
40}
41
42impl fmt::Display for StatusError {
43    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
44        write!(
45            f,
46            "{} failed with OSStatus {}: {}",
47            self.operation, self.status, self.message
48        )
49    }
50}
51
52impl std::error::Error for StatusError {}
53
54/// Top-level error type returned by this crate.
55#[derive(Debug, Clone, PartialEq, Eq)]
56#[non_exhaustive]
57pub enum SecurityError {
58    /// Invalid input crossed the FFI boundary.
59    InvalidArgument(String),
60    /// A requested keychain item was missing.
61    ItemNotFound(String),
62    /// A duplicate keychain item already existed.
63    DuplicateItem(String),
64    /// Authentication UI was suppressed or otherwise unavailable.
65    InteractionNotAllowed(String),
66    /// Trust evaluation failed and Security.framework provided a reason.
67    TrustEvaluationFailed(String),
68    /// Security.framework returned an unexpected Core Foundation type.
69    UnexpectedType {
70        /// API name being decoded.
71        operation: &'static str,
72        /// Expected Core Foundation family.
73        expected: &'static str,
74    },
75    /// JSON serialization or deserialization failed.
76    Serialization(String),
77    /// A Core Foundation creation call returned a null pointer.
78    CoreFoundation(NullPointerError),
79    /// Security.framework returned an unexpected `OSStatus`.
80    Status(StatusError),
81    Unsupported(String),
82}
83
84impl SecurityError {
85    #[must_use]
86    /// Returns the underlying `OSStatus` when Security.framework provided one.
87    pub const fn code(&self) -> Option<OsStatus> {
88        match self {
89            Self::ItemNotFound(_) => Some(status::ITEM_NOT_FOUND),
90            Self::DuplicateItem(_) => Some(status::DUPLICATE_ITEM),
91            Self::InteractionNotAllowed(_) => Some(status::INTERACTION_NOT_ALLOWED),
92            Self::Status(error) => Some(error.status),
93            _ => None,
94        }
95    }
96
97    pub(crate) fn from_status(operation: &'static str, status: OsStatus, message: String) -> Self {
98        match status {
99            status::ITEM_NOT_FOUND => Self::ItemNotFound(message),
100            status::DUPLICATE_ITEM => Self::DuplicateItem(message),
101            status::INTERACTION_NOT_ALLOWED => Self::InteractionNotAllowed(message),
102            _ => Self::Status(StatusError {
103                operation,
104                status,
105                message,
106            }),
107        }
108    }
109}
110
111impl fmt::Display for SecurityError {
112    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
113        match self {
114            Self::InvalidArgument(message) => write!(f, "invalid argument: {message}"),
115            Self::ItemNotFound(message) => write!(f, "item not found: {message}"),
116            Self::DuplicateItem(message) => write!(f, "duplicate item: {message}"),
117            Self::InteractionNotAllowed(message) => write!(f, "interaction not allowed: {message}"),
118            Self::TrustEvaluationFailed(message) => {
119                write!(f, "trust evaluation failed: {message}")
120            }
121            Self::UnexpectedType {
122                operation,
123                expected,
124            } => write!(
125                f,
126                "{operation} returned an unexpected value (expected {expected})"
127            ),
128            Self::Serialization(message) => write!(f, "serialization error: {message}"),
129            Self::CoreFoundation(error) => write!(f, "{error}"),
130            Self::Status(error) => write!(f, "{error}"),
131            Self::Unsupported(message) => write!(f, "unsupported: {message}"),
132        }
133    }
134}
135
136impl std::error::Error for SecurityError {
137    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
138        match self {
139            Self::CoreFoundation(error) => Some(error),
140            Self::Status(error) => Some(error),
141            _ => None,
142        }
143    }
144}
145
146#[cfg(test)]
147mod tests {
148    use super::*;
149
150    #[test]
151    fn status_error_display_includes_operation_status_and_message() {
152        let error = StatusError {
153            operation: "security_op",
154            status: -50,
155            message: "bad input".to_owned(),
156        };
157
158        assert_eq!(
159            error.to_string(),
160            "security_op failed with OSStatus -50: bad input"
161        );
162    }
163
164    #[test]
165    fn from_status_maps_known_codes_to_specialized_variants() {
166        assert_eq!(
167            SecurityError::from_status("op", status::ITEM_NOT_FOUND, "missing".to_owned()),
168            SecurityError::ItemNotFound("missing".to_owned())
169        );
170        assert_eq!(
171            SecurityError::from_status("op", status::DUPLICATE_ITEM, "duplicate".to_owned()),
172            SecurityError::DuplicateItem("duplicate".to_owned())
173        );
174        assert_eq!(
175            SecurityError::from_status(
176                "op",
177                status::INTERACTION_NOT_ALLOWED,
178                "suppressed".to_owned(),
179            ),
180            SecurityError::InteractionNotAllowed("suppressed".to_owned())
181        );
182    }
183
184    #[test]
185    fn from_status_wraps_unknown_codes_in_status_error() {
186        let error = SecurityError::from_status("security_op", -1_234, "unexpected".to_owned());
187
188        assert_eq!(
189            error,
190            SecurityError::Status(StatusError {
191                operation: "security_op",
192                status: -1_234,
193                message: "unexpected".to_owned(),
194            })
195        );
196        assert_eq!(error.code(), Some(-1_234));
197    }
198
199    #[test]
200    fn code_reports_expected_status_values() {
201        let status_error = SecurityError::Status(StatusError {
202            operation: "security_op",
203            status: -42,
204            message: "boom".to_owned(),
205        });
206
207        assert_eq!(
208            SecurityError::ItemNotFound("missing".to_owned()).code(),
209            Some(status::ITEM_NOT_FOUND)
210        );
211        assert_eq!(
212            SecurityError::DuplicateItem("duplicate".to_owned()).code(),
213            Some(status::DUPLICATE_ITEM)
214        );
215        assert_eq!(
216            SecurityError::InteractionNotAllowed("suppressed".to_owned()).code(),
217            Some(status::INTERACTION_NOT_ALLOWED)
218        );
219        assert_eq!(status_error.code(), Some(-42));
220        assert_eq!(
221            SecurityError::InvalidArgument("bad".to_owned()).code(),
222            None
223        );
224    }
225
226    #[test]
227    fn security_error_display_and_source_follow_wrapped_status() {
228        let wrapped = StatusError {
229            operation: "security_op",
230            status: -42,
231            message: "boom".to_owned(),
232        };
233        let error = SecurityError::Status(wrapped.clone());
234        let serialization = SecurityError::Serialization("invalid json".to_owned());
235
236        assert_eq!(error.to_string(), wrapped.to_string());
237        assert_eq!(
238            std::error::Error::source(&error).unwrap().to_string(),
239            wrapped.to_string()
240        );
241        assert!(std::error::Error::source(&serialization).is_none());
242    }
243}