use laravel::Application;
use laravel::config::Env;
use laravel::config::session::Driver;
use laravel::crypt::{Cipher, Encrypter};
use laravel::http::client::Attachment;
use laravel::http::middleware::{LimitBody, LimitUploads};
use laravel::http::{HeaderValue, Json, Middleware, Next, Request, Response, UploadedFile};
use laravel::routing::Router;
use laravel::testing::MakesHttpRequests;
use laravel::validation::{Valid, Validate};
use serde_json::{Value, json};
const PNG: &[u8] = b"\x89PNG\r\n\x1a\n\0\0\0\rIHDR";
fn describe(file: Option<&UploadedFile>) -> Value {
match file {
Some(file) => json!({
"client_name": file.client_name(),
"client_extension": file.client_extension(),
"client_content_type": file.client_content_type(),
"content_type": file.content_type(),
"extension": file.extension(),
"size": file.size(),
}),
None => Value::Null,
}
}
struct SeesUploads;
impl Middleware for SeesUploads {
async fn handle(&self, mut request: Request, next: Next) -> laravel::Result<Response> {
request.load_input().await?;
let seen = request.validate::<AvatarForm>().await?.avatar.is_some().to_string();
let mut response = next.run(request).await;
response
.headers_mut()
.insert("x-middleware-saw-file", HeaderValue::from_str(&seen).unwrap());
Ok(response)
}
}
#[derive(serde::Deserialize, Validate)]
#[validate(anyone)]
struct AvatarForm {
avatar: Option<UploadedFile>,
name: Option<String>,
}
#[derive(serde::Deserialize, Validate)]
#[validate(anyone)]
struct NoteForm {
note: Option<String>,
}
#[derive(serde::Deserialize, Validate)]
#[validate(anyone)]
struct VideoForm {
video: Option<UploadedFile>,
}
#[derive(serde::Deserialize, Validate)]
#[validate(anyone)]
struct GalleryForm {
#[serde(default)]
photos: Vec<UploadedFile>,
user: Option<UserAvatar>,
captions: Option<Vec<String>>,
}
#[derive(serde::Deserialize, Validate)]
struct UserAvatar {
avatar: Option<UploadedFile>,
}
#[derive(serde::Deserialize, Validate)]
#[validate(anyone)]
struct Profile {
#[validate(required)]
name: String,
#[validate(required, image, max_kilobytes = 1)]
avatar: UploadedFile,
}
#[derive(serde::Deserialize, Validate)]
#[validate(anyone)]
struct Import {
#[validate(extensions("csv"))]
contacts: Option<UploadedFile>,
#[validate(required, mimes("jpg", "png"))]
photos: Vec<UploadedFile>,
}
#[derive(serde::Deserialize, Validate)]
#[validate(anyone)]
struct Document {
#[validate(required, mimes("image/*", "pdf"))]
file: UploadedFile,
}
#[derive(serde::Deserialize, Validate)]
#[validate(anyone)]
struct AvatarChoice {
avatar: Option<UploadedFile>,
#[validate(required_without("avatar"))]
avatar_url: Option<String>,
#[validate(prohibited)]
attachment: Option<UploadedFile>,
}
#[derive(serde::Deserialize, Validate)]
#[validate(anyone)]
struct Attachments {
#[validate(required, each(max_kilobytes = 1))]
files: Vec<UploadedFile>,
}
#[derive(serde::Deserialize, Validate)]
#[validate(anyone)]
struct Listing {
cover: Cover,
gallery: Vec<Cover>,
}
#[derive(serde::Deserialize, Validate)]
#[validate(anyone)]
struct Album {
#[validate(min_items = 2)]
items: Vec<AlbumItem>,
}
#[derive(serde::Deserialize, Validate)]
struct AlbumItem {
caption: Option<String>,
photo: Option<UploadedFile>,
}
#[derive(serde::Deserialize, Validate)]
#[validate(anyone)]
struct Portrait {
#[serde(alias = "picture")]
#[validate(image)]
photo: Option<UploadedFile>,
}
#[derive(serde::Deserialize, Validate)]
struct Cover {
#[validate(required, image)]
photo: UploadedFile,
#[validate(max_length = 5)]
caption: Option<String>,
}
fn png(size: usize) -> Vec<u8> {
[PNG, &vec![0; size - PNG.len()]].concat()
}
fn app() -> Application {
app_with(|_| {})
}
fn app_with(configure: impl FnOnce(&mut laravel::config::Config) + 'static) -> Application {
Application::configure()
.replace_env(Env::default())
.with_config(|config, _| {
config.app.key = Some(Encrypter::generate_key(Cipher::Aes256Cbc));
config.session.driver = Driver::Memory;
configure(config);
})
.with_routing(|routing, _| {
routing.web(|route: &mut Router| {
route.post("/profile", async |Valid(profile): Valid<Profile>| {
format!("{}: {}", profile.name, profile.avatar.client_name())
});
route.post("/import", async |Valid(import): Valid<Import>| {
let photos: Vec<_> = import.photos.iter().map(|photo| photo.client_name()).collect();
let contacts = import.contacts.as_ref().map(|contacts| contacts.client_name());
format!("{} {}", photos.join(" "), contacts.unwrap_or("no contacts"))
});
route.post("/attachments", async |Valid(attachments): Valid<Attachments>| {
let names: Vec<_> = attachments.files.iter().map(UploadedFile::client_name).collect();
names.join(" ")
});
route.post("/listing", async |Valid(listing): Valid<Listing>| {
let gallery: Vec<_> = listing
.gallery
.iter()
.map(|cover| cover.caption.as_deref().unwrap_or(cover.photo.client_name()))
.collect();
format!("{} {}", listing.cover.photo.client_name(), gallery.join(" "))
});
route.post("/album", async |Valid(album): Valid<Album>| {
let items = album.items.iter().map(|item| match (&item.caption, &item.photo) {
(Some(caption), None) => caption.clone(),
(None, Some(photo)) => photo.client_name().to_owned(),
_ => "?".to_owned(),
});
items.collect::<Vec<_>>().join(" ")
});
route.post("/portrait", async |Valid(portrait): Valid<Portrait>| {
portrait
.photo
.map_or("no photo".to_owned(), |photo| photo.client_name().to_owned())
});
route.post("/attachment", async |Valid(document): Valid<Document>| {
document.file.client_name().to_owned()
});
route.post("/avatar-choice", async |Valid(choice): Valid<AvatarChoice>| {
let avatar = choice.avatar.as_ref().map(UploadedFile::client_name);
let attachment = choice.attachment.as_ref().map(UploadedFile::client_name);
format!("{avatar:?} {:?} {attachment:?}", choice.avatar_url)
});
route.post("/avatar", async |Valid(form): Valid<AvatarForm>| {
Json(json!({
"avatar": describe(form.avatar.as_ref()),
"name": form.name,
"has_avatar": form.avatar.is_some(),
}))
});
route.put("/avatar", async |Valid(form): Valid<AvatarForm>| {
Json(json!({ "method": "PUT", "avatar": describe(form.avatar.as_ref()) }))
});
route.post("/gallery", async |Valid(gallery): Valid<GalleryForm>| {
let name = |file: &UploadedFile| file.client_name().to_owned();
let user_avatar = gallery.user.as_ref().and_then(|user| user.avatar.as_ref());
Json(json!({
"photos": gallery.photos.iter().map(name).collect::<Vec<_>>(),
"second": gallery.photos.get(1).map(name),
"user_avatar": user_avatar.map(name),
"caption": gallery.captions,
}))
});
route.post("/temporary", async |Valid(form): Valid<AvatarForm>| {
let file = form.avatar.unwrap();
let contents = file.bytes().await.unwrap();
json!({ "path": file.path(), "length": contents.len() }).to_string()
});
route
.post("/small", async |Valid(form): Valid<AvatarForm>| {
form.avatar.is_some().to_string()
})
.middleware(LimitUploads::bytes(100));
route
.post("/seen", async |Valid(form): Valid<AvatarForm>| {
form.avatar.is_some().to_string()
})
.middleware(SeesUploads);
route
.put("/large", async |Valid(form): Valid<VideoForm>| {
form.video.map_or(0, |video| video.size()).to_string()
})
.middleware(LimitUploads::bytes(10_000));
route
.post("/notes", async |Valid(form): Valid<NoteForm>| {
form.note.map_or(0, |note| note.len()).to_string()
})
.middleware(LimitUploads::bytes(10_000))
.middleware(LimitBody::bytes(100));
});
routing.api(|route: &mut Router| {
route.delete("/posts/1", || async { "deleted" });
route.put("/stream", |mut multipart: axum::extract::Multipart| async move {
let mut fields = Vec::new();
while let Some(field) = multipart.next_field().await.unwrap() {
let name = field.name().unwrap_or_default().to_owned();
let length = field.bytes().await.unwrap().len();
fields.push(format!("{name}:{length}"));
}
fields.join(",")
});
});
})
.with_middleware(|middleware, _| {
middleware.prepend(LimitUploads::bytes(2_000));
})
.create()
}
#[tokio::test]
async fn files_are_uploaded_with_the_forms_fields() {
let response = app()
.post("/avatar")
.attach("avatar", Attachment::from_data(PNG, "Taylor's photo.PNG"))
.form([("name", " Taylor ")])
.await;
response.assert_ok().assert_json(json!({
"avatar": {
"client_name": "Taylor's photo.PNG",
"client_extension": "PNG",
"client_content_type": "image/png",
"content_type": "image/png",
"extension": "png",
"size": PNG.len(),
},
"name": "Taylor",
"has_avatar": true,
}));
}
#[tokio::test]
async fn a_files_content_decides_its_type_whatever_its_name() {
let response = app()
.post("/avatar")
.attach("avatar", Attachment::from_data(PNG, "notes.txt"))
.await;
assert_eq!(response.json()["avatar"]["client_content_type"], "text/plain");
assert_eq!(response.json()["avatar"]["content_type"], "image/png");
assert_eq!(response.json()["avatar"]["extension"], "png");
let text = app()
.post("/avatar")
.attach("avatar", Attachment::from_data("Just text", "notes.txt"))
.await;
assert_eq!(text.json()["avatar"]["content_type"], Value::Null);
}
#[tokio::test]
async fn lists_and_nested_names_are_dot_paths() {
let response = app()
.post("/gallery")
.attach("photos[]", Attachment::from_data(PNG, "one.png"))
.attach("photos[]", Attachment::from_data(PNG, "two.png"))
.attach("user[avatar]", Attachment::from_data(PNG, "me.png"))
.form([("captions[]", "First"), ("captions[]", "Second")])
.await;
response.assert_ok().assert_json(json!({
"photos": ["one.png", "two.png"],
"second": "two.png",
"user_avatar": "me.png",
"caption": ["First", "Second"],
}));
}
#[tokio::test]
async fn an_empty_file_input_uploads_nothing() {
let response = app()
.post("/avatar")
.attach("avatar", Attachment::from_data(Vec::new(), ""))
.await;
response.assert_ok();
assert_eq!(response.json()["has_avatar"], false);
}
#[tokio::test]
async fn uploads_are_deleted_when_the_request_is_done() {
let response = app()
.post("/temporary")
.attach("avatar", Attachment::from_data(PNG, "photo.png"))
.await;
let body: Value = serde_json::from_str(&response.text()).unwrap();
assert_eq!(body["length"], PNG.len());
let path = std::path::PathBuf::from(body["path"].as_str().unwrap());
assert!(!path.exists(), "{path:?} should be deleted");
}
#[tokio::test]
async fn uploads_are_held_to_the_routes_upload_limit() {
let response = app()
.post("/small")
.attach("avatar", Attachment::from_data(vec![0; 1000], "photo.png"))
.await;
response.assert_status(413).assert_see("Content Too Large");
assert!(response.error().is_some_and(|error| {
error.to_string()
== "the request body is larger than its 100-byte limit (`LimitUploads`): The POST data is too large."
}));
}
#[tokio::test]
async fn text_fields_are_held_to_the_body_limit_and_files_to_the_upload_limit() {
let app = app();
let response = app
.post("/notes")
.form([("note", "x".repeat(60)), ("title", "y".repeat(60))])
.attach("photo", Attachment::from_data(vec![0; 5000], "photo.png"))
.await;
response.assert_status(413);
assert!(response.error().is_some_and(|error| {
error
.to_string()
.starts_with("the form's text fields are larger than their 100-byte limit (`LimitBody`)")
}));
app.post("/notes")
.form([("note", "x".repeat(60))])
.attach("photo", Attachment::from_data(vec![0; 5000], "photo.png"))
.await
.assert_ok()
.assert_see("60");
}
#[tokio::test]
async fn middleware_see_uploads_once_they_read_the_body_and_so_does_the_handler() {
app()
.post("/seen")
.attach("avatar", Attachment::from_data(PNG, "photo.png"))
.await
.assert_see("true")
.assert_header("x-middleware-saw-file", "true");
}
#[tokio::test]
async fn client_names_leave_out_directories() {
for (sent, kept) in [("../../.env", ".env"), ("C:\\Users\\taylor\\photo.png", "photo.png")] {
let response = app()
.post("/avatar")
.attach("avatar", Attachment::from_data(PNG, sent))
.await;
response.assert_ok();
assert_eq!(response.json()["avatar"]["client_name"], kept);
}
}
#[tokio::test]
async fn forms_with_files_spoof_their_method() {
let response = app()
.post("/avatar")
.attach("avatar", Attachment::from_data(PNG, "photo.png"))
.form([("_method", "PUT")])
.await;
response.assert_ok();
assert_eq!(response.json()["method"], "PUT");
assert_eq!(response.json()["avatar"]["client_name"], "photo.png");
}
#[tokio::test]
async fn the_query_string_may_spoof_the_method() {
app()
.post("/api/posts/1?_method=DELETE")
.json(json!({}))
.await
.assert_ok()
.assert_see("deleted");
}
#[tokio::test]
async fn malformed_multipart_bodies_are_bad_requests() {
app()
.post("/avatar")
.form([("not", "multipart")])
.header("content-type", "multipart/form-data; boundary=nope")
.await
.assert_status(400);
}
#[tokio::test]
async fn method_spoofing_leaves_the_upload_for_the_route() {
app()
.post("/api/stream")
.form([("_method", "PUT")])
.attach("avatar", Attachment::from_data(vec![1; 1_500], "photo.png"))
.await
.assert_ok()
.assert_see("_method:3,avatar:1500");
}
#[tokio::test]
async fn uploads_over_the_global_limit_are_spoofed_under_the_routes() {
app()
.post("/large")
.form([("_method", "PUT")])
.attach("video", Attachment::from_data(vec![0; 5_000], "clip.mp4"))
.await
.assert_ok()
.assert_see("5000");
}
#[tokio::test]
async fn a_method_after_a_file_isnt_seen() {
let body = concat!(
"--b\r\nContent-Disposition: form-data; name=\"avatar\"; filename=\"a.png\"\r\n\r\npng\r\n",
"--b\r\nContent-Disposition: form-data; name=\"_method\"\r\n\r\nPUT\r\n",
"--b--\r\n",
);
let request = http::Request::post("/avatar")
.header("host", "localhost")
.header("sec-fetch-site", "same-origin")
.header("content-type", "multipart/form-data; boundary=b")
.body(laravel::axum::body::Body::from(body))
.unwrap();
let response = tower::ServiceExt::oneshot(app().into_router(), request).await.unwrap();
let bytes = http_body_util::BodyExt::collect(response.into_body())
.await
.unwrap()
.to_bytes();
let json: Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(json["has_avatar"], true, "{json}");
assert!(json.get("method").is_none(), "{json}");
}
#[tokio::test]
async fn forms_may_upload_only_so_many_files_and_fields() {
let app = app_with(|config| {
config.server.max_file_uploads = 2;
config.server.max_input_vars = 2;
});
let response = app
.post("/gallery")
.attach("photos[]", Attachment::from_data(PNG, "1.png"))
.attach("photos[]", Attachment::from_data(PNG, "2.png"))
.attach("photos[]", Attachment::from_data(PNG, "3.png"))
.await;
response.assert_status(413).assert_see("Content Too Large");
assert!(
response
.error()
.is_some_and(|error| error.to_string().contains("more than 2 files"))
);
let response = app
.post("/gallery")
.form([("a", "1"), ("b", "2"), ("c", "3")])
.attach("photos[]", Attachment::from_data(PNG, "1.png"))
.await;
response.assert_status(413).assert_see("Content Too Large");
assert!(
response
.error()
.is_some_and(|error| error.to_string().contains("more than 2 fields"))
);
}
#[tokio::test]
async fn forms_without_files_may_send_only_so_many_fields_too() {
let app = app_with(|config| config.server.max_input_vars = 2);
app.post("/avatar").form([("a", "1"), ("b", "2")]).await.assert_ok();
let response = app.post("/avatar").form([("a", "1"), ("b", "2"), ("c", "3")]).await;
response.assert_status(413).assert_see("Content Too Large");
assert!(
response
.error()
.is_some_and(|error| error.to_string().contains("more than 2 fields"))
);
}
#[tokio::test]
async fn file_inputs_left_empty_dont_count_toward_the_limit() {
let app = app_with(|config| config.server.max_file_uploads = 2);
let response = app
.post("/gallery")
.attach("photos[]", Attachment::from_data(PNG, "1.png"))
.attach("photos[]", Attachment::from_data(PNG, "2.png"))
.attach("photos[]", Attachment::from_data(Vec::new(), ""))
.await;
response.assert_ok();
assert_eq!(response.json()["photos"], json!(["1.png", "2.png"]));
}
#[tokio::test]
async fn file_rules_check_the_upload_under_the_fields_name() {
let app = app();
let profile = |avatar: Attachment| app.post("/profile").form([("name", "Taylor")]).attach("avatar", avatar);
profile(Attachment::from_data(png(1024), "me.png"))
.await
.assert_ok()
.assert_see("Taylor: me.png");
app.post("/profile")
.form([("name", "Taylor")])
.await
.assert_invalid_messages(&[("avatar", "The avatar field is required.")]);
profile(Attachment::from_data("Just text", "me.png"))
.await
.assert_invalid_messages(&[("avatar", "The avatar field must be an image.")]);
profile(Attachment::from_data(png(1025), "me.png"))
.await
.assert_invalid_messages(&[("avatar", "The avatar field must not be greater than 1 kilobytes.")]);
app.post("/profile")
.form([("name", "Taylor"), ("avatar", "me.png")])
.await
.assert_invalid_messages(&[("avatar", "The avatar field must be an image.")]);
}
#[tokio::test]
async fn fake_files_have_the_size_asked_for_and_no_detected_type() {
let response = app()
.post("/avatar")
.attach("avatar", Attachment::fake("report.pdf", 1))
.await;
response
.assert_ok()
.assert_json_path("avatar.size", 1024)
.assert_json_path("avatar.client_content_type", "application/pdf")
.assert_json_path("avatar.content_type", Value::Null);
let app = app();
app.post("/profile")
.form([("name", "Taylor")])
.attach("avatar", Attachment::fake("me.png", 1))
.await
.assert_invalid_messages(&[("avatar", "The avatar field must be an image.")]);
}
#[tokio::test]
async fn fake_images_are_pngs_of_the_size_asked_for() {
let app = app();
app.post("/profile")
.form([("name", "Taylor")])
.attach("avatar", Attachment::fake_image("me.png", 3, 2))
.await
.assert_ok()
.assert_see("Taylor: me.png");
let response = app
.post("/temporary")
.attach("avatar", Attachment::fake_image("wide.png", 300, 1))
.await;
response.assert_ok();
response.assert_json_path_where("length", |length: usize| length > 300);
}
#[test]
#[should_panic(expected = "a fake image is a PNG, so its name ends in `.png`, not `me.jpg`")]
fn fake_images_need_a_png_name() {
let _ = Attachment::fake_image("me.jpg", 1, 1);
}
#[tokio::test]
async fn mimes_accepts_extensions_and_mime_types() {
let app = app();
app.post("/attachment")
.attach("file", Attachment::from_data(PNG, "photo.png"))
.await
.assert_ok()
.assert_see("photo.png");
app.post("/attachment")
.attach("file", Attachment::from_data(b"%PDF-1.7\n%".to_vec(), "invoice.pdf"))
.await
.assert_ok()
.assert_see("invoice.pdf");
app.post("/attachment")
.attach("file", Attachment::from_data("Just text", "notes.png"))
.await
.assert_invalid_messages(&[("file", "The file field must be a file of type: image/*, pdf.")]);
}
#[tokio::test]
async fn file_rules_check_every_file_of_a_list_and_skip_a_missing_optional_file() {
let app = app();
app.post("/import")
.attach("photos[]", Attachment::from_data(PNG, "one.png"))
.attach("photos[]", Attachment::from_data(PNG, "two.png"))
.await
.assert_ok()
.assert_see("one.png two.png no contacts");
app.post("/import")
.attach("photos[]", Attachment::from_data(PNG, "one.png"))
.attach("photos[]", Attachment::from_data("Just text", "two.png"))
.await
.assert_invalid_messages(&[("photos", "The photos field must be a file of type: jpg, png.")]);
app.post("/import")
.attach("photos[0]", Attachment::from_data(PNG, "one.png"))
.attach("photos[+1]", Attachment::from_data("Just text", "two.png"))
.await
.assert_invalid_messages(&[("photos", "The photos field must be a file of type: jpg, png.")]);
app.post("/import")
.attach("photos[]", Attachment::from_data(PNG, "one.png"))
.attach("contacts", Attachment::from_data("a@example.com", "list.CSV"))
.await
.assert_ok()
.assert_see("one.png list.CSV");
app.post("/import")
.attach("photos[]", Attachment::from_data(PNG, "one.png"))
.attach("contacts", Attachment::from_data("a@example.com", "list.txt"))
.await
.assert_invalid_messages(&[(
"contacts",
"The contacts field must have one of the following extensions: csv.",
)]);
}
#[tokio::test]
async fn each_checks_every_file_of_a_list() {
let app = app();
app.post("/attachments")
.attach("files[]", Attachment::from_data(vec![b'a'; 10], "small.txt"))
.attach("files[]", Attachment::from_data(vec![b'a'; 1025], "large.txt"))
.await
.assert_invalid_messages(&[("files.1", "The files.1 field must not be greater than 1 kilobytes.")]);
app.post("/attachments")
.attach("files[]", Attachment::from_data(vec![b'a'; 1024], "one.txt"))
.attach("files[]", Attachment::from_data(vec![b'a'; 100], "two.txt"))
.await
.assert_ok()
.assert_see("one.txt two.txt");
}
#[tokio::test]
async fn text_under_a_file_lists_name_doesnt_skip_its_files_rules() {
let app = app();
for field in ["files[]", "files[0]"] {
app.post("/attachments")
.form([("files", "x")])
.attach(field, Attachment::from_data(vec![b'a'; 1100], "large.txt"))
.await
.assert_invalid_messages(&[("files", "The files field must be an array.")]);
}
for (query, field) in [
("?files=x", "files[]"),
("?files=x", "files[0]"),
("?files[]=x", "files[]"),
] {
app.post(format!("/attachments{query}"))
.attach(field, Attachment::from_data(vec![b'a'; 1100], "large.txt"))
.await
.assert_invalid_messages(&[("files.0", "The files.0 field must not be greater than 1 kilobytes.")]);
}
}
#[tokio::test]
async fn nested_structs_and_lists_that_hold_only_files_check_their_rules() {
let app = app();
app.post("/listing")
.attach("cover[photo]", Attachment::from_data(PNG, "cover.png"))
.attach("gallery[0][photo]", Attachment::from_data(PNG, "one.png"))
.attach("gallery[1][photo]", Attachment::from_data(PNG, "two.png"))
.await
.assert_ok()
.assert_see("cover.png one.png two.png");
app.post("/listing")
.form([("gallery[0][caption]", "Lakeside")])
.attach("cover[photo]", Attachment::from_data("Just text", "cover.png"))
.attach("gallery[0][photo]", Attachment::from_data(PNG, "one.png"))
.attach("gallery[1][photo]", Attachment::from_data("Just text", "two.png"))
.await
.assert_invalid_messages(&[
("cover.photo", "The cover.photo field must be an image."),
(
"gallery.0.caption",
"The gallery.0.caption field must not be greater than 5 characters.",
),
("gallery.1.photo", "The gallery.1.photo field must be an image."),
]);
}
#[tokio::test]
async fn presence_rules_count_an_upload_as_a_submitted_value() {
let app = app();
app.post("/avatar-choice")
.attach("avatar", Attachment::from_data(PNG, "me.png"))
.await
.assert_ok()
.assert_see("Some(\"me.png\") None None");
app.post("/avatar-choice")
.form([("avatar_url", "https://example.com/me.png")])
.attach("attachment", Attachment::from_data(PNG, "extra.png"))
.await
.assert_invalid_messages(&[("attachment", "The attachment field is prohibited.")]);
app.post("/avatar-choice")
.form([("note", "none")])
.await
.assert_invalid_messages(&[(
"avatar_url",
"The avatar url field is required when avatar is not present.",
)]);
}
#[tokio::test]
async fn a_text_field_in_a_file_list_is_invalid() {
app()
.post("/import")
.form([("photos[1]", "not-a-file")])
.attach("photos[0]", Attachment::from_data(PNG, "one.png"))
.attach("payload", Attachment::from_data(vec![b'A'; 1500], "evil.exe"))
.await
.assert_redirect()
.assert_invalid_messages(&[("photos.1", "The photos.1 field is invalid.")]);
}
#[tokio::test]
async fn a_file_under_a_fields_alias_checks_the_fields_rules() {
let app = app();
app.post("/portrait")
.attach("picture", Attachment::from_data("Just text", "evil.png"))
.await
.assert_invalid_messages(&[("picture", "The picture field must be an image.")]);
app.post("/portrait")
.attach("picture", Attachment::from_data(PNG, "me.png"))
.await
.assert_ok()
.assert_see("me.png");
}
#[tokio::test]
async fn text_entries_of_a_list_with_a_file_reach_the_handler() {
app()
.post("/album")
.form([("items[][caption]", "Lakeside")])
.attach("items[1][photo]", Attachment::from_data(PNG, "one.png"))
.await
.assert_ok()
.assert_see("Lakeside one.png");
}
#[tokio::test]
async fn an_upload_doesnt_decode_as_a_text_field() {
let app = app();
app.post("/profile")
.attach("name", Attachment::from_data(PNG, "name.png"))
.attach("avatar", Attachment::from_data(PNG, "me.png"))
.await
.assert_invalid_messages(&[("name", "The name field must be a string.")]);
app.post("/profile")
.form([("name", "Taylor")])
.attach("name", Attachment::from_data(PNG, "name.png"))
.attach("avatar", Attachment::from_data(PNG, "me.png"))
.await
.assert_invalid_messages(&[("name", "The name field is invalid.")]);
}
#[tokio::test]
async fn an_upload_and_other_input_at_overlapping_paths_are_invalid() {
let app = app();
app.post("/avatar-choice")
.form([("avatar_url", "")])
.attach("avatar_url", Attachment::from_data(PNG, "me.png"))
.await
.assert_invalid_messages(&[("avatar_url", "The avatar url field is invalid.")]);
app.post("/avatar-choice")
.form([("avatar_url", "https://example.com/me.png")])
.attach("avatar_url[0]", Attachment::from_data(PNG, "me.png"))
.await
.assert_invalid_messages(&[("avatar_url", "The avatar url field is invalid.")]);
app.post("/profile?avatar=evil")
.form([("name", "Taylor")])
.attach("avatar", Attachment::from_data(PNG, "me.png"))
.await
.assert_ok();
app.post("/attachments")
.attach("files[0]", Attachment::from_data(vec![b'a'; 10], "small.txt"))
.attach("files", Attachment::from_data(vec![b'a'; 1100], "large.txt"))
.await
.assert_invalid_messages(&[("files", "The files field is invalid.")]);
}
#[tokio::test]
async fn files_without_a_name_are_dropped_as_text_fields_are() {
app()
.post("/gallery")
.attach("", Attachment::from_data(PNG, "a.png"))
.attach("[]", Attachment::from_data(PNG, "b.png"))
.attach("[x]", Attachment::from_data(PNG, "c.png"))
.attach("photos[]", Attachment::from_data(PNG, "one.png"))
.await
.assert_ok()
.assert_json_path("photos", json!(["one.png"]));
}
#[tokio::test]
async fn custom_rules_and_dotted_map_keys_inspect_uploaded_files_through_input_value() {
use std::collections::BTreeMap;
use laravel::validation::{Field, InputValue, RuleError, ValidationRule};
struct NamedPng;
impl ValidationRule for NamedPng {
async fn validate(&self, field: &Field<'_>) -> Result<(), RuleError> {
let Some(file) = field.value.and_then(InputValue::as_file) else {
return Err(field.reject("The :attribute field must be an uploaded file."));
};
if file.client_name().ends_with(".png") {
Ok(())
} else {
Err(field.reject("The :attribute file must end with .png."))
}
}
}
struct MatchesAvatarName;
impl ValidationRule for MatchesAvatarName {
async fn validate(&self, field: &Field<'_>) -> Result<(), RuleError> {
let avatar_name = field
.get("avatar")
.and_then(InputValue::as_file)
.map(UploadedFile::client_name);
if field.value.and_then(InputValue::as_str) == avatar_name {
Ok(())
} else {
Err(field.reject("The :attribute must match the avatar filename."))
}
}
}
#[derive(Debug, serde::Deserialize, Validate)]
#[validate(anyone)]
#[expect(dead_code, reason = "only validated")]
struct CustomUploads {
#[validate(required, NamedPng)]
avatar: UploadedFile,
#[validate(MatchesAvatarName)]
expected_name: Option<String>,
#[validate(each(NamedPng))]
gallery: Vec<UploadedFile>,
#[validate(image)]
documents: BTreeMap<String, UploadedFile>,
}
let app = Application::configure()
.replace_env(Env::default())
.with_routing(|routing, _| {
routing.api(|route: &mut Router| {
route.post("/custom-uploads", |Valid(form): Valid<CustomUploads>| async move {
let docs: Vec<_> = form
.documents
.into_iter()
.map(|(k, f)| (k, f.client_name().to_owned()))
.collect();
Json(json!({ "avatar": form.avatar.client_name(), "docs": docs }))
});
});
})
.create();
app.post("/api/custom-uploads")
.form([("expected_name", "me.png")])
.attach("avatar", Attachment::from_data(PNG, "me.png"))
.attach("gallery[]", Attachment::from_data(PNG, "one.png"))
.attach("documents[a.b]", Attachment::from_data(PNG, "doc.png"))
.await
.assert_ok()
.assert_json(json!({ "avatar": "me.png", "docs": [["a.b", "doc.png"]] }));
app.post("/api/custom-uploads")
.form([("expected_name", "other.png")])
.attach("avatar", Attachment::from_data(PNG, "me.jpg"))
.attach("gallery[]", Attachment::from_data(PNG, "bad.gif"))
.attach("documents[a.b]", Attachment::from_data("not an image", "doc.txt"))
.await
.assert_status(422)
.assert_json_path(
"errors",
json!({
"avatar": ["The avatar file must end with .png."],
"expected_name": ["The expected name must match the avatar filename."],
"gallery.0": ["The gallery.0 file must end with .png."],
"documents": ["The documents field must be an image."],
}),
);
}