Skip to main content

seiva_contract/
lib.rs

1//! Transport-neutral wire-contract types for the Delonix Seiva framework.
2//!
3//! A module's `facade` is its versioned public contract. The write DTOs it
4//! publishes carry a [`Validate`] check — a structural, synchronous validation
5//! that is a *contract* concern, not a *transport* one. These types live here,
6//! with **no axum, no http, no framework**, so the `facade` layer can validate
7//! without depending on a transport crate (ADR 0003). `seiva-http` re-exports
8//! them (`seiva_http::{Validate, ValidationError}`), so existing code keeps
9//! compiling and the HTTP `Valid<T>` extractor runs the same check.
10//!
11//! ```
12//! use seiva_contract::{Validate, ValidationError};
13//!
14//! struct CreateRecord { title: String }
15//! impl Validate for CreateRecord {
16//!     fn validate(&self) -> Result<(), ValidationError> {
17//!         if self.title.trim().is_empty() {
18//!             return Err(ValidationError::new("title must not be empty"));
19//!         }
20//!         Ok(())
21//!     }
22//! }
23//! assert!(CreateRecord { title: "  ".into() }.validate().is_err());
24//! ```
25
26#![forbid(unsafe_code)]
27
28/// A domain-shaped validation check on a deserialized body. Keep it cheap and
29/// synchronous: structural and range checks, not I/O. Business rules that need
30/// ports belong in the application layer, not here.
31pub trait Validate {
32    /// Returns `Ok(())` when the value is acceptable, or a human-readable reason
33    /// why it is not.
34    fn validate(&self) -> Result<(), ValidationError>;
35}
36
37/// Why a body was rejected as invalid. A single message in this first cut; a
38/// later phase can carry a per-field map.
39///
40/// `#[non_exhaustive]`: construct it through [`ValidationError::new`], never by
41/// field literal, so a later per-field map is a non-breaking addition.
42#[derive(Debug, Clone)]
43#[non_exhaustive]
44pub struct ValidationError {
45    /// A human-readable reason, surfaced as the problem's `detail`.
46    pub message: String,
47}
48
49impl ValidationError {
50    /// A validation error with the given message.
51    pub fn new(message: impl Into<String>) -> Self {
52        Self {
53            message: message.into(),
54        }
55    }
56}
57
58impl std::fmt::Display for ValidationError {
59    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
60        f.write_str(&self.message)
61    }
62}
63
64impl std::error::Error for ValidationError {}
65
66// --- RFC 9457 Problem -------------------------------------------------------
67//
68// `Problem` is the error a use case maps to at the module boundary. It is pure
69// DATA (an `http::StatusCode` + the RFC 9457 members) with NO axum / response
70// impl, so the `facade` layer declares its error without naming a transport
71// crate. The HTTP transport (`seiva-http`) wraps it in a `ProblemResponse` that
72// implements `axum::IntoResponse`; another transport maps it its own way.
73
74use std::sync::atomic::{AtomicBool, Ordering};
75
76use http::StatusCode;
77use seiva_ports::BoxError;
78
79/// Whether a `500` may carry the internal error's text to the client. **Off by
80/// default (fail-closed):** an internal error that reaches [`From<BoxError>`] is
81/// logged server-side and the client sees only a generic detail, so a database or
82/// adapter message (SQL, column names, paths) never leaks (OWASP API8/API5). The
83/// runtime flips this from `SEIVA_EXPOSE_ERROR_DETAILS` at boot
84/// ([`set_expose_error_details`]); the production config guard rejects enabling it
85/// outside development.
86static EXPOSE_ERROR_DETAILS: AtomicBool = AtomicBool::new(false);
87
88/// Sets whether internal error detail is exposed to clients. Called once by the
89/// runtime at boot from the validated `SEIVA_EXPOSE_ERROR_DETAILS` config value. A
90/// development convenience; production must leave it off (fail-closed default).
91pub fn set_expose_error_details(expose: bool) {
92    EXPOSE_ERROR_DETAILS.store(expose, Ordering::Relaxed);
93}
94
95/// Whether internal error detail is currently exposed to clients.
96#[must_use]
97pub fn expose_error_details() -> bool {
98    EXPOSE_ERROR_DETAILS.load(Ordering::Relaxed)
99}
100
101/// An RFC 9457 problem detail: a machine-readable description of an error.
102///
103/// Construct one with a status helper ([`Problem::forbidden`],
104/// [`Problem::unprocessable_entity`], [`Problem::internal`], …) and refine it with
105/// the builder methods. The transport renders it (`seiva-http` as
106/// `application/problem+json`); here it is transport-neutral data.
107///
108/// The string members are stored as `Box<str>` rather than `String`: a problem is
109/// built once and never mutated after construction, so the extra `String` capacity
110/// word buys nothing, and the smaller footprint keeps the whole value comfortably
111/// under clippy's `result_large_err` threshold. That is why no crate returning
112/// `Result<_, Problem>` needs to silence that lint.
113///
114/// `#[non_exhaustive]`: build one through the status helpers ([`Problem::forbidden`],
115/// …) and the builder methods, never by field literal, so new RFC 9457 members are
116/// a non-breaking addition.
117#[derive(Debug, Clone)]
118#[non_exhaustive]
119pub struct Problem {
120    /// A URI reference identifying the problem type. Defaults to `about:blank`,
121    /// which RFC 9457 treats as "no extra semantics beyond the status code".
122    pub type_uri: Box<str>,
123    /// A short, human-readable summary of the problem type.
124    pub title: Box<str>,
125    /// The HTTP status code.
126    pub status: StatusCode,
127    /// A human-readable explanation specific to this occurrence.
128    pub detail: Option<Box<str>>,
129    /// A URI reference identifying this specific occurrence (e.g. the path).
130    pub instance: Option<Box<str>>,
131    /// The id of the request that produced the problem, for correlation.
132    pub request_id: Option<Box<str>>,
133}
134
135impl Problem {
136    /// A problem with the given status and title, `type` defaulting to
137    /// `about:blank` and no detail/instance/request id yet.
138    pub fn new(status: StatusCode, title: impl Into<String>) -> Self {
139        Self {
140            type_uri: "about:blank".into(),
141            title: title.into().into_boxed_str(),
142            status,
143            detail: None,
144            instance: None,
145            request_id: None,
146        }
147    }
148
149    /// A `401 Unauthorized` problem (the caller presented a bearer credential that
150    /// did not authenticate). The caller adds the `WWW-Authenticate` header.
151    pub fn unauthorized(detail: impl Into<String>) -> Self {
152        Self::new(StatusCode::UNAUTHORIZED, "Unauthorized").with_detail(detail)
153    }
154
155    /// A `403 Forbidden` problem (the permission guard denied the caller).
156    pub fn forbidden(detail: impl Into<String>) -> Self {
157        Self::new(StatusCode::FORBIDDEN, "Forbidden").with_detail(detail)
158    }
159
160    /// A `404 Not Found` problem.
161    pub fn not_found(detail: impl Into<String>) -> Self {
162        Self::new(StatusCode::NOT_FOUND, "Not Found").with_detail(detail)
163    }
164
165    /// A `422 Unprocessable Entity` problem (the body failed to parse or validate).
166    pub fn unprocessable_entity(detail: impl Into<String>) -> Self {
167        Self::new(StatusCode::UNPROCESSABLE_ENTITY, "Unprocessable Entity").with_detail(detail)
168    }
169
170    /// A `429 Too Many Requests` problem (the caller exceeded a rate limit). The
171    /// caller adds a `Retry-After` header separately.
172    pub fn too_many_requests(detail: impl Into<String>) -> Self {
173        Self::new(StatusCode::TOO_MANY_REQUESTS, "Too Many Requests").with_detail(detail)
174    }
175
176    /// A `500 Internal Server Error` problem.
177    pub fn internal(detail: impl Into<String>) -> Self {
178        Self::new(StatusCode::INTERNAL_SERVER_ERROR, "Internal Server Error").with_detail(detail)
179    }
180
181    /// Sets the `type` URI.
182    #[must_use]
183    pub fn with_type(mut self, type_uri: impl Into<String>) -> Self {
184        self.type_uri = type_uri.into().into_boxed_str();
185        self
186    }
187
188    /// Sets the human-readable `detail`.
189    #[must_use]
190    pub fn with_detail(mut self, detail: impl Into<String>) -> Self {
191        self.detail = Some(detail.into().into_boxed_str());
192        self
193    }
194
195    /// Sets the `instance` URI reference.
196    #[must_use]
197    pub fn with_instance(mut self, instance: impl Into<String>) -> Self {
198        self.instance = Some(instance.into().into_boxed_str());
199        self
200    }
201
202    /// Sets the correlation `request_id`.
203    #[must_use]
204    pub fn with_request_id(mut self, request_id: impl Into<String>) -> Self {
205        self.request_id = Some(request_id.into().into_boxed_str());
206        self
207    }
208
209    /// Sets the `request_id` when one is present, leaving it unset otherwise.
210    #[must_use]
211    pub fn with_request_id_opt(mut self, request_id: Option<String>) -> Self {
212        self.request_id = request_id.map(String::into_boxed_str);
213        self
214    }
215
216    /// The problem document as a JSON value, omitting absent optional members. The
217    /// transport serialises this (e.g. as `application/problem+json`).
218    #[must_use]
219    pub fn to_json(&self) -> serde_json::Value {
220        let mut map = serde_json::Map::new();
221        map.insert("type".to_owned(), self.type_uri.as_ref().into());
222        map.insert("title".to_owned(), self.title.as_ref().into());
223        map.insert("status".to_owned(), self.status.as_u16().into());
224        if let Some(detail) = &self.detail {
225            map.insert("detail".to_owned(), detail.as_ref().into());
226        }
227        if let Some(instance) = &self.instance {
228            map.insert("instance".to_owned(), instance.as_ref().into());
229        }
230        if let Some(request_id) = &self.request_id {
231            map.insert("request_id".to_owned(), request_id.as_ref().into());
232        }
233        serde_json::Value::Object(map)
234    }
235}
236
237impl std::fmt::Display for Problem {
238    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
239        write!(f, "{} {}", self.status.as_u16(), self.title)?;
240        if let Some(detail) = &self.detail {
241            write!(f, ": {detail}")?;
242        }
243        Ok(())
244    }
245}
246
247impl std::error::Error for Problem {}
248
249/// Maps the framework's opaque port error into a problem.
250///
251/// A port error that is **already a client-facing [`Problem`]** is recovered
252/// verbatim, status and all: a pipeline behavior or handler that returned a
253/// [`Problem`] boxed as the port's `BoxError` (a `403` from an authorize behavior,
254/// a `409` from an idempotency behavior) keeps its status instead of being
255/// flattened to `500`. Only an explicitly-constructed [`Problem`] matches this
256/// path — an opaque adapter/database error does not downcast and maps to `500`.
257///
258/// For every other error the internal `Display` is **not** sent to the client by
259/// default: it is logged server-side (correlate via the response's `request_id`)
260/// and the client receives a generic detail, so an adapter/database message never
261/// leaks (OWASP API8). Setting `SEIVA_EXPOSE_ERROR_DETAILS` (development only)
262/// flips [`set_expose_error_details`] and the real text is surfaced.
263impl From<BoxError> for Problem {
264    fn from(error: BoxError) -> Self {
265        match error.downcast::<Problem>() {
266            Ok(problem) => *problem,
267            Err(error) => {
268                if expose_error_details() {
269                    Problem::internal(error.to_string())
270                } else {
271                    tracing::error!(error = %error, "internal error mapped to 500");
272                    Problem::internal("an internal error occurred")
273                }
274            }
275        }
276    }
277}
278
279// Regression guard for the `result_large_err` win: should a future field push
280// `Problem` back over clippy's 128-byte threshold, the blanket allows return and
281// the `check` CI job fails on the integration test again. Fail the build here
282// instead, at the type, with a message pointing at the cause.
283const _: () = assert!(
284    std::mem::size_of::<Problem>() <= 112,
285    "Problem must stay small enough that Result<_, Problem> does not trip \
286     clippy::result_large_err; box or restructure a field before growing it",
287);
288
289#[cfg(test)]
290mod tests {
291    use super::*;
292
293    struct Name(String);
294
295    impl Validate for Name {
296        fn validate(&self) -> Result<(), ValidationError> {
297            if self.0.trim().is_empty() {
298                return Err(ValidationError::new("name must not be empty"));
299            }
300            Ok(())
301        }
302    }
303
304    #[test]
305    fn validate_rejects_and_accepts() {
306        assert!(Name("   ".into()).validate().is_err());
307        assert!(Name("ada".into()).validate().is_ok());
308    }
309
310    #[test]
311    fn validation_error_carries_the_message_as_display() {
312        let error = ValidationError::new("bad");
313        assert_eq!(error.message, "bad");
314        assert_eq!(error.to_string(), "bad");
315    }
316}