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