footing 0.5.4

Feature-gated foundations for Rust backend services
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
use std::fmt;

use axum::{
    Json,
    extract::rejection::JsonRejection,
    http::{HeaderValue, StatusCode, header::CONTENT_TYPE},
    response::{IntoResponse, Response},
};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use thiserror::Error;

use crate::result::{ClassifyError, ErrorBoundaryPolicy, ErrorDescriptor, ErrorKind};

use super::{ProblemCode, ProblemType};
use crate::http::request_context::{RequestContext, RequestId};

/// Media type used for RFC 9457 problem responses.
pub const PROBLEM_JSON_MEDIA_TYPE: &str = "application/problem+json";

#[derive(Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[non_exhaustive]
/// Client-safe RFC 9457 problem payload with correlation and validation details.
pub struct ProblemDetails {
    #[serde(rename = "type")]
    /// URI identifying the problem type.
    #[cfg_attr(feature = "openapi", schema(schema_with = schema::problem_type))]
    type_uri: ProblemType,
    /// Short, human-readable problem title.
    title: String,
    /// HTTP status code associated with the problem.
    #[serde(
        serialize_with = "serialize_problem_status",
        deserialize_with = "deserialize_problem_status"
    )]
    #[cfg_attr(feature = "openapi", schema(value_type = u16, minimum = 400, maximum = 599))]
    status: StatusCode,
    /// Stable machine-readable error code.
    #[cfg_attr(feature = "openapi", schema(schema_with = schema::problem_code))]
    code: ProblemCode,
    /// Human-readable explanation specific to this occurrence.
    detail: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    /// URI identifying this specific problem occurrence.
    #[cfg_attr(feature = "openapi", schema(nullable = false))]
    instance: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    /// Request identifier used for log correlation.
    #[cfg_attr(feature = "openapi", schema(schema_with = schema::request_id))]
    request_id: Option<RequestId>,
    #[serde(skip_serializing_if = "Option::is_none")]
    /// Distributed trace identifier, when tracing is active.
    #[cfg_attr(feature = "openapi", schema(nullable = false))]
    trace_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    /// Structured, client-safe problem-specific details.
    details: Option<Value>,
}

// Utoipa 6 wraps documented inline scalars in allOf with a type: object item.
// Put field descriptions on the composition itself so the string constraints
// remain satisfiable. The optional request ID is omitted rather than null.
#[cfg(feature = "openapi")]
mod schema {
    use utoipa::{PartialSchema, openapi::schema::AllOfBuilder};

    use super::{ProblemCode, ProblemType, RequestId};

    pub(super) fn problem_type() -> AllOfBuilder {
        AllOfBuilder::new()
            .item(ProblemType::schema())
            .description(Some("URI identifying the problem type."))
    }

    pub(super) fn problem_code() -> AllOfBuilder {
        AllOfBuilder::new()
            .item(ProblemCode::schema())
            .description(Some("Stable machine-readable error code."))
    }

    pub(super) fn request_id() -> AllOfBuilder {
        AllOfBuilder::new()
            .item(RequestId::schema())
            .description(Some("Request identifier used for log correlation."))
    }
}

impl ProblemDetails {
    #[must_use]
    /// Returns the problem type URI.
    pub fn type_uri(&self) -> &str {
        self.type_uri.as_str()
    }

    #[must_use]
    /// Returns the human-readable title.
    pub fn title(&self) -> &str {
        &self.title
    }

    #[must_use]
    /// Returns the HTTP status code.
    pub const fn status(&self) -> u16 {
        self.status.as_u16()
    }

    #[must_use]
    /// Returns the stable machine-readable code.
    pub fn code(&self) -> &str {
        self.code.as_str()
    }

    #[must_use]
    /// Returns the client-safe detail.
    pub fn detail(&self) -> &str {
        &self.detail
    }

    #[must_use]
    /// Returns the problem instance URI, when present.
    pub fn instance(&self) -> Option<&str> {
        self.instance.as_deref()
    }

    #[must_use]
    /// Returns the request identifier, when present.
    pub fn request_id(&self) -> Option<&str> {
        self.request_id.as_ref().map(RequestId::as_str)
    }

    #[must_use]
    /// Returns the trace identifier, when present.
    pub fn trace_id(&self) -> Option<&str> {
        self.trace_id.as_deref()
    }

    #[must_use]
    /// Returns structured client-safe details, when present.
    pub const fn details(&self) -> Option<&Value> {
        self.details.as_ref()
    }
}

impl fmt::Debug for ProblemDetails {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ProblemDetails")
            .field("status", &self.status)
            .field("code", &self.code)
            .field("request_id", &self.request_id)
            .field("trace_id", &self.trace_id)
            .field("type_uri", &"[REDACTED]")
            .field("title", &"[REDACTED]")
            .field("detail", &"[REDACTED]")
            .field("instance", &self.instance.as_ref().map(|_| "[REDACTED]"))
            .field("details", &self.details.as_ref().map(|_| "[REDACTED]"))
            .finish()
    }
}

#[derive(Debug, Clone)]
/// Represents API problem.
pub struct ApiProblem {
    body: Box<ProblemDetails>,
}

impl ApiProblem {
    /// Applies the disclosure policy and converts a classified error into an HTTP problem.
    ///
    /// Attach safe correlation identifiers with [`Self::with_request_context`].
    /// To also inspect logging and alert decisions, call [`ErrorBoundaryPolicy::decide`]
    /// and pass its descriptor to [`Self::from_descriptor`].
    #[must_use]
    pub fn from_error<E: ClassifyError + ?Sized>(error: &E, policy: ErrorBoundaryPolicy) -> Self {
        Self::from_descriptor(policy.decide(error).into_descriptor())
    }

    #[must_use]
    /// Converts an explicitly public descriptor into an HTTP problem.
    ///
    /// To apply a disclosure policy to a classified error, use [`Self::from_error`].
    pub fn from_descriptor(descriptor: ErrorDescriptor) -> Self {
        let status = match descriptor.kind() {
            ErrorKind::Validation => StatusCode::BAD_REQUEST,
            ErrorKind::Authentication => StatusCode::UNAUTHORIZED,
            ErrorKind::Authorization => StatusCode::FORBIDDEN,
            ErrorKind::NotFound => StatusCode::NOT_FOUND,
            ErrorKind::Conflict => StatusCode::CONFLICT,
            ErrorKind::RateLimit => StatusCode::TOO_MANY_REQUESTS,
            ErrorKind::Timeout | ErrorKind::Dependency | ErrorKind::Unavailable => {
                StatusCode::SERVICE_UNAVAILABLE
            }
            ErrorKind::Internal => StatusCode::INTERNAL_SERVER_ERROR,
        };
        Self::from_valid_status(
            status,
            ProblemCode::from_error_code(descriptor.code().clone()),
            descriptor.public_message(),
        )
    }

    /// Attempts to create an API problem with an error status.
    pub fn try_new(
        status: StatusCode,
        code: ProblemCode,
        detail: impl Into<String>,
    ) -> Result<Self, ApiProblemStatusError> {
        if !is_problem_status(status) {
            return Err(ApiProblemStatusError::InvalidStatus {
                status: status.as_u16(),
            });
        }

        Ok(Self::from_valid_status(status, code, detail))
    }

    fn from_valid_status(status: StatusCode, code: ProblemCode, detail: impl Into<String>) -> Self {
        Self {
            body: Box::new(ProblemDetails {
                type_uri: ProblemType::about_blank(),
                title: status.canonical_reason().unwrap_or("HTTP error").to_owned(),
                detail: detail.into(),
                status,
                code,
                instance: None,
                request_id: None,
                trace_id: None,
                details: None,
            }),
        }
    }

    #[must_use]
    /// Creates bad request.
    pub fn bad_request(code: ProblemCode, detail: impl Into<String>) -> Self {
        Self::from_valid_status(StatusCode::BAD_REQUEST, code, detail)
    }

    #[must_use]
    /// Creates unauthorized.
    pub fn unauthorized(code: ProblemCode, detail: impl Into<String>) -> Self {
        Self::from_valid_status(StatusCode::UNAUTHORIZED, code, detail)
    }

    #[must_use]
    /// Creates forbidden.
    pub fn forbidden(code: ProblemCode, detail: impl Into<String>) -> Self {
        Self::from_valid_status(StatusCode::FORBIDDEN, code, detail)
    }

    #[must_use]
    /// Creates not found.
    pub fn not_found(code: ProblemCode, detail: impl Into<String>) -> Self {
        Self::from_valid_status(StatusCode::NOT_FOUND, code, detail)
    }

    #[must_use]
    /// Creates a `408 Request Timeout` problem.
    pub fn request_timeout(code: ProblemCode, detail: impl Into<String>) -> Self {
        Self::from_valid_status(StatusCode::REQUEST_TIMEOUT, code, detail)
    }

    #[must_use]
    /// Creates service unavailable.
    pub fn service_unavailable(code: ProblemCode, detail: impl Into<String>) -> Self {
        Self::from_valid_status(StatusCode::SERVICE_UNAVAILABLE, code, detail)
    }

    #[must_use]
    /// Creates conflict.
    pub fn conflict(code: ProblemCode, detail: impl Into<String>) -> Self {
        Self::from_valid_status(StatusCode::CONFLICT, code, detail)
    }

    #[must_use]
    /// Creates unprocessable entity.
    pub fn unprocessable_entity(code: ProblemCode, detail: impl Into<String>) -> Self {
        Self::from_valid_status(StatusCode::UNPROCESSABLE_ENTITY, code, detail)
    }

    #[must_use]
    /// Creates payload too large.
    pub fn payload_too_large(code: ProblemCode, detail: impl Into<String>) -> Self {
        Self::from_valid_status(StatusCode::PAYLOAD_TOO_LARGE, code, detail)
    }

    #[must_use]
    /// Creates too many requests.
    pub fn too_many_requests(code: ProblemCode, detail: impl Into<String>) -> Self {
        Self::from_valid_status(StatusCode::TOO_MANY_REQUESTS, code, detail)
    }

    #[must_use]
    /// Creates internal error.
    pub fn internal_error() -> Self {
        Self::from_valid_status(
            StatusCode::INTERNAL_SERVER_ERROR,
            ProblemCode::INTERNAL_ERROR,
            "internal server error",
        )
    }

    #[must_use]
    /// Configures request identifier and returns the updated value.
    pub fn with_request_id(mut self, request_id: &RequestId) -> Self {
        self.body.request_id = Some(request_id.clone());
        self
    }

    #[must_use]
    /// Configures trace identifier and returns the updated value.
    pub fn with_trace_id(mut self, trace_id: impl Into<String>) -> Self {
        let trace_id = trace_id.into();
        if !trace_id.trim().is_empty() {
            self.body.trace_id = Some(trace_id);
        }
        self
    }

    #[must_use]
    /// Adds request and trace identifiers safe for client correlation.
    pub fn with_request_context(mut self, context: &RequestContext) -> Self {
        self.body.request_id = Some(context.request_id().clone());
        if let Some(trace_id) = context.trace_id() {
            self.body.trace_id = Some(trace_id.to_owned());
        }
        self
    }

    #[must_use]
    /// Returns the maybe request identifier.
    pub fn maybe_request_id(self, request_id: Option<&RequestId>) -> Self {
        if let Some(request_id) = request_id {
            self.with_request_id(request_id)
        } else {
            self
        }
    }

    #[must_use]
    /// Configures type and returns the updated value.
    pub fn with_type(mut self, type_uri: ProblemType) -> Self {
        self.body.type_uri = type_uri;
        self
    }

    #[must_use]
    /// Configures title and returns the updated value.
    pub fn with_title(mut self, title: impl Into<String>) -> Self {
        self.body.title = title.into();
        self
    }

    #[must_use]
    /// Configures instance and returns the updated value.
    pub fn with_instance(mut self, instance: impl Into<String>) -> Self {
        self.body.instance = Some(instance.into());
        self
    }

    #[must_use]
    /// Adds structured details explicitly intended for the client.
    ///
    /// Secrets and internal diagnostic data must not be included.
    pub fn with_details(mut self, details: Value) -> Self {
        self.body.details = Some(details);
        self
    }

    #[must_use]
    /// Returns the status.
    pub const fn status(&self) -> StatusCode {
        self.body.status
    }

    #[must_use]
    /// Returns the body.
    pub fn body(&self) -> &ProblemDetails {
        &self.body
    }

    #[must_use]
    /// Consumes this value and returns body.
    pub fn into_body(self) -> ProblemDetails {
        *self.body
    }
}

impl From<JsonRejection> for ApiProblem {
    fn from(rejection: JsonRejection) -> Self {
        let status = rejection.status();
        let code = match status {
            StatusCode::UNSUPPORTED_MEDIA_TYPE => ProblemCode::UNSUPPORTED_MEDIA_TYPE,
            StatusCode::PAYLOAD_TOO_LARGE => ProblemCode::PAYLOAD_TOO_LARGE,
            _ => ProblemCode::INVALID_JSON,
        };

        // Axum's JSON rejections always carry an error status.
        Self::from_valid_status(status, code, rejection.body_text())
            .with_details(serde_json::json!({ "reason": rejection.to_string() }))
    }
}

impl IntoResponse for ApiProblem {
    fn into_response(self) -> Response {
        let mut response = (self.body.status, Json(self.body)).into_response();
        response.headers_mut().insert(
            CONTENT_TYPE,
            HeaderValue::from_static(PROBLEM_JSON_MEDIA_TYPE),
        );
        response
    }
}

impl std::fmt::Display for ApiProblem {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            formatter,
            "HTTP problem {} ({})",
            self.body.code,
            self.body.status.as_u16()
        )
    }
}

impl std::error::Error for ApiProblem {}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
#[non_exhaustive]
/// Errors that can occur while handling API problem status.
pub enum ApiProblemStatusError {
    #[error("problem status must be a 4xx or 5xx status code, got {status}")]
    /// The status is invalid.
    InvalidStatus {
        #[doc = "The HTTP status code."]
        status: u16,
    },
}

impl ClassifyError for ApiProblemStatusError {
    fn error_kind(&self) -> ErrorKind {
        ErrorKind::Validation
    }

    fn error_code(&self) -> crate::result::ErrorCode {
        crate::result::ErrorCode::internal("api_problem_invalid_status")
    }
}

fn is_problem_status(status: StatusCode) -> bool {
    status.is_client_error() || status.is_server_error()
}

fn serialize_problem_status<S>(status: &StatusCode, serializer: S) -> Result<S::Ok, S::Error>
where
    S: serde::Serializer,
{
    serializer.serialize_u16(status.as_u16())
}

fn deserialize_problem_status<'de, D>(deserializer: D) -> Result<StatusCode, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let status = u16::deserialize(deserializer)?;
    let status = StatusCode::from_u16(status).map_err(serde::de::Error::custom)?;
    if !is_problem_status(status) {
        return Err(serde::de::Error::custom(
            "problem status must be a 4xx or 5xx status code",
        ));
    }
    Ok(status)
}