footing 0.6.3

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
use std::fmt;

use axum::{body::Body, extract::FromRequest, http::Request};
use serde::{Serialize, de::DeserializeOwned};
use serde_json::{Value, json};
use thiserror::Error;

use crate::http::{ApiProblem, ProblemCode, json::extract_json};
use crate::result::{ClassifyError, ErrorCode, ErrorKind};

const DEFAULT_VALIDATION_CODE: &str = "validation_failed";
const DEFAULT_VALIDATION_MESSAGE: &str = "request validation failed";
const DEFAULT_VALIDATION_FIELD: &str = "request";

/// Validates a request value at the HTTP boundary.
pub trait Validate {
    /// Validates this value.
    fn validate(&self) -> Result<(), ValidationError>;
}

#[derive(Clone, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
/// Represents field violation.
pub struct FieldViolation {
    field: String,
    code: String,
    message: String,
}

impl fmt::Debug for FieldViolation {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("FieldViolation")
            .field("field", &self.field)
            .field("code", &self.code)
            .field("message", &"[REDACTED]")
            .finish()
    }
}

impl FieldViolation {
    #[must_use]
    /// Creates a new instance.
    pub fn new(
        field: impl Into<String>,
        code: impl Into<String>,
        message: impl Into<String>,
    ) -> Self {
        Self {
            field: normalize_with_default(field, DEFAULT_VALIDATION_FIELD),
            code: normalize_with_default(code, DEFAULT_VALIDATION_CODE),
            message: normalize_with_default(message, DEFAULT_VALIDATION_MESSAGE),
        }
    }

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

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

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

#[derive(Clone, Error)]
#[error("request validation failed ({code})")]
/// Errors that can occur while handling validation.
pub struct ValidationError {
    code: ErrorCode,
    message: String,
    details: Option<Value>,
}

impl fmt::Debug for ValidationError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ValidationError")
            .field("code", &self.code)
            .field("message", &"[REDACTED]")
            .field("details", &self.details.as_ref().map(|_| "[REDACTED]"))
            .finish()
    }
}

impl ValidationError {
    #[must_use]
    /// Creates a new instance.
    pub fn new(code: ErrorCode, message: impl Into<String>) -> Self {
        Self {
            code,
            message: normalize_with_default(message, DEFAULT_VALIDATION_MESSAGE),
            details: None,
        }
    }

    #[must_use]
    /// Configures details and returns the updated value.
    pub fn with_details(mut self, details: Value) -> Self {
        self.details = Some(details);
        self
    }

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

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

    #[must_use]
    /// Returns the details.
    pub const fn details(&self) -> Option<&Value> {
        self.details.as_ref()
    }
}

impl From<Vec<FieldViolation>> for ValidationError {
    fn from(violations: Vec<FieldViolation>) -> Self {
        Self::new(
            ErrorCode::internal(DEFAULT_VALIDATION_CODE),
            DEFAULT_VALIDATION_MESSAGE,
        )
        .with_details(json!({ "fields": violations }))
    }
}

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

    fn error_code(&self) -> ErrorCode {
        self.code.clone()
    }
}

impl From<ValidationError> for ApiProblem {
    fn from(error: ValidationError) -> Self {
        let mut problem =
            Self::unprocessable_entity(ProblemCode::from_error_code(error.code), error.message);
        if let Some(details) = error.details {
            problem = problem.with_details(details);
        }
        problem
    }
}

#[derive(Clone)]
/// JSON deserialization followed by explicit application validation.
///
/// Parsing failures return client-safe descriptions without exposing parser or
/// custom deserializer diagnostics. [`Validate`] errors retain their explicitly
/// public messages and field details. Use [`super::JsonBody`] when no additional
/// validation is needed; both extractors share the same parsing behavior.
pub struct ValidatedJson<T>(T);

impl<T> fmt::Debug for ValidatedJson<T> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_tuple("ValidatedJson")
            .field(&"[REDACTED]")
            .finish()
    }
}

impl<T> ValidatedJson<T> {
    /// Creates a new instance.
    pub fn new(value: T) -> Result<Self, ValidationError>
    where
        T: Validate,
    {
        value.validate()?;
        Ok(Self(value))
    }

    #[must_use]
    /// Returns the validated inner value.
    pub const fn get(&self) -> &T {
        &self.0
    }

    #[must_use]
    /// Consumes this value and returns inner.
    pub fn into_inner(self) -> T {
        self.0
    }
}

impl<T> AsRef<T> for ValidatedJson<T> {
    fn as_ref(&self) -> &T {
        self.get()
    }
}

impl<T> std::ops::Deref for ValidatedJson<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        self.get()
    }
}

impl<S, T> FromRequest<S> for ValidatedJson<T>
where
    S: Send + Sync,
    T: DeserializeOwned + Validate,
{
    type Rejection = ApiProblem;

    async fn from_request(request: Request<Body>, state: &S) -> Result<Self, Self::Rejection> {
        let (value, context) = extract_json(request, state).await?;
        Self::new(value).map_err(|error| ApiProblem::from(error).with_request_context(&context))
    }
}

fn normalize_with_default(value: impl Into<String>, default: &str) -> String {
    let value = value.into().trim().to_owned();
    if value.is_empty() {
        default.to_owned()
    } else {
        value
    }
}

#[cfg(test)]
mod tests {
    use axum::{
        Router,
        body::{Body, to_bytes},
        extract::DefaultBodyLimit,
        http::{Request, StatusCode, header::CONTENT_TYPE},
        routing::post,
    };
    use serde::{Deserialize, Deserializer, Serialize};
    use serde_json::json;
    use tower::ServiceExt;

    use super::{FieldViolation, Validate, ValidatedJson, ValidationError};
    use crate::result::{ClassifyError, ErrorKind};

    #[derive(Debug, Deserialize, Serialize)]
    struct Payload {
        name: String,
    }

    impl Validate for Payload {
        fn validate(&self) -> Result<(), ValidationError> {
            if self.name.trim().is_empty() {
                Err(ValidationError::new(
                    crate::result::ErrorCode::internal("invalid_name"),
                    "name is required",
                )
                .with_details(json!({
                    "fields": [FieldViolation::new("name", "required", "name is required")],
                })))
            } else {
                Ok(())
            }
        }
    }

    #[test]
    fn normalizes_field_violations() {
        let violation = FieldViolation::new(" name ", "", "");

        assert_eq!(violation.field(), "name");
        assert_eq!(violation.code(), "validation_failed");
        assert_eq!(violation.message(), "request validation failed");
    }

    #[test]
    fn field_violation_uses_stable_field_fallback() {
        let violation = FieldViolation::new(" ", "required", "is required");

        assert_eq!(violation.field(), "request");
        assert_eq!(violation.code(), "required");
        assert_eq!(violation.message(), "is required");
    }

    #[test]
    fn validation_errors_are_classified() {
        let error = ValidationError::new(
            crate::result::ErrorCode::internal("invalid_payload"),
            "payload is invalid",
        );

        assert_eq!(error.error_kind(), ErrorKind::Validation);
        assert_eq!(error.error_code(), "invalid_payload");
    }

    #[test]
    fn validation_debug_redacts_messages_details_and_json_payloads() {
        let message = "private-validation-message";
        let detail = "private-validation-detail";
        let error = ValidationError::new(
            crate::result::ErrorCode::internal("invalid_payload"),
            message,
        )
        .with_details(json!({ "credential": detail }));
        let validated = ValidatedJson(Payload {
            name: "private-json-payload".to_owned(),
        });

        let violation = FieldViolation::new("credential", "invalid", message);
        let output = format!("{error:?} {error} {validated:?} {violation:?}");
        assert!(output.contains("invalid_payload"));
        assert!(output.contains("[REDACTED]"));
        for sensitive in [message, detail, "private-json-payload"] {
            assert!(!output.contains(sensitive));
        }
        assert_eq!(error.message(), message);
        assert_eq!(error.details(), Some(&json!({ "credential": detail })));
    }

    #[test]
    fn serializes_private_field_violations() {
        let violations = vec![FieldViolation::new("name", "required", "name is required")];

        assert_eq!(
            serde_json::to_value(&violations).expect("violations should serialize"),
            json!([{ "field": "name", "code": "required", "message": "name is required" }])
        );
        for fields in [violations, vec![]] {
            let expected_details = json!({ "fields": fields });
            let error = ValidationError::from(fields);
            assert_eq!(error.code().as_str(), "validation_failed");
            assert_eq!(error.message(), "request validation failed");
            assert_eq!(error.details(), Some(&expected_details));
            let problem = crate::http::ApiProblem::from(error);
            assert_eq!(problem.status(), StatusCode::UNPROCESSABLE_ENTITY);
            assert_eq!(problem.body().code(), "validation_failed");
            assert_eq!(problem.body().detail(), "request validation failed");
            assert_eq!(problem.body().details(), Some(&expected_details));
        }
    }

    #[test]
    fn validated_json_constructor_runs_validation() {
        assert!(
            ValidatedJson::new(Payload {
                name: "example".into()
            })
            .is_ok()
        );
        assert!(ValidatedJson::new(Payload { name: " ".into() }).is_err());
    }

    #[tokio::test]
    async fn validated_json_preserves_rejection_status_and_request_context() {
        let app = Router::new()
            .route(
                "/",
                post(|_: ValidatedJson<Payload>| async { StatusCode::NO_CONTENT }),
            )
            .layer(DefaultBodyLimit::max(64));

        let json = Some("application/json");
        for (body, content_type, status, code, detail) in [
            (
                "{}",
                None,
                415,
                "unsupported_media_type",
                "request content type must be application/json or application/*+json",
            ),
            (
                r#"{"name":"#,
                json,
                400,
                "invalid_json",
                "request body is not valid JSON",
            ),
            (
                r#"{"name":1}"#,
                json,
                422,
                "invalid_json",
                "JSON body does not match the expected format",
            ),
            (
                "null",
                json,
                422,
                "invalid_json",
                "JSON body does not match the expected format",
            ),
            (
                &"x".repeat(65),
                json,
                413,
                "payload_too_large",
                "request body is too large",
            ),
            (
                r#"{"name":" "}"#,
                json,
                422,
                "invalid_name",
                "name is required",
            ),
        ] {
            let mut request = Request::builder()
                .uri("/")
                .method("POST")
                .header("x-request-id", "req_json");
            if let Some(content_type) = content_type {
                request = request.header(CONTENT_TYPE, content_type);
            }
            let response = app
                .clone()
                .oneshot(request.body(Body::from(body.to_owned())).unwrap())
                .await
                .unwrap();
            assert_eq!(response.status().as_u16(), status);
            assert_eq!(response.headers()[CONTENT_TYPE], "application/problem+json");
            let body = to_bytes(response.into_body(), 4096).await.unwrap();
            let problem: serde_json::Value = serde_json::from_slice(&body).unwrap();
            assert_eq!(problem["status"], status);
            assert_eq!(problem["code"], code);
            assert_eq!(problem["request_id"], "req_json");
            assert_eq!(problem["detail"], detail);
            if code == "invalid_name" {
                assert_eq!(
                    problem["details"],
                    json!({ "fields": [{ "field": "name", "code": "required", "message": "name is required" }] })
                );
            } else {
                assert!(problem.get("details").is_none());
                assert!(!String::from_utf8_lossy(&body).contains("struct Payload"));
            }
        }
    }

    #[tokio::test]
    async fn validated_json_accepts_json_and_vendor_json_content_types() {
        let app = Router::new().route(
            "/",
            post(|payload: ValidatedJson<Payload>| async move { payload.into_inner().name }),
        );

        for content_type in ["application/json", "application/vnd.example+json"] {
            let response = app
                .clone()
                .oneshot(
                    Request::builder()
                        .method("POST")
                        .uri("/")
                        .header(CONTENT_TYPE, content_type)
                        .body(Body::from(r#"{"name":"example"}"#))
                        .unwrap(),
                )
                .await
                .unwrap();

            assert_eq!(response.status(), StatusCode::OK);
            let body = to_bytes(response.into_body(), 4096).await.unwrap();
            assert_eq!(body.as_ref(), b"example");
        }
    }

    #[tokio::test]
    async fn validated_json_does_not_disclose_custom_deserializer_errors() {
        struct PrivatePayload;

        impl<'de> Deserialize<'de> for PrivatePayload {
            fn deserialize<D: Deserializer<'de>>(_: D) -> Result<Self, D::Error> {
                Err(serde::de::Error::custom(
                    "private credential from application deserializer",
                ))
            }
        }

        impl Validate for PrivatePayload {
            fn validate(&self) -> Result<(), ValidationError> {
                Ok(())
            }
        }

        let app = Router::new().route(
            "/",
            post(|_: ValidatedJson<PrivatePayload>| async { StatusCode::NO_CONTENT }),
        );
        let response = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/")
                    .header(CONTENT_TYPE, "application/json")
                    .header("x-request-id", "req_custom_json")
                    .body(Body::from("{}"))
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
        let body = to_bytes(response.into_body(), 4096).await.unwrap();
        let problem: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(problem["code"], "invalid_json");
        assert_eq!(problem["request_id"], "req_custom_json");
        assert_eq!(
            problem["detail"],
            "JSON body does not match the expected format"
        );
        assert!(problem.get("details").is_none());
        assert!(!String::from_utf8_lossy(&body).contains("private credential"));
    }
}