laravel-rust 0.1.0

Laravel for Rust: a full-stack Rust web framework, inspired by PHP Laravel
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
use std::sync::{Arc, Mutex};

use laravel::Application;
use laravel::config::{Env, session::Driver};
use laravel::crypt::{Cipher, Encrypter};
use laravel::http::{Json, Request};
use laravel::routing::Router;
use laravel::testing::MakesHttpRequests;
use laravel::validation::{
    Field, InputValue, Rule, RuleError, Rules, Valid, Validate, ValidationError, ValidationRule,
};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};

use crate::support::Invalid;

mod package {
    use super::*;

    pub struct Slug;

    impl ValidationRule for Slug {
        async fn validate(&self, field: &Field<'_>) -> Result<(), RuleError> {
            match field.value.and_then(InputValue::as_str) {
                Some(value) if value.chars().all(|c| c.is_ascii_lowercase() || c == '-') => Ok(()),
                _ => Err(RuleError::invalid(format!("The {} field must be a slug.", field.name))),
            }
        }
    }

    pub struct StartsWith(&'static str);

    impl StartsWith {
        pub fn new() -> Self {
            Self("")
        }

        pub fn prefix(mut self, prefix: &'static str) -> Self {
            self.0 = prefix;
            self
        }
    }

    impl ValidationRule for StartsWith {
        async fn validate(&self, field: &Field<'_>) -> Result<(), RuleError> {
            if field
                .value
                .and_then(InputValue::as_str)
                .is_some_and(|value| value.starts_with(self.0))
            {
                Ok(())
            } else {
                Err(RuleError::invalid(format!(
                    "The {} field must start with {}.",
                    field.name, self.0
                )))
            }
        }
    }
}

#[derive(Debug, Deserialize, Serialize, Validate)]
struct Item {
    #[serde(alias = "title")]
    #[validate(required, max_length = 5, package::Slug)]
    name: String,
    quantity: u32,
}

#[derive(Debug, Deserialize, Serialize, Validate)]
#[validate(anyone)]
struct Order {
    #[serde(alias = "products")]
    #[validate(required, each)]
    items: Vec<Item>,
    #[validate(each(required, max_length = 5, package::Slug))]
    tags: Vec<String>,
    #[validate(package::StartsWith::new().prefix("order-"))]
    reference: String,
}

async fn store(Valid(order): Valid<Order>) -> Json<Order> {
    Json(order)
}

fn app() -> Application {
    Application::configure()
        .replace_env(Env::default())
        .with_config(|config, _| {
            config.app.key = Some(Encrypter::generate_key(Cipher::Aes256Cbc));
            config.session.driver = Driver::Memory;
        })
        .with_routing(|routing, _| {
            routing.api(|route: &mut Router| {
                route.post("/orders", store);
            });
            routing.web(|route: &mut Router| {
                route.post("/orders", store);
            });
        })
        .create()
}

#[tokio::test]
async fn list_rules_collect_custom_builtin_and_decoding_errors() {
    app().post("/api/orders")
        .json(json!({
            "items": [{"name":"rust", "quantity":1}, {"name":"TOO-LONG", "quantity":"many"}, {}],
            "tags": ["rust", "UPPER", "", 42], "reference":"wrong"
        }))
        .await
        .assert_status(422)
        .assert_nothing_reported()
        .assert_json(json!({"errors": {
            "items.1.name": ["The items.1.name field must not be greater than 5 characters.", "The items.1.name field must be a slug."],
            "items.1.quantity": ["The items.1.quantity field must be an integer."],
            "items.2.name": ["The items.2.name field is required."],
            "items.2.quantity": ["The items.2.quantity field is required."],
            "tags.1": ["The tags.1 field must be a slug."],
            "tags.2": ["The tags.2 field is required."],
            "tags.3": ["The tags.3 field must be a string.", "The tags.3 field must be a slug."],
            "reference": ["The reference field must start with order-."]
        }}));
}

#[tokio::test]
async fn a_huge_list_of_failing_items_reports_only_the_first_thousand_fields() {
    let response = app()
        .post("/api/orders")
        .json(json!({ "items": [{"name": "rust", "quantity": 1}], "tags": vec![""; 5_000], "reference": "order-one" }))
        .await;
    let errors = response.assert_status(422).json()["errors"]
        .as_object()
        .unwrap()
        .clone();

    assert_eq!(errors.len(), 1_000);
    assert_eq!(errors["tags.999"], json!(["The tags.999 field is required."]));
    assert!(!errors.contains_key("tags.1000"));
}

#[tokio::test]
async fn lists_accept_json_and_sparse_form_keys_with_aliases() {
    let app = app();
    app.post("/api/orders")
        .json(json!({"items":[{"name":"rust", "quantity":1}], "tags":["rust"], "reference":" order-one "}))
        .await
        .assert_ok()
        .assert_json(json!({"reference":"order-one"}));
    app.post("/api/orders")
        .form([
            ("products[7][title]", "UPPER"),
            ("products[7][quantity]", "1"),
            ("products[2][name]", "rust"),
            ("products[2][quantity]", "2"),
            ("tags[9]", "TOO-LONG"),
            ("reference", "order-one"),
        ])
        .await
        .assert_status(422)
        .assert_invalid(&["products.7.title", "tags.9"])
        .assert_valid(&["items.7.name", "products.2.name", "tags.0"]);
    app.post("/api/orders")
        .form([
            ("items[7][name]", "rust"),
            ("items[7][quantity]", "1"),
            ("tags[9]", "rust"),
            ("reference", "order-one"),
        ])
        .await
        .assert_ok()
        .assert_json(json!({"items":[{"name":"rust", "quantity":1}], "tags":["rust"]}));
}

#[derive(Debug, Deserialize, Serialize, Validate)]
#[validate(anyone)]
struct Optional {
    #[validate(each)]
    items: Option<Vec<Option<Item>>>,
    #[validate(each(required, max_length = 2))]
    required_tags: Option<Vec<Option<String>>>,
    #[validate(each(max_length = 2, package::Slug))]
    tags: Option<Vec<Option<String>>>,
}

#[tokio::test]
async fn nullable_lists_and_entries_preserve_required_semantics() {
    let app = Application::configure()
        .replace_env(Env::default())
        .with_routing(|routing, _| {
            routing.api(|route: &mut Router| {
                route.post("/optional", |Valid(input): Valid<Optional>| async move { Json(input) });
            });
        })
        .create();
    for body in [
        json!({}),
        json!({"items":null, "tags":null}),
        json!({"items":[], "tags":[]}),
        json!({"items":[null], "tags":[null, "ok"]}),
    ] {
        app.post("/api/optional").json(&body).await.assert_ok();
    }
    app.post("/api/optional")
        .json(json!({"required_tags":[null, "", "abc"], "tags":[null, "ABC"]}))
        .await
        .assert_invalid(&["required_tags.0", "required_tags.1", "required_tags.2", "tags.1"])
        .assert_valid(&["tags.0"])
        .assert_json(json!({"errors": {
            "required_tags.0": ["The required_tags.0 field is required."],
            "required_tags.1": ["The required_tags.1 field is required."],
            "required_tags.2": ["The required_tags.2 field must not be greater than 2 characters."],
            "tags.1": ["The tags.1 field must not be greater than 2 characters.", "The tags.1 field must be a slug."]
        }}));
}

#[derive(Debug, Deserialize, Validate)]
#[expect(dead_code, reason = "only validation is exercised")]
struct Node {
    #[validate(required, max_length = 2)]
    name: String,
    #[serde(default)]
    #[validate]
    children: Vec<Node>,
}

#[derive(Debug, Deserialize, Validate)]
#[expect(dead_code, reason = "only validation is exercised")]
struct Batch<T> {
    #[validate]
    entries: Vec<T>,
}

impl<T: laravel::validation::Validate> laravel::validation::ValidatesRequest for Batch<T> {
    async fn authorize(_: &laravel::http::Request) -> laravel::Result<bool> {
        Ok(true)
    }
}

#[tokio::test]
async fn malformed_lists_and_items_report_shapes_without_descendant_errors() {
    let app = Application::configure()
        .replace_env(Env::default())
        .with_routing(|routing, _| {
            routing.api(|route: &mut Router| {
                route.post("/nodes", |Valid(_): Valid<Batch<Node>>| async { "ok" });
            });
        })
        .create();
    for body in [json!({"entries":42}), json!({"entries":{"named":{"name":"ok"}}})] {
        let response = app.post("/api/nodes").json(&body).await;
        assert_eq!(
            response.json()["errors"],
            json!({"entries": ["The entries field must be an array."]})
        );
    }
    let response = app
        .post("/api/nodes")
        .json(json!({"entries":[null, 42, [], {"name":"long"}]}))
        .await;
    assert_eq!(
        response.json()["errors"],
        json!({
            "entries.0": ["The entries.0 field is required."],
            "entries.1": ["The entries.1 field must be an array."],
            "entries.2": ["The entries.2 field must be an array."],
            "entries.3.name": ["The entries.3.name field must not be greater than 2 characters."]
        })
    );
}

type RecordedValues = Arc<Mutex<Vec<(String, Option<InputValue>)>>>;

struct Recording {
    seen: RecordedValues,
    implicit: bool,
    fail: bool,
}

impl ValidationRule for Recording {
    async fn validate(&self, field: &Field<'_>) -> Result<(), RuleError> {
        self.seen
            .lock()
            .unwrap()
            .push((field.name.to_owned(), field.value.cloned()));
        if self.fail {
            Err(RuleError::invalid("Rejected.".to_owned()))
        } else {
            Ok(())
        }
    }

    fn implicit(&self) -> bool {
        self.implicit
    }
}

struct MatchesRoot;

impl ValidationRule for MatchesRoot {
    async fn validate(&self, field: &Field<'_>) -> Result<(), RuleError> {
        if field.input.get("expected") == field.value {
            Ok(())
        } else {
            Err(RuleError::invalid(format!(
                "The {} field must match expected.",
                field.name
            )))
        }
    }
}

#[derive(Debug, Deserialize, Validate)]
#[expect(dead_code, reason = "only validation is exercised")]
struct MatchingItem {
    #[serde(rename = "display", alias = "label")]
    #[validate(MatchesRoot)]
    name: String,
}

#[derive(Debug, Deserialize, Validate)]
#[validate(anyone)]
#[expect(dead_code, reason = "only validation is exercised")]
struct MatchingBatch {
    #[validate(each)]
    items: Vec<MatchingItem>,
}

#[tokio::test]
async fn nested_custom_rules_receive_original_paths_and_complete_input() {
    let mut request = Request::from_http(
        http::Request::post("/")
            .header("content-type", "application/json")
            .body(laravel::axum::body::Body::from(
                json!({"expected":"ok", "items":[{"label":"bad"},{"display":"ok"}]}).to_string(),
            ))
            .unwrap(),
    );
    request.load_input().await.unwrap();
    let ValidationError::Invalid(errors) = request.validate::<MatchingBatch>().await.unwrap_err() else {
        panic!("expected field errors");
    };
    assert_eq!(
        serde_json::to_value(errors).unwrap(),
        json!({"items.0.label":["The items.0.label field must match expected."]})
    );
}

#[tokio::test]
async fn custom_rule_execution_and_list_paths_match_classic_fixtures() {
    let fixtures: Vec<Value> = serde_json::from_str(include_str!("fixtures/validation-rules.json")).unwrap();
    for fixture in fixtures {
        let seen = Arc::new(Mutex::new(Vec::new()));
        let mut rules = Rules::new();
        if fixture["kind"] == "custom" {
            if fixture["nullable"] == true {
                rules = rules.nullable("value");
            }
            if fixture["required"] == true {
                rules = rules.field("value", [Rule::required()]);
            }
            rules = rules.field(
                "value",
                (0..2).map(|_| {
                    Rule::custom(Recording {
                        seen: seen.clone(),
                        implicit: fixture["implicit"] == true,
                        fail: true,
                    })
                }),
            );
        } else {
            rules = rules.each::<Node>("items");
        }
        let errors = rules
            .validate(fixture["input"].as_object().unwrap())
            .await
            .err()
            .map(|error| error.invalid().clone())
            .unwrap_or_default();
        assert_eq!(
            serde_json::to_value(errors).unwrap(),
            fixture["errors"],
            "{}",
            fixture["name"]
        );
        if fixture["kind"] == "custom" {
            for (name, value) in seen.lock().unwrap().iter() {
                assert_eq!(
                    value,
                    &fixture["input"].get(name).cloned().map(InputValue::from),
                    "{}",
                    fixture["name"]
                );
            }
            let calls: Vec<_> = seen.lock().unwrap().iter().map(|(name, _)| name.clone()).collect();
            assert_eq!(
                serde_json::to_value(calls).unwrap(),
                fixture["calls"],
                "{}",
                fixture["name"]
            );
        }
    }
}