footing 0.1.21

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

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

use crate::http::{ApiProblem, IntoApiProblem, ProblemCode, RequestContext};
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(Debug, Clone, Default, PartialEq, Eq, Serialize)]
#[serde(transparent)]
/// Represents field violations.
pub struct FieldViolations {
    violations: Vec<FieldViolation>,
}

impl FieldViolations {
    #[must_use]
    /// Creates a new instance.
    pub fn new() -> Self {
        Self::default()
    }

    #[must_use]
    /// Creates a value from vec.
    pub fn from_vec(violations: Vec<FieldViolation>) -> Self {
        Self { violations }
    }

    /// Returns the push.
    pub fn push(&mut self, violation: FieldViolation) {
        self.violations.push(violation);
    }

    #[must_use]
    /// Returns the with.
    pub fn with(mut self, violation: FieldViolation) -> Self {
        self.violations.push(violation);
        self
    }

    /// Returns the add.
    pub fn add(
        &mut self,
        field: impl Into<String>,
        code: impl Into<String>,
        message: impl Into<String>,
    ) -> &mut Self {
        self.violations
            .push(FieldViolation::new(field, code, message));
        self
    }

    #[must_use]
    /// Returns the number of contained values.
    pub fn len(&self) -> usize {
        self.violations.len()
    }

    #[must_use]
    /// Returns whether the collection is empty.
    pub fn is_empty(&self) -> bool {
        self.violations.is_empty()
    }

    #[must_use]
    /// Returns this value as slice.
    pub fn as_slice(&self) -> &[FieldViolation] {
        &self.violations
    }

    /// Returns the iter.
    pub fn iter(&self) -> impl Iterator<Item = &FieldViolation> {
        self.violations.iter()
    }

    #[must_use]
    /// Consumes this value and returns vec.
    pub fn into_vec(self) -> Vec<FieldViolation> {
        self.violations
    }

    #[must_use]
    /// Consumes this value and returns validation error.
    pub fn into_validation_error(self) -> ValidationError {
        ValidationError::new(
            ErrorCode::internal("validation_failed"),
            "request validation failed",
        )
        .with_details(json!({ "fields": self.violations }))
    }
}

impl FromIterator<FieldViolation> for FieldViolations {
    fn from_iter<T: IntoIterator<Item = FieldViolation>>(iter: T) -> Self {
        Self::from_vec(iter.into_iter().collect())
    }
}

impl IntoIterator for FieldViolations {
    type Item = FieldViolation;
    type IntoIter = std::vec::IntoIter<FieldViolation>;

    fn into_iter(self) -> Self::IntoIter {
        self.violations.into_iter()
    }
}

#[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<FieldViolations> for ValidationError {
    fn from(value: FieldViolations) -> Self {
        value.into_validation_error()
    }
}

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

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

impl IntoApiProblem for ValidationError {
    fn into_api_problem(self) -> ApiProblem {
        validation_error_to_problem(self)
    }
}

#[derive(Clone)]
/// Represents validated JSON.
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(mut request: Request<Body>, state: &S) -> Result<Self, Self::Rejection> {
        // Json consumes the request, so its context can be moved instead of cloned.
        let context = request
            .extensions_mut()
            .remove::<RequestContext>()
            .unwrap_or_else(|| RequestContext::from_headers(request.headers()));

        let Json(value) = Json::<T>::from_request(request, state)
            .await
            .map_err(|rejection| {
                json_rejection_to_problem(rejection).with_request_context(&context)
            })?;

        value
            .validate()
            .map_err(|error| validation_error_to_problem(error).with_request_context(&context))?;

        Ok(Self(value))
    }
}

fn json_rejection_to_problem(rejection: JsonRejection) -> ApiProblem {
    let status = rejection.status();
    let code = match status {
        axum::http::StatusCode::UNSUPPORTED_MEDIA_TYPE => ProblemCode::UNSUPPORTED_MEDIA_TYPE,
        axum::http::StatusCode::PAYLOAD_TOO_LARGE => ProblemCode::PAYLOAD_TOO_LARGE,
        _ => ProblemCode::INVALID_JSON,
    };

    let detail = rejection.body_text();
    let problem = ApiProblem::try_new(status, code.clone(), detail.clone())
        .unwrap_or_else(|_| ApiProblem::bad_request(code, detail));

    problem.with_details(json!({
        "reason": rejection.to_string(),
    }))
}

fn validation_error_to_problem(error: ValidationError) -> ApiProblem {
    let mut problem =
        ApiProblem::unprocessable_entity(ProblemCode::from_error_code(error.code), error.message);
    if let Some(details) = error.details {
        problem = problem.with_details(details);
    }
    problem
}

fn normalize(value: impl Into<String>) -> String {
    value.into().trim().to_owned()
}

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

#[cfg(test)]
mod tests {
    use serde::Serialize;
    use serde_json::json;

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

    #[derive(Debug, 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",
                ))
            } 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 = FieldViolations::new().with(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" }])
        );
    }

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