1use axum::body::Bytes;
2use std::collections::HashMap;
3
4use axum::extract::multipart::MultipartError;
5use axum::extract::{FromRequest, Multipart, Request};
6use axum::http::header::CONTENT_TYPE;
7use axum::http::{Method, StatusCode};
8use axum::response::{IntoResponse, Response};
9use serde::de::DeserializeOwned;
10use serde_json::{Map, Value};
11
12use super::messages::render;
13use super::nested;
14use super::{Errors, Validate, ValidationError, Validator};
15use crate::upload::{self, Upload};
16use crate::{AppState, Error};
17
18pub struct Valid<T>(pub T);
30
31type FormFiles = (Vec<(String, String)>, HashMap<String, Upload>);
33
34pub(crate) struct Messages {
36 pub(crate) texts: crate::i18n::Texts,
37}
38
39impl Messages {
40 fn template(&self, key: &str) -> std::borrow::Cow<'static, str> {
41 super::messages::template_for(Some(&self.texts), key)
42 }
43
44 fn label(&self, field: &str) -> String {
45 nested::label(field, |key| {
46 self.texts
47 .get(&format!("renox.validation.attributes.{key}"))
48 .cloned()
49 })
50 }
51}
52
53pub(crate) enum Parsed<T> {
54 Ok(T, Errors),
57 Invalid(Errors),
58}
59
60impl<T> FromRequest<AppState> for Valid<T>
61where
62 T: DeserializeOwned + Validate + Send,
63{
64 type Rejection = Response;
65
66 async fn from_request(req: Request, state: &AppState) -> Result<Self, Response> {
67 validate_request(req, state, |_: &T, _, _| {})
68 .await
69 .map(|(data, _)| Valid(data))
70 }
71}
72
73pub(crate) const LIVE_HEADER: &str = "x-renox-validate";
75
76#[derive(Clone)]
78pub(crate) struct SubmittedInput(pub Map<String, Value>);
79
80#[allow(clippy::result_large_err)] pub(crate) async fn validate_request<T>(
84 req: Request,
85 state: &AppState,
86 extra: impl FnOnce(&T, &Map<String, Value>, &mut Validator) + Send,
87) -> Result<(T, Map<String, Value>), Response>
88where
89 T: DeserializeOwned + Validate + Send,
90{
91 let live_field = req
92 .headers()
93 .get(LIVE_HEADER)
94 .and_then(|v| v.to_str().ok())
95 .filter(|f| !f.is_empty() && f.len() <= 200)
96 .map(str::to_owned);
97 let user = req
99 .extensions()
100 .get::<crate::auth::CurrentUser>()
101 .and_then(|current| current.user.clone());
102 let method = req.method().clone();
103 let path = req.uri().path().to_owned();
104 let locale_name = crate::i18n::request_locale(req.extensions(), state);
105 let locale = &Messages {
106 texts: state.translator.texts(&locale_name),
107 };
108 let content_type = req
109 .headers()
110 .get(CONTENT_TYPE)
111 .and_then(|v| v.to_str().ok())
112 .unwrap_or_default()
113 .to_ascii_lowercase();
114 let is_json = req
115 .headers()
116 .get(CONTENT_TYPE)
117 .and_then(|v| v.to_str().ok())
118 .is_some_and(|v| v.starts_with("application/json"));
119
120 let is_multipart = req
121 .headers()
122 .get(CONTENT_TYPE)
123 .and_then(|v| v.to_str().ok())
124 .is_some_and(|v| v.starts_with("multipart/form-data"));
125
126 let mut files: Option<FormFiles> = None;
129 let (parsed, input) = if matches!(*req.method(), Method::GET | Method::HEAD) {
130 let query = req.uri().query().unwrap_or_default().as_bytes();
131 let pairs = form_urlencoded::parse(query).into_owned().collect();
132 parse_pairs(pairs, &HashMap::new(), locale)
133 } else if is_multipart {
134 let multipart = Multipart::from_request(req, state)
135 .await
136 .map_err(IntoResponse::into_response)?;
137 let (pairs, uploads) = read_multipart(multipart)
139 .await
140 .map_err(IntoResponse::into_response)?;
141 let parsed = parse_pairs(pairs.clone(), &uploads, locale);
142 if !uploads.is_empty() && !state.uploads.is_empty() {
143 files = Some((pairs, uploads));
144 }
145 parsed
146 } else {
147 let bytes = Bytes::from_request(req, state)
148 .await
149 .map_err(IntoResponse::into_response)?;
150 if is_json {
151 parse_json(&bytes, locale).map_err(IntoResponse::into_response)?
152 } else if !content_type.is_empty()
153 && !content_type.starts_with("application/x-www-form-urlencoded")
154 {
155 return Err(
156 (StatusCode::UNSUPPORTED_MEDIA_TYPE, "Send a form or JSON.").into_response()
157 );
158 } else {
159 let pairs = form_urlencoded::parse(&bytes).into_owned().collect();
160 parse_pairs(pairs, &HashMap::new(), locale)
161 }
162 };
163
164 let (mut data, mut errors): (T, Errors) = match parsed {
165 Parsed::Ok(data, errors) => (data, errors),
166 Parsed::Invalid(errors) => {
167 return Err(bagged::<T>(ValidationError::new(errors))
168 .with_input_map(input)
169 .into_response());
170 }
171 };
172 data.prepare();
173 let form = super::FormContext {
174 state,
175 user: user.as_deref(),
176 method: &method,
177 path: &path,
178 locale: &locale_name,
179 };
180 if !data
181 .authorize(&form)
182 .await
183 .map_err(IntoResponse::into_response)?
184 {
185 return Err(Error::Forbidden.into_response());
186 }
187 let mut validator = Validator::rules_with_texts(&data, locale.texts.clone());
188 extra(&data, &input, &mut validator);
189 let rule_errors = validator
190 .finish_for(state, user.as_deref())
191 .await
192 .map_err(IntoResponse::into_response)?;
193 for (field, messages) in rule_errors.iter() {
196 if !errors.has(field) {
197 for message in messages {
198 errors.add(field, message.clone());
199 }
200 }
201 }
202 if errors.is_empty()
207 && live_field.is_none()
208 && let Some((pairs, mut uploads)) = files
209 {
210 let changed = state
211 .uploads
212 .run_form(state, &pairs, &mut uploads, &mut errors)
213 .await
214 .map_err(IntoResponse::into_response)?;
215 if changed
216 && errors.is_empty()
217 && let (Parsed::Ok(mut again, parse_errors), _) =
218 parse_pairs::<T>(pairs, &uploads, locale)
219 && parse_errors.is_empty()
220 {
221 again.prepare();
222 data = again;
223 }
224 }
225 if errors.is_empty() {
226 data.after(&form, &mut errors)
227 .await
228 .map_err(IntoResponse::into_response)?;
229 }
230 if let Some(field) = live_field {
234 let key = nested::normalize(&field);
236 let item = |name: &str| {
239 name.strip_prefix(key.as_str())
240 .and_then(|rest| rest.strip_prefix('.'))
241 .is_some_and(|rest| !rest.is_empty() && rest.bytes().all(|b| b.is_ascii_digit()))
242 };
243 let messages: Vec<String> = errors
244 .iter()
245 .filter(|(name, _)| *name == key || item(name))
246 .flat_map(|(_, messages)| messages.iter().cloned())
247 .collect();
248 let body = serde_json::json!({ "field": field, "errors": messages });
249 return Err((axum::http::StatusCode::OK, axum::Json(body)).into_response());
250 }
251 if errors.is_empty() {
252 crate::context::set(SubmittedInput(input.clone()));
255 Ok((data, input))
256 } else {
257 Err(bagged::<T>(ValidationError::new(errors))
258 .with_input_map(input)
259 .into_response())
260 }
261}
262
263fn bagged<T: Validate>(error: ValidationError) -> ValidationError {
265 match T::ERROR_BAG {
266 Some(bag) => error.in_bag(bag),
267 None => error,
268 }
269}
270
271async fn read_multipart(
274 mut multipart: Multipart,
275) -> Result<(Vec<(String, String)>, HashMap<String, Upload>), MultipartError> {
276 let mut pairs = Vec::new();
277 let mut uploads = HashMap::new();
278 while let Some(field) = multipart.next_field().await? {
279 let Some(name) = field.name().map(str::to_owned) else {
280 continue;
281 };
282 match field.file_name().map(str::to_owned) {
283 Some(file_name) => {
284 let content_type = field.content_type().unwrap_or_default().to_owned();
285 let bytes = field.bytes().await?;
286 if file_name.is_empty() && bytes.is_empty() {
287 continue;
288 }
289 let token = upload::token(uploads.len());
290 uploads.insert(token.clone(), Upload::new(file_name, content_type, bytes));
291 pairs.push((name, token));
292 }
293 None => pairs.push((name, field.text().await?)),
294 }
295 }
296 Ok((pairs, uploads))
297}
298
299pub(crate) fn parse_pairs<T: DeserializeOwned>(
300 pairs: Vec<(String, String)>,
301 uploads: &HashMap<String, Upload>,
302 locale: &Messages,
303) -> (Parsed<T>, Map<String, Value>) {
304 if nested::is_nested(pairs.iter().map(|(k, _)| k.as_str())) {
305 return parse_nested(pairs, uploads, locale);
306 }
307 let mut input = Map::new();
308 for (key, value) in pairs.iter().filter(|(_, v)| !uploads.contains_key(v)) {
309 match input.get_mut(key) {
310 Some(Value::Array(values)) => values.push(Value::String(value.clone())),
311 Some(existing) => {
312 let first = existing.take();
313 *existing = Value::Array(vec![first, Value::String(value.clone())]);
314 }
315 None => {
316 input.insert(key.clone(), Value::String(value.clone()));
317 }
318 }
319 }
320
321 let mut filled: Vec<(String, String)> = pairs
329 .iter()
330 .filter(|(_, v)| !v.trim().is_empty())
331 .cloned()
332 .collect();
333 let mut errors = Errors::new();
334 let mut tries: HashMap<String, usize> = HashMap::new();
335 let mut coerced: std::collections::HashSet<String> = std::collections::HashSet::new();
336 let parsed = loop {
337 let encoded = form_urlencoded::Serializer::new(String::new())
338 .extend_pairs(&filled)
339 .finish();
340 let deserializer = serde_html_form::Deserializer::from_bytes(encoded.as_bytes());
343 match upload::with_uploads(uploads, || serde_path_to_error::deserialize(deserializer)) {
344 Ok(data) => break Parsed::Ok(data, errors),
345 Err(err) => {
346 let message = err.inner().to_string();
347 if let Some(field) = missing_field(&message)
348 && !filled.iter().any(|(k, _)| k == field)
349 {
350 filled.push((field.to_owned(), String::new()));
351 continue;
352 }
353 let path = err.path().to_string();
354 if coerce_browser_value(&mut filled, &path, &message, &mut coerced) {
355 continue;
356 }
357 let blank = filled.iter().any(|(k, v)| *k == path && v.is_empty());
358 let tried = tries.entry(path.clone()).or_default();
359 if *tried == 0 {
360 for (field, messages) in field_error(&path, &message, blank, locale).iter() {
361 for message in messages {
362 errors.add(field, message.clone());
363 }
364 }
365 }
366 let placeholder = match *tried {
369 0 => expected_variant(&message)
370 .or_else(|| PLACEHOLDERS.first().map(|p| (*p).to_owned())),
371 n => PLACEHOLDERS.get(n).map(|p| (*p).to_owned()),
372 };
373 *tried += 1;
374 match placeholder {
375 Some(value) if filled.iter().any(|(k, _)| *k == path) => {
376 filled.retain(|(k, _)| *k != path);
377 filled.push((path, value));
378 }
379 _ => break Parsed::Invalid(errors),
380 }
381 }
382 }
383 };
384 (parsed, input)
385}
386
387const PLACEHOLDERS: &[&str] = &["0", "false"];
388
389fn parse_nested<T: DeserializeOwned>(
395 pairs: Vec<(String, String)>,
396 uploads: &HashMap<String, Upload>,
397 locale: &Messages,
398) -> (Parsed<T>, Map<String, Value>) {
399 let shown: Vec<(String, String)> = pairs
400 .iter()
401 .filter(|(_, v)| !uploads.contains_key(v))
402 .cloned()
403 .collect();
404 let input = match nested::Node::build(&shown).into_json() {
405 Value::Object(map) => map,
406 _ => Map::new(),
407 };
408 let mut filled: Vec<(String, String)> = pairs
411 .into_iter()
412 .map(|(k, v)| {
413 let key = nested::normalize(&k);
414 if k.ends_with("[]") {
415 (key + "[]", v)
416 } else {
417 (key, v)
418 }
419 })
420 .collect();
421 let mut errors = Errors::new();
422 let mut tries: HashMap<String, usize> = HashMap::new();
423 let mut coerced: std::collections::HashSet<String> = std::collections::HashSet::new();
424 let parsed = loop {
425 let tree = nested::Node::build(&filled);
426 match upload::with_uploads(uploads, || nested::deserialize::<T>(tree)) {
427 Ok(data) => break Parsed::Ok(data, errors),
428 Err(err) => {
429 let message = err.inner().to_string();
430 let path = nested::normalize(&err.path().to_string());
431 let path = path.trim_start_matches('.').to_owned();
432 let path = if path.is_empty() {
433 ".".to_owned()
434 } else {
435 path
436 };
437 if let Some(field) = missing_field(&message) {
438 let full = if path == "." {
439 field.to_owned()
440 } else {
441 format!("{path}.{field}")
442 };
443 if !filled.iter().any(|(k, _)| *k == full) {
444 filled.push((full, String::new()));
445 continue;
446 }
447 }
448 if coerce_browser_value(&mut filled, &path, &message, &mut coerced) {
449 continue;
450 }
451 let blank = filled
452 .iter()
453 .any(|(k, v)| *k == path && v.trim().is_empty());
454 let tried = tries.entry(path.clone()).or_default();
455 if *tried == 0 {
456 for (field, messages) in field_error(&path, &message, blank, locale).iter() {
457 for message in messages {
458 errors.add(field, message.clone());
459 }
460 }
461 }
462 let placeholder = match *tried {
463 0 => expected_variant(&message)
464 .or_else(|| PLACEHOLDERS.first().map(|p| (*p).to_owned())),
465 n => PLACEHOLDERS.get(n).map(|p| (*p).to_owned()),
466 };
467 *tried += 1;
468 match placeholder {
469 Some(value) if filled.iter().any(|(k, _)| *k == path) => {
470 filled.retain(|(k, _)| *k != path);
471 filled.push((path, value));
472 }
473 _ => break Parsed::Invalid(errors),
474 }
475 }
476 }
477 };
478 (parsed, input)
479}
480
481fn expected_variant(message: &str) -> Option<String> {
484 let rest = message.split("expected one of").nth(1)?;
485 let rest = rest.trim_start_matches([':', ' ']);
486 let first = rest.split(',').next()?.trim().trim_matches('`');
487 (!first.is_empty()).then(|| first.to_owned())
488}
489
490fn is_bool_error(message: &str) -> bool {
494 message.contains("`true` or `false`") || message.contains("expected \"true\"")
495}
496
497fn coerce_browser_value(
502 filled: &mut [(String, String)],
503 path: &str,
504 message: &str,
505 coerced: &mut std::collections::HashSet<String>,
506) -> bool {
507 if coerced.contains(path) {
508 return false;
509 }
510 let mut changed = false;
511 for (_, value) in filled.iter_mut().filter(|(k, _)| k == path) {
512 let new = if is_bool_error(message) {
513 match value.trim().to_ascii_lowercase().as_str() {
514 "on" | "1" | "yes" | "checked" => Some("true".to_owned()),
515 "" | "off" | "0" | "no" => Some("false".to_owned()),
516 _ => None,
517 }
518 } else if is_minute_datetime(value) {
519 Some(format!("{value}:00"))
520 } else {
521 None
522 };
523 if let Some(new) = new {
524 *value = new;
525 changed = true;
526 }
527 }
528 if changed {
529 coerced.insert(path.to_owned());
530 }
531 changed
532}
533
534fn is_minute_datetime(value: &str) -> bool {
536 let b = value.as_bytes();
537 b.len() == 16
538 && b[4] == b'-'
539 && b[7] == b'-'
540 && b[10] == b'T'
541 && b[13] == b':'
542 && b.iter()
543 .enumerate()
544 .all(|(i, c)| matches!(i, 4 | 7 | 10 | 13) || c.is_ascii_digit())
545}
546
547fn parse_json<T: DeserializeOwned>(
548 bytes: &[u8],
549 locale: &Messages,
550) -> Result<(Parsed<T>, Map<String, Value>), Error> {
551 let input = match serde_json::from_slice(bytes) {
552 Ok(Value::Object(map)) => map,
553 Ok(_) => return Err(Error::BadRequest("The JSON body must be an object.".into())),
554 Err(err) => return Err(Error::BadRequest(format!("Invalid JSON: {err}"))),
555 };
556 let mut body = input.clone();
560 let mut errors = Errors::new();
561 let mut tries: HashMap<String, usize> = HashMap::new();
562 let parsed = loop {
563 match serde_path_to_error::deserialize(Value::Object(body.clone())) {
564 Ok(data) => break Parsed::Ok(data, errors),
565 Err(err) => {
566 let message = err.inner().to_string();
567 if let Some(field) = missing_field(&message)
568 && !body.contains_key(field)
569 {
570 body.insert(field.to_owned(), Value::String(String::new()));
571 continue;
572 }
573 let path = err.path().to_string();
574 let blank = body.get(&path).is_some_and(|v| {
575 v.is_null() || v.as_str().is_some_and(|s| s.trim().is_empty())
576 });
577 let tried = tries.entry(path.clone()).or_default();
578 if *tried == 0 {
579 for (field, messages) in field_error(&path, &message, blank, locale).iter() {
580 for message in messages {
581 errors.add(field, message.clone());
582 }
583 }
584 }
585 let placeholder = match (*tried, expected_variant(&message)) {
586 (0, Some(variant)) => Some(Value::String(variant)),
587 (n, _) => JSON_PLACEHOLDERS.get(n).map(|p| p()),
588 };
589 *tried += 1;
590 match placeholder {
591 Some(value) if body.contains_key(&path) => {
592 body.insert(path, value);
593 }
594 _ => break Parsed::Invalid(errors),
595 }
596 }
597 }
598 };
599 Ok((parsed, input))
600}
601
602const JSON_PLACEHOLDERS: &[fn() -> Value] = &[
604 || Value::from(0),
605 || Value::Bool(false),
606 || Value::String(String::new()),
607 || Value::Null,
608];
609
610fn missing_field(message: &str) -> Option<&str> {
611 message
612 .strip_prefix("missing field `")
613 .and_then(|rest| rest.split('`').next())
614}
615
616fn field_error(path: &str, message: &str, blank: bool, locale: &Messages) -> Errors {
619 let mut errors = Errors::new();
620 if let Some(field) = missing_field(message) {
621 let field = if path == "." {
622 field.to_owned()
623 } else {
624 format!("{path}.{field}")
625 };
626 errors.add(
627 &field,
628 render(&locale.template("required"), &locale.label(&field), &[]),
629 );
630 return errors;
631 }
632
633 let field = if path == "." { "_form" } else { path };
634 let numeric = [
635 "invalid digit",
636 "invalid float",
637 "cannot parse integer",
638 "number too large",
639 "expected i",
640 "expected u",
641 "expected f",
642 ]
643 .iter()
644 .any(|needle| message.contains(needle));
645 let key = match (blank, numeric) {
646 (true, _) => "required",
647 _ if message.contains(upload::NOT_A_FILE) => "file",
648 (false, true) => "numeric",
649 (false, false) => "invalid",
650 };
651 errors.add(
652 field,
653 render(&locale.template(key), &locale.label(field), &[]),
654 );
655 errors
656}
657
658#[cfg(test)]
659mod tests {
660 use super::*;
661 use serde::Deserialize;
662
663 fn plain() -> Messages {
664 Messages {
665 texts: Default::default(),
666 }
667 }
668
669 #[derive(Deserialize, Debug)]
670 #[allow(dead_code)]
671 struct Form {
672 name: String,
673 price: i64,
674 note: Option<String>,
675 }
676
677 fn parse(body: &str) -> Result<Form, Errors> {
678 let pairs = form_urlencoded::parse(body.as_bytes())
679 .into_owned()
680 .collect();
681 match parse_pairs::<Form>(pairs, &HashMap::new(), &plain()).0 {
682 Parsed::Ok(form, errors) if errors.is_empty() => Ok(form),
683 Parsed::Ok(_, errors) | Parsed::Invalid(errors) => Err(errors),
684 }
685 }
686
687 #[derive(Deserialize, Debug)]
688 struct Browser {
689 agree: bool,
690 news: bool,
691 starts_at: chrono::NaiveDateTime,
692 #[serde(default)]
693 tags: Vec<String>,
694 #[serde(default)]
695 sizes: Vec<i64>,
696 }
697
698 fn parse_browser(body: &str) -> Result<Browser, Errors> {
699 let pairs = form_urlencoded::parse(body.as_bytes())
700 .into_owned()
701 .collect();
702 match parse_pairs::<Browser>(pairs, &HashMap::new(), &plain()).0 {
703 Parsed::Ok(form, errors) if errors.is_empty() => Ok(form),
704 Parsed::Ok(_, errors) | Parsed::Invalid(errors) => Err(errors),
705 }
706 }
707
708 #[test]
709 fn bool_errors_are_recognised_in_either_wording() {
710 assert!(is_bool_error("provided string was not `true` or `false`"));
711 assert!(is_bool_error(
712 r#"invalid value: string "", expected "true", "on" or "false""#
713 ));
714 assert!(!is_bool_error("invalid digit found in string"));
715 let err = serde_html_form::from_str::<Browser>("agree=&news=&starts_at=x").unwrap_err();
717 assert!(is_bool_error(&err.to_string()), "{err}");
718 }
719
720 #[test]
721 fn reads_what_browsers_send() {
722 let form =
725 parse_browser("agree=on&starts_at=2026-10-01T10%3A30&tags=a&tags=b&sizes=1&sizes=2")
726 .unwrap();
727 assert!(form.agree);
728 assert!(!form.news);
729 assert_eq!(form.starts_at.to_string(), "2026-10-01 10:30:00");
730 assert_eq!(form.tags, ["a", "b"]);
731 assert_eq!(form.sizes, [1, 2]);
732 let form = parse_browser("agree=1&news=true&starts_at=2026-10-01T10%3A30%3A15").unwrap();
733 assert!(form.agree && form.news);
734 assert!(form.tags.is_empty());
735 let errors = parse_browser("agree=maybe&starts_at=soon").unwrap_err();
736 assert!(errors.has("agree") && errors.has("starts_at"));
737 for unchecked in ["agree=on&news=", "agree=on&news=off", "agree=on&news=0"] {
741 let form = parse_browser(&format!("{unchecked}&starts_at=2026-10-01T10%3A30"))
742 .unwrap_or_else(|errors| panic!("{unchecked}: {errors:?}"));
743 assert!(form.agree && !form.news, "{unchecked}");
744 }
745 }
746
747 #[test]
748 fn empty_fields_are_missing() {
749 let form = parse("name=Coffee&price=5¬e=").unwrap();
750 assert!(form.note.is_none());
751 assert_eq!(parse("name=&price=5").unwrap().name, "");
753 assert_eq!(parse("price=5").unwrap().name, "");
754 let errors = parse("name=Coffee&price=").unwrap_err();
755 assert_eq!(errors.first("price"), Some("The price field is required."));
756 }
757
758 #[test]
759 fn wrong_types_name_the_field() {
760 let errors = parse("name=Coffee&price=cheap").unwrap_err();
761 assert_eq!(errors.first("price"), Some("The price must be a number."));
762 }
763
764 #[test]
765 fn keeps_every_input_for_old_values() {
766 let pairs = form_urlencoded::parse(b"name=Coffee&tag=a&tag=b&price=")
767 .into_owned()
768 .collect();
769 let (_, input) = parse_pairs::<Form>(pairs, &HashMap::new(), &plain());
770 assert_eq!(input["name"], "Coffee");
771 assert_eq!(input["tag"], serde_json::json!(["a", "b"]));
772 assert_eq!(input["price"], "");
773 }
774
775 fn errors<T: DeserializeOwned>(parsed: Parsed<T>) -> Errors {
778 match parsed {
779 Parsed::Ok(_, errors) | Parsed::Invalid(errors) => errors,
780 }
781 }
782
783 #[test]
784 fn a_json_body_must_be_an_object() {
785 for body in [&b"[1, 2]"[..], b"\"name\"", b"42"] {
786 match parse_json::<Form>(body, &plain()) {
787 Err(Error::BadRequest(message)) => {
788 assert_eq!(message, "The JSON body must be an object.")
789 }
790 Err(other) => panic!("{other:?}"),
791 Ok(_) => panic!("accepted a body that isn't an object"),
792 }
793 }
794 assert!(matches!(
795 parse_json::<Form>(b"{", &plain()),
796 Err(Error::BadRequest(m)) if m.starts_with("Invalid JSON")
797 ));
798 }
799
800 #[derive(Deserialize, Debug)]
801 #[serde(deny_unknown_fields)]
802 #[allow(dead_code)]
803 struct Strict {
804 name: String,
805 }
806
807 #[test]
808 fn an_unknown_json_field_is_reported_under_its_name() {
809 let (parsed, _) = parse_json::<Strict>(br#"{"name": "a", "extra": 1}"#, &plain()).unwrap();
810 let errors = errors(parsed);
811 assert_eq!(errors.first("extra"), Some("The extra is invalid."));
812 }
813
814 #[test]
815 fn errors_at_the_root_name_the_field_or_the_form() {
816 let errors = field_error(".", "missing field `name`", false, &plain());
818 assert_eq!(errors.first("name"), Some("The name field is required."));
819 let errors = field_error(".", "invalid type: sequence", false, &plain());
821 assert!(errors.has("_form"), "{errors:?}");
822 let errors = field_error("address", "missing field `city`", false, &plain());
824 assert_eq!(
825 errors.first("address.city"),
826 Some("The city field is required.")
827 );
828 }
829
830 #[derive(Deserialize, Debug)]
831 #[allow(dead_code)]
832 struct Address {
833 city: String,
834 zip: i64,
835 }
836
837 #[derive(Deserialize, Debug)]
838 #[allow(dead_code)]
839 struct Shipping {
840 address: Address,
841 }
842
843 #[test]
844 fn json_errors_inside_an_object_name_the_nested_field() {
845 let (parsed, _) =
846 parse_json::<Shipping>(br#"{"address": {"city": "Bandung", "zip": "x"}}"#, &plain())
847 .unwrap();
848 let errors = errors(parsed);
849 assert!(errors.has("address.zip"), "{errors:?}");
850 let (parsed, _) = parse_json::<Shipping>(br#"{"address": {"zip": 1}}"#, &plain()).unwrap();
853 assert!(!errors_of_parsed_is_empty(parsed));
854 }
855
856 fn errors_of_parsed_is_empty<T>(parsed: Parsed<T>) -> bool {
857 match parsed {
858 Parsed::Ok(_, errors) => errors.is_empty(),
859 Parsed::Invalid(_) => false,
860 }
861 }
862
863 #[derive(Deserialize, Debug)]
864 #[allow(dead_code)]
865 struct Line {
866 name: String,
867 qty: i64,
868 }
869
870 #[derive(Deserialize, Debug)]
871 #[allow(dead_code)]
872 struct Order {
873 title: String,
874 lines: Vec<Line>,
875 }
876
877 fn nested_errors<T: DeserializeOwned>(body: &str) -> Errors {
878 let pairs = form_urlencoded::parse(body.as_bytes())
879 .into_owned()
880 .collect();
881 errors(parse_pairs::<T>(pairs, &HashMap::new(), &plain()).0)
882 }
883
884 #[test]
885 fn nested_forms_put_back_missing_fields_at_every_level() {
886 let errors = nested_errors::<Order>("lines%5B0%5D%5Bname%5D=Tea");
890 assert!(!errors.has("title"), "{errors:?}");
891 assert_eq!(
892 errors.first("lines.0.qty"),
893 Some("The qty field is required.")
894 );
895 let errors =
897 nested_errors::<Order>("title=T&lines%5B0%5D%5Bname%5D=Tea&lines%5B0%5D%5Bqty%5D=lots");
898 assert_eq!(
899 errors.first("lines.0.qty"),
900 Some("The qty must be a number.")
901 );
902 }
903
904 #[derive(Deserialize, Debug)]
905 #[serde(deny_unknown_fields)]
906 #[allow(dead_code)]
907 struct StrictOrder {
908 lines: Vec<Line>,
909 }
910
911 #[test]
912 fn an_unknown_nested_field_is_reported_under_its_name() {
913 let errors = nested_errors::<StrictOrder>(
914 "lines%5B0%5D%5Bname%5D=Tea&lines%5B0%5D%5Bqty%5D=1&extra%5Bx%5D=1",
915 );
916 assert_eq!(errors.first("extra"), Some("The extra is invalid."));
917 }
918
919 #[test]
920 fn a_nested_form_can_be_a_list_at_its_root() {
921 let pairs =
924 form_urlencoded::parse(b"0%5Bname%5D=Tea&0%5Bqty%5D=1&1%5Bname%5D=Coffee&1%5Bqty%5D=2")
925 .into_owned()
926 .collect();
927 let (parsed, input) = parse_pairs::<Vec<Line>>(pairs, &HashMap::new(), &plain());
928 match parsed {
929 Parsed::Ok(lines, errors) => {
930 assert!(errors.is_empty(), "{errors:?}");
931 assert_eq!(lines.len(), 2);
932 assert_eq!(lines[1].name, "Coffee");
933 }
934 Parsed::Invalid(errors) => panic!("{errors:?}"),
935 }
936 assert!(input.is_empty());
937 }
938
939 #[derive(Deserialize, Debug)]
940 #[allow(dead_code)]
941 struct Visit {
942 title: String,
943 slots: Vec<Slot>,
944 }
945
946 #[derive(Deserialize, Debug)]
947 #[allow(dead_code)]
948 struct Slot {
949 starts_at: chrono::NaiveDateTime,
950 }
951
952 #[test]
953 fn nested_forms_rewrite_what_browsers_send_and_try_every_placeholder() {
954 let pairs =
956 form_urlencoded::parse(b"title=T&slots%5B0%5D%5Bstarts_at%5D=2026-10-01T10%3A30")
957 .into_owned()
958 .collect();
959 let (parsed, _) = parse_pairs::<Visit>(pairs, &HashMap::new(), &plain());
960 assert!(errors_of_parsed_is_empty(parsed));
961 let errors =
965 nested_errors::<Visit>("title=T&slots%5B0%5D%5Bstarts_at%5D=2026-13-01T10%3A30");
966 let messages: Vec<_> = errors.iter().collect();
967 assert_eq!(messages.len(), 1, "{errors:?}");
968 assert_eq!(messages[0].0, "slots.0.starts_at");
969 assert_eq!(messages[0].1.len(), 1, "{errors:?}");
970 }
971
972 #[test]
973 fn a_plain_form_rewrites_a_value_once() {
974 let errors = parse_browser("agree=on&news=off&starts_at=2026-13-01T10%3A30").unwrap_err();
975 assert!(errors.has("starts_at"), "{errors:?}");
976 assert!(!errors.has("agree") && !errors.has("news"), "{errors:?}");
977 }
978
979 #[test]
980 fn a_json_enum_of_an_unknown_variant_gets_a_valid_one_as_placeholder() {
981 #[derive(Deserialize, Debug)]
982 #[serde(rename_all = "lowercase")]
983 #[allow(dead_code)]
984 enum Size {
985 Small,
986 Large,
987 }
988 #[derive(Deserialize, Debug)]
989 #[allow(dead_code)]
990 struct Cup {
991 size: Size,
992 name: String,
993 }
994 let (parsed, _) = parse_json::<Cup>(br#"{"size": "huge", "name": 5}"#, &plain()).unwrap();
995 let errors = errors(parsed);
996 assert!(errors.has("size"), "{errors:?}");
999 assert!(errors.has("name"), "{errors:?}");
1000 }
1001
1002 #[tokio::test]
1003 async fn a_multipart_part_without_a_name_is_skipped() {
1004 let body = "--XX\r\nContent-Disposition: form-data\r\n\r\nlost\r\n\
1005 --XX\r\nContent-Disposition: form-data; name=\"name\"\r\n\r\nCoffee\r\n\
1006 --XX--\r\n";
1007 let req = Request::builder()
1008 .method(Method::POST)
1009 .header(CONTENT_TYPE, "multipart/form-data; boundary=XX")
1010 .body(axum::body::Body::from(body))
1011 .unwrap();
1012 let multipart = Multipart::from_request(req, &()).await.unwrap();
1013 let (pairs, uploads) = read_multipart(multipart).await.unwrap();
1014 assert_eq!(pairs, [("name".to_owned(), "Coffee".to_owned())]);
1015 assert!(uploads.is_empty());
1016 }
1017}