1use std::{
2 collections::HashMap,
3 convert::Infallible,
4 future::Future,
5 net::SocketAddr,
6 ops::{Deref, DerefMut},
7 panic::{AssertUnwindSafe, catch_unwind},
8 pin::Pin,
9 sync::{Arc, Mutex},
10 task::{Context, Poll},
11 time::Duration,
12};
13
14pub use bytes::Bytes;
15use futures_util::{Stream, StreamExt};
16pub use http::{
17 Extensions, HeaderMap, HeaderName, HeaderValue, Method, StatusCode, Uri, Version, header,
18};
19pub use mime::Mime;
20use percent_encoding::{NON_ALPHANUMERIC, utf8_percent_encode};
21use serde::{Serialize, de::DeserializeOwned};
22use thiserror::Error;
23#[doc(hidden)]
24pub use tokio_util::sync::CancellationToken as ResponseCancellationToken;
25
26mod upgrade;
27#[cfg(feature = "sse")]
28mod sse;
29#[cfg(feature = "websocket")]
30mod ws;
31
32pub use upgrade::ConnectionUpgrade;
33#[cfg(feature = "sse")]
34pub use sse::{
35 InvalidSseField, KeepAlive, LastEventId, LastEventIdRejection, Sse, SseConfigError, SseEvent,
36};
37#[cfg(feature = "websocket")]
38pub use ws::{
39 CloseCode, CloseFrame, Message, WebSocket, WebSocketConfigError, WebSocketError,
40 WebSocketUpgrade, WebSocketUpgradeRejection,
41};
42
43pub type BoxFuture<T> = Pin<Box<dyn Future<Output = T> + Send + 'static>>;
44
45#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
47pub enum TransportScheme {
48 #[default]
49 Http,
50 Https,
51}
52
53impl TransportScheme {
54 #[must_use]
55 pub const fn as_str(self) -> &'static str {
56 match self {
57 Self::Http => "http",
58 Self::Https => "https",
59 }
60 }
61
62 #[must_use]
63 pub const fn is_secure(self) -> bool {
64 matches!(self, Self::Https)
65 }
66}
67
68#[derive(Clone, Debug, Eq, PartialEq)]
70pub struct ConnectionInfo {
71 peer_addr: Option<SocketAddr>,
72 scheme: TransportScheme,
73 alpn_protocol: Option<String>,
74}
75
76#[derive(Clone, Eq, PartialEq)]
78pub struct CspNonce(String);
79
80impl CspNonce {
81 pub fn new(value: impl Into<String>) -> Result<Self, InvalidCspNonce> {
87 let value = value.into();
88 if !(16..=128).contains(&value.len())
89 || !value.bytes().all(|byte| {
90 byte.is_ascii_alphanumeric() || matches!(byte, b'+' | b'/' | b'_' | b'-' | b'=')
91 })
92 {
93 return Err(InvalidCspNonce);
94 }
95 Ok(Self(value))
96 }
97
98 #[must_use]
99 pub fn as_str(&self) -> &str {
100 &self.0
101 }
102}
103
104impl std::fmt::Debug for CspNonce {
105 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
106 formatter
107 .debug_tuple("CspNonce")
108 .field(&"[REDACTED]")
109 .finish()
110 }
111}
112
113#[derive(Clone, Copy, Debug, thiserror::Error)]
114#[error("CSP nonce is invalid")]
115pub struct InvalidCspNonce;
116
117impl ConnectionInfo {
118 #[must_use]
119 pub const fn new(
120 peer_addr: Option<SocketAddr>,
121 scheme: TransportScheme,
122 alpn_protocol: Option<String>,
123 ) -> Self {
124 Self {
125 peer_addr,
126 scheme,
127 alpn_protocol,
128 }
129 }
130
131 #[must_use]
132 pub const fn peer_addr(&self) -> Option<SocketAddr> {
133 self.peer_addr
134 }
135
136 #[must_use]
137 pub const fn scheme(&self) -> TransportScheme {
138 self.scheme
139 }
140
141 #[must_use]
142 pub fn alpn_protocol(&self) -> Option<&str> {
143 self.alpn_protocol.as_deref()
144 }
145
146 #[must_use]
147 pub const fn is_secure(&self) -> bool {
148 self.scheme.is_secure()
149 }
150}
151
152#[derive(Clone, Debug, Default)]
153pub struct RouteManifest(Arc<HashMap<String, String>>);
154
155impl RouteManifest {
156 #[must_use]
157 pub fn new(routes: Arc<HashMap<String, String>>) -> Self {
158 Self(routes)
159 }
160
161 #[must_use]
162 pub fn routes(&self) -> &HashMap<String, String> {
163 &self.0
164 }
165}
166
167#[derive(Clone)]
173pub struct ResponseContext {
174 uri: Uri,
175 page_request: bool,
176 csp_nonce: Option<CspNonce>,
177 route_manifest: Option<RouteManifest>,
178}
179
180impl ResponseContext {
181 #[must_use]
182 pub fn from_request(request: &Request) -> Self {
183 Self {
184 uri: request.uri().clone(),
185 page_request: request
186 .headers()
187 .get("x-phoenix-page")
188 .is_some_and(|value| value == "1"),
189 csp_nonce: request.extensions().get::<CspNonce>().cloned(),
190 route_manifest: request.extensions().get::<RouteManifest>().cloned(),
191 }
192 }
193
194 #[must_use]
195 pub const fn uri(&self) -> &Uri {
196 &self.uri
197 }
198
199 #[must_use]
200 pub const fn is_page_request(&self) -> bool {
201 self.page_request
202 }
203
204 #[must_use]
205 pub const fn csp_nonce(&self) -> Option<&CspNonce> {
206 self.csp_nonce.as_ref()
207 }
208
209 #[must_use]
210 pub const fn route_manifest(&self) -> Option<&RouteManifest> {
211 self.route_manifest.as_ref()
212 }
213}
214
215impl std::fmt::Debug for ResponseContext {
216 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
217 formatter
218 .debug_struct("ResponseContext")
219 .field("path", &self.uri.path())
220 .field("page_request", &self.page_request)
221 .field("has_csp_nonce", &self.csp_nonce.is_some())
222 .field("has_route_manifest", &self.route_manifest.is_some())
223 .finish_non_exhaustive()
224 }
225}
226
227#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
229pub enum RequestBodyMode {
230 #[default]
232 Buffered,
233 Streaming,
235}
236
237pub struct RequestBodyStream {
239 inner: Pin<Box<dyn Stream<Item = Result<Bytes, RequestBodyError>> + Send + 'static>>,
240}
241
242impl RequestBodyStream {
243 #[doc(hidden)]
244 #[must_use]
245 pub fn new<S>(stream: S) -> Self
246 where
247 S: Stream<Item = Result<Bytes, RequestBodyError>> + Send + 'static,
248 {
249 Self {
250 inner: Box::pin(stream),
251 }
252 }
253
254 pub async fn next_chunk(&mut self) -> Option<Result<Bytes, RequestBodyError>> {
257 self.next().await
258 }
259
260 pub async fn into_bytes(mut self) -> Result<Bytes, RequestBodyError> {
266 let mut output = Vec::new();
267 while let Some(chunk) = self.next().await {
268 output.extend_from_slice(&chunk?);
269 }
270 Ok(Bytes::from(output))
271 }
272}
273
274impl Stream for RequestBodyStream {
275 type Item = Result<Bytes, RequestBodyError>;
276
277 fn poll_next(mut self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Option<Self::Item>> {
278 self.inner.as_mut().poll_next(context)
279 }
280}
281
282impl std::fmt::Debug for RequestBodyStream {
283 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
284 formatter.write_str("RequestBodyStream(<body>)")
285 }
286}
287
288#[derive(Clone, Copy, Debug, Error, Eq, PartialEq)]
289pub enum RequestBodyError {
290 #[error("The request body exceeds the configured size limit.")]
291 TooLarge,
292 #[error("The request body exceeded its {0:?} deadline.")]
293 Timeout(Duration),
294 #[error("The request body transport failed.")]
295 Transport,
296}
297
298#[derive(Clone, Copy, Debug, Error, Eq, PartialEq)]
299#[error("A streaming request body is unavailable or has already been consumed.")]
300pub struct RequestBodyStreamRejection;
301
302#[derive(Debug)]
303pub struct Request {
304 method: Method,
305 uri: Uri,
306 version: Version,
307 headers: HeaderMap,
308 body: Bytes,
309 params: Vec<(String, String)>,
310 route_name: Option<String>,
311 extensions: Extensions,
312 body_stream: Option<Arc<Mutex<Option<RequestBodyStream>>>>,
313}
314
315impl Request {
316 #[must_use]
317 pub fn new(method: Method, uri: Uri) -> Self {
318 Self {
319 method,
320 uri,
321 version: Version::HTTP_11,
322 headers: HeaderMap::new(),
323 body: Bytes::new(),
324 params: Vec::new(),
325 route_name: None,
326 extensions: Extensions::new(),
327 body_stream: None,
328 }
329 }
330
331 #[must_use]
332 pub fn from_parts(method: Method, uri: Uri, headers: HeaderMap, body: Bytes) -> Self {
333 Self {
334 method,
335 uri,
336 version: Version::HTTP_11,
337 headers,
338 body,
339 params: Vec::new(),
340 route_name: None,
341 extensions: Extensions::new(),
342 body_stream: None,
343 }
344 }
345
346 #[doc(hidden)]
347 #[must_use]
348 pub fn from_server_parts(
349 method: Method,
350 uri: Uri,
351 version: Version,
352 headers: HeaderMap,
353 extensions: Extensions,
354 body: Bytes,
355 ) -> Self {
356 Self {
357 method,
358 uri,
359 version,
360 headers,
361 body,
362 params: Vec::new(),
363 route_name: None,
364 extensions,
365 body_stream: None,
366 }
367 }
368
369 #[must_use]
370 pub fn method(&self) -> &Method {
371 &self.method
372 }
373
374 #[must_use]
375 pub fn uri(&self) -> &Uri {
376 &self.uri
377 }
378
379 #[must_use]
380 pub const fn version(&self) -> Version {
381 self.version
382 }
383
384 #[must_use]
385 pub fn headers(&self) -> &HeaderMap {
386 &self.headers
387 }
388
389 pub fn headers_mut(&mut self) -> &mut HeaderMap {
390 &mut self.headers
391 }
392
393 #[must_use]
394 pub fn body(&self) -> &Bytes {
399 &self.body
400 }
401
402 #[must_use]
403 pub const fn is_body_streaming(&self) -> bool {
404 self.body_stream.is_some()
405 }
406
407 pub fn take_body_stream(&self) -> Result<RequestBodyStream, RequestBodyStreamRejection> {
413 let body = self
414 .body_stream
415 .as_ref()
416 .ok_or(RequestBodyStreamRejection)?;
417 body.lock()
418 .map_err(|_| RequestBodyStreamRejection)?
419 .take()
420 .ok_or(RequestBodyStreamRejection)
421 }
422
423 pub fn json<T: DeserializeOwned>(&self) -> Result<T, JsonRejection> {
430 if self.is_body_streaming() {
431 return Err(JsonRejection::StreamingBody);
432 }
433 let content_type = self
434 .headers
435 .get(header::CONTENT_TYPE)
436 .ok_or(JsonRejection::MissingContentType)?
437 .to_str()
438 .map_err(|_| JsonRejection::UnsupportedContentType)?
439 .parse::<mime::Mime>()
440 .map_err(|_| JsonRejection::UnsupportedContentType)?;
441
442 let is_json = content_type.type_() == mime::APPLICATION
443 && (content_type.subtype() == mime::JSON || content_type.suffix() == Some(mime::JSON));
444 if !is_json {
445 return Err(JsonRejection::UnsupportedContentType);
446 }
447
448 serde_json::from_slice(&self.body).map_err(JsonRejection::InvalidJson)
449 }
450
451 #[must_use]
452 pub fn param(&self, name: &str) -> Option<&str> {
453 self.params
454 .iter()
455 .find_map(|(key, value)| (key == name).then_some(value.as_str()))
456 }
457
458 #[must_use]
459 pub fn route_name(&self) -> Option<&str> {
460 self.route_name.as_deref()
461 }
462
463 #[must_use]
464 pub fn extensions(&self) -> &Extensions {
465 &self.extensions
466 }
467
468 pub fn extensions_mut(&mut self) -> &mut Extensions {
469 &mut self.extensions
470 }
471
472 #[doc(hidden)]
473 pub fn set_route(&mut self, name: Option<String>, params: Vec<(String, String)>) {
474 self.route_name = name;
475 self.params = params;
476 }
477
478 #[doc(hidden)]
479 pub fn set_buffered_body(&mut self, body: Bytes) {
480 self.body = body;
481 self.body_stream = None;
482 }
483
484 #[doc(hidden)]
485 pub fn set_streaming_body(&mut self, body: RequestBodyStream) {
486 self.body = Bytes::new();
487 self.body_stream = Some(Arc::new(Mutex::new(Some(body))));
488 }
489}
490
491#[derive(Debug, Error)]
492pub enum JsonRejection {
493 #[error("JSON extraction cannot read a streaming request body.")]
494 StreamingBody,
495 #[error("The Content-Type header must be application/json.")]
496 MissingContentType,
497 #[error("The Content-Type header must be application/json.")]
498 UnsupportedContentType,
499 #[error("The request body contains invalid JSON.")]
500 InvalidJson(#[source] serde_json::Error),
501}
502
503impl JsonRejection {
504 #[must_use]
505 pub const fn status(&self) -> StatusCode {
506 match self {
507 Self::StreamingBody => StatusCode::INTERNAL_SERVER_ERROR,
508 Self::MissingContentType | Self::UnsupportedContentType => {
509 StatusCode::UNSUPPORTED_MEDIA_TYPE
510 }
511 Self::InvalidJson(_) => StatusCode::BAD_REQUEST,
512 }
513 }
514}
515
516pub trait FromRequest: Sized + Send + 'static {
517 type Rejection: IntoResponse + Send + 'static;
518
519 fn from_request(request: &Request) -> Result<Self, Self::Rejection>;
529}
530
531impl FromRequest for RequestBodyStream {
532 type Rejection = RequestBodyStreamRejection;
533
534 fn from_request(request: &Request) -> Result<Self, Self::Rejection> {
535 request.take_body_stream()
536 }
537}
538
539#[derive(Clone, Debug, PartialEq, Eq)]
540pub struct Query<T>(pub T);
541
542#[derive(Clone, Debug, PartialEq, Eq)]
543pub struct Path<T>(pub T);
544
545#[derive(Clone, Debug, PartialEq, Eq)]
546pub struct Header<T>(pub T);
547
548#[derive(Clone, Debug, PartialEq, Eq)]
549pub struct Form<T>(pub T);
550
551#[derive(Clone, Debug)]
553pub struct State<T>(pub T);
554
555macro_rules! extractor_deref {
556 ($extractor:ident) => {
557 impl<T> Deref for $extractor<T> {
558 type Target = T;
559
560 fn deref(&self) -> &Self::Target {
561 &self.0
562 }
563 }
564
565 impl<T> DerefMut for $extractor<T> {
566 fn deref_mut(&mut self) -> &mut Self::Target {
567 &mut self.0
568 }
569 }
570 };
571}
572
573extractor_deref!(Query);
574extractor_deref!(Path);
575extractor_deref!(Header);
576extractor_deref!(Form);
577extractor_deref!(Json);
578extractor_deref!(State);
579
580#[derive(Clone, Copy, Debug, Error)]
581#[error("Required application state is unavailable.")]
582pub struct StateRejection;
583
584impl<T> FromRequest for State<T>
585where
586 T: Clone + Send + Sync + 'static,
587{
588 type Rejection = StateRejection;
589
590 fn from_request(request: &Request) -> Result<Self, Self::Rejection> {
591 request
592 .extensions()
593 .get::<T>()
594 .cloned()
595 .map(Self)
596 .ok_or(StateRejection)
597 }
598}
599
600#[derive(Debug, Error)]
601#[error("The query string is invalid.")]
602pub struct QueryRejection(#[source] serde_urlencoded::de::Error);
603
604#[derive(Debug, Error)]
605#[error("The route parameters are invalid.")]
606pub struct PathRejection(#[source] StringMapRejection);
607
608#[derive(Debug, Error)]
609pub enum HeaderRejection {
610 #[error("A request header contains invalid text.")]
611 InvalidValue,
612 #[error("The request headers are invalid.")]
613 InvalidData(#[source] StringMapRejection),
614}
615
616#[derive(Debug, Error)]
617pub enum StringMapRejection {
618 #[error("could not encode string fields")]
619 Encode(#[source] serde_urlencoded::ser::Error),
620 #[error("could not decode string fields")]
621 Decode(#[source] serde_urlencoded::de::Error),
622}
623
624#[derive(Debug, Error)]
625pub enum FormRejection {
626 #[error("Form extraction cannot read a streaming request body.")]
627 StreamingBody,
628 #[error("The Content-Type header must be application/x-www-form-urlencoded.")]
629 MissingContentType,
630 #[error("The Content-Type header must be application/x-www-form-urlencoded.")]
631 UnsupportedContentType,
632 #[error("The form body is invalid.")]
633 InvalidForm(#[source] serde_urlencoded::de::Error),
634}
635
636impl<T> FromRequest for Query<T>
637where
638 T: DeserializeOwned + Send + 'static,
639{
640 type Rejection = QueryRejection;
641
642 fn from_request(request: &Request) -> Result<Self, Self::Rejection> {
643 serde_urlencoded::from_str(request.uri().query().unwrap_or_default())
644 .map(Self)
645 .map_err(QueryRejection)
646 }
647}
648
649impl<T> FromRequest for Path<T>
650where
651 T: DeserializeOwned + Send + 'static,
652{
653 type Rejection = PathRejection;
654
655 fn from_request(request: &Request) -> Result<Self, Self::Rejection> {
656 deserialize_string_pairs(request.params.iter().cloned())
657 .map(Self)
658 .map_err(PathRejection)
659 }
660}
661
662impl<T> FromRequest for Header<T>
663where
664 T: DeserializeOwned + Send + 'static,
665{
666 type Rejection = HeaderRejection;
667
668 fn from_request(request: &Request) -> Result<Self, Self::Rejection> {
669 let pairs = request
670 .headers()
671 .iter()
672 .map(|(name, header)| {
673 header
674 .to_str()
675 .map(|value| (name.as_str().to_owned(), value.to_owned()))
676 .map_err(|_| HeaderRejection::InvalidValue)
677 })
678 .collect::<Result<Vec<_>, _>>()?;
679 deserialize_string_pairs(pairs)
680 .map(Self)
681 .map_err(HeaderRejection::InvalidData)
682 }
683}
684
685impl<T> FromRequest for Json<T>
686where
687 T: DeserializeOwned + Send + 'static,
688{
689 type Rejection = JsonRejection;
690
691 fn from_request(request: &Request) -> Result<Self, Self::Rejection> {
692 request.json().map(Self)
693 }
694}
695
696impl<T> FromRequest for Form<T>
697where
698 T: DeserializeOwned + Send + 'static,
699{
700 type Rejection = FormRejection;
701
702 fn from_request(request: &Request) -> Result<Self, Self::Rejection> {
703 if request.is_body_streaming() {
704 return Err(FormRejection::StreamingBody);
705 }
706 let content_type = request
707 .headers()
708 .get(header::CONTENT_TYPE)
709 .ok_or(FormRejection::MissingContentType)?
710 .to_str()
711 .map_err(|_| FormRejection::UnsupportedContentType)?
712 .parse::<mime::Mime>()
713 .map_err(|_| FormRejection::UnsupportedContentType)?;
714 if content_type.type_() != mime::APPLICATION
715 || content_type.subtype().as_str() != "x-www-form-urlencoded"
716 {
717 return Err(FormRejection::UnsupportedContentType);
718 }
719 serde_urlencoded::from_bytes(request.body())
720 .map(Self)
721 .map_err(FormRejection::InvalidForm)
722 }
723}
724
725fn deserialize_string_pairs<T>(
726 pairs: impl IntoIterator<Item = (String, String)>,
727) -> Result<T, StringMapRejection>
728where
729 T: DeserializeOwned,
730{
731 let fields: HashMap<String, String> = pairs.into_iter().collect();
732 let encoded = serde_urlencoded::to_string(fields).map_err(StringMapRejection::Encode)?;
733 serde_urlencoded::from_str(&encoded).map_err(StringMapRejection::Decode)
734}
735
736#[derive(Clone, Debug, PartialEq, Eq)]
737pub struct Multipart<T = MultipartData>(pub T);
738
739impl<T> Deref for Multipart<T> {
740 type Target = T;
741
742 fn deref(&self) -> &Self::Target {
743 &self.0
744 }
745}
746
747impl<T> DerefMut for Multipart<T> {
748 fn deref_mut(&mut self) -> &mut Self::Target {
749 &mut self.0
750 }
751}
752
753pub trait FromMultipart: Sized + Send + 'static {
754 fn from_multipart(multipart: MultipartData) -> Result<Self, MultipartRejection>;
761}
762
763#[derive(Clone, Debug, PartialEq, Eq)]
764pub struct MultipartData {
765 fields: Vec<MultipartField>,
766}
767
768impl MultipartData {
769 #[must_use]
770 pub fn field(&self, name: &str) -> Option<&MultipartField> {
771 self.fields.iter().find(|field| field.name == name)
772 }
773
774 pub fn fields(&self, name: &str) -> impl Iterator<Item = &MultipartField> {
775 self.fields.iter().filter(move |field| field.name == name)
776 }
777
778 #[must_use]
779 pub fn all(&self) -> &[MultipartField] {
780 &self.fields
781 }
782
783 pub fn remove(&mut self, name: &str) -> Option<MultipartField> {
784 let index = self.fields.iter().position(|field| field.name == name)?;
785 Some(self.fields.remove(index))
786 }
787
788 #[must_use]
789 pub fn into_fields(self) -> Vec<MultipartField> {
790 self.fields
791 }
792}
793
794impl FromMultipart for MultipartData {
795 fn from_multipart(multipart: Self) -> Result<Self, MultipartRejection> {
796 Ok(multipart)
797 }
798}
799
800#[derive(Clone, Debug, PartialEq, Eq)]
801pub struct MultipartField {
802 name: String,
803 file_name: Option<String>,
804 content_type: Option<String>,
805 data: Bytes,
806}
807
808impl MultipartField {
809 #[must_use]
810 pub fn name(&self) -> &str {
811 &self.name
812 }
813
814 #[must_use]
815 pub fn file_name(&self) -> Option<&str> {
816 self.file_name.as_deref()
817 }
818
819 #[must_use]
820 pub fn content_type(&self) -> Option<&str> {
821 self.content_type.as_deref()
822 }
823
824 #[must_use]
825 pub fn bytes(&self) -> &Bytes {
826 &self.data
827 }
828
829 pub fn text(&self) -> Result<&str, std::str::Utf8Error> {
835 std::str::from_utf8(&self.data)
836 }
837}
838
839#[derive(Debug, Error)]
840pub enum MultipartRejection {
841 #[error("Multipart extraction cannot read a streaming request body.")]
842 StreamingBody,
843 #[error("The Content-Type header must be multipart/form-data.")]
844 MissingContentType,
845 #[error("The Content-Type header must be multipart/form-data with a boundary.")]
846 UnsupportedContentType,
847 #[error("The multipart body is invalid.")]
848 InvalidBody,
849 #[error("The multipart field {0} is invalid or missing.")]
850 InvalidField(String),
851}
852
853impl<T> FromRequest for Multipart<T>
854where
855 T: FromMultipart,
856{
857 type Rejection = MultipartRejection;
858
859 fn from_request(request: &Request) -> Result<Self, Self::Rejection> {
860 if request.is_body_streaming() {
861 return Err(MultipartRejection::StreamingBody);
862 }
863 let content_type = request
864 .headers()
865 .get(header::CONTENT_TYPE)
866 .ok_or(MultipartRejection::MissingContentType)?
867 .to_str()
868 .map_err(|_| MultipartRejection::UnsupportedContentType)?
869 .parse::<mime::Mime>()
870 .map_err(|_| MultipartRejection::UnsupportedContentType)?;
871 if content_type.type_() != mime::MULTIPART || content_type.subtype().as_str() != "form-data"
872 {
873 return Err(MultipartRejection::UnsupportedContentType);
874 }
875 let boundary = content_type
876 .get_param("boundary")
877 .map(|name| name.as_str().to_owned())
878 .filter(|boundary| !boundary.is_empty() && boundary.len() <= 70)
879 .ok_or(MultipartRejection::UnsupportedContentType)?;
880 let fields = parse_multipart(request.body(), &boundary)?;
881 T::from_multipart(MultipartData { fields }).map(Self)
882 }
883}
884
885fn parse_multipart(body: &[u8], boundary: &str) -> Result<Vec<MultipartField>, MultipartRejection> {
886 let delimiter = format!("--{boundary}").into_bytes();
887 if !body.starts_with(&delimiter) {
888 return Err(MultipartRejection::InvalidBody);
889 }
890
891 let mut fields = Vec::new();
892 let mut cursor = delimiter.len();
893 loop {
894 if body.get(cursor..cursor + 2) == Some(b"--") {
895 cursor += 2;
896 if body
897 .get(cursor..)
898 .is_some_and(|tail| tail.is_empty() || tail == b"\r\n")
899 {
900 return Ok(fields);
901 }
902 return Err(MultipartRejection::InvalidBody);
903 }
904 if body.get(cursor..cursor + 2) != Some(b"\r\n") {
905 return Err(MultipartRejection::InvalidBody);
906 }
907 cursor += 2;
908
909 let header_end = find_bytes(&body[cursor..], b"\r\n\r\n")
910 .map(|index| cursor + index)
911 .ok_or(MultipartRejection::InvalidBody)?;
912 let headers = std::str::from_utf8(&body[cursor..header_end])
913 .map_err(|_| MultipartRejection::InvalidBody)?;
914 let data_start = header_end + 4;
915 let mut marker = b"\r\n".to_vec();
916 marker.extend_from_slice(&delimiter);
917 let data_end = find_bytes(&body[data_start..], &marker)
918 .map(|index| data_start + index)
919 .ok_or(MultipartRejection::InvalidBody)?;
920
921 let (name, file_name, content_type) = parse_multipart_headers(headers)?;
922 fields.push(MultipartField {
923 name,
924 file_name,
925 content_type,
926 data: Bytes::copy_from_slice(&body[data_start..data_end]),
927 });
928 cursor = data_end + marker.len();
929 }
930}
931
932fn parse_multipart_headers(
933 headers: &str,
934) -> Result<(String, Option<String>, Option<String>), MultipartRejection> {
935 let mut disposition = None;
936 let mut content_type = None;
937 for line in headers.split("\r\n") {
938 let (name, value) = line
939 .split_once(':')
940 .ok_or(MultipartRejection::InvalidBody)?;
941 match name.trim().to_ascii_lowercase().as_str() {
942 "content-disposition" => disposition = Some(value.trim()),
943 "content-type" => {
944 value
945 .trim()
946 .parse::<mime::Mime>()
947 .map_err(|_| MultipartRejection::InvalidBody)?;
948 content_type = Some(value.trim().to_owned());
949 }
950 _ => {}
951 }
952 }
953
954 let disposition = disposition.ok_or(MultipartRejection::InvalidBody)?;
955 let parts = split_quoted(disposition, ';')?;
956 if parts.first().map(|part| part.trim()) != Some("form-data") {
957 return Err(MultipartRejection::InvalidBody);
958 }
959 let mut name = None;
960 let mut file_name = None;
961 for part in parts.iter().skip(1) {
962 let (key, value) = part
963 .split_once('=')
964 .ok_or(MultipartRejection::InvalidBody)?;
965 let value = unquote_parameter(value.trim())?;
966 match key.trim() {
967 "name" => name = Some(value),
968 "filename" => file_name = Some(value),
969 _ => {}
970 }
971 }
972 Ok((
973 name.filter(|value| !value.is_empty())
974 .ok_or(MultipartRejection::InvalidBody)?,
975 file_name,
976 content_type,
977 ))
978}
979
980fn split_quoted(value: &str, separator: char) -> Result<Vec<&str>, MultipartRejection> {
981 let mut parts = Vec::new();
982 let mut start = 0;
983 let mut quoted = false;
984 let mut escaped = false;
985 for (index, character) in value.char_indices() {
986 if escaped {
987 escaped = false;
988 } else if character == '\\' && quoted {
989 escaped = true;
990 } else if character == '"' {
991 quoted = !quoted;
992 } else if character == separator && !quoted {
993 parts.push(&value[start..index]);
994 start = index + character.len_utf8();
995 }
996 }
997 if quoted || escaped {
998 return Err(MultipartRejection::InvalidBody);
999 }
1000 parts.push(&value[start..]);
1001 Ok(parts)
1002}
1003
1004fn unquote_parameter(value: &str) -> Result<String, MultipartRejection> {
1005 if let Some(value) = value
1006 .strip_prefix('"')
1007 .and_then(|value| value.strip_suffix('"'))
1008 {
1009 let mut output = String::with_capacity(value.len());
1010 let mut escaped = false;
1011 for character in value.chars() {
1012 if escaped {
1013 if character != '"' && character != '\\' {
1014 return Err(MultipartRejection::InvalidBody);
1015 }
1016 output.push(character);
1017 escaped = false;
1018 } else if character == '\\' {
1019 escaped = true;
1020 } else {
1021 output.push(character);
1022 }
1023 }
1024 if escaped {
1025 return Err(MultipartRejection::InvalidBody);
1026 }
1027 Ok(output)
1028 } else if value.bytes().all(|byte| byte.is_ascii_graphic()) {
1029 Ok(value.to_owned())
1030 } else {
1031 Err(MultipartRejection::InvalidBody)
1032 }
1033}
1034
1035fn find_bytes(haystack: &[u8], needle: &[u8]) -> Option<usize> {
1036 (!needle.is_empty())
1037 .then(|| {
1038 haystack
1039 .windows(needle.len())
1040 .position(|window| window == needle)
1041 })
1042 .flatten()
1043}
1044
1045#[derive(Clone, Copy, Debug, Error, Eq, PartialEq)]
1047#[error("response body stream failed")]
1048pub struct ResponseBodyError;
1049
1050pub type ByteStream =
1051 Pin<Box<dyn Stream<Item = Result<Bytes, ResponseBodyError>> + Send + 'static>>;
1052
1053#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1055pub enum ResponseBodyOutcome {
1056 Complete,
1057 StreamError,
1058 DeliveryCancelled,
1061 Shutdown,
1062 Aborted,
1063}
1064
1065impl ResponseBodyOutcome {
1066 #[must_use]
1067 pub const fn as_str(self) -> &'static str {
1068 match self {
1069 Self::Complete => "complete",
1070 Self::StreamError => "stream_error",
1071 Self::DeliveryCancelled => "delivery_cancelled",
1072 Self::Shutdown => "shutdown",
1073 Self::Aborted => "aborted",
1074 }
1075 }
1076}
1077
1078#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1080pub struct ResponseBodySummary {
1081 outcome: ResponseBodyOutcome,
1082 bytes_yielded: u64,
1083}
1084
1085impl ResponseBodySummary {
1086 const fn new(outcome: ResponseBodyOutcome, bytes_yielded: u64) -> Self {
1087 Self {
1088 outcome,
1089 bytes_yielded,
1090 }
1091 }
1092
1093 #[must_use]
1094 pub const fn outcome(self) -> ResponseBodyOutcome {
1095 self.outcome
1096 }
1097
1098 #[must_use]
1101 pub const fn bytes_yielded(self) -> u64 {
1102 self.bytes_yielded
1103 }
1104}
1105
1106type BodyObserver = Box<dyn FnOnce(ResponseBodySummary) + Send + 'static>;
1107
1108pub enum ResponseBody {
1109 Buffered(Bytes),
1110 Stream(ByteStream),
1111}
1112
1113impl std::fmt::Debug for ResponseBody {
1114 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1115 match self {
1116 Self::Buffered(bytes) => formatter
1117 .debug_tuple("Buffered")
1118 .field(&bytes.len())
1119 .finish(),
1120 Self::Stream(_) => formatter.write_str("Stream(<body>)"),
1121 }
1122 }
1123}
1124
1125pub struct Response {
1126 status: StatusCode,
1127 headers: HeaderMap,
1128 body: Option<ResponseBody>,
1129 body_observers: Vec<BodyObserver>,
1130}
1131
1132impl std::fmt::Debug for Response {
1133 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1134 formatter
1135 .debug_struct("Response")
1136 .field("status", &self.status)
1137 .field("headers", &self.headers)
1138 .field("body", &self.body)
1139 .field("body_observers", &self.body_observers.len())
1140 .finish()
1141 }
1142}
1143
1144impl Response {
1145 #[must_use]
1146 pub fn new(status: StatusCode, body: impl Into<Bytes>) -> Self {
1147 Self {
1148 status,
1149 headers: HeaderMap::new(),
1150 body: Some(ResponseBody::Buffered(body.into())),
1151 body_observers: Vec::new(),
1152 }
1153 }
1154
1155 #[must_use]
1156 pub fn stream<S>(stream: S) -> Self
1157 where
1158 S: Stream<Item = Bytes> + Send + 'static,
1159 {
1160 Self {
1161 status: StatusCode::OK,
1162 headers: HeaderMap::new(),
1163 body: Some(ResponseBody::Stream(Box::pin(
1164 stream.map(Ok::<_, ResponseBodyError>),
1165 ))),
1166 body_observers: Vec::new(),
1167 }
1168 }
1169
1170 #[must_use]
1176 pub fn try_stream<S, E>(stream: S) -> Self
1177 where
1178 S: Stream<Item = Result<Bytes, E>> + Send + 'static,
1179 E: Send + 'static,
1180 {
1181 Self {
1182 status: StatusCode::OK,
1183 headers: HeaderMap::new(),
1184 body: Some(ResponseBody::Stream(Box::pin(
1185 stream.map(|item| item.map_err(|_| ResponseBodyError)),
1186 ))),
1187 body_observers: Vec::new(),
1188 }
1189 }
1190
1191 #[must_use]
1192 pub fn text(body: impl Into<Bytes>) -> Self {
1193 let mut response = Self::new(StatusCode::OK, body);
1194 response.headers.insert(
1195 http::header::CONTENT_TYPE,
1196 HeaderValue::from_static("text/plain; charset=utf-8"),
1197 );
1198 response
1199 }
1200
1201 fn json<T: Serialize>(value: &T) -> Result<Self, serde_json::Error> {
1202 let mut response = Self::new(StatusCode::OK, serde_json::to_vec(value)?);
1203 response.headers.insert(
1204 http::header::CONTENT_TYPE,
1205 HeaderValue::from_static("application/json"),
1206 );
1207 Ok(response)
1208 }
1209
1210 #[must_use]
1211 pub fn status(&self) -> StatusCode {
1212 self.status
1213 }
1214
1215 #[must_use]
1216 pub fn headers(&self) -> &HeaderMap {
1217 &self.headers
1218 }
1219
1220 pub fn headers_mut(&mut self) -> &mut HeaderMap {
1221 &mut self.headers
1222 }
1223
1224 #[must_use]
1231 pub fn body(&self) -> &Bytes {
1232 match self.body.as_ref().expect("response body is available") {
1233 ResponseBody::Buffered(body) => body,
1234 ResponseBody::Stream(_) => panic!("streaming response bodies are not buffered"),
1235 }
1236 }
1237
1238 #[must_use]
1239 pub const fn is_streaming(&self) -> bool {
1240 matches!(&self.body, Some(ResponseBody::Stream(_)))
1241 }
1242
1243 #[must_use]
1244 pub fn with_status(mut self, status: StatusCode) -> Self {
1245 self.status = status;
1246 self
1247 }
1248
1249 pub fn with_header(
1256 mut self,
1257 name: impl TryInto<HeaderName>,
1258 value: impl TryInto<HeaderValue>,
1259 ) -> Result<Self, InvalidHeader> {
1260 let name = name.try_into().map_err(|_| InvalidHeader)?;
1261 let value = value.try_into().map_err(|_| InvalidHeader)?;
1262 self.headers.insert(name, value);
1263 Ok(self)
1264 }
1265
1266 #[doc(hidden)]
1268 pub fn on_body_finish<F>(&mut self, observer: F)
1269 where
1270 F: FnOnce(ResponseBodySummary) + Send + 'static,
1271 {
1272 match self.body.as_ref().expect("response body is available") {
1273 ResponseBody::Buffered(body) => notify_body_observer(
1274 Box::new(observer),
1275 ResponseBodySummary::new(
1276 ResponseBodyOutcome::Complete,
1277 u64::try_from(body.len()).unwrap_or(u64::MAX),
1278 ),
1279 ),
1280 ResponseBody::Stream(_) => self.body_observers.push(Box::new(observer)),
1281 }
1282 }
1283
1284 #[doc(hidden)]
1285 #[must_use]
1286 pub fn into_head(mut self) -> Self {
1287 let body = self.body.take().expect("response body is available");
1288 match body {
1289 ResponseBody::Buffered(body) => {
1290 if !self.headers.contains_key(header::CONTENT_LENGTH)
1291 && !self.status.is_informational()
1292 && self.status != StatusCode::NO_CONTENT
1293 {
1294 self.headers.insert(
1295 header::CONTENT_LENGTH,
1296 HeaderValue::from_str(&body.len().to_string())
1297 .expect("a byte length is a valid header value"),
1298 );
1299 }
1300 }
1301 ResponseBody::Stream(_) => notify_body_observers(
1302 std::mem::take(&mut self.body_observers),
1303 ResponseBodySummary::new(ResponseBodyOutcome::Complete, 0),
1304 ),
1305 }
1306 self.body = Some(ResponseBody::Buffered(Bytes::new()));
1307 self
1308 }
1309
1310 #[doc(hidden)]
1311 pub fn into_parts(mut self) -> (StatusCode, HeaderMap, ResponseBody) {
1312 self.take_parts(None)
1313 }
1314
1315 #[doc(hidden)]
1316 pub fn into_network_parts(
1317 mut self,
1318 cancellation: ResponseCancellationToken,
1319 ) -> (StatusCode, HeaderMap, ResponseBody) {
1320 self.take_parts(Some(cancellation))
1321 }
1322
1323 fn take_parts(
1324 &mut self,
1325 cancellation: Option<ResponseCancellationToken>,
1326 ) -> (StatusCode, HeaderMap, ResponseBody) {
1327 let mut body = self
1328 .body
1329 .take()
1330 .expect("response body can only be consumed once");
1331 if let ResponseBody::Stream(stream) = body {
1332 body = if self.body_observers.is_empty() && cancellation.is_none() {
1333 ResponseBody::Stream(stream)
1334 } else {
1335 ResponseBody::Stream(Box::pin(LifecycleStream::new(
1336 stream,
1337 std::mem::take(&mut self.body_observers),
1338 cancellation,
1339 )))
1340 };
1341 }
1342 (self.status, std::mem::take(&mut self.headers), body)
1343 }
1344}
1345
1346impl Drop for Response {
1347 fn drop(&mut self) {
1348 if matches!(self.body, Some(ResponseBody::Stream(_))) {
1349 notify_body_observers(
1350 std::mem::take(&mut self.body_observers),
1351 ResponseBodySummary::new(ResponseBodyOutcome::Aborted, 0),
1352 );
1353 }
1354 }
1355}
1356
1357struct LifecycleStream {
1358 inner: ByteStream,
1359 observers: Vec<BodyObserver>,
1360 cancellation: Option<ResponseCancellationToken>,
1361 cancellation_wait: Option<Pin<Box<dyn Future<Output = ()> + Send + 'static>>>,
1362 bytes_yielded: u64,
1363 finished: bool,
1364}
1365
1366impl LifecycleStream {
1367 fn new(
1368 inner: ByteStream,
1369 observers: Vec<BodyObserver>,
1370 cancellation: Option<ResponseCancellationToken>,
1371 ) -> Self {
1372 let cancellation_wait = cancellation.as_ref().map(|token| {
1373 Box::pin(token.clone().cancelled_owned())
1374 as Pin<Box<dyn Future<Output = ()> + Send + 'static>>
1375 });
1376 Self {
1377 inner,
1378 observers,
1379 cancellation,
1380 cancellation_wait,
1381 bytes_yielded: 0,
1382 finished: false,
1383 }
1384 }
1385
1386 fn finish(&mut self, outcome: ResponseBodyOutcome) {
1387 if self.finished {
1388 return;
1389 }
1390 self.finished = true;
1391 notify_body_observers(
1392 std::mem::take(&mut self.observers),
1393 ResponseBodySummary::new(outcome, self.bytes_yielded),
1394 );
1395 }
1396}
1397
1398impl Stream for LifecycleStream {
1399 type Item = Result<Bytes, ResponseBodyError>;
1400
1401 fn poll_next(mut self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Option<Self::Item>> {
1402 let this = self.as_mut().get_mut();
1403 if this.finished {
1404 return Poll::Ready(None);
1405 }
1406 if this
1407 .cancellation_wait
1408 .as_mut()
1409 .is_some_and(|wait| wait.as_mut().poll(context).is_ready())
1410 {
1411 this.finish(ResponseBodyOutcome::Shutdown);
1412 return Poll::Ready(None);
1413 }
1414
1415 match catch_unwind(AssertUnwindSafe(|| this.inner.as_mut().poll_next(context))) {
1416 Ok(Poll::Ready(Some(Ok(chunk)))) => {
1417 this.bytes_yielded = this
1418 .bytes_yielded
1419 .saturating_add(u64::try_from(chunk.len()).unwrap_or(u64::MAX));
1420 Poll::Ready(Some(Ok(chunk)))
1421 }
1422 Ok(Poll::Ready(Some(Err(error)))) => {
1423 this.finish(ResponseBodyOutcome::StreamError);
1424 Poll::Ready(Some(Err(error)))
1425 }
1426 Ok(Poll::Ready(None)) => {
1427 this.finish(ResponseBodyOutcome::Complete);
1428 Poll::Ready(None)
1429 }
1430 Ok(Poll::Pending) => Poll::Pending,
1431 Err(_) => {
1432 this.finish(ResponseBodyOutcome::StreamError);
1433 Poll::Ready(Some(Err(ResponseBodyError)))
1434 }
1435 }
1436 }
1437}
1438
1439impl Drop for LifecycleStream {
1440 fn drop(&mut self) {
1441 if self.finished {
1442 return;
1443 }
1444 let outcome = if self
1445 .cancellation
1446 .as_ref()
1447 .is_some_and(ResponseCancellationToken::is_cancelled)
1448 {
1449 ResponseBodyOutcome::Shutdown
1450 } else if self.cancellation.is_some() {
1451 ResponseBodyOutcome::DeliveryCancelled
1452 } else {
1453 ResponseBodyOutcome::Aborted
1454 };
1455 self.finish(outcome);
1456 }
1457}
1458
1459fn notify_body_observers(observers: Vec<BodyObserver>, summary: ResponseBodySummary) {
1460 for observer in observers {
1461 notify_body_observer(observer, summary);
1462 }
1463}
1464
1465fn notify_body_observer(observer: BodyObserver, summary: ResponseBodySummary) {
1466 let _ = catch_unwind(AssertUnwindSafe(|| observer(summary)));
1467}
1468
1469#[derive(Clone, Copy, Debug)]
1470pub struct InvalidHeader;
1471
1472impl std::fmt::Display for InvalidHeader {
1473 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1474 formatter.write_str("invalid HTTP header name or value")
1475 }
1476}
1477
1478impl std::error::Error for InvalidHeader {}
1479
1480#[derive(Clone, Debug)]
1482pub struct Redirect {
1483 status: StatusCode,
1484 location: HeaderValue,
1485}
1486
1487impl Redirect {
1488 pub fn to(location: impl TryInto<HeaderValue>) -> Result<Self, InvalidHeader> {
1494 Self::with_status(StatusCode::FOUND, location)
1495 }
1496
1497 pub fn see_other(location: impl TryInto<HeaderValue>) -> Result<Self, InvalidHeader> {
1503 Self::with_status(StatusCode::SEE_OTHER, location)
1504 }
1505
1506 pub fn temporary(location: impl TryInto<HeaderValue>) -> Result<Self, InvalidHeader> {
1512 Self::with_status(StatusCode::TEMPORARY_REDIRECT, location)
1513 }
1514
1515 fn with_status(
1516 status: StatusCode,
1517 location: impl TryInto<HeaderValue>,
1518 ) -> Result<Self, InvalidHeader> {
1519 Ok(Self {
1520 status,
1521 location: location.try_into().map_err(|_| InvalidHeader)?,
1522 })
1523 }
1524}
1525
1526impl IntoResponse for Redirect {
1527 fn into_response(self) -> Response {
1528 let mut response = Response::new(self.status, Bytes::new());
1529 response
1530 .headers_mut()
1531 .insert(header::LOCATION, self.location);
1532 response
1533 }
1534}
1535
1536#[derive(Clone, Debug)]
1538pub struct Download {
1539 body: Bytes,
1540 content_type: Mime,
1541 disposition: &'static str,
1542 file_name: String,
1543 cache_control: HeaderValue,
1544}
1545
1546impl Download {
1547 #[must_use]
1548 pub fn attachment(
1549 body: impl Into<Bytes>,
1550 file_name: impl Into<String>,
1551 content_type: Mime,
1552 ) -> Self {
1553 Self::new(body, file_name, content_type, "attachment")
1554 }
1555
1556 #[must_use]
1557 pub fn inline(
1558 body: impl Into<Bytes>,
1559 file_name: impl Into<String>,
1560 content_type: Mime,
1561 ) -> Self {
1562 Self::new(body, file_name, content_type, "inline")
1563 }
1564
1565 fn new(
1566 body: impl Into<Bytes>,
1567 file_name: impl Into<String>,
1568 content_type: Mime,
1569 disposition: &'static str,
1570 ) -> Self {
1571 Self {
1572 body: body.into(),
1573 content_type,
1574 disposition,
1575 file_name: file_name.into(),
1576 cache_control: HeaderValue::from_static("private, no-store"),
1577 }
1578 }
1579
1580 pub fn with_cache_control(
1586 mut self,
1587 value: impl TryInto<HeaderValue>,
1588 ) -> Result<Self, InvalidHeader> {
1589 self.cache_control = value.try_into().map_err(|_| InvalidHeader)?;
1590 Ok(self)
1591 }
1592}
1593
1594impl IntoResponse for Download {
1595 fn into_response(self) -> Response {
1596 let fallback = ascii_file_name(&self.file_name);
1597 let encoded = utf8_percent_encode(&self.file_name, NON_ALPHANUMERIC);
1598 let content_disposition = format!(
1599 "{}; filename=\"{fallback}\"; filename*=UTF-8''{encoded}",
1600 self.disposition
1601 );
1602 let mut response = Response::new(StatusCode::OK, self.body);
1603 response.headers_mut().insert(
1604 header::CONTENT_TYPE,
1605 HeaderValue::from_str(self.content_type.as_ref())
1606 .expect("a parsed MIME value is a valid header"),
1607 );
1608 response.headers_mut().insert(
1609 header::CONTENT_DISPOSITION,
1610 HeaderValue::from_str(&content_disposition)
1611 .expect("sanitized content disposition is a valid header"),
1612 );
1613 response
1614 .headers_mut()
1615 .insert(header::CACHE_CONTROL, self.cache_control);
1616 response.headers_mut().insert(
1617 HeaderName::from_static("x-content-type-options"),
1618 HeaderValue::from_static("nosniff"),
1619 );
1620 response
1621 }
1622}
1623
1624fn ascii_file_name(file_name: &str) -> String {
1625 let sanitized = file_name
1626 .chars()
1627 .map(|character| {
1628 if character.is_ascii_alphanumeric() || matches!(character, '.' | '_' | '-') {
1629 character
1630 } else {
1631 '_'
1632 }
1633 })
1634 .collect::<String>();
1635 if sanitized.trim_matches(['.', '_', '-']).is_empty() {
1636 "download".to_owned()
1637 } else {
1638 sanitized
1639 }
1640}
1641
1642pub trait IntoResponse {
1643 fn into_response(self) -> Response;
1644
1645 #[doc(hidden)]
1647 fn into_response_with_context(self, _context: &ResponseContext) -> Response
1648 where
1649 Self: Sized,
1650 {
1651 self.into_response()
1652 }
1653}
1654
1655#[derive(Clone, Debug)]
1656pub struct Json<T>(pub T);
1657
1658impl<T> IntoResponse for Json<T>
1659where
1660 T: Serialize,
1661{
1662 fn into_response(self) -> Response {
1663 Response::json(&self.0).unwrap_or_else(|_| {
1664 Response::text("Internal Server Error").with_status(StatusCode::INTERNAL_SERVER_ERROR)
1665 })
1666 }
1667}
1668
1669impl IntoResponse for Response {
1670 fn into_response(self) -> Response {
1671 self
1672 }
1673}
1674
1675impl IntoResponse for String {
1676 fn into_response(self) -> Response {
1677 Response::text(self)
1678 }
1679}
1680
1681impl IntoResponse for &'static str {
1682 fn into_response(self) -> Response {
1683 Response::text(self)
1684 }
1685}
1686
1687impl IntoResponse for Bytes {
1688 fn into_response(self) -> Response {
1689 Response::new(StatusCode::OK, self)
1690 }
1691}
1692
1693impl IntoResponse for () {
1694 fn into_response(self) -> Response {
1695 Response::new(StatusCode::NO_CONTENT, Bytes::new())
1696 }
1697}
1698
1699impl<T> IntoResponse for (StatusCode, T)
1700where
1701 T: IntoResponse,
1702{
1703 fn into_response(self) -> Response {
1704 self.1.into_response().with_status(self.0)
1705 }
1706
1707 fn into_response_with_context(self, context: &ResponseContext) -> Response {
1708 self.1
1709 .into_response_with_context(context)
1710 .with_status(self.0)
1711 }
1712}
1713
1714impl<T, E> IntoResponse for Result<T, E>
1715where
1716 T: IntoResponse,
1717 E: IntoResponse,
1718{
1719 fn into_response(self) -> Response {
1720 match self {
1721 Ok(value) => value.into_response(),
1722 Err(error) => error.into_response(),
1723 }
1724 }
1725
1726 fn into_response_with_context(self, context: &ResponseContext) -> Response {
1727 match self {
1728 Ok(value) => value.into_response_with_context(context),
1729 Err(error) => error.into_response_with_context(context),
1730 }
1731 }
1732}
1733
1734impl IntoResponse for Infallible {
1735 fn into_response(self) -> Response {
1736 match self {}
1737 }
1738}
1739
1740impl IntoResponse for JsonRejection {
1741 fn into_response(self) -> Response {
1742 let status = self.status();
1743 rejection_response(status, &self.to_string())
1744 }
1745}
1746
1747impl IntoResponse for RequestBodyError {
1748 fn into_response(self) -> Response {
1749 let status = match self {
1750 Self::TooLarge => StatusCode::PAYLOAD_TOO_LARGE,
1751 Self::Timeout(_) => StatusCode::REQUEST_TIMEOUT,
1752 Self::Transport => StatusCode::BAD_REQUEST,
1753 };
1754 rejection_response(status, &self.to_string())
1755 }
1756}
1757
1758impl IntoResponse for QueryRejection {
1759 fn into_response(self) -> Response {
1760 rejection_response(StatusCode::BAD_REQUEST, &self.to_string())
1761 }
1762}
1763
1764impl IntoResponse for PathRejection {
1765 fn into_response(self) -> Response {
1766 rejection_response(StatusCode::BAD_REQUEST, &self.to_string())
1767 }
1768}
1769
1770impl IntoResponse for HeaderRejection {
1771 fn into_response(self) -> Response {
1772 rejection_response(StatusCode::BAD_REQUEST, &self.to_string())
1773 }
1774}
1775
1776impl IntoResponse for FormRejection {
1777 fn into_response(self) -> Response {
1778 let status = match self {
1779 Self::StreamingBody => StatusCode::INTERNAL_SERVER_ERROR,
1780 Self::MissingContentType | Self::UnsupportedContentType => {
1781 StatusCode::UNSUPPORTED_MEDIA_TYPE
1782 }
1783 Self::InvalidForm(_) => StatusCode::BAD_REQUEST,
1784 };
1785 rejection_response(status, &self.to_string())
1786 }
1787}
1788
1789impl IntoResponse for StateRejection {
1790 fn into_response(self) -> Response {
1791 rejection_response(StatusCode::INTERNAL_SERVER_ERROR, &self.to_string())
1792 }
1793}
1794
1795impl IntoResponse for RequestBodyStreamRejection {
1796 fn into_response(self) -> Response {
1797 rejection_response(StatusCode::INTERNAL_SERVER_ERROR, &self.to_string())
1798 }
1799}
1800
1801impl IntoResponse for MultipartRejection {
1802 fn into_response(self) -> Response {
1803 let status = match self {
1804 Self::StreamingBody => StatusCode::INTERNAL_SERVER_ERROR,
1805 Self::MissingContentType | Self::UnsupportedContentType => {
1806 StatusCode::UNSUPPORTED_MEDIA_TYPE
1807 }
1808 Self::InvalidBody | Self::InvalidField(_) => StatusCode::BAD_REQUEST,
1809 };
1810 rejection_response(status, &self.to_string())
1811 }
1812}
1813
1814pub(crate) fn rejection_response(status: StatusCode, message: &str) -> Response {
1815 #[derive(Serialize)]
1816 struct RejectionBody<'a> {
1817 message: &'a str,
1818 }
1819
1820 Json(RejectionBody { message })
1821 .into_response()
1822 .with_status(status)
1823}
1824
1825pub trait Handler: Send + Sync + 'static {
1826 fn call(&self, request: Request) -> BoxFuture<Response>;
1827
1828 #[doc(hidden)]
1829 fn request_body_mode(&self) -> RequestBodyMode {
1830 RequestBodyMode::Buffered
1831 }
1832}
1833
1834pub struct TypedHandler {
1835 handler: Arc<dyn Handler>,
1836}
1837
1838impl Handler for TypedHandler {
1839 fn call(&self, request: Request) -> BoxFuture<Response> {
1840 self.handler.call(request)
1841 }
1842
1843 fn request_body_mode(&self) -> RequestBodyMode {
1844 self.handler.request_body_mode()
1845 }
1846}
1847
1848pub struct StreamingHandler<H> {
1850 handler: H,
1851}
1852
1853#[must_use]
1858pub const fn streaming<H>(handler: H) -> StreamingHandler<H> {
1859 StreamingHandler { handler }
1860}
1861
1862impl<H> Handler for StreamingHandler<H>
1863where
1864 H: Handler,
1865{
1866 fn call(&self, request: Request) -> BoxFuture<Response> {
1867 self.handler.call(request)
1868 }
1869
1870 fn request_body_mode(&self) -> RequestBodyMode {
1871 RequestBodyMode::Streaming
1872 }
1873}
1874
1875pub trait IntoTypedHandler<Args>: Send + Sync + Sized + 'static {
1876 fn into_typed_handler(self) -> TypedHandler;
1877}
1878
1879#[must_use]
1880pub fn typed<H, Args>(handler: H) -> TypedHandler
1881where
1882 H: IntoTypedHandler<Args>,
1883{
1884 handler.into_typed_handler()
1885}
1886
1887impl<F, Fut, Output, A> IntoTypedHandler<(A,)> for F
1888where
1889 F: Fn(A) -> Fut + Send + Sync + 'static,
1890 Fut: Future<Output = Output> + Send + 'static,
1891 Output: IntoResponse + 'static,
1892 A: FromRequest,
1893{
1894 fn into_typed_handler(self) -> TypedHandler {
1895 let function = Arc::new(self);
1896 let handler = move |request: Request| {
1897 let function = Arc::clone(&function);
1898 async move {
1899 let context = ResponseContext::from_request(&request);
1900 match A::from_request(&request) {
1901 Ok(first) => function(first).await.into_response_with_context(&context),
1902 Err(rejection) => rejection.into_response_with_context(&context),
1903 }
1904 }
1905 };
1906 TypedHandler {
1907 handler: Arc::new(handler),
1908 }
1909 }
1910}
1911
1912macro_rules! impl_typed_handler {
1913 ($(($type:ident, $value:ident)),+ $(,)?) => {
1914 impl<F, Fut, Output, $($type),+> IntoTypedHandler<($($type,)+)> for F
1915 where
1916 F: Fn($($type),+) -> Fut + Send + Sync + 'static,
1917 Fut: Future<Output = Output> + Send + 'static,
1918 Output: IntoResponse + 'static,
1919 $($type: FromRequest,)+
1920 {
1921 fn into_typed_handler(self) -> TypedHandler {
1922 let function = Arc::new(self);
1923 let handler = move |request: Request| {
1924 let function = Arc::clone(&function);
1925 async move {
1926 let context = ResponseContext::from_request(&request);
1927 $(
1928 let $value = match $type::from_request(&request) {
1929 Ok(value) => value,
1930 Err(rejection) => {
1931 return rejection.into_response_with_context(&context);
1932 }
1933 };
1934 )+
1935 function($($value),+).await.into_response_with_context(&context)
1936 }
1937 };
1938 TypedHandler {
1939 handler: Arc::new(handler),
1940 }
1941 }
1942 }
1943 };
1944}
1945
1946impl_typed_handler!((A, first), (B, second));
1947impl_typed_handler!((A, first), (B, second), (C, third));
1948impl_typed_handler!((A, first), (B, second), (C, third), (D, fourth));
1949
1950impl<F, Fut, Output> Handler for F
1951where
1952 F: Fn(Request) -> Fut + Send + Sync + 'static,
1953 Fut: Future<Output = Output> + Send + 'static,
1954 Output: IntoResponse + 'static,
1955{
1956 fn call(&self, request: Request) -> BoxFuture<Response> {
1957 let context = ResponseContext::from_request(&request);
1958 let future = (self)(request);
1959 Box::pin(async move { future.await.into_response_with_context(&context) })
1960 }
1961}
1962
1963#[derive(Clone)]
1964pub struct Next {
1965 handler: Arc<dyn Handler>,
1966}
1967
1968impl Next {
1969 #[must_use]
1970 fn new(handler: Arc<dyn Handler>) -> Self {
1971 Self { handler }
1972 }
1973
1974 pub async fn run(self, request: Request) -> Response {
1975 self.handler.call(request).await
1976 }
1977}
1978
1979pub trait Middleware: Send + Sync + 'static {
1980 fn handle(&self, request: Request, next: Next) -> BoxFuture<Response>;
1981}
1982
1983#[derive(Clone, Debug)]
1985pub struct StateMiddleware<T> {
1986 value: T,
1987}
1988
1989impl<T> StateMiddleware<T> {
1990 #[must_use]
1991 pub const fn new(value: T) -> Self {
1992 Self { value }
1993 }
1994}
1995
1996impl<T> Middleware for StateMiddleware<T>
1997where
1998 T: Clone + Send + Sync + 'static,
1999{
2000 fn handle(&self, mut request: Request, next: Next) -> BoxFuture<Response> {
2001 request.extensions_mut().insert(self.value.clone());
2002 Box::pin(async move { next.run(request).await })
2003 }
2004}
2005
2006pub struct MiddlewareFn<F>(F);
2007
2008#[must_use]
2009pub fn middleware_fn<F>(function: F) -> MiddlewareFn<F> {
2010 MiddlewareFn(function)
2011}
2012
2013impl<F, Fut, Output> Middleware for MiddlewareFn<F>
2014where
2015 F: Fn(Request, Next) -> Fut + Send + Sync + 'static,
2016 Fut: Future<Output = Output> + Send + 'static,
2017 Output: IntoResponse + 'static,
2018{
2019 fn handle(&self, request: Request, next: Next) -> BoxFuture<Response> {
2020 let context = ResponseContext::from_request(&request);
2021 let future = (self.0)(request, next);
2022 Box::pin(async move { future.await.into_response_with_context(&context) })
2023 }
2024}
2025
2026#[derive(Clone, Copy, Debug, Default)]
2027pub struct SecurityHeaders;
2028
2029impl Middleware for SecurityHeaders {
2030 fn handle(&self, request: Request, next: Next) -> BoxFuture<Response> {
2031 Box::pin(async move {
2032 let mut response = next.run(request).await;
2033 insert_default_header(
2034 response.headers_mut(),
2035 HeaderName::from_static("x-content-type-options"),
2036 HeaderValue::from_static("nosniff"),
2037 );
2038 insert_default_header(
2039 response.headers_mut(),
2040 HeaderName::from_static("x-frame-options"),
2041 HeaderValue::from_static("DENY"),
2042 );
2043 insert_default_header(
2044 response.headers_mut(),
2045 header::REFERRER_POLICY,
2046 HeaderValue::from_static("strict-origin-when-cross-origin"),
2047 );
2048 response
2049 })
2050 }
2051}
2052
2053fn insert_default_header(headers: &mut HeaderMap, name: HeaderName, value: HeaderValue) {
2054 headers.entry(name).or_insert(value);
2055}
2056
2057struct MiddlewareHandler {
2058 middleware: Arc<dyn Middleware>,
2059 next: Arc<dyn Handler>,
2060}
2061
2062impl Handler for MiddlewareHandler {
2063 fn call(&self, request: Request) -> BoxFuture<Response> {
2064 self.middleware
2065 .handle(request, Next::new(Arc::clone(&self.next)))
2066 }
2067}
2068
2069#[must_use]
2070#[doc(hidden)]
2071pub fn apply_middleware(
2072 handler: Arc<dyn Handler>,
2073 middleware: &[Arc<dyn Middleware>],
2074) -> Arc<dyn Handler> {
2075 middleware.iter().rev().fold(handler, |next, current| {
2076 Arc::new(MiddlewareHandler {
2077 middleware: Arc::clone(current),
2078 next,
2079 })
2080 })
2081}
2082
2083#[cfg(test)]
2084mod tests {
2085 use futures_util::stream;
2086 use serde::Deserialize;
2087 use std::sync::atomic::{AtomicUsize, Ordering};
2088
2089 use super::*;
2090
2091 #[derive(Debug, Deserialize, PartialEq, Serialize)]
2092 struct SearchInput {
2093 page: u32,
2094 term: String,
2095 }
2096
2097 #[derive(Debug, Deserialize, PartialEq)]
2098 struct UserPath {
2099 user: u64,
2100 }
2101
2102 #[derive(Debug, Deserialize, PartialEq)]
2103 struct RequestHeaders {
2104 #[serde(rename = "x-request-id")]
2105 request_id: String,
2106 }
2107
2108 struct UploadInput {
2109 title: String,
2110 document: MultipartField,
2111 }
2112
2113 #[test]
2114 fn csp_nonce_validation_and_debug_are_fail_closed() {
2115 let nonce = CspNonce::new("0123456789abcdef0123456789abcdef").unwrap();
2116 assert_eq!(nonce.as_str(), "0123456789abcdef0123456789abcdef");
2117 let debug = format!("{nonce:?}");
2118 assert!(debug.contains("[REDACTED]"));
2119 assert!(!debug.contains(nonce.as_str()));
2120 for invalid in [
2121 "short",
2122 "0123456789abcde!",
2123 "0123456789abcdef\r\n",
2124 &"a".repeat(129),
2125 ] {
2126 assert!(CspNonce::new(invalid).is_err());
2127 }
2128
2129 let mut request = Request::new(Method::GET, "/account?reset_token=secret".parse().unwrap());
2130 request.headers_mut().insert(
2131 header::AUTHORIZATION,
2132 HeaderValue::from_static("Bearer secret"),
2133 );
2134 request
2135 .headers_mut()
2136 .insert(header::COOKIE, HeaderValue::from_static("session=secret"));
2137 request
2138 .headers_mut()
2139 .insert("x-phoenix-page", HeaderValue::from_static("1"));
2140 let context = ResponseContext::from_request(&request);
2141 let debug = format!("{context:?}");
2142 assert!(context.is_page_request());
2143 assert!(debug.contains("/account"));
2144 assert!(!debug.contains("reset_token"));
2145 assert!(!debug.contains("secret"));
2146 }
2147
2148 impl FromMultipart for UploadInput {
2149 fn from_multipart(mut multipart: MultipartData) -> Result<Self, MultipartRejection> {
2150 let title = multipart
2151 .remove("title")
2152 .ok_or_else(|| MultipartRejection::InvalidField("title".to_owned()))?
2153 .text()
2154 .map_err(|_| MultipartRejection::InvalidField("title".to_owned()))?
2155 .to_owned();
2156 let document = multipart
2157 .remove("document")
2158 .ok_or_else(|| MultipartRejection::InvalidField("document".to_owned()))?;
2159 Ok(Self { title, document })
2160 }
2161 }
2162
2163 #[test]
2164 fn extracts_query_path_headers_json_and_form() {
2165 let query_request = Request::new(
2166 Method::GET,
2167 "/search?page=2&term=rust%20web".parse().expect("valid URI"),
2168 );
2169 assert_eq!(
2170 Query::<SearchInput>::from_request(&query_request)
2171 .expect("query should extract")
2172 .0,
2173 SearchInput {
2174 page: 2,
2175 term: "rust web".to_owned(),
2176 }
2177 );
2178
2179 let mut path_request = Request::new(Method::GET, "/users/42".parse().expect("valid URI"));
2180 path_request.set_route(None, vec![("user".to_owned(), "42".to_owned())]);
2181 assert_eq!(
2182 Path::<UserPath>::from_request(&path_request)
2183 .expect("path should extract")
2184 .0,
2185 UserPath { user: 42 }
2186 );
2187
2188 let mut header_request = Request::new(Method::GET, "/".parse().expect("valid URI"));
2189 header_request
2190 .headers_mut()
2191 .insert("x-request-id", HeaderValue::from_static("request-123"));
2192 assert_eq!(
2193 Header::<RequestHeaders>::from_request(&header_request)
2194 .expect("headers should extract")
2195 .0,
2196 RequestHeaders {
2197 request_id: "request-123".to_owned(),
2198 }
2199 );
2200
2201 let mut json_headers = HeaderMap::new();
2202 json_headers.insert(
2203 header::CONTENT_TYPE,
2204 HeaderValue::from_static("application/json"),
2205 );
2206 let json_request = Request::from_parts(
2207 Method::POST,
2208 "/".parse().expect("valid URI"),
2209 json_headers,
2210 Bytes::from_static(br#"{"page":3,"term":"contracts"}"#),
2211 );
2212 assert_eq!(
2213 Json::<SearchInput>::from_request(&json_request)
2214 .expect("JSON should extract")
2215 .0,
2216 SearchInput {
2217 page: 3,
2218 term: "contracts".to_owned(),
2219 }
2220 );
2221
2222 let mut form_headers = HeaderMap::new();
2223 form_headers.insert(
2224 header::CONTENT_TYPE,
2225 HeaderValue::from_static("application/x-www-form-urlencoded"),
2226 );
2227 let form_request = Request::from_parts(
2228 Method::POST,
2229 "/".parse().expect("valid URI"),
2230 form_headers,
2231 Bytes::from_static(b"page=4&term=typed+form"),
2232 );
2233 assert_eq!(
2234 Form::<SearchInput>::from_request(&form_request)
2235 .expect("form should extract")
2236 .0,
2237 SearchInput {
2238 page: 4,
2239 term: "typed form".to_owned(),
2240 }
2241 );
2242 }
2243
2244 #[test]
2245 fn extracts_multipart_text_and_file_fields() {
2246 let mut headers = HeaderMap::new();
2247 headers.insert(
2248 header::CONTENT_TYPE,
2249 HeaderValue::from_static("multipart/form-data; boundary=phoenix-boundary"),
2250 );
2251 let body = concat!(
2252 "--phoenix-boundary\r\n",
2253 "Content-Disposition: form-data; name=\"title\"\r\n\r\n",
2254 "Typed upload\r\n",
2255 "--phoenix-boundary\r\n",
2256 "Content-Disposition: form-data; name=\"document\"; filename=\"notes.txt\"\r\n",
2257 "Content-Type: text/plain\r\n\r\n",
2258 "hello\r\n",
2259 "--phoenix-boundary--\r\n",
2260 );
2261 let request = Request::from_parts(
2262 Method::POST,
2263 "/upload".parse().expect("valid URI"),
2264 headers,
2265 Bytes::from_static(body.as_bytes()),
2266 );
2267
2268 let multipart =
2269 Multipart::<MultipartData>::from_request(&request).expect("multipart should extract");
2270 assert_eq!(
2271 multipart
2272 .field("title")
2273 .expect("title")
2274 .text()
2275 .expect("UTF-8"),
2276 "Typed upload"
2277 );
2278 let file = multipart.field("document").expect("document");
2279 assert_eq!(file.file_name(), Some("notes.txt"));
2280 assert_eq!(file.content_type(), Some("text/plain"));
2281 assert_eq!(file.bytes(), &Bytes::from_static(b"hello"));
2282
2283 let input = Multipart::<UploadInput>::from_request(&request)
2284 .expect("typed multipart DTO should extract")
2285 .0;
2286 assert_eq!(input.title, "Typed upload");
2287 assert_eq!(input.document.file_name(), Some("notes.txt"));
2288 }
2289
2290 #[tokio::test]
2291 async fn typed_handler_extracts_arguments_and_maps_rejections() {
2292 let handler = typed(|Query(input): Query<SearchInput>| async move { Json(input) });
2293 let response = handler
2294 .call(Request::new(
2295 Method::GET,
2296 "/search?page=5&term=handler".parse().expect("valid URI"),
2297 ))
2298 .await;
2299 assert_eq!(response.status(), StatusCode::OK);
2300 assert_eq!(
2301 serde_json::from_slice::<SearchInput>(response.body()).expect("JSON response"),
2302 SearchInput {
2303 page: 5,
2304 term: "handler".to_owned(),
2305 }
2306 );
2307
2308 let response = handler
2309 .call(Request::new(
2310 Method::GET,
2311 "/search?page=wrong&term=handler"
2312 .parse()
2313 .expect("valid URI"),
2314 ))
2315 .await;
2316 assert_eq!(response.status(), StatusCode::BAD_REQUEST);
2317 }
2318
2319 #[tokio::test]
2320 async fn streaming_body_is_typed_one_shot_and_rejects_buffered_extractors() {
2321 let handler = streaming(typed(
2322 |Query(input): Query<SearchInput>, body: RequestBodyStream| async move {
2323 let body = body.into_bytes().await?;
2324 Ok::<_, RequestBodyError>(format!(
2325 "{}:{}",
2326 input.term,
2327 String::from_utf8_lossy(&body)
2328 ))
2329 },
2330 ));
2331 assert_eq!(handler.request_body_mode(), RequestBodyMode::Streaming);
2332
2333 let mut request = Request::new(Method::POST, "/upload?page=1&term=stream".parse().unwrap());
2334 request.set_streaming_body(RequestBodyStream::new(stream::iter([
2335 Ok(Bytes::from_static(b"first-")),
2336 Ok(Bytes::from_static(b"second")),
2337 ])));
2338 let response = handler.call(request).await;
2339 assert_eq!(response.status(), StatusCode::OK);
2340 assert_eq!(response.body(), "stream:first-second");
2341
2342 let mut request = Request::new(Method::POST, "/upload".parse().unwrap());
2343 request.set_streaming_body(RequestBodyStream::new(stream::empty()));
2344 assert!(matches!(
2345 Json::<SearchInput>::from_request(&request),
2346 Err(JsonRejection::StreamingBody)
2347 ));
2348 assert!(matches!(
2349 Form::<SearchInput>::from_request(&request),
2350 Err(FormRejection::StreamingBody)
2351 ));
2352 assert!(matches!(
2353 Multipart::<MultipartData>::from_request(&request),
2354 Err(MultipartRejection::StreamingBody)
2355 ));
2356 assert!(RequestBodyStream::from_request(&request).is_ok());
2357 assert!(RequestBodyStream::from_request(&request).is_err());
2358 assert!(request.is_body_streaming());
2359 assert!(request.body().is_empty());
2360 }
2361
2362 #[tokio::test]
2363 async fn request_body_stream_preserves_chunk_order_and_errors() {
2364 let mut body = RequestBodyStream::new(stream::iter([
2365 Ok(Bytes::from_static(b"one")),
2366 Ok(Bytes::from_static(b"two")),
2367 ]));
2368 assert_eq!(body.next_chunk().await.unwrap().unwrap(), "one");
2369 assert_eq!(body.next_chunk().await.unwrap().unwrap(), "two");
2370 assert!(body.next_chunk().await.is_none());
2371
2372 for (error, expected_status) in [
2373 (RequestBodyError::TooLarge, StatusCode::PAYLOAD_TOO_LARGE),
2374 (
2375 RequestBodyError::Timeout(Duration::from_secs(1)),
2376 StatusCode::REQUEST_TIMEOUT,
2377 ),
2378 (RequestBodyError::Transport, StatusCode::BAD_REQUEST),
2379 ] {
2380 let body = RequestBodyStream::new(stream::iter([
2381 Ok(Bytes::from_static(b"partial")),
2382 Err(error),
2383 ]));
2384 assert_eq!(body.into_bytes().await, Err(error));
2385 assert_eq!(error.into_response().status(), expected_status);
2386 }
2387 }
2388
2389 #[tokio::test]
2390 async fn response_body_lifecycle_reports_exactly_one_redacted_outcome() {
2391 fn observer(
2392 observed: &Arc<Mutex<Vec<ResponseBodySummary>>>,
2393 ) -> impl FnOnce(ResponseBodySummary) + Send + 'static {
2394 let observed = Arc::clone(observed);
2395 move |summary| observed.lock().unwrap().push(summary)
2396 }
2397
2398 let observed = Arc::new(Mutex::new(Vec::new()));
2399 let mut buffered = Response::text("body");
2400 buffered.on_body_finish(observer(&observed));
2401 assert_eq!(
2402 *observed.lock().unwrap(),
2403 [ResponseBodySummary::new(ResponseBodyOutcome::Complete, 4)]
2404 );
2405
2406 let observed = Arc::new(Mutex::new(Vec::new()));
2407 let mut complete = Response::stream(stream::iter([
2408 Bytes::from_static(b"one"),
2409 Bytes::from_static(b"two"),
2410 ]));
2411 complete
2412 .headers_mut()
2413 .insert(header::CONTENT_LENGTH, HeaderValue::from_static("6"));
2414 complete.on_body_finish(observer(&observed));
2415 let (_, headers, body) = complete.into_parts();
2416 assert_eq!(headers[header::CONTENT_LENGTH], "6");
2417 let ResponseBody::Stream(stream) = body else {
2418 panic!("expected stream");
2419 };
2420 assert_eq!(stream.collect::<Vec<_>>().await.len(), 2);
2421 assert_eq!(
2422 *observed.lock().unwrap(),
2423 [ResponseBodySummary::new(ResponseBodyOutcome::Complete, 6)]
2424 );
2425
2426 let observed = Arc::new(Mutex::new(Vec::new()));
2427 let mut failed = Response::try_stream(stream::iter([
2428 Ok::<_, &'static str>(Bytes::from_static(b"partial")),
2429 Err("private failure details"),
2430 ]));
2431 failed.on_body_finish(observer(&observed));
2432 let (_, _, body) = failed.into_parts();
2433 let ResponseBody::Stream(stream) = body else {
2434 panic!("expected stream");
2435 };
2436 let chunks = stream.collect::<Vec<_>>().await;
2437 assert_eq!(
2438 chunks[1].as_ref().unwrap_err().to_string(),
2439 "response body stream failed"
2440 );
2441 assert_eq!(
2442 *observed.lock().unwrap(),
2443 [ResponseBodySummary::new(
2444 ResponseBodyOutcome::StreamError,
2445 7,
2446 )]
2447 );
2448
2449 let observed = Arc::new(Mutex::new(Vec::new()));
2450 let mut panicking = Response::stream(stream::poll_fn(|_| -> Poll<Option<Bytes>> {
2451 panic!("private stream panic")
2452 }));
2453 panicking.on_body_finish(observer(&observed));
2454 let (_, _, body) = panicking.into_parts();
2455 let ResponseBody::Stream(mut stream) = body else {
2456 panic!("expected stream");
2457 };
2458 assert!(stream.next().await.unwrap().is_err());
2459 assert!(stream.next().await.is_none());
2460 assert_eq!(
2461 *observed.lock().unwrap(),
2462 [ResponseBodySummary::new(
2463 ResponseBodyOutcome::StreamError,
2464 0,
2465 )]
2466 );
2467 }
2468
2469 #[tokio::test]
2470 async fn network_stream_lifecycle_distinguishes_disconnect_shutdown_and_abort() {
2471 fn observed_response(observed: &Arc<Mutex<Vec<ResponseBodySummary>>>) -> Response {
2472 let mut response = Response::stream(stream::pending::<Bytes>());
2473 let observed = Arc::clone(observed);
2474 response.on_body_finish(move |summary| observed.lock().unwrap().push(summary));
2475 response
2476 }
2477
2478 let observed = Arc::new(Mutex::new(Vec::new()));
2479 drop(observed_response(&observed));
2480 assert_eq!(
2481 *observed.lock().unwrap(),
2482 [ResponseBodySummary::new(ResponseBodyOutcome::Aborted, 0)]
2483 );
2484
2485 let observed = Arc::new(Mutex::new(Vec::new()));
2486 let (_, _, body) =
2487 observed_response(&observed).into_network_parts(ResponseCancellationToken::new());
2488 drop(body);
2489 assert_eq!(
2490 *observed.lock().unwrap(),
2491 [ResponseBodySummary::new(
2492 ResponseBodyOutcome::DeliveryCancelled,
2493 0,
2494 )]
2495 );
2496
2497 let observed = Arc::new(Mutex::new(Vec::new()));
2498 let cancellation = ResponseCancellationToken::new();
2499 let (_, _, body) = observed_response(&observed).into_network_parts(cancellation.clone());
2500 let ResponseBody::Stream(mut stream) = body else {
2501 panic!("expected stream");
2502 };
2503 cancellation.cancel();
2504 assert!(stream.next().await.is_none());
2505 drop(stream);
2506 assert_eq!(
2507 *observed.lock().unwrap(),
2508 [ResponseBodySummary::new(ResponseBodyOutcome::Shutdown, 0)]
2509 );
2510 }
2511
2512 #[test]
2513 fn head_suppresses_bodies_without_losing_representation_length() {
2514 let buffered = Response::text("hello").into_head();
2515 assert!(buffered.body().is_empty());
2516 assert_eq!(buffered.headers()[header::CONTENT_LENGTH], "5");
2517
2518 let mut explicit = Response::text("hello");
2519 explicit
2520 .headers_mut()
2521 .insert(header::CONTENT_LENGTH, HeaderValue::from_static("99"));
2522 let explicit = explicit.into_head();
2523 assert_eq!(explicit.headers()[header::CONTENT_LENGTH], "99");
2524
2525 let no_content = Response::text("ignored")
2526 .with_status(StatusCode::NO_CONTENT)
2527 .into_head();
2528 assert!(!no_content.headers().contains_key(header::CONTENT_LENGTH));
2529
2530 let polls = Arc::new(AtomicUsize::new(0));
2531 let source_polls = Arc::clone(&polls);
2532 let mut stream = Response::stream(stream::poll_fn(move |_| {
2533 source_polls.fetch_add(1, Ordering::SeqCst);
2534 Poll::Ready(Some(Bytes::from_static(b"unexpected")))
2535 }));
2536 stream
2537 .headers_mut()
2538 .insert(header::CONTENT_LENGTH, HeaderValue::from_static("10"));
2539 let observed = Arc::new(Mutex::new(Vec::new()));
2540 let callback_observed = Arc::clone(&observed);
2541 stream.on_body_finish(move |summary| callback_observed.lock().unwrap().push(summary));
2542 let stream = stream.into_head();
2543 assert!(stream.body().is_empty());
2544 assert_eq!(stream.headers()[header::CONTENT_LENGTH], "10");
2545 assert_eq!(polls.load(Ordering::SeqCst), 0);
2546 assert_eq!(
2547 *observed.lock().unwrap(),
2548 [ResponseBodySummary::new(ResponseBodyOutcome::Complete, 0)]
2549 );
2550 }
2551
2552 #[test]
2553 fn server_request_parts_preserve_version_and_extensions() {
2554 #[derive(Clone, Debug, Eq, PartialEq)]
2555 struct Marker(&'static str);
2556
2557 let mut extensions = Extensions::new();
2558 extensions.insert(Marker("preserved"));
2559 let request = Request::from_server_parts(
2560 Method::POST,
2561 "/upload".parse().unwrap(),
2562 Version::HTTP_2,
2563 HeaderMap::new(),
2564 extensions,
2565 Bytes::new(),
2566 );
2567
2568 assert_eq!(request.version(), Version::HTTP_2);
2569 assert_eq!(
2570 request.extensions().get::<Marker>(),
2571 Some(&Marker("preserved"))
2572 );
2573 }
2574
2575 #[tokio::test]
2576 async fn state_middleware_feeds_typed_handlers_and_missing_state_is_safe() {
2577 #[derive(Clone, Debug)]
2578 struct AppName(&'static str);
2579
2580 let handler = typed(|State(name): State<AppName>| async move { name.0 });
2581 let request = Request::new(Method::GET, "/".parse().expect("valid URI"));
2582 let response = Handler::call(&handler, request).await;
2583 assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
2584
2585 let handler: Arc<dyn Handler> = Arc::new(handler);
2586 let handler = apply_middleware(
2587 handler,
2588 &[Arc::new(StateMiddleware::new(AppName("Phoenix")))],
2589 );
2590 let response = handler
2591 .call(Request::new(Method::GET, "/".parse().expect("valid URI")))
2592 .await;
2593 assert_eq!(response.status(), StatusCode::OK);
2594 assert_eq!(response.body(), "Phoenix");
2595 }
2596
2597 #[tokio::test]
2598 async fn handler_response_conversion_retains_safe_request_context() {
2599 struct ContextResponse;
2600
2601 impl IntoResponse for ContextResponse {
2602 fn into_response(self) -> Response {
2603 Response::text("missing context")
2604 }
2605
2606 fn into_response_with_context(self, context: &ResponseContext) -> Response {
2607 let nonce = context.csp_nonce().map_or("missing", CspNonce::as_str);
2608 let route_count = context
2609 .route_manifest()
2610 .map_or(0, |manifest| manifest.routes().len());
2611 Response::text(format!("{}|{nonce}|{route_count}", context.uri()))
2612 }
2613 }
2614
2615 let handler =
2616 |_request: Request| async { Ok::<_, Response>((StatusCode::CREATED, ContextResponse)) };
2617 let mut request = Request::new(Method::GET, "/context".parse().unwrap());
2618 request
2619 .extensions_mut()
2620 .insert(CspNonce::new("0123456789abcdef0123456789abcdef").unwrap());
2621 request
2622 .extensions_mut()
2623 .insert(RouteManifest::new(Arc::new(HashMap::from([(
2624 "home".to_owned(),
2625 "/".to_owned(),
2626 )]))));
2627
2628 let response = Handler::call(&handler, request).await;
2629
2630 assert_eq!(response.status(), StatusCode::CREATED);
2631 assert_eq!(
2632 response.body(),
2633 "/context|0123456789abcdef0123456789abcdef|1"
2634 );
2635 }
2636
2637 #[test]
2638 fn redirect_and_download_headers_reject_injection_and_preserve_unicode() {
2639 assert!(Redirect::see_other("/safe\r\nx-injected: yes").is_err());
2640 let redirect = Redirect::see_other("/account")
2641 .expect("valid redirect")
2642 .into_response();
2643 assert_eq!(redirect.status(), StatusCode::SEE_OTHER);
2644 assert_eq!(redirect.headers()[header::LOCATION], "/account");
2645
2646 let response = Download::attachment(
2647 Bytes::from_static(b"profile"),
2648 "证书\r\nset-cookie: bad.mobileconfig",
2649 "application/x-apple-aspen-config"
2650 .parse()
2651 .expect("valid MIME"),
2652 )
2653 .into_response();
2654 let disposition = response.headers()[header::CONTENT_DISPOSITION]
2655 .to_str()
2656 .expect("ASCII header");
2657 assert!(disposition.contains("filename*=UTF-8''"));
2658 assert!(!disposition.contains("\r\n"));
2659 assert_eq!(
2660 response.headers()[header::CACHE_CONTROL],
2661 "private, no-store"
2662 );
2663 assert_eq!(response.headers()["x-content-type-options"], "nosniff");
2664 }
2665}