use laravel::Application;
use laravel::config::Env;
use laravel::config::session::Driver;
use laravel::crypt::{Cipher, Encrypter};
#[cfg(feature = "minijinja")]
use laravel::http::StatusCode;
use laravel::http::{Json, Redirect, Request};
use laravel::routing::Router;
use laravel::testing::MakesHttpRequests;
use laravel::validation::{Rule, Rules, Sometimes, Valid, Validate, ValidatesRequest, ValidationError, invalid};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use std::borrow::Borrow;
use crate::support::Invalid;
#[derive(Debug, Deserialize, Serialize, Validate)]
#[validate(anyone)]
struct NewUser {
#[validate(required, max_length = 5)]
name: String,
#[validate(required)]
email: String,
nickname: Option<String>,
}
#[derive(Debug, Deserialize, Serialize, Validate)]
#[validate(anyone)]
struct Address {
#[validate(required)]
city: String,
country: String,
}
#[derive(Deserialize, Validate)]
#[validate(anyone)]
struct EditProfile {
#[validate(required, max_length = 5)]
name: Sometimes<String>,
#[validate(max_length = 5)]
bio: Sometimes<Option<String>>,
nickname: Sometimes<String>,
age: Sometimes<u8>,
}
async fn store(Valid(user): Valid<NewUser>) -> Json<NewUser> {
Json(user)
}
async fn manual(request: Request) -> laravel::Result<Redirect> {
let _: NewUser = request.validate().await?;
Ok(Redirect::to("/done"))
}
async fn login() -> laravel::Result<Redirect> {
invalid!(
email => "These credentials do not match our records.",
password => ["The password is too common.", "The password appeared in a data breach."],
email => "Too many attempts.",
"remember.device" => "Unknown device.",
);
}
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_errors(|errors, _| {
errors.dont_flash(["ssn", "card.cvc"]);
})
.with_routing(|routing, _| {
routing.api(|route: &mut Router| {
route.post("/users", store);
route.get("/users", store);
route.post("/manual", manual);
route.post("/login", login);
route.post("/profile", |Valid(profile): Valid<EditProfile>| async move {
let missing: Vec<_> = [
("name", profile.name.is_missing()),
("bio", profile.bio.is_missing()),
("nickname", profile.nickname.is_missing()),
("age", profile.age.is_missing()),
]
.into_iter()
.filter_map(|(name, missing)| missing.then_some(name))
.collect();
Json(json!({
"missing": missing,
"name": profile.name.present(),
"bio": profile.bio.present(),
"nickname": profile.nickname.present(),
"age": profile.age.present(),
}))
});
route.post(
"/addresses",
|Valid(address): Valid<Address>| async move { Json(address) },
);
});
routing.web(|route: &mut Router| {
route.post("/manual", manual);
route.get("/form", |request: Request| async move {
Json(json!({
"errors": request.session().unwrap().get::<Value>("errors.default"),
"old": request.old::<String>("name"),
}))
});
route.post("/login", login);
});
routing.routes(|route: &mut Router| {
route.post("/sessionless", store);
});
})
.create()
}
#[tokio::test]
async fn typed_input_normalizes_and_accepts_unicode_and_nullable_fields() {
app()
.post("/api/users")
.json(json!({ "name": " ééééé ", "email": " hi ", "nickname": " " }))
.await
.assert_ok()
.assert_valid(&[])
.assert_json(json!({ "name": "ééééé", "email": "hi", "nickname": null }));
}
#[tokio::test]
async fn valid_reads_only_the_body_and_ignores_query_parameters() {
let app = app();
app.get("/api/users?name=Alice&email=alice&nickname=")
.await
.assert_status(422)
.assert_invalid(&["name", "email"]);
app.post("/api/users?nickname=from_query")
.form([("name", "Alice"), ("email", "alice")])
.await
.assert_ok()
.assert_valid(&[])
.assert_json(json!({ "name": "Alice", "email": "alice", "nickname": null }));
}
#[tokio::test]
async fn rules_and_decoding_errors_are_reported_together() {
app()
.post("/api/users")
.json(json!({ "name": "longer", "email": 123, "nickname": [] }))
.await
.assert_status(422)
.assert_invalid(&["name", "email", "nickname"])
.assert_nothing_reported()
.assert_json(json!({
"message": "The name field must not be greater than 5 characters. (and 2 more errors)",
"errors": {
"name": ["The name field must not be greater than 5 characters."],
"email": ["The email field must be a string."],
"nickname": ["The nickname field must be a string."],
}
}));
}
#[tokio::test]
async fn blank_and_null_strings_without_rules_are_required() {
let app = app();
let required = json!({ "country": ["The country field is required."] });
app.post("/api/addresses")
.form([("city", "Paris"), ("country", "")])
.await
.assert_status(422)
.assert_json_path("errors", &required);
app.post("/api/addresses")
.json(json!({ "city": "Paris", "country": null }))
.await
.assert_status(422)
.assert_json_path("errors", &required);
app.post("/api/addresses")
.json(json!({ "city": "Paris", "country": 33 }))
.await
.assert_status(422)
.assert_json_path("errors", json!({ "country": ["The country field must be a string."] }));
}
#[tokio::test]
async fn sometimes_fields_check_only_what_the_request_sends() {
let app = app();
app.post("/api/profile")
.json(json!({}))
.await
.assert_ok()
.assert_exact_json(json!({
"missing": ["name", "bio", "nickname", "age"],
"name": null, "bio": null, "nickname": null, "age": null,
}));
app.post("/api/profile")
.json(json!({ "bio": null }))
.await
.assert_ok()
.assert_exact_json(json!({
"missing": ["name", "nickname", "age"],
"name": null, "bio": null, "nickname": null, "age": null,
}));
app.post("/api/profile")
.form([("name", "Ann"), ("bio", ""), ("nickname", "Tay"), ("age", "40")])
.await
.assert_ok()
.assert_exact_json(json!({ "missing": [], "name": "Ann", "bio": null, "nickname": "Tay", "age": 40 }));
app.post("/api/profile")
.form([("name", ""), ("bio", "too long"), ("nickname", ""), ("age", "forty")])
.await
.assert_status(422)
.assert_json_path(
"errors",
json!({
"name": ["The name field is required."],
"bio": ["The bio field must not be greater than 5 characters."],
"nickname": ["The nickname field is required."],
"age": ["The age field must be an integer."],
}),
);
app.post("/api/profile")
.json(json!({ "name": null, "nickname": null }))
.await
.assert_status(422)
.assert_json_path(
"errors",
json!({
"name": ["The name field is required."],
"nickname": ["The nickname field is required."],
}),
);
}
#[tokio::test]
async fn nul_bytes_that_skip_rules_as_blank_dont_reach_the_handler() {
app()
.post("/api/profile")
.json(json!({ "bio": "\0\0\0\0\0\0 \0" }))
.await
.assert_ok()
.assert_json_path("bio", Value::Null);
}
#[tokio::test]
async fn browser_forms_redirect_with_errors_and_old_input_for_one_request() {
let app = app();
let response = app
.post("/manual")
.header("referer", "/form")
.form([
("name", "longer"),
("email", ""),
("password", "secret"),
("password_confirmation", "secret"),
("current_password", "secret"),
("ssn", "078-05-1120"),
("card[name]", "Taylor"),
("card[cvc]", "123"),
])
.await;
response
.assert_redirect_to("/form")
.assert_invalid(&["name", "email"])
.assert_valid(&["nickname"])
.assert_session_has("_old_input.name", "longer")
.assert_session_has("_old_input.card", json!({ "name": "Taylor" }))
.assert_session_missing("_old_input.password")
.assert_session_missing("_old_input.password_confirmation")
.assert_session_missing("_old_input.current_password")
.assert_session_missing("_old_input.ssn");
let next = app.get("/form").with_cookies_from(&response).await;
next.assert_json(json!({ "old": "longer", "errors": { "email": ["The email field is required."] } }));
app.get("/form")
.with_cookies_from(&next)
.await
.assert_json(json!({ "errors": null, "old": null }));
}
#[tokio::test]
async fn invalid_input_from_a_handler_redirects_like_validation_does() {
let app = app();
let response = app
.post("/login")
.header("referer", "/form")
.form([("email", "taylor@laravel.com"), ("password", "secret")])
.await;
response
.assert_redirect_to("/form")
.assert_invalid(&["email"])
.assert_session_has("_old_input.email", "taylor@laravel.com")
.assert_session_missing("_old_input.password");
app.post("/api/login")
.json(json!({ "email": "taylor@laravel.com", "password": "secret" }))
.await
.assert_status(422)
.assert_json(json!({
"message": "These credentials do not match our records. (and 4 more errors)",
"errors": {
"email": ["These credentials do not match our records.", "Too many attempts."],
"password": ["The password is too common.", "The password appeared in a data breach."],
"remember.device": ["Unknown device."],
},
}));
app.post("/api/manual")
.json(json!({ "name": "longer" }))
.await
.assert_status(422);
}
#[tokio::test]
async fn unrelated_headers_do_not_bypass_the_validation_redirect() {
app()
.post("/manual")
.header("referer", "/form")
.header("hx-request", "true")
.form([("name", "longer"), ("email", "")])
.await
.assert_redirect_to("/form")
.assert_invalid(&["name", "email"])
.assert_session_has("_old_input.name", "longer");
}
#[tokio::test]
async fn browser_forms_without_a_session_receive_the_error_page() {
app()
.post("/sessionless")
.form([("name", "longer")])
.await
.assert_status(422)
.assert_header("content-type", "text/html; charset=utf-8")
.assert_see("Unprocessable Content");
}
#[tokio::test]
async fn rule_semantics_and_messages_match_classic_fixtures() {
let fixtures: Vec<Value> = serde_json::from_str(include_str!("fixtures/validation.json")).unwrap();
for fixture in fixtures {
let mut rules = Vec::new();
let mut nullable = false;
for rule in fixture["rules"].as_str().unwrap().split('|') {
match rule {
"required" => rules.push(Rule::required()),
"string" => rules.push(Rule::string()),
"max:2" => rules.push(Rule::max_length(2)),
"nullable" => nullable = true,
_ => unreachable!("fixture rule"),
}
}
let mut rules = Rules::new().field("value", rules);
if nullable {
rules = rules.nullable("value");
}
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"]
);
}
}
#[derive(Debug, Deserialize, Validate)]
#[validate(anyone)]
#[serde(rename_all = "camelCase")]
#[expect(dead_code, reason = "only decoding is exercised")]
struct Renamed {
#[validate(required, max_length = 2)]
first_name: String,
#[serde(rename(deserialize = "display"), alias = "label")]
#[validate(required)]
display_name: String,
#[serde(default)]
#[validate(required)]
defaulted: String,
}
#[tokio::test]
async fn rules_use_serde_names_aliases_and_submitted_values_before_defaults() {
let mut request = Request::from_http(
http::Request::post("/")
.header("content-type", "application/x-www-form-urlencoded")
.body(laravel::axum::body::Body::from("firstName=long&label=&defaulted=x"))
.unwrap(),
);
request.load_input().await.unwrap();
let ValidationError::Invalid(errors) = request.validate::<Renamed>().await.unwrap_err() else {
panic!("expected field errors");
};
assert!(errors.errors().contains_key("firstName"));
assert_eq!(errors.errors()["label"], ["The label field is required."]);
let mut request = Request::from_http(
http::Request::post("/")
.header("content-type", "application/x-www-form-urlencoded")
.body(laravel::axum::body::Body::from("firstName=ok&display=x"))
.unwrap(),
);
request.load_input().await.unwrap();
let ValidationError::Invalid(errors) = request.validate::<Renamed>().await.unwrap_err() else {
panic!("expected field errors");
};
assert_eq!(errors.errors()["defaulted"], ["The defaulted field is required."]);
}
#[derive(Debug, Deserialize)]
#[expect(dead_code, reason = "only decoding is exercised")]
struct Nested {
items: Vec<Item>,
}
#[derive(Debug, Deserialize)]
#[expect(dead_code, reason = "only decoding is exercised")]
struct Item {
name: String,
}
impl Validate for Nested {
fn declared_rules() -> Rules {
Rules::new().field("items.0.name", [Rule::required(), Rule::string(), Rule::max_length(2)])
}
}
impl ValidatesRequest for Nested {
async fn authorize(_: &laravel::http::Request) -> laravel::Result<bool> {
Ok(true)
}
}
#[tokio::test]
async fn dotted_rule_and_decoding_paths_share_one_report() {
let app = Application::configure()
.replace_env(Env::default())
.with_routing(|routing, _| {
routing.api(|route: &mut Router| {
route.post("/items", |Valid(_): Valid<Nested>| async { "ok" });
});
})
.create();
app.post("/api/items")
.json(json!({"items":[{"name":"long"},{}]}))
.await
.assert_invalid(&["items.0.name", "items.1.name"])
.assert_json(json!({"errors": {
"items.0.name": ["The items.0.name field must not be greater than 2 characters."],
"items.1.name": ["The items.1.name field is required."]
}}));
}
#[cfg(feature = "minijinja")]
#[tokio::test]
async fn pages_and_fragments_can_render_the_same_field_errors() {
use laravel::http::IntoResponse;
let root = crate::support::TempDir::with_files(
"validation",
&[(
"resources/views/form.html",
r#"{% block form %}<input value="{{ old('name', 'Guest') }}"><p>{{ error('name') }}</p>{% endblock %}"#,
)],
);
let base = root.to_path_buf();
let app = Application::configure()
.replace_env(Env::default())
.with_config(move |config, _| {
config.app.base_path = base;
config.app.key = Some(Encrypter::generate_key(Cipher::Aes256Cbc));
config.session.driver = Driver::Memory;
})
.with_routing(|routing, _| {
routing.web(|route: &mut Router| {
route.get("/form", || async { laravel::view("form", ()) });
route.post("/form", manual);
route.post("/fragment", |request: Request| async move {
match request.validate::<NewUser>().await {
Ok(_) => Ok("saved".into_response()),
Err(ValidationError::Invalid(errors)) => Ok((
StatusCode::UNPROCESSABLE_ENTITY,
laravel::view("form", ()).with_errors(&errors).fragment("form"),
)
.into_response()),
Err(ValidationError::Failed(error)) => Err(error),
}
});
});
})
.create();
app.get("/form").await.assert_see("Guest");
let invalid = app.post("/form").form([("name", "longer")]).await;
let page = app.get("/form").with_cookies_from(&invalid).await;
page.assert_see("longer")
.assert_see("The name field must not be greater than 5 characters.");
app.post("/fragment")
.form([("name", "")])
.await
.assert_status(422)
.assert_fragment_is("form")
.assert_see("The name field is required.");
}
#[cfg(feature = "inertia")]
#[tokio::test]
async fn inertia_redirects_and_version_reload_preserve_errors() {
use laravel::inertia::{self, Inertia};
struct Handle;
impl inertia::Middleware for Handle {
fn version(&self) -> Option<String> {
Some("1".to_owned())
}
}
let app = 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.web(|route: &mut Router| {
route.get("/form", |inertia: Inertia| async move {
inertia.render("Form", inertia::props! {})
});
route.put("/form", store);
route.patch("/form", store);
route.delete("/form", store);
});
})
.with_middleware(|middleware, _| {
middleware.web(|web| {
web.append(inertia::middleware(Handle));
});
})
.create();
for method in [http::Method::PUT, http::Method::PATCH, http::Method::DELETE] {
let invalid = app
.request(method, "/form")
.header("x-inertia", "true")
.header("referer", "/form")
.form([("name", "longer")])
.await;
invalid
.assert_status(303)
.assert_redirect_to("/form")
.assert_invalid(&["name", "email"]);
let reload = app
.get("/form")
.header("x-inertia", "true")
.header("x-inertia-version", "old")
.with_cookies_from(&invalid)
.await;
reload
.assert_status(409)
.assert_header("x-inertia-location", "http://localhost/form");
let page = app
.get("/form")
.header("x-inertia", "true")
.header("x-inertia-version", "1")
.with_cookies_from(&reload)
.await;
page.assert_inertia().equals(
"errors",
json!({
"name":"The name field must not be greater than 5 characters.", "email":"The email field is required."
}),
);
app.get("/form")
.header("x-inertia", "true")
.header("x-inertia-version", "1")
.with_cookies_from(&page)
.await
.assert_inertia()
.equals("errors", json!({}));
}
}
#[cfg(any(feature = "minijinja", feature = "inertia"))]
#[derive(Debug, Deserialize, Validate)]
#[validate(anyone, form = "login")]
struct Login {
#[validate(required)]
email: String,
}
#[cfg(any(feature = "minijinja", feature = "inertia"))]
async fn unknown_login(Valid(_): Valid<Login>) -> laravel::Result<Redirect> {
invalid!(email => "These credentials do not match our records.");
}
#[cfg(feature = "minijinja")]
#[tokio::test]
async fn named_forms_keep_each_form_on_a_page_to_its_own_errors() {
use laravel::validation::InvalidInput;
let root = crate::support::TempDir::with_files(
"forms",
&[(
"resources/views/account.html",
r#"login:{{ error('email', form='login') }}|register:{{ error('email') }}|count:{{ errors | length }}|reply:{{ error('email', form='reply-7') }}"#,
)],
);
let base = root.to_path_buf();
let app = Application::configure()
.replace_env(Env::default())
.with_config(move |config, _| {
config.app.base_path = base;
config.app.key = Some(Encrypter::generate_key(Cipher::Aes256Cbc));
config.session.driver = Driver::Memory;
})
.with_routing(|routing, _| {
routing.web(|route: &mut Router| {
route.get("/account", || async { laravel::view("account", ()) });
route.post("/login", |Valid(login): Valid<Login>| async move { login.email });
route.post("/check", unknown_login);
route.post("/check-redirect", |Valid(_): Valid<Login>| async {
Redirect::back().with_errors(InvalidInput::new().with("email", "Unknown."))
});
route.post("/check-default", |Valid(_): Valid<Login>| async move {
Err::<(), laravel::Error>(InvalidInput::new().with("email", "Taken.").for_form("default").into())
});
route.post("/sign-in", login);
route.post("/both", || async {
Redirect::back()
.with_errors(InvalidInput::new().with("email", "Taken."))
.with_errors(InvalidInput::new().with("email", "Unknown.").for_form("login"))
.with_errors(InvalidInput::new().with("email", "Locked.").for_form("login"))
});
route.post("/fragment", |request: Request| async move {
let errors = request.validate::<Login>().await.unwrap_err();
let ValidationError::Invalid(errors) = errors else {
unreachable!()
};
laravel::view("account", ()).with_errors(errors)
});
});
})
.create();
let login = app
.post("/login")
.header("referer", "/account")
.form([("email", "")])
.await;
login
.assert_redirect_to("/account")
.assert_invalid_in("login", &["email"])
.assert_session_has("_old_input.email", Value::Null)
.assert_valid(&[]);
app.get("/account")
.with_cookies_from(&login)
.await
.assert_see("login:The email field is required.|register:|count:0");
let sign_in = app
.post("/sign-in")
.header("referer", "/account")
.form([("email", "taylor@laravel.com"), ("_form", "sign_in")])
.await;
sign_in
.assert_invalid_in("sign_in", &["email", "password"])
.assert_valid(&[]);
app.post("/check")
.header("referer", "/account")
.form([("email", "taylor@laravel.com")])
.await
.assert_invalid_in("login", &["email"])
.assert_valid(&[]);
app.post("/check-redirect")
.header("referer", "/account")
.form([("email", "taylor@laravel.com")])
.await
.assert_invalid_in("login", &["email"]);
app.post("/check-default")
.header("referer", "/account")
.form([("email", "taylor@laravel.com")])
.await
.assert_invalid(&["email"]);
let both = app.post("/both").header("referer", "/account").await;
assert_eq!(
both.session("errors"),
Some(&json!({ "default": { "email": ["Taken."] }, "login": { "email": ["Locked."] } }))
);
app.get("/account")
.with_cookies_from(&both)
.await
.assert_see("login:Locked.|register:Taken.|count:1");
app.post("/fragment")
.form([("email", "")])
.await
.assert_see("login:The email field is required.|register:|count:0");
for (path, email, form, message) in [
("/login", "", "reply-7", "The email field is required."),
(
"/check",
"taylor@example.com",
"reply-7",
"These credentials do not match our records.",
),
("/check-redirect", "taylor@example.com", "reply-7", "Unknown."),
("/check-default", "taylor@example.com", "default", "Taken."),
] {
app.post(path)
.from("/account")
.form([("email", email), ("_form", "reply-7")])
.await
.assert_session_has("errors", json!({ form: { "email": [message] } }));
}
app.post("/fragment")
.form([("email", ""), ("_form", "reply-7")])
.await
.assert_see("login:|register:|count:0|reply:The email field is required.");
}
#[cfg(feature = "inertia")]
#[tokio::test]
async fn inertia_pages_receive_a_forms_errors_under_its_name() {
use laravel::inertia::{self, Inertia};
struct Handle;
impl inertia::Middleware for Handle {}
let app = 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.web(|route: &mut Router| {
route.get("/account", |inertia: Inertia| async move {
inertia.render("Account", inertia::props! {})
});
route.post("/login", |Valid(login): Valid<Login>| async move { login.email });
route.post("/check", unknown_login);
});
})
.with_middleware(|middleware, _| {
middleware.web(|web| {
web.append(inertia::middleware(Handle));
});
})
.create();
let invalid = app
.post("/login")
.header("x-inertia", "true")
.header("referer", "/account")
.form([("email", "")])
.await;
app.get("/account")
.header("x-inertia", "true")
.with_cookies_from(&invalid)
.await
.assert_inertia()
.equals(
"errors",
json!({ "login": { "email": "The email field is required." } }),
);
let checked = app
.post("/check")
.header("x-inertia", "true")
.header("referer", "/account")
.form([("email", "taylor@laravel.com")])
.await;
app.get("/account")
.header("x-inertia", "true")
.with_cookies_from(&checked)
.await
.assert_inertia()
.equals(
"errors",
json!({ "login": { "email": "These credentials do not match our records." } }),
);
}
#[derive(Debug, Deserialize, Validate)]
#[validate(anyone)]
#[expect(dead_code, reason = "only validated")]
struct ChangePassword {
#[validate(required, max_length = 5)]
name: String,
#[validate(required, confirmed)]
new_password: laravel::hash::Password,
#[validate]
vault: Vault,
#[validate(each(required))]
pins: Vec<laravel::hash::Password>,
codes: Vec<laravel::hash::Password>,
#[validate]
keys: Vec<Key>,
}
#[derive(Debug, Deserialize, Validate)]
#[expect(dead_code, reason = "only validated")]
struct Vault {
label: String,
secret: laravel::hash::Password,
}
#[derive(Debug, Deserialize, Validate)]
#[expect(dead_code, reason = "only validated")]
struct Key {
secret: laravel::hash::Password,
}
const SECRETS: [(&str, &str); 6] = [
("new_password", "hunter2-secret"),
("new_password_confirmation", "hunter2-secret"),
("vault[secret]", "vault-secret"),
("pins[0]", "pin-secret"),
("codes[0]", "code-secret"),
("keys[0][secret]", "key-secret"),
];
fn password_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.web(|route: &mut Router| {
route.post("/password", |Valid(_): Valid<ChangePassword>| async {
Redirect::to("/done")
});
route.post("/password/taken", name_taken);
route.post(
"/password/debug",
|input: laravel::validation::ValidRequest<ChangePassword>| async move {
format!("{:?}", input.request())
},
);
});
})
.create()
}
async fn name_taken(Valid(_): Valid<ChangePassword>) -> laravel::Result<Redirect> {
invalid!(name => "That name is taken.");
}
fn password_form(name: &str) -> Vec<(&str, &str)> {
[("name", name), ("vault[label]", "Home")]
.into_iter()
.chain(SECRETS)
.collect()
}
#[tokio::test]
async fn password_typed_fields_are_never_flashed_whatever_their_names() {
let app = password_app();
let old_input =
json!({ "name": "longer", "vault": { "label": "Home" }, "pins": {}, "codes": {}, "keys": { "0": {} } });
app.post("/password")
.header("referer", "/form")
.form(password_form("longer"))
.await
.assert_invalid(&["name"])
.assert_session_has("_old_input", &old_input);
app.post("/password/taken")
.header("referer", "/form")
.form(password_form("Ann"))
.await
.assert_invalid(&["name"])
.assert_session_has(
"_old_input",
json!({ "name": "Ann", "vault": { "label": "Home" }, "pins": {}, "codes": {}, "keys": { "0": {} } }),
);
}
#[tokio::test]
async fn debug_output_of_a_validated_request_redacts_password_typed_fields() {
let response = password_app().post("/password/debug").form(password_form("Ann")).await;
let debug = response.assert_ok().text();
let leaked: Vec<_> = SECRETS.iter().filter(|(_, secret)| debug.contains(secret)).collect();
assert!(leaked.is_empty(), "the debug output shows {leaked:?}: {debug}");
assert!(debug.contains("Home"), "the debug output hides other input: {debug}");
}
#[derive(Clone)]
struct Guest;
impl laravel::auth::Authenticatable for Guest {
type Id = i64;
fn auth_id(&self) -> i64 {
0
}
fn auth_password(&self) -> Option<&laravel::hash::PasswordHash> {
None
}
fn remember_token(&self) -> Option<&str> {
None
}
}
struct NoUsers;
impl laravel::auth::UserProvider for NoUsers {
type User = Guest;
async fn find(&self, _: &i64) -> laravel::Result<Option<Guest>> {
Ok(None)
}
async fn find_for_login(&self, _: &str) -> laravel::Result<Option<Guest>> {
Ok(None)
}
async fn update_password(&self, _: &Guest, _: &laravel::hash::PasswordHash) -> laravel::Result<()> {
Ok(())
}
async fn update_remember_token(&self, _: &Guest, _: &str) -> laravel::Result<()> {
Ok(())
}
}
#[derive(Debug, Deserialize, Validate)]
#[validate(anyone)]
#[expect(dead_code, reason = "only validated")]
struct ConfirmSecret {
#[validate(required, max_length = 5)]
name: String,
#[validate(required, current_password)]
existing_secret: String,
#[serde(alias = "pass")]
#[validate(required, confirmed)]
new_secret: laravel::hash::Password,
}
#[tokio::test]
async fn current_password_alias_and_orphaned_confirmation_fields_are_never_flashed() {
let app = Application::configure()
.replace_env(Env::default())
.with_config(|config, _| {
config.app.key = Some(Encrypter::generate_key(Cipher::Aes256Cbc));
config.session.driver = Driver::Memory;
})
.with_services(|app| {
app.instance(NoUsers);
})
.with_auth(|auth, _| {
auth.session::<NoUsers>();
})
.with_routing(|routing, _| {
routing.web(|route: &mut Router| {
route.post("/confirm", |Valid(_): Valid<ConfirmSecret>| async {
Redirect::to("/done")
});
});
})
.create();
app.post("/confirm")
.header("referer", "/form")
.form([
("name", "longer"),
("existing_secret", "current-hunter2"),
("new_secret_confirmation", "orphan-hunter2"),
])
.await
.assert_invalid(&["name", "existing_secret", "new_secret"])
.assert_session_has("_old_input", json!({ "name": "longer" }));
app.post("/confirm")
.header("referer", "/form")
.form([
("name", "longer"),
("existing_secret", "current-hunter2"),
("new_secret", "new-hunter2"),
("pass", "alias-hunter2"),
("new_secret_confirmation", "new-hunter2"),
])
.await
.assert_invalid(&["name", "existing_secret"])
.assert_session_has("_old_input", json!({ "name": "longer" }));
}
#[derive(Debug, Deserialize, Validate)]
#[validate(anyone)]
#[expect(dead_code, reason = "only validated")]
struct NewPost {
#[validate(required)]
author: Author,
tags: Vec<Tag>,
reviewer: Option<Author>,
editors: Option<Vec<Option<Author>>>,
}
#[derive(Debug, Deserialize, Validate)]
struct Author {
#[validate(required, max_length = 5)]
name: String,
}
#[derive(Debug, Deserialize, Validate)]
#[expect(dead_code, reason = "only validated")]
struct Tag {
#[validate(max_length = 3)]
name: String,
}
#[tokio::test]
async fn fields_of_validated_types_apply_their_rules_without_an_attribute() {
let app = Application::configure()
.replace_env(Env::default())
.with_routing(|routing, _| {
routing.api(|route: &mut Router| {
route.post("/posts", |Valid(post): Valid<NewPost>| async move { post.author.name });
});
})
.create();
app.post("/api/posts")
.json(json!({
"author": { "name": "Taylor" },
"tags": [{ "name": "rust" }],
"reviewer": { "name": "Abigail" },
"editors": [null, { "name": "Jessica" }],
}))
.await
.assert_status(422)
.assert_json_path(
"errors",
json!({
"author.name": ["The author.name field must not be greater than 5 characters."],
"tags.0.name": ["The tags.0.name field must not be greater than 3 characters."],
"reviewer.name": ["The reviewer.name field must not be greater than 5 characters."],
"editors.1.name": ["The editors.1.name field must not be greater than 5 characters."],
}),
);
app.post("/api/posts")
.json(json!({ "author": { "name": "Ann" }, "tags": [], "reviewer": null, "editors": [null] }))
.await
.assert_ok()
.assert_see("Ann");
}
#[derive(Validate)]
#[expect(dead_code, reason = "only validated")]
struct Wrapper<T> {
value: T,
}
#[derive(Validate)]
#[expect(dead_code, reason = "only validated")]
struct Bounded<T: Validate> {
value: T,
}
#[tokio::test]
async fn a_generic_field_applies_its_types_rules_only_when_the_struct_requires_validate() {
let input = serde_json::from_value(json!({ "value": { "name": "Abigail" } })).unwrap();
assert!(Wrapper::<Author>::declared_rules().validate(&input).await.is_ok());
let Err(ValidationError::Invalid(errors)) = Bounded::<Author>::declared_rules().validate(&input).await else {
panic!("a bounded generic field applies its type's rules");
};
assert_eq!(
errors.errors()["value.name"],
["The value.name field must not be greater than 5 characters."]
);
}
#[derive(Debug, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "snake_case")]
enum Priority {
Low,
High,
}
#[laravel::query]
#[derive(Serialize)]
struct LenientFilters {
priority: Option<Priority>,
assignee: Option<i64>,
#[default]
#[validate(max_length = 10)]
q: String,
#[default = 1]
#[validate(min_value = 1)]
page: u32,
#[serde(skip_serializing)]
status: Sometimes<String>,
#[default]
labels: Vec<i64>,
}
#[derive(Deserialize, Serialize, Validate)]
#[validate(anyone)]
struct StrictFilters {
priority: Option<Priority>,
assignee: Option<i64>,
}
#[laravel::query]
#[derive(Serialize)]
struct TaggedFilters {
#[default]
#[validate(each(max_length = 1))]
tags: Vec<String>,
#[validate(max_length = 3)]
q: Option<String>,
}
#[laravel::query]
#[derive(Serialize)]
struct SortedFilters {
#[serde(alias = "order")]
#[validate(one_of("name", "created_at"))]
sort: Option<String>,
}
#[laravel::query]
#[derive(Serialize)]
struct CallbackQuery {
#[validate(min_length = 4)]
code: String,
#[default = 1]
#[validate(min_value = 1)]
page: u32,
}
fn filters_app() -> Application {
use laravel::http::Query;
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.web(|route: &mut Router| {
route.get("/lenient", |Query(filters): Query<LenientFilters>| async move {
Json(json!({ "filters": filters, "status": filters.status.present() }))
});
route.post("/strict", |Valid(filters): Valid<StrictFilters>| async move {
Json(filters)
});
route.get("/tagged", |Query(filters): Query<TaggedFilters>| async move {
Json(filters)
});
route.get("/sorted", |Query(filters): Query<SortedFilters>| async move {
Json(filters)
});
route.get(
"/callback",
|Query(query): Query<CallbackQuery>| async move { Json(query) },
);
});
routing.api(|route: &mut Router| {
route.get(
"/callback",
|Query(query): Query<CallbackQuery>| async move { Json(query) },
);
route.post(
"/query-before-body",
|Query(filters): Query<LenientFilters>, Valid(body): Valid<StrictFilters>| async move {
Json(json!({ "query": filters, "body": body }))
},
);
});
})
.create()
}
#[tokio::test]
async fn a_query_struct_leaves_out_lenient_fields_that_fail_and_applies_defaults() {
let app = filters_app();
app.get("/lenient?priority=bogus&assignee=abc&q=a+long+search&page=0&status=&labels[]=1&labels[]=x")
.header("referer", "/projects")
.await
.assert_ok()
.assert_exact_json(json!({
"filters": { "priority": null, "assignee": null, "q": "", "page": 1, "labels": [] },
"status": null,
}));
app.get("/lenient?q=&page=abc")
.await
.assert_ok()
.assert_exact_json(json!({
"filters": { "priority": null, "assignee": null, "q": "", "page": 1, "labels": [] },
"status": null,
}));
app.get("/lenient?priority=high&assignee=7&q=crash&page=3&status=open&labels[]=3")
.await
.assert_ok()
.assert_exact_json(json!({
"filters": { "priority": "high", "assignee": 7, "q": "crash", "page": 3, "labels": [3] },
"status": "open",
}));
app.get("/lenient?priority=bogus&assignee=7")
.await
.assert_ok()
.assert_json_path("filters.assignee", 7);
}
#[tokio::test]
async fn a_query_struct_leaves_out_a_failed_field_under_every_name() {
let app = filters_app();
app.get("/sorted?order=name")
.await
.assert_ok()
.assert_exact_json(json!({ "sort": "name" }));
app.get("/sorted?sort=bogus&order=password")
.await
.assert_ok()
.assert_exact_json(json!({ "sort": null }));
}
#[tokio::test]
async fn a_query_struct_requires_fields_without_a_fallback_and_works_before_valid() {
let app = filters_app();
app.post("/strict")
.header("referer", "/projects")
.form([("priority", "bogus"), ("assignee", "7")])
.await
.assert_redirect_to("/projects")
.assert_invalid(&["priority"]);
app.get("/callback?code=abcd&page=abc")
.await
.assert_ok()
.assert_exact_json(json!({ "code": "abcd", "page": 1 }));
app.get("/callback?code=&page=abc")
.header("referer", "/login")
.await
.assert_status(400);
app.get("/api/callback?code=ab&page=0")
.await
.assert_status(400)
.assert_json_path(
"errors",
json!({ "code": ["The code field must be at least 4 characters."] }),
);
app.post("/api/query-before-body?q=freight&page=abc")
.json(json!({ "priority": "high", "assignee": 42 }))
.await
.assert_ok()
.assert_json_path("query.q", "freight")
.assert_json_path("query.page", 1)
.assert_json_path("query.priority", serde_json::Value::Null)
.assert_json_path("body.priority", "high")
.assert_json_path("body.assignee", 42);
}
#[tokio::test]
async fn a_query_struct_fails_with_400_when_too_many_fields_fail_to_check_the_rest() {
let app = filters_app();
let tags = "tags[]=xx&".repeat(1_000);
app.get(format!("/tagged?{tags}q=far+too+long"))
.header("referer", "/projects")
.await
.assert_status(400);
app.get("/tagged?tags[]=xx&tags[]=a&q=far+too+long")
.await
.assert_ok()
.assert_exact_json(json!({ "tags": [], "q": null }));
}
pub(crate) async fn errors(rules: impl Borrow<Rules>, input: impl Borrow<Value>) -> Value {
match rules.borrow().validate(input.borrow().as_object().unwrap()).await {
Ok(()) => json!({}),
Err(error) => serde_json::to_value(error.invalid().errors()).unwrap(),
}
}
#[derive(Deserialize, Validate)]
#[validate(anyone)]
#[expect(dead_code, reason = "the test checks only the declared rules")]
struct TypedFormats {
address: std::net::IpAddr,
v4: Option<std::net::Ipv4Addr>,
v6: std::net::Ipv6Addr,
id: laravel::str::Uuid,
#[validate(uuid = 7)]
v7: laravel::str::Uuid,
key: laravel::str::Ulid,
starts_on: laravel::time::civil::Date,
starts_at: laravel::time::Timestamp,
#[validate(each(required))]
ids: Vec<laravel::str::Uuid>,
}
#[tokio::test]
async fn typed_fields_check_their_format_without_a_rule() {
let input = json!({
"address": "nowhere",
"v4": "::1",
"v6": "10.0.0.1",
"id": "nope",
"v7": "018f6b9e-4c3a-4b2d-9e1f-0a1b2c3d4e5f",
"key": "nope",
"starts_on": "2024-13-01",
"starts_at": "tomorrow",
"ids": ["nope"],
});
assert_eq!(
errors(TypedFormats::declared_rules(), input).await,
json!({
"address": ["The address field must be a valid IP address."],
"v4": ["The v4 field must be a valid IPv4 address."],
"v6": ["The v6 field must be a valid IPv6 address."],
"id": ["The id field must be a valid UUID."],
"v7": ["The v7 field must be a valid UUID."],
"key": ["The key field must be a valid ULID."],
"starts_on": ["The starts on field must be a valid date."],
"starts_at": ["The starts at field must be a valid date."],
"ids.0": ["The ids.0 field must be a valid UUID."],
})
);
}
#[derive(Deserialize, Validate)]
#[serde(rename_all = "camelCase")]
#[expect(dead_code, reason = "the test checks only the declared rules")]
struct ShippingAddress {
country_code: String,
#[validate(required_if("country_code", "US"))]
postal_code: Option<String>,
}
#[derive(Deserialize, Validate)]
#[validate(anyone)]
#[serde(rename_all = "camelCase")]
#[expect(dead_code, reason = "the test checks only the declared rules")]
struct CheckoutForm {
shipping_address: ShippingAddress,
#[validate(required_if("shipping_address.country_code", "US"))]
phone_number: Option<String>,
}
#[tokio::test]
async fn field_references_name_rust_fields_and_reach_renamed_input() {
let input = json!({ "shippingAddress": { "countryCode": "US" } });
assert_eq!(
errors(CheckoutForm::declared_rules(), input).await,
json!({
"shippingAddress.postalCode": [
"The shipping address.postal code field is required when shipping address.country code is US."
],
"phoneNumber": ["The phone number field is required when shipping address.country code is US."],
})
);
}
#[derive(Deserialize, Validate)]
#[validate(anyone)]
#[expect(dead_code, reason = "the test checks only the validation errors")]
struct Tickets {
#[validate(messages(invalid = "Enter a whole number of tickets."))]
quantity: u32,
#[validate(messages(invalid = "That event ID isn't valid."))]
event_id: laravel::str::Uuid,
#[validate(messages(invalid = "Choose at least one seat."))]
seats: std::num::NonZeroU32,
#[validate(uuid = 7, messages(invalid = "Not this one."))]
order_id: laravel::str::Uuid,
#[validate(messages(invalid = "Generic.", ip = "Enter an IP address."))]
address: std::net::IpAddr,
}
#[tokio::test]
async fn invalid_messages_cover_every_check_a_field_gets_from_its_type() {
let response = app_with_tickets()
.post("/api/tickets")
.json(json!({
"quantity": "two",
"event_id": "nope",
"seats": "0",
"order_id": "018f6b9e-4c3a-4b2d-9e1f-0a1b2c3d4e5f",
"address": "nowhere",
}))
.await;
response.assert_status(422);
assert_eq!(
response.json()["errors"],
json!({
"quantity": ["Enter a whole number of tickets."],
"event_id": ["That event ID isn't valid."],
"seats": ["Choose at least one seat."],
"order_id": ["The order id field must be a valid UUID."],
"address": ["Enter an IP address."],
})
);
}
fn app_with_tickets() -> Application {
Application::configure()
.replace_env(Env::default())
.with_routing(|routing, _| {
routing.api(|route: &mut Router| {
route.post("/tickets", async |Valid(_): Valid<Tickets>| "ok");
});
})
.create()
}
#[derive(Debug, Deserialize, Validate)]
#[validate(anyone)]
#[expect(dead_code, reason = "only validated")]
struct Register {
#[validate(required, password, confirmed)]
password: laravel::hash::Password,
#[validate(
password(min = 4, numbers),
messages(password_numbers = "The :attribute needs a digit.")
)]
pin: Option<String>,
}
#[tokio::test]
async fn passwords_meet_the_applications_defaults_or_the_fields_own_requirements() {
use laravel::validation::PasswordRule;
let app = Application::configure()
.replace_env(Env::default())
.with_services(|app| {
app.instance(PasswordRule::min(10).letters().mixed_case().numbers().symbols());
})
.with_routing(|routing, _| {
routing.api(|route: &mut Router| {
route.post("/register", |Valid(_): Valid<Register>| async { "ok" });
});
})
.create();
app.post("/api/register")
.json(json!({ "password": "abc", "password_confirmation": "abc", "pin": "abcd" }))
.await
.assert_status(422)
.assert_json_path(
"errors",
json!({
"password": [
"The password field must be at least 10 characters.",
"The password field must contain at least one uppercase and one lowercase letter.",
"The password field must contain at least one symbol.",
"The password field must contain at least one number.",
],
"pin": ["The pin needs a digit."],
}),
);
app.post("/api/register")
.json(json!({ "password": "١٢٣٤٥٦٧٨٩٠", "password_confirmation": "١٢٣٤٥٦٧٨٩٠", "pin": "ab1" }))
.await
.assert_status(422)
.assert_json_path(
"errors",
json!({
"password": [
"The password field must contain at least one uppercase and one lowercase letter.",
"The password field must contain at least one letter.",
"The password field must contain at least one symbol.",
],
"pin": ["The pin field must be at least 4 characters."],
}),
);
app.post("/api/register")
.json(json!({ "password": "Correct horse 9", "password_confirmation": "Correct horse 9", "pin": "1234" }))
.await
.assert_ok();
let rules = Rules::new().field("password", [Rule::password()]);
let input = serde_json::from_value(json!({ "password": "Short1!" })).unwrap();
let Err(ValidationError::Invalid(errors)) = rules.validate(&input).await else {
panic!("expected the default minimum of 8 characters");
};
assert_eq!(
errors.errors()["password"],
["The password field must be at least 8 characters."]
);
}
#[tokio::test]
async fn dotted_map_keys_keep_cross_field_rules_and_confirmation_within_their_entry() {
#[derive(Debug, Deserialize, Validate)]
#[expect(dead_code, reason = "only validated")]
struct ScopedLine {
kind: String,
#[validate(prohibited_if("kind", "free"))]
price: Option<u32>,
#[validate(confirmed)]
secret: Option<laravel::hash::Password>,
#[validate(label = "item code")]
code: Option<String>,
#[validate(same("code"))]
repeat_code: Option<String>,
}
#[derive(Debug, Deserialize, Validate)]
#[validate(anyone)]
#[expect(dead_code, reason = "only validated")]
struct ScopedOrder {
lines: std::collections::BTreeMap<String, ScopedLine>,
}
let app = Application::configure()
.replace_env(Env::default())
.with_routing(|routing, _| {
routing.api(|route: &mut Router| {
route.post("/scoped", |Valid(_): Valid<ScopedOrder>| async { "ok" });
});
})
.create();
app.post("/api/scoped")
.json(json!({
"lines": {
"a.b": {
"kind": "free",
"price": 100,
"secret": "s1",
"code": "X",
"repeat_code": "Y"
},
"a": {
"b": {
"secret_confirmation": "s1",
"code": "Y"
}
}
}
}))
.await
.assert_status(422)
.assert_json_path(
"errors",
json!({
"lines.a.b.price": ["The lines.a.b.price field is prohibited when lines.a.b.kind is free."],
"lines.a.b.secret": ["The lines.a.b.secret field confirmation does not match."],
"lines.a.b.repeat_code": ["The lines.a.b.repeat code field must match item code."],
"lines.a.kind": ["The lines.a.kind field is required."],
}),
);
app.post("/api/scoped")
.form([
("lines[a.b][kind]", "free"),
("lines[a.b][price]", "100"),
("lines[a.b][secret]", "s1"),
("lines[a.b][secret_confirmation]", "s1"),
("lines[a.b][code]", "X"),
("lines[a.b][repeat_code]", "X"),
])
.await
.assert_status(422)
.assert_json_path(
"errors",
json!({
"lines.a.b.price": ["The lines.a.b.price field is prohibited when lines.a.b.kind is free."],
}),
);
}
#[tokio::test]
async fn dotted_map_keys_and_nested_containers_scrub_passwords_from_old_input_and_debug() {
#[derive(Debug, Deserialize, Validate)]
#[expect(dead_code, reason = "only validated")]
struct Account {
label: String,
pin: laravel::hash::Password,
}
#[derive(Debug, Deserialize, Validate)]
#[validate(anyone)]
#[expect(dead_code, reason = "only validated")]
struct Vaults {
#[validate(max_length = 3)]
name: String,
accounts: std::collections::BTreeMap<String, Account>,
tokens: std::collections::BTreeMap<String, laravel::hash::Password>,
matrix: Vec<Vec<laravel::hash::Password>>,
buckets: std::collections::BTreeMap<String, Vec<laravel::hash::Password>>,
}
let app = 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.web(|route: &mut Router| {
route.post("/vaults", |Valid(_): Valid<Vaults>| async { Redirect::to("/done") });
route.post(
"/vaults/debug",
|input: laravel::validation::ValidRequest<Vaults>| async move { format!("{:?}", input.request()) },
);
});
routing.api(|route: &mut Router| {
route.post("/vaults", |Valid(_): Valid<Vaults>| async { "ok" });
});
})
.create();
app.post("/vaults")
.header("referer", "/form")
.form([
("name", "longer"),
("accounts[foo.bar][label]", "Primary"),
("accounts[foo.bar][pin]", "account-secret"),
("tokens[x.y]", "token-secret"),
("matrix[0][0]", "matrix-secret"),
("buckets[p.q][0]", "bucket-secret"),
])
.await
.assert_invalid(&["name"])
.assert_session_has(
"_old_input",
json!({
"name": "longer",
"accounts": { "foo.bar": { "label": "Primary" } },
"tokens": {},
"matrix": { "0": {} },
"buckets": { "p.q": {} },
}),
);
app.post("/vaults")
.header("referer", "/form")
.form([("name", "Ann"), ("tokens", "scalar-secret"), ("matrix", "flat-secret")])
.await
.assert_invalid(&["tokens", "matrix"])
.assert_session_has("_old_input", json!({ "name": "Ann" }));
let debug = app
.post("/vaults/debug")
.json(json!({
"name": "Ann",
"accounts": { "foo.bar": { "label": "Primary", "pin": "account-secret" } },
"tokens": { "x.y": "token-secret" },
"matrix": [["matrix-secret"]],
"buckets": { "p.q": ["bucket-secret"] },
}))
.await
.assert_ok()
.text();
for secret in ["account-secret", "token-secret", "matrix-secret", "bucket-secret"] {
assert!(!debug.contains(secret), "debug output leaked {secret}: {debug}");
}
assert!(debug.contains("Primary"), "debug output hid non-secret input: {debug}");
let long = "x".repeat(73);
app.post("/api/vaults")
.json(json!({
"name": "Ann",
"accounts": { "foo.bar": { "label": "Primary", "pin": "ok" } },
"tokens": { "x.y": long },
"matrix": [[long]],
"buckets": { "p.q": ["ok"] },
}))
.await
.assert_status(422)
.assert_invalid(&["tokens.x.y", "matrix.0.0"]);
}
#[tokio::test]
async fn nested_containers_and_type_aliases_run_child_rules() {
#[derive(Debug, Deserialize, Validate)]
#[expect(dead_code, reason = "only validated")]
struct LineItem {
#[validate(required, min_length = 3)]
sku: String,
}
type LineMap = std::collections::BTreeMap<String, LineItem>;
#[derive(Debug, Deserialize, Validate)]
#[validate(anyone)]
#[expect(dead_code, reason = "only validated")]
struct NestedShipment {
groups: Vec<Vec<LineItem>>,
buckets: std::collections::BTreeMap<String, Vec<Option<LineItem>>>,
boxed: Option<Box<LineItem>>,
aliased: LineMap,
}
let app = Application::configure()
.replace_env(Env::default())
.with_routing(|routing, _| {
routing.api(|route: &mut Router| {
route.post("/shipments", |Valid(_): Valid<NestedShipment>| async { "ok" });
});
})
.create();
app.post("/api/shipments")
.json(json!({
"groups": [[{"sku": "ABC"}, {"sku": "x"}]],
"buckets": { "west": [{"sku": "y"}, null] },
"boxed": { "sku": "z" },
"aliased": { "main": { "sku": "w" } },
}))
.await
.assert_status(422)
.assert_json_path(
"errors",
json!({
"groups.0.1.sku": ["The groups.0.1.sku field must be at least 3 characters."],
"buckets.west.0.sku": ["The buckets.west.0.sku field must be at least 3 characters."],
"boxed.sku": ["The boxed.sku field must be at least 3 characters."],
"aliased.main.sku": ["The aliased.main.sku field must be at least 3 characters."],
}),
);
}
#[tokio::test]
async fn middleware_validation_persists_hidden_passwords_through_into_http() {
#[derive(Debug, Deserialize, Validate)]
#[expect(dead_code, reason = "only validated")]
struct InnerSecret {
label: String,
pin: laravel::hash::Password,
}
#[derive(Debug, Deserialize, Validate)]
#[validate(anyone)]
#[expect(dead_code, reason = "only validated")]
struct MiddlewareSecret {
accounts: std::collections::BTreeMap<String, InnerSecret>,
}
#[laravel::http::middleware]
async fn check_secrets(
mut request: Request,
next: laravel::http::Next,
) -> laravel::Result<laravel::http::Response> {
request.load_input().await?;
let _: MiddlewareSecret = request.validate().await?;
Ok(next.run(request).await)
}
let app = 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.web(|route: &mut Router| {
route
.post("/mw-redirect", |request: Request| async move {
Redirect::back().with_input(&request)
})
.middleware(check_secrets);
route
.post("/mw-debug", |request: Request| async move { format!("{request:?}") })
.middleware(check_secrets);
});
})
.create();
let body = json!({
"accounts": { "foo.bar": { "label": "Work", "pin": "mw-top-secret" } }
});
app.post("/mw-redirect")
.header("referer", "/form")
.json(body.clone())
.await
.assert_redirect_to("/form")
.assert_session_has("_old_input", json!({ "accounts": { "foo.bar": { "label": "Work" } } }));
let debug = app.post("/mw-debug").json(body).await.assert_ok().text();
assert!(!debug.contains("mw-top-secret"), "debug leaked password: {debug}");
assert!(debug.contains("Work"), "debug hid non-secret: {debug}");
}