Skip to main content

hyperlane_plugin_problem_details/
impl.rs

1use super::*;
2
3/// Construction, fluent builders, and response application for [`ProblemDetails`].
4impl ProblemDetails {
5    /// Creates a new [`ProblemDetails`] with `status` and its standard HTTP title.
6    ///
7    /// # Arguments
8    ///
9    /// - `HttpStatus` - HTTP error status.
10    ///
11    /// # Returns
12    ///
13    /// - `Self` - Constructed Problem Details object.
14    pub fn from_status(status: HttpStatus) -> Self {
15        let code: usize = status.code();
16        Self {
17            problem_type: ABOUT_BLANK_TYPE.to_owned(),
18            title: default_title_for_status(code).to_owned(),
19            status: code,
20            detail: None,
21            instance: None,
22            extensions: BTreeMap::new(),
23        }
24    }
25
26    /// Creates a new [`ProblemDetails`] with explicit numeric status code and `title`.
27    ///
28    /// # Arguments
29    ///
30    /// - `usize` - HTTP status code.
31    /// - `T` - Human-readable title.
32    ///
33    /// # Returns
34    ///
35    /// - `Self` - Constructed Problem Details object.
36    pub fn new<T>(status: usize, title: T) -> Self
37    where
38        T: Into<String>,
39    {
40        Self {
41            problem_type: ABOUT_BLANK_TYPE.to_owned(),
42            title: title.into(),
43            status,
44            detail: None,
45            instance: None,
46            extensions: BTreeMap::new(),
47        }
48    }
49
50    /// Sets the RFC 9457 `type` URI reference.
51    ///
52    /// # Arguments
53    ///
54    /// - `S` - Problem type URI.
55    ///
56    /// # Returns
57    ///
58    /// - `Self` - Updated Problem Details.
59    pub fn with_type<S>(mut self, problem_type: S) -> Self
60    where
61        S: Into<String>,
62    {
63        self.set_problem_type(problem_type.into());
64        self
65    }
66
67    /// Sets the `detail` explanation string.
68    ///
69    /// # Arguments
70    ///
71    /// - `S` - Detailed explanation for this error occurrence.
72    ///
73    /// # Returns
74    ///
75    /// - `Self` - Updated Problem Details.
76    pub fn with_detail<S>(mut self, detail: S) -> Self
77    where
78        S: Into<String>,
79    {
80        self.set_detail(Some(detail.into()));
81        self
82    }
83
84    /// Sets the `instance` URI reference.
85    ///
86    /// # Arguments
87    ///
88    /// - `S` - Instance URI (typically the request path or trace URI).
89    ///
90    /// # Returns
91    ///
92    /// - `Self` - Updated Problem Details.
93    pub fn with_instance<S>(mut self, instance: S) -> Self
94    where
95        S: Into<String>,
96    {
97        self.set_instance(Some(instance.into()));
98        self
99    }
100
101    /// Attaches a custom top-level JSON extension member.
102    ///
103    /// # Arguments
104    ///
105    /// - `K` - Extension key name.
106    /// - `Value` - JSON extension value.
107    ///
108    /// # Returns
109    ///
110    /// - `Self` - Updated Problem Details.
111    pub fn with_extension<K>(mut self, key: K, value: Value) -> Self
112    where
113        K: Into<String>,
114    {
115        let _: Option<Value> = self.get_mut_extensions().insert(key.into(), value);
116        self
117    }
118
119    /// Serializes this [`ProblemDetails`] into UTF-8 JSON bytes.
120    ///
121    /// # Returns
122    ///
123    /// - `Vec<u8>` - JSON bytes.
124    pub fn to_json_bytes(&self) -> Vec<u8> {
125        to_vec(self).unwrap_or_default()
126    }
127
128    /// Writes this [`ProblemDetails`] directly into a Hyperlane [`Response`].
129    ///
130    /// # Arguments
131    ///
132    /// - `&mut Response` - Target HTTP response.
133    pub fn write_to_response(&self, response: &mut Response) {
134        response
135            .set_status_code(self.get_status())
136            .set_header(CONTENT_TYPE, PROBLEM_JSON_MEDIA_TYPE)
137            .set_body(self.to_json_bytes());
138    }
139
140    /// Writes this [`ProblemDetails`] into `ctx.get_mut_response()`, automatically filling `instance` from request path if unset.
141    ///
142    /// # Arguments
143    ///
144    /// - `&mut Context` - Active Hyperlane context.
145    pub fn apply(&self, ctx: &mut Context) {
146        if self.try_get_instance().is_some() {
147            self.write_to_response(ctx.get_mut_response());
148            return;
149        }
150        let mut owned: Self = self.clone();
151        owned.set_instance(Some(ctx.get_request().get_path().to_owned()));
152        owned.write_to_response(ctx.get_mut_response());
153    }
154}
155
156/// Default construction for [`ProblemDetailsConfig`].
157impl Default for ProblemDetailsConfig {
158    /// Builds a default config enabling auto-normalization, request `instance`, and `5xx` detail masking.
159    ///
160    /// # Returns
161    ///
162    /// - `Self` - Default configuration.
163    fn default() -> Self {
164        Self {
165            auto_normalize: true,
166            include_instance: true,
167            type_base_uri: None,
168            mask_server_error_details: true,
169        }
170    }
171}
172
173/// Fluent builders for [`ProblemDetailsConfig`].
174impl ProblemDetailsConfig {
175    /// Sets a base URI used to construct `<base>/<status>` problem type URIs.
176    ///
177    /// # Arguments
178    ///
179    /// - `S` - Base URI prefix.
180    ///
181    /// # Returns
182    ///
183    /// - `Self` - Updated configuration.
184    pub fn with_type_base_uri<S>(mut self, base_uri: S) -> Self
185    where
186        S: Into<String>,
187    {
188        self.set_type_base_uri(Some(base_uri.into()));
189        self
190    }
191
192    /// Configures whether raw `5xx` plain-text bodies are hidden during auto-normalization.
193    ///
194    /// # Arguments
195    ///
196    /// - `bool` - `true` to mask `5xx` details.
197    ///
198    /// # Returns
199    ///
200    /// - `Self` - Updated configuration.
201    pub fn with_mask_server_error_details(mut self, mask: bool) -> Self {
202        self.set_mask_server_error_details(mask);
203        self
204    }
205}
206
207/// Normalization engine for [`ProblemDetailsPlugin`].
208impl ProblemDetailsPlugin {
209    /// Compiles a standalone [`ProblemDetailsPlugin`] from `config`.
210    ///
211    /// # Arguments
212    ///
213    /// - `ProblemDetailsConfig` - Problem Details configuration.
214    ///
215    /// # Returns
216    ///
217    /// - `Self` - Compiled plugin.
218    pub fn new(config: ProblemDetailsConfig) -> Self {
219        let type_base_clean: Option<String> = config
220            .try_get_type_base_uri()
221            .as_ref()
222            .map(|u: &String| u.trim().trim_end_matches('/').to_owned())
223            .filter(|u: &String| !u.is_empty());
224        Self {
225            config,
226            type_base_clean,
227        }
228    }
229
230    /// Initializes the global [`ProblemDetailsPlugin`] singleton once.
231    ///
232    /// # Arguments
233    ///
234    /// - `ProblemDetailsConfig` - Configuration.
235    ///
236    /// # Returns
237    ///
238    /// - `&'static Self` - Reference to the global plugin.
239    pub fn init(config: ProblemDetailsConfig) -> &'static Self {
240        PROBLEM_DETAILS_PLUGIN.get_or_init(|| Self::new(config))
241    }
242
243    /// Returns the initialized global [`ProblemDetailsPlugin`], if configured.
244    ///
245    /// # Returns
246    ///
247    /// - `Option<&'static Self>` - Reference to the global plugin, or `None`.
248    #[inline(always)]
249    pub fn get() -> Option<&'static Self> {
250        PROBLEM_DETAILS_PLUGIN.get()
251    }
252
253    /// Normalizes a `4xx`/`5xx` response in `ctx` into `application/problem+json` if eligible.
254    ///
255    /// # Arguments
256    ///
257    /// - `&mut Context` - Active request/response context.
258    ///
259    /// # Returns
260    ///
261    /// - `bool` - `true` if the response was converted to RFC 9457 JSON.
262    #[inline]
263    pub fn normalize_context(&self, ctx: &mut Context) -> bool {
264        let Self {
265            config,
266            type_base_clean,
267            ..
268        } = self;
269        if !config.get_auto_normalize() {
270            return false;
271        }
272        let status: usize = ctx.get_response().get_status_code();
273        if status < 400 {
274            return false;
275        }
276        let existing_ct: Option<&str> = ctx
277            .get_response()
278            .get_headers()
279            .get(CONTENT_TYPE)
280            .and_then(|vals: &VecDeque<String>| vals.back().map(String::as_str));
281        if let Some(ct) = existing_ct {
282            let trimmed: &str = ct.trim();
283            if trimmed.len() >= PROBLEM_JSON_PREFIX.len()
284                && trimmed.as_bytes()[..PROBLEM_JSON_PREFIX.len()]
285                    .eq_ignore_ascii_case(PROBLEM_JSON_PREFIX.as_bytes())
286            {
287                return false;
288            }
289            let is_plain: bool = trimmed.len() >= TEXT_PLAIN_PREFIX.len()
290                && trimmed.as_bytes()[..TEXT_PLAIN_PREFIX.len()]
291                    .eq_ignore_ascii_case(TEXT_PLAIN_PREFIX.as_bytes());
292            if !is_plain && !ctx.get_response().get_body().is_empty() {
293                return false;
294            }
295        }
296        let problem_type: String = match type_base_clean {
297            Some(base) => format!("{base}/{status}"),
298            None => ABOUT_BLANK_TYPE.to_owned(),
299        };
300        let detail: Option<String> = if status >= 500 && config.get_mask_server_error_details() {
301            None
302        } else {
303            let body: &[u8] = ctx.get_response().get_body();
304            if body.is_empty() {
305                None
306            } else {
307                from_utf8(body)
308                    .ok()
309                    .map(|s: &str| s.trim().to_owned())
310                    .filter(|s: &String| !s.is_empty())
311            }
312        };
313        let instance: Option<String> = if config.get_include_instance() {
314            Some(ctx.get_request().get_path().to_owned())
315        } else {
316            None
317        };
318        let problem: ProblemDetails = ProblemDetails {
319            problem_type,
320            title: default_title_for_status(status).to_owned(),
321            status,
322            detail,
323            instance,
324            extensions: BTreeMap::new(),
325        };
326        problem.write_to_response(ctx.get_mut_response());
327        true
328    }
329}
330
331/// Implements [`ServerHook`] for [`ProblemDetailsHook`].
332impl ServerHook for ProblemDetailsHook {
333    /// Constructs a per-response [`ProblemDetailsHook`].
334    ///
335    /// # Arguments
336    ///
337    /// - `&mut Stream` - Connection stream.
338    /// - `&mut Context` - Request context.
339    ///
340    /// # Returns
341    ///
342    /// - `Self` - Hook instance.
343    #[inline(always)]
344    async fn new(_: &mut Stream, _: &mut Context) -> Self {
345        Self
346    }
347
348    /// Synchronously normalizes bare `4xx`/`5xx` responses and skips `2xx`/`3xx` responses without async futures.
349    ///
350    /// # Arguments
351    ///
352    /// - `&mut Stream` - Connection stream.
353    /// - `&mut Context` - Request context.
354    ///
355    /// # Returns
356    ///
357    /// - `Option<Status>` - Always `Some(Status::Continue)`.
358    #[inline(always)]
359    fn try_handle_sync(_: &mut Stream, ctx: &mut Context) -> Option<Status> {
360        let Some(plugin) = ProblemDetailsPlugin::get() else {
361            return Some(Status::Continue);
362        };
363        let _: bool = plugin.normalize_context(ctx);
364        Some(Status::Continue)
365    }
366
367    /// Converts bare `4xx`/`5xx` error responses into structured RFC 9457 `application/problem+json`.
368    ///
369    /// # Arguments
370    ///
371    /// - `Self` - Hook instance.
372    /// - `&mut Stream` - Connection stream.
373    /// - `&mut Context` - Request context.
374    ///
375    /// # Returns
376    ///
377    /// - `Status` - Always `Status::Continue`.
378    #[inline(always)]
379    async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
380        Self::try_handle_sync(stream, ctx).unwrap_or(Status::Continue)
381    }
382}