footing 0.6.2

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
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
use std::fmt;

use axum::{
    Json,
    extract::rejection::{JsonRejection, PathRejection},
    http::{
        HeaderMap, HeaderValue, StatusCode,
        header::{CACHE_CONTROL, 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, ProblemUri};
use crate::http::AuthenticationChallenge;
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: ProblemUri,
    /// 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(schema_with = schema::instance))]
    instance: Option<ProblemUri>,
    #[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, ProblemUri, RequestId};

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

    pub(super) fn instance() -> AllOfBuilder {
        AllOfBuilder::new()
            .item(ProblemUri::schema())
            .description(Some("URI identifying this specific problem occurrence."))
    }

    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_ref().map(ProblemUri::as_str)
    }

    #[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(Clone)]
/// Client-safe HTTP error response using RFC 9457 Problem Details.
///
/// Responses always use `application/problem+json`. `Cache-Control` defaults to
/// `no-store`, so caches do not reuse request-specific details or correlation
/// identifiers. [`Self::headers_mut`] carries explicit response headers through
/// authentication hooks and other APIs returning `ApiProblem`, including repeated
/// authentication challenges or cookies. Header values are omitted from `Debug`.
/// Applications that deliberately cache a particular error can set its
/// `Cache-Control` or use ordinary Axum response headers:
///
/// ```
/// use axum::{http::header::CACHE_CONTROL, response::IntoResponse};
/// use footing::http::{ApiProblem, ProblemCode};
///
/// let problem = ApiProblem::not_found(
///     ProblemCode::from_static("resource_not_found"),
///     "Resource not found",
/// );
/// let response = ([(CACHE_CONTROL, "private, max-age=60")], problem).into_response();
/// assert_eq!(response.headers()[CACHE_CONTROL], "private, max-age=60");
/// ```
pub struct ApiProblem {
    body: Box<ProblemDetails>,
    headers: HeaderMap,
}

impl fmt::Debug for ApiProblem {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ApiProblem")
            .field("body", &self.body)
            .field("header_count", &self.headers.len())
            .finish()
    }
}

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::try_from_descriptor`].
    ///
    /// Authentication errors require an application-selected challenge. Handle
    /// those with [`Self::unauthorized`]; this conversion returns
    /// [`ApiProblemStatusError::AuthenticationChallengeRequired`] for them.
    pub fn try_from_error<E: ClassifyError + ?Sized>(
        error: &E,
        policy: ErrorBoundaryPolicy,
    ) -> Result<Self, ApiProblemStatusError> {
        Self::try_from_descriptor(policy.decide(error).into_descriptor())
    }

    /// Converts an explicitly public descriptor into an HTTP problem.
    ///
    /// To apply a disclosure policy to a classified error, use [`Self::try_from_error`].
    /// Authentication errors require [`Self::unauthorized`] with a challenge.
    pub fn try_from_descriptor(descriptor: ErrorDescriptor) -> Result<Self, ApiProblemStatusError> {
        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::try_new(
            status,
            ProblemCode::from_error_code(descriptor.code().clone()),
            descriptor.public_message(),
        )
    }

    /// Attempts to create an API problem with an error status.
    ///
    /// `401` requires [`Self::unauthorized`] and an explicit challenge. For other
    /// statuses, the caller supplies any required headers (for example `Allow`
    /// for `405`, or `Proxy-Authenticate` for `407`) through [`Self::headers_mut`].
    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(),
            });
        }
        if status == StatusCode::UNAUTHORIZED {
            return Err(ApiProblemStatusError::AuthenticationChallengeRequired);
        }

        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: ProblemUri::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,
            }),
            headers: HeaderMap::new(),
        }
    }

    #[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 a `401 Unauthorized` problem.
    ///
    /// Attaches the application's validated challenge as `WWW-Authenticate`.
    /// Additional challenges can be appended through [`Self::headers_mut`].
    /// The library does not select an authentication scheme.
    pub fn unauthorized(
        code: ProblemCode,
        detail: impl Into<String>,
        challenge: &AuthenticationChallenge,
    ) -> Self {
        let mut problem = Self::from_valid_status(StatusCode::UNAUTHORIZED, code, detail);
        problem.headers.insert(
            axum::http::header::WWW_AUTHENTICATE,
            challenge.as_header_value().clone(),
        );
        problem
    }

    #[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)
    }

    /// Creates a `405 Method Not Allowed` problem.
    ///
    /// The caller must supply the appropriate `Allow` response header.
    /// [`crate::http::method_not_allowed`] delegates that header to Axum's
    /// method routing when installed as a method fallback.
    #[must_use]
    pub fn method_not_allowed(code: ProblemCode, detail: impl Into<String>) -> Self {
        Self::from_valid_status(StatusCode::METHOD_NOT_ALLOWED, code, detail)
    }

    #[must_use]
    /// Creates a `408 Request Timeout` problem for an incomplete request message.
    ///
    /// This status describes a timeout while receiving a request, not a deadline
    /// for the application to produce a response. The middleware's response
    /// deadline uses `503 Service Unavailable` with code `response_timeout`.
    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: ProblemUri) -> 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]
    /// Identifies this occurrence with a validated URI reference.
    ///
    /// ```
    /// use footing::http::{ApiProblem, ProblemCode, ProblemUri};
    ///
    /// let problem = ApiProblem::bad_request(
    ///     ProblemCode::from_static("invalid_input"), "Invalid input",
    /// ).with_instance(ProblemUri::try_new("/problems/occurrences/123")?);
    /// assert_eq!(problem.body().instance(), Some("/problems/occurrences/123"));
    /// # Ok::<(), footing::http::ProblemIdentifierError>(())
    /// ```
    pub fn with_instance(mut self, instance: ProblemUri) -> Self {
        self.body.instance = Some(instance);
        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
    }

    /// Returns explicitly configured response headers, without generated defaults.
    #[must_use]
    pub const fn headers(&self) -> &HeaderMap {
        &self.headers
    }

    /// Changes explicitly configured response headers.
    ///
    /// Use [`HeaderMap::append`] for repeated fields such as `WWW-Authenticate`
    /// and `Set-Cookie`, or [`HeaderMap::insert`] to replace a field's values.
    /// A `401` must retain at least one applicable authentication challenge.
    /// `Content-Type` is always rendered as `application/problem+json` regardless
    /// of values set here. An explicit `Cache-Control` overrides the `no-store`
    /// default. These headers are not part of the serialized problem payload.
    pub fn headers_mut(&mut self) -> &mut HeaderMap {
        &mut self.headers
    }

    #[must_use]
    /// Returns the problem payload, discarding response headers.
    pub fn into_body(self) -> ProblemDetails {
        *self.body
    }
}

impl From<JsonRejection> for ApiProblem {
    fn from(rejection: JsonRejection) -> Self {
        let status = rejection.status();
        let (code, detail) = match rejection {
            JsonRejection::MissingJsonContentType(_) => (
                ProblemCode::UNSUPPORTED_MEDIA_TYPE,
                "request content type must be application/json or application/*+json",
            ),
            JsonRejection::JsonDataError(_) => (
                ProblemCode::INVALID_JSON,
                "JSON body does not match the expected format",
            ),
            JsonRejection::JsonSyntaxError(_) => {
                (ProblemCode::INVALID_JSON, "request body is not valid JSON")
            }
            JsonRejection::BytesRejection(_) if status == StatusCode::PAYLOAD_TOO_LARGE => {
                (ProblemCode::PAYLOAD_TOO_LARGE, "request body is too large")
            }
            _ => (ProblemCode::INVALID_JSON, "request body could not be read"),
        };

        // Axum's JSON rejections always carry an error status.
        // Parser diagnostics can contain Rust type names, input values, or
        // arbitrary messages from application deserializers.
        Self::from_valid_status(status, code, detail)
    }
}

impl From<PathRejection> for ApiProblem {
    fn from(rejection: PathRejection) -> Self {
        if rejection.status().is_server_error() {
            Self::internal_error()
        } else {
            Self::bad_request(
                ProblemCode::INVALID_PATH,
                "path parameters do not match the expected format",
            )
        }
    }
}

impl IntoResponse for ApiProblem {
    fn into_response(self) -> Response {
        let mut response = (self.body.status, Json(self.body)).into_response();
        response.headers_mut().extend(self.headers);
        response.headers_mut().insert(
            CONTENT_TYPE,
            HeaderValue::from_static(PROBLEM_JSON_MEDIA_TYPE),
        );
        response
            .headers_mut()
            .entry(CACHE_CONTROL)
            .or_insert(HeaderValue::from_static("no-store"));
        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 {
    /// A `401` response cannot be constructed without an authentication challenge.
    #[error("HTTP 401 requires an explicit authentication challenge")]
    AuthenticationChallengeRequired,
    #[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(match self {
            Self::InvalidStatus { .. } => "api_problem_invalid_status",
            Self::AuthenticationChallengeRequired => {
                "api_problem_authentication_challenge_required"
            }
        })
    }
}

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)
}