1use std::task::{Context, Poll, ready};
3use std::{
4 fmt, future::Future, future::poll_fn, marker::PhantomData, mem, ops, pin::Pin, sync::Arc,
5};
6
7use serde::{Serialize, de::DeserializeOwned};
8
9use crate::http::header::CONTENT_LENGTH;
10use crate::http::{HttpMessage, Payload, Response, StatusCode, error::PayloadError};
11use crate::web::error::{JsonError, JsonPayloadError, WebResponseError};
12use crate::web::{FromRequest, HttpRequest, Responder, State};
13
14pub struct Json<T>(pub T);
70
71impl<T> Json<T> {
72 pub fn into_inner(self) -> T {
74 self.0
75 }
76}
77
78impl<T> ops::Deref for Json<T> {
79 type Target = T;
80
81 fn deref(&self) -> &T {
82 &self.0
83 }
84}
85
86impl<T> ops::DerefMut for Json<T> {
87 fn deref_mut(&mut self) -> &mut T {
88 &mut self.0
89 }
90}
91
92impl<T> fmt::Debug for Json<T>
93where
94 T: fmt::Debug,
95{
96 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
97 f.debug_tuple("Json").field(&self.0).finish()
98 }
99}
100
101impl<T> fmt::Display for Json<T>
102where
103 T: fmt::Display,
104{
105 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
106 fmt::Display::fmt(&self.0, f)
107 }
108}
109
110impl<St, T: Serialize> Responder<St> for Json<T>
111where
112 St: State,
113 JsonError: WebResponseError<St, St::Error>,
114{
115 async fn respond_to(self, st: &St, _: &HttpRequest) -> Response {
116 let body = match crate::http::json::to_bytes(&self.0) {
117 Ok(body) => body,
118 Err(e) => return e.error_response(st),
119 };
120
121 Response::builder(StatusCode::OK)
122 .content_type("application/json")
123 .body(body)
124 }
125}
126
127impl<St, T> FromRequest<St> for Json<T>
159where
160 St: State,
161 T: DeserializeOwned + 'static,
162{
163 type Error = JsonPayloadError;
164
165 fn from_request(
167 _: &St,
168 req: &HttpRequest,
169 payload: &mut Payload,
170 ) -> impl Future<Output = Result<Self, Self::Error>> {
171 let (limit, ctype) = req
172 .app_value::<JsonConfig>()
173 .map_or((32768, None), |c| (c.limit, c.content_type.as_ref()));
174
175 let mut body = JsonBody::new(req, payload, ctype).limit(limit);
176 poll_fn(move |cx| match ready!(Pin::new(&mut body).poll(cx)) {
177 Err(e) => {
178 log::debug!(
179 "Failed to deserialize Json from payload. \
180 Request path: {}",
181 req.path()
182 );
183 Poll::Ready(Err(e))
184 }
185 Ok(data) => Poll::Ready(Ok(Json(data))),
186 })
187 }
188}
189
190#[derive(Clone)]
231pub struct JsonConfig {
232 limit: usize,
233 content_type: Option<Arc<dyn Fn(mime::Mime) -> bool + Send + Sync>>,
234}
235
236impl JsonConfig {
237 #[must_use]
238 pub fn limit(mut self, limit: usize) -> Self {
242 self.limit = limit;
243 self
244 }
245
246 #[must_use]
247 pub fn content_type<F>(mut self, predicate: F) -> Self
255 where
256 F: Fn(mime::Mime) -> bool + Send + Sync + 'static,
257 {
258 self.content_type = Some(Arc::new(predicate));
259 self
260 }
261}
262
263impl Default for JsonConfig {
264 fn default() -> Self {
265 JsonConfig {
266 limit: 32768,
267 content_type: None,
268 }
269 }
270}
271
272impl fmt::Debug for JsonConfig {
273 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
274 f.debug_struct("JsonConfig")
275 .field("limit", &self.limit)
276 .field(
277 "content_type",
278 &self
279 .content_type
280 .as_ref()
281 .map(|_| "Arc<dyn Fn(mime::Mime) -> bool + Send + Sync>"),
282 )
283 .finish()
284 }
285}
286
287enum JsonBody<U> {
296 Body(super::ReadBody<super::BodyStream>, PhantomData<fn() -> U>),
297 Err(JsonPayloadError),
298 Done,
299}
300
301impl<U> JsonBody<U>
302where
303 U: DeserializeOwned + 'static,
304{
305 fn new(
307 req: &HttpRequest,
308 payload: &mut Payload,
309 ctype: Option<&Arc<dyn Fn(mime::Mime) -> bool + Send + Sync>>,
310 ) -> Self {
311 let json = if let Ok(Some(mime)) = req.mime_type() {
313 if let Some(predicate) = ctype {
314 predicate(mime)
315 } else {
316 mime.subtype() == mime::JSON || mime.suffix() == Some(mime::JSON)
317 }
318 } else {
319 false
320 };
321
322 if !json {
323 return Self::err(JsonPayloadError::ContentType);
324 }
325
326 let len = match req.headers().get(&CONTENT_LENGTH).map(|l| {
327 l.to_str()
328 .ok()
329 .and_then(|s| s.parse::<usize>().ok())
330 .ok_or(PayloadError::UnknownLength)
331 }) {
332 None => None,
333 Some(Ok(len)) => Some(len),
334 Some(Err(e)) => return Self::err(JsonPayloadError::Payload(e)),
335 };
336
337 JsonBody::Body(
338 super::ReadBody::from_request(req, payload, 262_144).length(len),
339 PhantomData,
340 )
341 }
342
343 fn err(err: JsonPayloadError) -> Self {
344 JsonBody::Err(err)
345 }
346
347 fn limit(mut self, limit: usize) -> Self {
349 if let JsonBody::Body(body, _) = &mut self {
350 body.limit = limit;
351 }
352 self
353 }
354}
355
356impl<U> Future for JsonBody<U>
357where
358 U: DeserializeOwned + 'static,
359{
360 type Output = Result<U, JsonPayloadError>;
361
362 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
363 let this = self.get_mut();
364 let body = match this {
365 JsonBody::Body(body, _) => body,
366 JsonBody::Err(_) => {
367 let JsonBody::Err(err) = mem::replace(this, JsonBody::Done) else {
368 unreachable!()
369 };
370 return Poll::Ready(Err(err));
371 }
372 JsonBody::Done => panic!("polled after completion"),
373 };
374 if let Some(len) = body.length
375 && len > body.limit
376 {
377 return Poll::Ready(Err(JsonPayloadError::Overflow));
378 }
379 let body = match ready!(Pin::new(body).poll(cx)) {
380 Ok(body) => body,
381 Err(super::ReadBodyError::Overflow(_)) => {
382 return Poll::Ready(Err(JsonPayloadError::Overflow));
383 }
384 Err(super::ReadBodyError::Payload(err)) => {
385 return Poll::Ready(Err(JsonPayloadError::Payload(err)));
386 }
387 };
388 Poll::Ready(crate::http::json::from_slice::<U>(&body).map_err(JsonPayloadError::from))
389 }
390}
391
392#[cfg(test)]
393mod tests {
394 use super::*;
395 use crate::http::header;
396 use crate::util::Bytes;
397 use crate::web::test::{TestRequest, from_request, respond_to};
398
399 #[derive(serde::Serialize, serde::Deserialize, PartialEq, Debug, thiserror::Error)]
400 #[error("MyObject({name})")]
401 struct MyObject {
402 name: String,
403 }
404
405 fn json_eq(err: &JsonPayloadError, other: &JsonPayloadError) -> bool {
406 if let JsonPayloadError::Overflow = err
407 && let JsonPayloadError::Overflow = other
408 {
409 return true;
410 } else if let JsonPayloadError::ContentType = err
411 && let JsonPayloadError::ContentType = other
412 {
413 return true;
414 }
415 false
416 }
417
418 #[test]
424 fn test_json() {
425 let mut j = Json(MyObject {
426 name: "test2".to_string(),
427 });
428 assert_eq!(j.name, "test2");
429 j.name = "test".to_string();
430 assert_eq!(j.name, "test");
431 assert!(format!("{j:?}").contains("Json"));
432 assert!(format!("{j}").contains("test"));
433
434 let cfg = JsonConfig::default().content_type(|mime: mime::Mime| {
435 mime.type_() == mime::TEXT && mime.subtype() == mime::PLAIN
436 });
437 assert!(format!("{cfg:?}").contains("JsonConfig"));
438 }
439
440 #[crate::rt_test]
446 async fn test_responder() {
447 let req = TestRequest::default().to_http_request();
448
449 let j = Json(MyObject {
450 name: "test".to_string(),
451 });
452 let resp = respond_to(j, &req).await;
453 assert_eq!(resp.status(), StatusCode::OK);
454 assert_eq!(
455 resp.headers().get(header::CONTENT_TYPE).unwrap(),
456 header::HeaderValue::from_static("application/json")
457 );
458
459 assert_eq!(resp.get_body_ref(), b"{\"name\":\"test\"}");
460 }
461
462 #[crate::rt_test]
468 async fn test_responder_serialize_error() {
469 struct Invalid;
470
471 impl Serialize for Invalid {
472 fn serialize<S: serde::Serializer>(&self, _: S) -> Result<S::Ok, S::Error> {
473 Err(serde::ser::Error::custom("invalid"))
474 }
475 }
476
477 let req = TestRequest::default().to_http_request();
478 let resp = respond_to(Json(Invalid), &req).await;
479 assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
480 }
481
482 #[crate::rt_test]
490 async fn test_extract() {
491 let (req, mut pl, ()) = TestRequest::default()
492 .header(
493 header::CONTENT_TYPE,
494 header::HeaderValue::from_static("application/json"),
495 )
496 .header(
497 header::CONTENT_LENGTH,
498 header::HeaderValue::from_static("16"),
499 )
500 .payload(Bytes::from_static(b"{\"name\": \"test\"}"))
501 .to_http_parts();
502
503 let s = from_request::<_, Json<MyObject>>(&(), &req, &mut pl)
504 .await
505 .unwrap();
506 assert_eq!(s.name, "test");
507 assert_eq!(
508 s.into_inner(),
509 MyObject {
510 name: "test".to_string()
511 }
512 );
513
514 let (req, mut pl, ()) = TestRequest::default()
515 .header(
516 header::CONTENT_TYPE,
517 header::HeaderValue::from_static("application/json"),
518 )
519 .header(
520 header::CONTENT_LENGTH,
521 header::HeaderValue::from_static("16"),
522 )
523 .payload(Bytes::from_static(b"{\"name\": \"test\"}"))
524 .app_value(JsonConfig::default().limit(10))
525 .to_http_parts();
526
527 let s = from_request::<_, Json<MyObject>>(&(), &req, &mut pl).await;
528 assert!(
529 format!("{}", s.err().unwrap()).contains("Json payload size is bigger than allowed")
530 );
531
532 let (req, mut pl, ()) = TestRequest::default()
533 .header(
534 header::CONTENT_TYPE,
535 header::HeaderValue::from_static("application/json"),
536 )
537 .header(
538 header::CONTENT_LENGTH,
539 header::HeaderValue::from_static("16"),
540 )
541 .payload(Bytes::from_static(b"--name-: -test--"))
542 .to_http_parts();
543 let s = from_request::<_, Json<serde_json::Value>>(&(), &req, &mut pl).await;
544 let err = s.err().unwrap();
545 assert!(format!("{err:?}").contains("Deserialize(JsonError("));
546 assert!(matches!(err, JsonPayloadError::Deserialize(ref e) if e.is_syntax()));
547 }
548
549 #[crate::rt_test]
556 async fn test_config_not_read_from_state() {
557 let req = || {
558 TestRequest::default()
559 .header(
560 header::CONTENT_TYPE,
561 header::HeaderValue::from_static("application/json"),
562 )
563 .header(
564 header::CONTENT_LENGTH,
565 header::HeaderValue::from_static("16"),
566 )
567 .payload(Bytes::from_static(b"{\"name\": \"test\"}"))
568 };
569
570 let (http_req, mut pl, st) = req()
571 .state(crate::web::AppState::new(JsonConfig::default().limit(10)))
572 .to_http_parts();
573 let s = from_request::<_, Json<MyObject>>(&st, &http_req, &mut pl).await;
574 assert_eq!(s.unwrap().name, "test");
575
576 #[allow(deprecated)]
577 let (http_req, mut pl, ()) = req()
578 .app_state(JsonConfig::default().limit(10))
579 .to_http_parts();
580 let s = from_request::<_, Json<MyObject>>(&(), &http_req, &mut pl).await;
581 assert!(
582 format!("{}", s.err().unwrap()).contains("Json payload size is bigger than allowed")
583 );
584 }
585
586 #[crate::rt_test]
593 async fn test_json_body() {
594 let (req, mut pl, ()) = TestRequest::default().to_http_parts();
595 let json = JsonBody::<MyObject>::new(&req, &mut pl, None).await;
596 assert!(json_eq(
597 &json.err().unwrap(),
598 &JsonPayloadError::ContentType
599 ));
600
601 let (req, mut pl, ()) = TestRequest::default()
602 .header(
603 header::CONTENT_TYPE,
604 header::HeaderValue::from_static("application/text"),
605 )
606 .to_http_parts();
607 let json = JsonBody::<MyObject>::new(&req, &mut pl, None).await;
608 assert!(json_eq(
609 &json.err().unwrap(),
610 &JsonPayloadError::ContentType
611 ));
612
613 let (req, mut pl, ()) = TestRequest::default()
614 .header(
615 header::CONTENT_TYPE,
616 header::HeaderValue::from_static("application/json"),
617 )
618 .header(
619 header::CONTENT_LENGTH,
620 header::HeaderValue::from_static("10000"),
621 )
622 .to_http_parts();
623
624 let json = JsonBody::<MyObject>::new(&req, &mut pl, None)
625 .limit(100)
626 .await;
627 assert!(json_eq(&json.err().unwrap(), &JsonPayloadError::Overflow));
628
629 let (req, mut pl, ()) = TestRequest::default()
630 .header(
631 header::CONTENT_TYPE,
632 header::HeaderValue::from_static("application/json"),
633 )
634 .header(
635 header::CONTENT_LENGTH,
636 header::HeaderValue::from_static("16"),
637 )
638 .payload(Bytes::from_static(b"{\"name\": \"test\"}"))
639 .to_http_parts();
640
641 let json = JsonBody::<MyObject>::new(&req, &mut pl, None).await;
642 assert_eq!(
643 json.ok().unwrap(),
644 MyObject {
645 name: "test".to_owned()
646 }
647 );
648
649 let (req, mut pl, ()) = TestRequest::default()
650 .header(
651 header::CONTENT_TYPE,
652 header::HeaderValue::from_static("application/json"),
653 )
654 .header(
655 header::CONTENT_LENGTH,
656 header::HeaderValue::from_static("16x"),
657 )
658 .payload(Bytes::from_static(b"{\"name\": \"test\"}"))
659 .to_http_parts();
660
661 let json = JsonBody::<MyObject>::new(&req, &mut pl, None).await;
662 assert!(matches!(
663 json.err().unwrap(),
664 JsonPayloadError::Payload(PayloadError::UnknownLength)
665 ));
666 }
667
668 #[crate::rt_test]
674 async fn test_with_json_and_bad_content_type() {
675 let (req, mut pl, ()) = TestRequest::with_header(
676 header::CONTENT_TYPE,
677 header::HeaderValue::from_static("text/plain"),
678 )
679 .header(
680 header::CONTENT_LENGTH,
681 header::HeaderValue::from_static("16"),
682 )
683 .payload(Bytes::from_static(b"{\"name\": \"test\"}"))
684 .app_value(JsonConfig::default().limit(4096))
685 .to_http_parts();
686
687 let s = from_request::<_, Json<MyObject>>(&(), &req, &mut pl).await;
688 assert!(s.is_err());
689 }
690
691 #[crate::rt_test]
697 async fn test_with_json_and_good_custom_content_type() {
698 let (req, mut pl, ()) = TestRequest::with_header(
699 header::CONTENT_TYPE,
700 header::HeaderValue::from_static("text/plain"),
701 )
702 .header(
703 header::CONTENT_LENGTH,
704 header::HeaderValue::from_static("16"),
705 )
706 .payload(Bytes::from_static(b"{\"name\": \"test\"}"))
707 .app_value(JsonConfig::default().content_type(|mime: mime::Mime| {
708 mime.type_() == mime::TEXT && mime.subtype() == mime::PLAIN
709 }))
710 .to_http_parts();
711
712 let s = from_request::<_, Json<MyObject>>(&(), &req, &mut pl).await;
713 assert!(s.is_ok());
714 }
715
716 #[crate::rt_test]
722 async fn test_with_json_and_bad_custom_content_type() {
723 let (req, mut pl, ()) = TestRequest::with_header(
724 header::CONTENT_TYPE,
725 header::HeaderValue::from_static("text/html"),
726 )
727 .header(
728 header::CONTENT_LENGTH,
729 header::HeaderValue::from_static("16"),
730 )
731 .payload(Bytes::from_static(b"{\"name\": \"test\"}"))
732 .app_value(JsonConfig::default().content_type(|mime: mime::Mime| {
733 mime.type_() == mime::TEXT && mime.subtype() == mime::PLAIN
734 }))
735 .to_http_parts();
736
737 let s = from_request::<_, Json<MyObject>>(&(), &req, &mut pl).await;
738 assert!(s.is_err());
739 }
740
741 #[crate::rt_test]
749 async fn test_content_type_predicate_replaces_default() {
750 async fn extract(
751 ctype: &'static str,
752 cfg: Option<JsonConfig>,
753 ) -> Result<(), JsonPayloadError> {
754 let mut req = TestRequest::with_header(
755 header::CONTENT_TYPE,
756 header::HeaderValue::from_static(ctype),
757 )
758 .header(
759 header::CONTENT_LENGTH,
760 header::HeaderValue::from_static("16"),
761 )
762 .payload(Bytes::from_static(b"{\"name\": \"test\"}"));
763 if let Some(cfg) = cfg {
764 req = req.app_value(cfg);
765 }
766 let (req, mut pl, ()) = req.to_http_parts();
767 from_request::<_, Json<MyObject>>(&(), &req, &mut pl)
768 .await
769 .map(|j| assert_eq!(j.name, "test"))
770 }
771
772 for ctype in ["application/json", "text/json", "application/vnd.api+json"] {
773 assert!(extract(ctype, None).await.is_ok(), "{ctype}");
774 }
775 assert!(matches!(
776 extract("text/plain", None).await,
777 Err(JsonPayloadError::ContentType)
778 ));
779
780 let only_vnd = || {
781 JsonConfig::default()
782 .content_type(|mime: mime::Mime| mime.essence_str() == "application/vnd.api+json")
783 };
784 assert!(
785 extract("application/vnd.api+json", Some(only_vnd()))
786 .await
787 .is_ok()
788 );
789 for ctype in ["application/json", "text/json", "text/plain"] {
790 assert!(
791 matches!(
792 extract(ctype, Some(only_vnd())).await,
793 Err(JsonPayloadError::ContentType)
794 ),
795 "{ctype}"
796 );
797 }
798 }
799}