Skip to main content

crucible_wire/
error.rs

1//! Errors. An implementation returns `crucible_server_runtime_rust::Result<T>` and may fail with
2//! anything: a modelled error, or any other error through `?`. The framework
3//! decides afterwards what reaches the caller (see `docs/framework.md`).
4
5use std::fmt;
6
7use serde_json::Value;
8
9use crate::operation::ErrorInfo;
10use crate::permissions::{PermissionInfo, ResourceInfo};
11
12pub type Result<T, E = Error> = std::result::Result<T, E>;
13
14/// Maximum depth of error source traversal to protect against cycles.
15pub const MAX_SOURCE_DEPTH: usize = 64;
16
17/// Any error. Like `anyhow::Error` it is not itself a `std::error::Error`,
18/// so every error type converts into it with `?`.
19pub struct Error {
20    inner: Box<dyn std::error::Error + Send + Sync + 'static>,
21}
22
23impl Error {
24    pub fn new(error: impl std::error::Error + Send + Sync + 'static) -> Self {
25        Self {
26            inner: Box::new(error),
27        }
28    }
29
30    /// An internal failure with a message for the logs. Callers never see it.
31    pub fn internal(message: impl Into<String>) -> Self {
32        Self::new(Internal(message.into()))
33    }
34
35    pub fn get_ref(&self) -> &(dyn std::error::Error + Send + Sync + 'static) {
36        &*self.inner
37    }
38
39    pub fn downcast_ref<E: std::error::Error + 'static>(&self) -> Option<&E> {
40        self.inner.downcast_ref::<E>()
41    }
42
43    /// This error and its sources, for a log line. Traversal depth is bounded
44    /// by [`MAX_SOURCE_DEPTH`] to protect against cycles in source chains.
45    pub fn chain(&self) -> String {
46        let mut text = self.inner.to_string();
47        let mut source = self.inner.source();
48        for _ in 0..MAX_SOURCE_DEPTH {
49            let Some(next) = source else { break };
50            text.push_str(": ");
51            text.push_str(&next.to_string());
52            source = next.source();
53        }
54        text
55    }
56}
57
58impl<E: std::error::Error + Send + Sync + 'static> From<E> for Error {
59    fn from(error: E) -> Self {
60        Self::new(error)
61    }
62}
63
64impl fmt::Debug for Error {
65    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66        fmt::Debug::fmt(&self.inner, f)
67    }
68}
69
70impl fmt::Display for Error {
71    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72        fmt::Display::fmt(&self.inner, f)
73    }
74}
75
76#[derive(Debug)]
77struct Internal(String);
78
79impl fmt::Display for Internal {
80    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
81        f.write_str(&self.0)
82    }
83}
84
85impl std::error::Error for Internal {}
86
87/// An error shape from the model. Generated for every `@error` structure.
88pub trait ModelledError: std::error::Error + Send + Sync + 'static {
89    fn info(&self) -> &'static ErrorInfo;
90    /// The model's shape id, independent of Rust renames.
91    fn shape_id(&self) -> &'static str {
92        self.info().name
93    }
94    /// Every member, as on the wire; the protocol moves header members out.
95    fn to_json(&self) -> Value;
96
97    /// Writes all fields as a document, including members bound to HTTP
98    /// headers or payloads in unary responses. Generated errors override
99    /// this to support bounded stream serialization without an intermediate value.
100    fn write_json_to(&self, out: &mut dyn std::io::Write) -> serde_json::Result<()> {
101        serde_json::to_writer(out, &self.to_json())
102    }
103
104    /// The body (members plus `"__type"`) straight into `out`, without the
105    /// header members, which come back as (header, text). Generated errors
106    /// write in one pass through [`write_error`]; this default goes through
107    /// [`ModelledError::to_json`].
108    fn write_json(&self, out: &mut Vec<u8>) -> serde_json::Result<Vec<(&'static str, String)>> {
109        let info = self.info();
110        crate::split::write_typed(&self.to_json(), info.members, Some(info.name), out)
111    }
112}
113
114/// How a generated error implements [`ModelledError::write_json`]: one pass,
115/// no JSON value in between.
116#[doc(hidden)]
117pub fn write_error<E: ModelledError + serde::Serialize>(
118    error: &E,
119    out: &mut Vec<u8>,
120) -> serde_json::Result<Vec<(&'static str, String)>> {
121    let info = error.info();
122    crate::split::write_typed(error, info.members, Some(info.name), out)
123}
124
125/// Errors the framework answers itself, outside any model: a request no
126/// operation serves, or an internal failure when the service models no
127/// internal error.
128///
129/// Non-exhaustive: the framework may answer new errors, so a `match` outside
130/// this crate needs a wildcard arm. [`name`](Self::name),
131/// [`status`](Self::status) and [`message`](Self::message) cover every
132/// variant.
133#[derive(Debug, Clone, PartialEq, Eq)]
134#[non_exhaustive]
135pub enum FrameworkError {
136    /// Credentials were absent or refused by an authentication extension.
137    Unauthenticated,
138    /// An authenticated principal cannot perform the requested action.
139    Forbidden,
140    /// The request conflicts with one the service already accepted: an
141    /// idempotency token reused for a different request, or for one still
142    /// running. The message says which, and what the caller can do.
143    Conflict {
144        message: &'static str,
145    },
146    /// The resource does not exist, or the caller may not know that it
147    /// does: the modelled `crucible.errors#NotFoundException` (404), whose
148    /// members are the resource's fixed message ([`ResourceInfo::not_found`])
149    /// and `resourceType`, its authorization name. An authorization that
150    /// hides a resource and a handler reporting genuine absence both answer
151    /// it, so the two are indistinguishable. It never names a permission or
152    /// an identifier.
153    NotFound {
154        resource: &'static ResourceInfo,
155    },
156    /// An authenticated caller can see the resource but lacks `permission`
157    /// on it: a 403 `ForbiddenException`, like `Forbidden`, whose message is
158    /// the permission's [`PermissionInfo::denied`], naming its value and
159    /// resource type, unless the permission is internal: then the message
160    /// names neither. Unlike `Forbidden` it sends no `insufficient_scope`
161    /// challenge: no token would carry a grant.
162    PermissionDenied {
163        permission: &'static PermissionInfo,
164    },
165    UnknownOperation,
166    MethodNotAllowed {
167        allowed: Vec<&'static str>,
168    },
169    UnsupportedMediaType,
170    InternalFailure,
171}
172
173impl FrameworkError {
174    pub fn name(&self) -> &'static str {
175        match self {
176            Self::Unauthenticated => "UnauthenticatedException",
177            Self::Forbidden => "ForbiddenException",
178            Self::Conflict { .. } => "ConflictException",
179            Self::NotFound { .. } => "NotFoundException",
180            Self::PermissionDenied { .. } => "ForbiddenException",
181            Self::UnknownOperation => "UnknownOperation",
182            Self::MethodNotAllowed { .. } => "MethodNotAllowed",
183            Self::UnsupportedMediaType => "UnsupportedMediaTypeException",
184            Self::InternalFailure => "InternalFailure",
185        }
186    }
187
188    pub fn status(&self) -> u16 {
189        match self {
190            Self::Unauthenticated => 401,
191            Self::Forbidden => 403,
192            Self::Conflict { .. } => 409,
193            Self::NotFound { .. } => 404,
194            Self::PermissionDenied { .. } => 403,
195            Self::UnknownOperation => 404,
196            Self::MethodNotAllowed { .. } => 405,
197            Self::UnsupportedMediaType => 415,
198            Self::InternalFailure => 500,
199        }
200    }
201
202    pub fn message(&self) -> &'static str {
203        match self {
204            Self::Unauthenticated => "authentication is required",
205            Self::Forbidden => "access is forbidden",
206            Self::Conflict { message } => message,
207            Self::NotFound { resource } => resource.not_found,
208            Self::PermissionDenied { permission } if permission.is_public() => permission.denied,
209            Self::PermissionDenied { .. } => "This principal may not perform this operation.",
210            Self::UnknownOperation => "no operation serves this request",
211            Self::MethodNotAllowed { .. } => "the request method is not allowed for this target",
212            Self::UnsupportedMediaType => "the request content-type is not supported",
213            Self::InternalFailure => "the request failed; quote the request id when reporting it",
214        }
215    }
216}
217
218impl fmt::Display for FrameworkError {
219    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
220        f.write_str(self.message())
221    }
222}
223
224impl std::error::Error for FrameworkError {}
225
226#[cfg(test)]
227mod tests {
228    use super::*;
229
230    #[derive(Debug)]
231    struct SimpleError(&'static str);
232
233    impl fmt::Display for SimpleError {
234        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
235            f.write_str(self.0)
236        }
237    }
238
239    impl std::error::Error for SimpleError {}
240
241    #[derive(Debug)]
242    struct NestedError {
243        msg: &'static str,
244        source: Option<Box<dyn std::error::Error + Send + Sync + 'static>>,
245    }
246
247    impl fmt::Display for NestedError {
248        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
249            f.write_str(self.msg)
250        }
251    }
252
253    impl std::error::Error for NestedError {
254        fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
255            self.source
256                .as_deref()
257                .map(|s| s as &(dyn std::error::Error + 'static))
258        }
259    }
260
261    #[derive(Debug)]
262    struct CyclicError;
263
264    impl fmt::Display for CyclicError {
265        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
266            f.write_str("loop")
267        }
268    }
269
270    impl std::error::Error for CyclicError {
271        fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
272            Some(self)
273        }
274    }
275
276    #[derive(Debug)]
277    struct CycleA;
278    #[derive(Debug)]
279    struct CycleB;
280    static CYCLE_A: CycleA = CycleA;
281    static CYCLE_B: CycleB = CycleB;
282
283    impl fmt::Display for CycleA {
284        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
285            f.write_str("node_a")
286        }
287    }
288
289    impl std::error::Error for CycleA {
290        fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
291            Some(&CYCLE_B)
292        }
293    }
294
295    impl fmt::Display for CycleB {
296        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
297            f.write_str("node_b")
298        }
299    }
300
301    impl std::error::Error for CycleB {
302        fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
303            Some(&CYCLE_A)
304        }
305    }
306
307    #[test]
308    fn not_found_and_permission_denied_name_only_what_they_may() {
309        use crate::permissions::Tier;
310
311        static INBOX: ResourceInfo = ResourceInfo {
312            name: "inbox",
313            identifiers: &["workspaceId", "inboxId"],
314            not_found: "No such inbox.",
315        };
316        static SEND: PermissionInfo = PermissionInfo {
317            resource: &INBOX,
318            symbol: "mailSend",
319            value: "mail:send",
320            aliases: &[],
321            tier: Tier::Public,
322            denied: "This principal does not hold mail:send on that inbox.",
323        };
324        static WATCH: PermissionInfo = PermissionInfo {
325            resource: &INBOX,
326            symbol: "watch",
327            value: "inbox:watch",
328            aliases: &[],
329            tier: Tier::Internal,
330            denied: "This principal does not hold inbox:watch on that inbox.",
331        };
332        let missing = FrameworkError::NotFound { resource: &INBOX };
333        assert_eq!(missing.status(), 404);
334        assert_eq!(missing.name(), "NotFoundException");
335        assert_eq!(missing.message(), "No such inbox.");
336
337        let denied = FrameworkError::PermissionDenied { permission: &SEND };
338        assert_eq!(denied.status(), 403);
339        assert_eq!(denied.name(), "ForbiddenException");
340        assert_eq!(
341            denied.message(),
342            "This principal does not hold mail:send on that inbox."
343        );
344        // An internal permission's own message is never used.
345        let internal = FrameworkError::PermissionDenied { permission: &WATCH };
346        assert_eq!(
347            internal.message(),
348            "This principal may not perform this operation."
349        );
350    }
351
352    #[test]
353    fn chain_with_no_source() {
354        let error = Error::internal("standalone");
355        assert_eq!(error.chain(), "standalone");
356    }
357
358    #[test]
359    fn chain_with_sources() {
360        let leaf = SimpleError("leaf");
361        let middle = NestedError {
362            msg: "middle",
363            source: Some(Box::new(leaf)),
364        };
365        let root = NestedError {
366            msg: "root",
367            source: Some(Box::new(middle)),
368        };
369        let error = Error::new(root);
370        assert_eq!(error.chain(), "root: middle: leaf");
371    }
372
373    #[test]
374    fn chain_terminates_on_self_referential_cycle() {
375        let error = Error::new(CyclicError);
376        let chain = error.chain();
377        assert_eq!(chain.matches(": loop").count(), MAX_SOURCE_DEPTH);
378        assert!(chain.starts_with("loop: loop"));
379    }
380
381    #[test]
382    fn chain_terminates_on_mutual_cycle() {
383        let error = Error::new(CycleA);
384        let chain = error.chain();
385        let total_sources = chain.matches(": node_a").count() + chain.matches(": node_b").count();
386        assert_eq!(total_sources, MAX_SOURCE_DEPTH);
387        assert!(chain.starts_with("node_a: node_b: node_a"));
388    }
389
390    #[test]
391    fn chain_bounds_deep_error_hierarchy() {
392        let mut current = NestedError {
393            msg: "leaf",
394            source: None,
395        };
396        for _ in 0..100 {
397            current = NestedError {
398                msg: "step",
399                source: Some(Box::new(current)),
400            };
401        }
402        let error = Error::new(current);
403        let chain = error.chain();
404        assert_eq!(chain.matches(": ").count(), MAX_SOURCE_DEPTH);
405    }
406}