vespera 0.3.0

A fully automated OpenAPI engine for Axum with zero-config route and schema discovery
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
//! End-to-end test: `Validated<Json<T>>` axum extractor rejects invalid
//! payloads with `422 Unprocessable Entity` + a JSON error envelope, and
//! lets valid payloads through to the handler.

#![cfg(feature = "validation")]

use ::axum::{Router, body::Body, http::Request, routing::post};
use ::serde::Deserialize;
use ::tower::ServiceExt;
use ::vespera::{Schema, Validated, ValidatedWith};

#[derive(Deserialize, Schema)]
#[allow(dead_code)]
struct CreatePost {
    #[schema(min_length = 3, max_length = 50)]
    title: String,

    #[schema(min_length = 1)]
    content: String,
}

async fn create_post(
    Validated(::axum::Json(_payload)): Validated<::axum::Json<CreatePost>>,
) -> &'static str {
    "ok"
}

#[derive(Clone)]
struct SlugContext {
    required_prefix: String,
}

#[derive(Deserialize, garde::Validate)]
#[garde(context(SlugContext as ctx))]
struct ContextPost {
    #[garde(custom(|value: &str, ctx: &SlugContext| {
        if value.starts_with(&ctx.required_prefix) {
            Ok(())
        } else {
            Err(garde::Error::new(format!(
                "must start with {}",
                ctx.required_prefix
            )))
        }
    }))]
    slug: String,
}

async fn create_context_post(
    validated: ValidatedWith<SlugContext, ::axum::Json<ContextPost>>,
) -> &'static str {
    let ::axum::Json(_payload) = validated.into_inner();
    "ok"
}

fn context_router() -> Router<SlugContext> {
    Router::new().route("/context-posts", post(create_context_post))
}

fn router() -> Router {
    Router::new().route("/posts", post(create_post))
}

fn post_json_request(uri: &str, body: impl Into<Body>) -> Request<Body> {
    Request::builder()
        .method("POST")
        .uri(uri)
        .header("content-type", "application/json")
        .body(body.into())
        .unwrap()
}

async fn body_to_string(body: Body) -> String {
    let bytes = ::axum::body::to_bytes(body, usize::MAX).await.unwrap();
    String::from_utf8(bytes.to_vec()).unwrap()
}

fn assert_json_content_type(headers: &::axum::http::HeaderMap) {
    assert_eq!(
        headers.get("content-type").map(|v| v.to_str().unwrap()),
        Some("application/json"),
    );
}

#[tokio::test]
async fn valid_payload_returns_200() {
    let app = router();
    let req = post_json_request("/posts", r#"{"title":"My Post","content":"hello world"}"#);

    let res = app.oneshot(req).await.unwrap();
    assert_eq!(res.status(), 200);
    assert_eq!(body_to_string(res.into_body()).await, "ok");
}

#[tokio::test]
async fn short_title_returns_422_with_path_keyed_envelope() {
    let app = router();
    let req = post_json_request("/posts", r#"{"title":"X","content":"ok"}"#);

    let res = app.oneshot(req).await.unwrap();
    assert_eq!(res.status(), 422);
    assert_json_content_type(res.headers());

    let body: ::serde_json::Value =
        ::serde_json::from_str(&body_to_string(res.into_body()).await).unwrap();

    let errors = body["errors"].as_array().expect("errors array missing");
    assert!(!errors.is_empty(), "errors array is empty");
    assert!(
        errors
            .iter()
            .any(|e| e["path"].as_str() == Some("title") && e["message"].as_str().is_some()),
        "expected an error with path=\"title\", got {body:#}"
    );
}

#[tokio::test]
async fn empty_content_returns_422() {
    let app = router();
    let req = post_json_request("/posts", r#"{"title":"Valid title","content":""}"#);

    let res = app.oneshot(req).await.unwrap();
    assert_eq!(res.status(), 422);

    let body: ::serde_json::Value =
        ::serde_json::from_str(&body_to_string(res.into_body()).await).unwrap();
    let errors = body["errors"].as_array().unwrap();
    assert!(errors.iter().any(|e| e["path"].as_str() == Some("content")));
}

#[tokio::test]
async fn multiple_violations_all_appear_in_envelope() {
    let app = router();
    let req = post_json_request("/posts", r#"{"title":"X","content":""}"#);

    let res = app.oneshot(req).await.unwrap();
    assert_eq!(res.status(), 422);

    let body: ::serde_json::Value =
        ::serde_json::from_str(&body_to_string(res.into_body()).await).unwrap();
    let errors = body["errors"].as_array().unwrap();
    let paths: Vec<&str> = errors.iter().filter_map(|e| e["path"].as_str()).collect();
    assert!(paths.contains(&"title"), "got {paths:?}");
    assert!(paths.contains(&"content"), "got {paths:?}");
}

#[tokio::test]
async fn malformed_json_propagates_400_not_422() {
    // When the inner extractor itself fails (e.g. invalid JSON),
    // `Validated<T>` must forward that rejection unchanged rather than
    // synthesizing a 422 from a non-existent garde report.
    let app = router();
    let req = post_json_request("/posts", "not json");

    let res = app.oneshot(req).await.unwrap();
    // Axum's Json extractor returns 400 (or 415 depending on cause) —
    // anything that is NOT our 422 envelope is acceptable here.
    assert_ne!(res.status(), 422);
}

#[tokio::test]
async fn context_validated_payload_returns_200_when_state_context_accepts_value() {
    let app = context_router().with_state(SlugContext {
        required_prefix: "vespera-".to_owned(),
    });
    let req = post_json_request("/context-posts", r#"{"slug":"vespera-release"}"#);

    let res = app.oneshot(req).await.unwrap();

    assert_eq!(res.status(), 200);
    assert_eq!(body_to_string(res.into_body()).await, "ok");
}

#[tokio::test]
async fn context_validated_payload_returns_422_when_state_context_rejects_value() {
    let app = context_router().with_state(SlugContext {
        required_prefix: "vespera-".to_owned(),
    });
    let req = post_json_request("/context-posts", r#"{"slug":"other-release"}"#);

    let res = app.oneshot(req).await.unwrap();

    assert_eq!(res.status(), 422);
    assert_json_content_type(res.headers());
    let body: ::serde_json::Value =
        ::serde_json::from_str(&body_to_string(res.into_body()).await).unwrap();
    assert_envelope_has_field_error(&body, "slug");
}

#[test]
fn context_validated_wrapper_accessors_and_deref_mutate_the_inner_value() {
    let mut validated = ValidatedWith::<SlugContext, String>::new("vespera".to_owned());

    assert_eq!(validated.get(), "vespera");
    validated.get_mut().push('-');
    assert_eq!(&*validated, "vespera-");
    validated.push_str("release");

    assert_eq!(validated.into_inner(), "vespera-release");
}

// ── per-rule 422 coverage ────────────────────────────────────────────
//
// `CreatePost` only exercises `min_length` / `max_length`.  The model
// below pulls in every other rule we emit so each runs through the
// full extractor → garde → 422 envelope flow at least once.

#[derive(Deserialize, Schema)]
#[allow(dead_code)]
struct AllRules {
    /// String length + pattern + format.
    #[schema(min_length = 3, max_length = 32, pattern = "^[a-z0-9_]+$")]
    username: String,

    /// `format = "email"` → garde `email::apply`.
    #[schema(format = "email")]
    email: String,

    /// `format = "uri"` → garde `url::apply`.
    #[schema(format = "uri")]
    homepage: String,

    /// `format = "ipv4"` → garde `ip::apply(IpKind::V4)`.
    #[schema(format = "ipv4")]
    addr_v4: String,

    /// `format = "ipv6"` → garde `ip::apply(IpKind::V6)`.
    #[schema(format = "ipv6")]
    addr_v6: String,

    /// Numeric range.
    #[schema(minimum = 0, maximum = 150)]
    age: u32,

    /// `Vec` length + uniqueness annotation (uniqueness itself is
    /// OpenAPI-only — no garde rule).
    #[schema(min_items = 1, max_items = 3, unique_items)]
    tags: Vec<String>,

    /// `Option<T>` field — should validate only when `Some`.
    #[schema(min_length = 8)]
    nickname: Option<String>,
}

async fn create_all_rules(
    Validated(::axum::Json(_p)): Validated<::axum::Json<AllRules>>,
) -> &'static str {
    "ok"
}

fn all_rules_router() -> Router {
    Router::new().route("/all", post(create_all_rules))
}

fn good_payload() -> ::serde_json::Value {
    ::serde_json::json!({
        "username":  "alice_99",
        "email":     "alice@example.com",
        "homepage":  "https://alice.example.com",
        "addr_v4":   "192.168.0.1",
        "addr_v6":   "::1",
        "age":       30,
        "tags":      ["a", "b"],
        "nickname":  null
    })
}

/// Send `payload` to `/all` and decode the response as
/// `(status, body_json)`.  Asserts `application/json` content-type when
/// the status is `422` (the canonical validation envelope).
async fn dispatch(app: Router, payload: ::serde_json::Value) -> (u16, ::serde_json::Value) {
    let req = Request::builder()
        .method("POST")
        .uri("/all")
        .header("content-type", "application/json")
        .body(Body::from(payload.to_string()))
        .unwrap();
    let res = app.oneshot(req).await.unwrap();
    let status = res.status().as_u16();
    if status == 422 {
        assert_json_content_type(res.headers());
    }
    let body: ::serde_json::Value = ::serde_json::from_str(&body_to_string(res.into_body()).await)
        .unwrap_or(::serde_json::Value::Null);
    (status, body)
}

/// Assert that `body` is the 422 envelope and contains at least one
/// error whose `path == field`.
fn assert_envelope_has_field_error(body: &::serde_json::Value, field: &str) {
    let errors = body["errors"]
        .as_array()
        .unwrap_or_else(|| panic!("missing `errors` array in {body:#}"));
    assert!(
        errors
            .iter()
            .any(|e| e["path"].as_str() == Some(field) && e["message"].as_str().is_some()),
        "expected an error with path=\"{field}\" + message, got {body:#}",
    );
}

#[tokio::test]
async fn all_rules_happy_path_returns_200() {
    let (status, _) = dispatch(all_rules_router(), good_payload()).await;
    assert_eq!(status, 200);
}

#[tokio::test]
async fn rule_pattern_violation_returns_422() {
    let mut bad = good_payload();
    bad["username"] = ::serde_json::json!("Alice99"); // uppercase fails `^[a-z0-9_]+$`
    let (status, body) = dispatch(all_rules_router(), bad).await;
    assert_eq!(status, 422);
    assert_envelope_has_field_error(&body, "username");
}

#[tokio::test]
async fn rule_format_email_violation_returns_422() {
    let mut bad = good_payload();
    bad["email"] = ::serde_json::json!("not-an-email");
    let (status, body) = dispatch(all_rules_router(), bad).await;
    assert_eq!(status, 422);
    assert_envelope_has_field_error(&body, "email");
}

#[tokio::test]
async fn rule_format_uri_violation_returns_422() {
    let mut bad = good_payload();
    bad["homepage"] = ::serde_json::json!("not a url");
    let (status, body) = dispatch(all_rules_router(), bad).await;
    assert_eq!(status, 422);
    assert_envelope_has_field_error(&body, "homepage");
}

#[tokio::test]
async fn rule_format_ipv4_violation_returns_422() {
    let mut bad = good_payload();
    bad["addr_v4"] = ::serde_json::json!("999.999.999.999");
    let (status, body) = dispatch(all_rules_router(), bad).await;
    assert_eq!(status, 422);
    assert_envelope_has_field_error(&body, "addr_v4");
}

#[tokio::test]
async fn rule_format_ipv6_violation_returns_422() {
    let mut bad = good_payload();
    bad["addr_v6"] = ::serde_json::json!("not-an-ipv6-address");
    let (status, body) = dispatch(all_rules_router(), bad).await;
    assert_eq!(status, 422);
    assert_envelope_has_field_error(&body, "addr_v6");
}

#[tokio::test]
async fn rule_range_minimum_violation_returns_422() {
    // `age` lives in `u32`; the only sub-`minimum=0` value JSON can
    // express against a `u32` is via serde rejecting -1.  To exercise
    // the `range::apply` rule itself we use a type that allows a value
    // below the schema minimum on a fresh struct.
    #[derive(Deserialize, Schema)]
    #[allow(dead_code)]
    struct Signed {
        #[schema(minimum = 0, maximum = 150)]
        age: i32,
    }
    async fn handler(Validated(::axum::Json(_)): Validated<::axum::Json<Signed>>) -> &'static str {
        "ok"
    }
    let app = Router::new().route("/n", post(handler));
    let req = post_json_request("/n", r#"{"age":-1}"#);
    let res = app.oneshot(req).await.unwrap();
    assert_eq!(res.status(), 422);
    let body: ::serde_json::Value =
        ::serde_json::from_str(&body_to_string(res.into_body()).await).unwrap();
    assert_envelope_has_field_error(&body, "age");
}

#[tokio::test]
async fn rule_range_maximum_violation_returns_422() {
    let mut bad = good_payload();
    bad["age"] = ::serde_json::json!(9999);
    let (status, body) = dispatch(all_rules_router(), bad).await;
    assert_eq!(status, 422);
    assert_envelope_has_field_error(&body, "age");
}

#[tokio::test]
async fn rule_min_items_violation_returns_422() {
    let mut bad = good_payload();
    bad["tags"] = ::serde_json::json!([]); // empty Vec < min_items=1
    let (status, body) = dispatch(all_rules_router(), bad).await;
    assert_eq!(status, 422);
    assert_envelope_has_field_error(&body, "tags");
}

#[tokio::test]
async fn rule_max_items_violation_returns_422() {
    let mut bad = good_payload();
    bad["tags"] = ::serde_json::json!(["a", "b", "c", "d"]); // 4 > max_items=3
    let (status, body) = dispatch(all_rules_router(), bad).await;
    assert_eq!(status, 422);
    assert_envelope_has_field_error(&body, "tags");
}

#[tokio::test]
async fn rule_option_field_validates_only_when_some_returns_422() {
    let mut bad = good_payload();
    bad["nickname"] = ::serde_json::json!("hi"); // 2 chars < min_length=8
    let (status, body) = dispatch(all_rules_router(), bad).await;
    assert_eq!(status, 422);
    assert_envelope_has_field_error(&body, "nickname");
}

#[tokio::test]
async fn rule_option_field_none_skips_validation() {
    // `nickname: null` must not contribute a 422 — Option<T> validates
    // only when `Some`.  The rest of the payload is valid, so we
    // expect a clean 200.
    let mut p = good_payload();
    p["nickname"] = ::serde_json::Value::Null;
    let (status, _) = dispatch(all_rules_router(), p).await;
    assert_eq!(status, 200);
}

#[tokio::test]
async fn multiple_per_rule_violations_all_appear_in_envelope() {
    let bad = ::serde_json::json!({
        "username":  "BAD!",                  // pattern + (length OK at 4)
        "email":     "broken",                // format=email
        "homepage":  "broken",                // format=uri
        "addr_v4":   "999.999.999.999",       // format=ipv4
        "addr_v6":   "broken",                // format=ipv6
        "age":       9999,                    // range
        "tags":      [],                      // min_items
        "nickname":  "x"                      // Option's min_length
    });
    let (status, body) = dispatch(all_rules_router(), bad).await;
    assert_eq!(status, 422);
    for field in [
        "username", "email", "homepage", "addr_v4", "addr_v6", "age", "tags", "nickname",
    ] {
        assert_envelope_has_field_error(&body, field);
    }
}

// ── byte-snapshot test: 422 validation envelope contract ────────────────
//
// This test locks the EXACT serialized bytes of the 422 validation-error
// envelope produced by `Validated<T>`. The snapshot proves byte-identity
// across refactors of `crates/vespera/src/validated.rs`.
//
// The envelope shape is a public contract:
// - Used by axum handlers (JSON response body)
// - Hoisted into JNI wire headers as `"validation_errors": [...]`
// - Consumed by Java decoders and client libraries
//
// Multi-error coverage: triggers 2+ field errors to verify the full
// envelope structure (message before path, array ordering, etc.).

#[tokio::test]
async fn byte_snapshot_422_envelope_multi_error() {
    let app = router();
    let req = post_json_request("/posts", r#"{"title":"X","content":""}"#);

    let res = app.oneshot(req).await.unwrap();
    assert_eq!(res.status(), 422);

    let body_bytes = ::axum::body::to_bytes(res.into_body(), usize::MAX)
        .await
        .unwrap();
    let body_str = String::from_utf8(body_bytes.to_vec()).unwrap();

    insta::assert_snapshot!("validated_422_envelope_multi_error", body_str);
}