Skip to main content

security/
error.rs

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