Skip to main content

phoenix_http/
lib.rs

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