1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
//! Body limit extractor.
//!
//! See [`BodyLimit`] docs.

use std::{
    fmt,
    future::Future,
    pin::Pin,
    task::{ready, Context, Poll},
};

use actix_web::{
    dev::{self, Payload},
    FromRequest, HttpMessage as _, HttpRequest, ResponseError,
};
use derive_more::{AsRef, Display, From};
use futures_core::Stream as _;

use crate::header::ContentLength;

/// Default body size limit of 2MiB.
pub const DEFAULT_BODY_LIMIT: usize = 2_097_152;

/// Extractor wrapper that limits size of payload used.
///
/// # Examples
/// ```no_run
/// use actix_web::{Responder, get, web::Bytes};
/// use actix_web_lab::extract::BodyLimit;
///
/// const BODY_LIMIT: usize = 1_048_576; // 1MB
///
/// #[get("/")]
/// async fn handler(body: BodyLimit<Bytes, BODY_LIMIT>) -> impl Responder {
///     let body = body.into_inner();
///     assert!(body.len() < BODY_LIMIT);
///     body
/// }
/// ```
#[derive(Debug, PartialEq, Eq, AsRef, Display, From)]
pub struct BodyLimit<T, const LIMIT: usize = DEFAULT_BODY_LIMIT> {
    inner: T,
}

impl<T, const LIMIT: usize> BodyLimit<T, LIMIT> {
    /// Returns inner extracted type.
    pub fn into_inner(self) -> T {
        self.inner
    }
}

impl<T, const LIMIT: usize> FromRequest for BodyLimit<T, LIMIT>
where
    T: FromRequest + 'static,
    T::Error: fmt::Debug + fmt::Display,
{
    type Error = BodyLimitError<T>;
    type Future = BodyLimitFut<T, LIMIT>;

    fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future {
        // fast check of Content-Length header
        match req.get_header::<ContentLength>() {
            // CL header indicated that payload would be too large
            Some(len) if len > LIMIT => return BodyLimitFut::new_error(BodyLimitError::Overflow),
            _ => {}
        }

        let counter = crate::util::fork_request_payload(payload);

        BodyLimitFut {
            inner: Inner::Body {
                fut: Box::pin(T::from_request(req, payload)),
                counter_pl: counter,
                size: 0,
            },
        }
    }
}

pub struct BodyLimitFut<T, const LIMIT: usize>
where
    T: FromRequest + 'static,
    T::Error: fmt::Debug + fmt::Display,
{
    inner: Inner<T, LIMIT>,
}

impl<T, const LIMIT: usize> BodyLimitFut<T, LIMIT>
where
    T: FromRequest + 'static,
    T::Error: fmt::Debug + fmt::Display,
{
    fn new_error(err: BodyLimitError<T>) -> Self {
        Self {
            inner: Inner::Error { err: Some(err) },
        }
    }
}

enum Inner<T, const LIMIT: usize>
where
    T: FromRequest + 'static,
    T::Error: fmt::Debug + fmt::Display,
{
    Error {
        err: Option<BodyLimitError<T>>,
    },

    Body {
        /// Wrapped extractor future.
        fut: Pin<Box<T::Future>>,

        /// Forked request payload.
        counter_pl: dev::Payload,

        /// Running payload size count.
        size: usize,
    },
}

impl<T, const LIMIT: usize> Unpin for Inner<T, LIMIT>
where
    T: FromRequest + 'static,
    T::Error: fmt::Debug + fmt::Display,
{
}

impl<T, const LIMIT: usize> Future for BodyLimitFut<T, LIMIT>
where
    T: FromRequest + 'static,
    T::Error: fmt::Debug + fmt::Display,
{
    type Output = Result<BodyLimit<T, LIMIT>, BodyLimitError<T>>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let this = &mut self.get_mut().inner;

        match this {
            Inner::Error { err } => Poll::Ready(Err(err.take().unwrap())),

            Inner::Body {
                fut,
                counter_pl,
                size,
            } => {
                // poll inner extractor first which also polls original payload stream
                let res = ready!(fut.as_mut().poll(cx).map_err(BodyLimitError::Extractor)?);

                // catch up with payload length counter checks
                while let Poll::Ready(Some(Ok(chunk))) = Pin::new(&mut *counter_pl).poll_next(cx) {
                    // update running size
                    *size += chunk.len();

                    if *size > LIMIT {
                        return Poll::Ready(Err(BodyLimitError::Overflow));
                    }
                }

                let ret = BodyLimit { inner: res };

                Poll::Ready(Ok(ret))
            }
        }
    }
}

#[derive(Display)]
pub enum BodyLimitError<T>
where
    T: FromRequest + 'static,
    T::Error: fmt::Debug + fmt::Display,
{
    #[display(fmt = "Wrapped extractor error: {_0}")]
    Extractor(T::Error),

    #[display(fmt = "Body was too large")]
    Overflow,
}

impl<T> fmt::Debug for BodyLimitError<T>
where
    T: FromRequest + 'static,
    T::Error: fmt::Debug + fmt::Display,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Extractor(err) => f
                .debug_tuple("BodyLimitError::Extractor")
                .field(err)
                .finish(),

            Self::Overflow => write!(f, "BodyLimitError::Overflow"),
        }
    }
}

impl<T> ResponseError for BodyLimitError<T>
where
    T: FromRequest + 'static,
    T::Error: fmt::Debug + fmt::Display,
{
}

#[cfg(test)]
mod tests {
    use actix_web::{http::header, test::TestRequest};
    use bytes::Bytes;

    use super::*;

    static_assertions::assert_impl_all!(BodyLimitFut<(), 100>: Unpin);
    static_assertions::assert_impl_all!(BodyLimitFut<Bytes, 100>: Unpin);

    #[actix_web::test]
    async fn within_limit() {
        let (req, mut pl) = TestRequest::default()
            .insert_header(header::ContentType::plaintext())
            .insert_header((
                header::CONTENT_LENGTH,
                header::HeaderValue::from_static("9"),
            ))
            .set_payload(Bytes::from_static(b"123456789"))
            .to_http_parts();

        let body = BodyLimit::<Bytes, 10>::from_request(&req, &mut pl).await;
        assert_eq!(
            body.ok().unwrap().into_inner(),
            Bytes::from_static(b"123456789")
        );
    }

    #[actix_web::test]
    async fn exceeds_limit() {
        let (req, mut pl) = TestRequest::default()
            .insert_header(header::ContentType::plaintext())
            .insert_header((
                header::CONTENT_LENGTH,
                header::HeaderValue::from_static("10"),
            ))
            .set_payload(Bytes::from_static(b"0123456789"))
            .to_http_parts();

        let body = BodyLimit::<Bytes, 4>::from_request(&req, &mut pl).await;
        assert!(matches!(body.unwrap_err(), BodyLimitError::Overflow));

        let (req, mut pl) = TestRequest::default()
            .insert_header(header::ContentType::plaintext())
            .insert_header((
                header::TRANSFER_ENCODING,
                header::HeaderValue::from_static("chunked"),
            ))
            .set_payload(Bytes::from_static(b"10\r\n0123456789\r\n0"))
            .to_http_parts();

        let body = BodyLimit::<Bytes, 4>::from_request(&req, &mut pl).await;
        assert!(matches!(body.unwrap_err(), BodyLimitError::Overflow));
    }
}