From 91a75b0c586a22362cd20bfbc2f1b31f9dae3688 Mon Sep 17 00:00:00 2001 From: Sean McArthur Date: Fri, 19 Aug 2022 11:24:59 -0700 Subject: [PATCH] docs(examples): add a length check to reversed echo route --- examples/echo.rs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/examples/echo.rs b/examples/echo.rs index 097851795d..e3a2170061 100644 --- a/examples/echo.rs +++ b/examples/echo.rs @@ -2,6 +2,7 @@ use std::net::SocketAddr; +use hyper::body::HttpBody as _; use hyper::server::conn::Http; use hyper::service::service_fn; use hyper::{Body, Method, Request, Response, StatusCode}; @@ -38,6 +39,15 @@ async fn echo(req: Request) -> Result, hyper::Error> { // So here we do `.await` on the future, waiting on concatenating the full body, // then afterwards the content can be reversed. Only then can we return a `Response`. (&Method::POST, "/echo/reversed") => { + // To protect our server, reject requests with bodies larger than + // 64kbs of data. + let max = req.body().size_hint().upper().unwrap_or(u64::MAX); + if max > 1024 * 64 { + let mut resp = Response::new(Body::from("Body too big")); + *resp.status_mut() = hyper::StatusCode::PAYLOAD_TOO_LARGE; + return Ok(resp); + } + let whole_body = hyper::body::to_bytes(req.into_body()).await?; let reversed_body = whole_body.iter().rev().cloned().collect::>();