-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathbody_limit.rs
More file actions
325 lines (279 loc) · 10.5 KB
/
Copy pathbody_limit.rs
File metadata and controls
325 lines (279 loc) · 10.5 KB
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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
//! Body size limit middleware for RustAPI
//!
//! This module provides middleware to enforce request body size limits,
//! protecting against denial-of-service attacks via large payloads.
//!
//! # Example
//!
//! ```rust,ignore
//! use rustapi_rs::prelude::*;
//! use rustapi_core::middleware::BodyLimitLayer;
//!
//! RustApi::new()
//! .layer(BodyLimitLayer::new(1024 * 1024)) // 1MB limit
//! .route("/upload", post(upload_handler))
//! .run("127.0.0.1:8080")
//! .await
//! ```
use super::{BoxedNext, MiddlewareLayer};
use crate::error::ApiError;
use crate::request::Request;
use crate::response::{IntoResponse, Response};
use http::StatusCode;
use std::future::Future;
use std::pin::Pin;
/// Default body size limit: 1MB
pub const DEFAULT_BODY_LIMIT: usize = 1024 * 1024;
/// Body size limit middleware layer
///
/// Enforces a maximum size for request bodies. When a request body exceeds
/// the configured limit, a 413 Payload Too Large response is returned.
#[derive(Clone)]
pub struct BodyLimitLayer {
limit: usize,
}
impl BodyLimitLayer {
/// Create a new body limit layer with the specified limit in bytes
///
/// # Arguments
///
/// * `limit` - Maximum body size in bytes
///
/// # Example
///
/// ```rust,ignore
/// // 2MB limit
/// let layer = BodyLimitLayer::new(2 * 1024 * 1024);
/// ```
pub fn new(limit: usize) -> Self {
Self { limit }
}
/// Create a body limit layer with the default limit (1MB)
pub fn default_limit() -> Self {
Self::new(DEFAULT_BODY_LIMIT)
}
/// Get the configured limit
pub fn limit(&self) -> usize {
self.limit
}
}
impl Default for BodyLimitLayer {
fn default() -> Self {
Self::default_limit()
}
}
impl MiddlewareLayer for BodyLimitLayer {
fn call(
&self,
req: Request,
next: BoxedNext,
) -> Pin<Box<dyn Future<Output = Response> + Send + 'static>> {
let limit = self.limit;
Box::pin(async move {
// Check Content-Length header first if available
if let Some(content_length) = req.headers().get(http::header::CONTENT_LENGTH) {
if let Ok(length_str) = content_length.to_str() {
if let Ok(length) = length_str.parse::<usize>() {
if length > limit {
return ApiError::new(
StatusCode::PAYLOAD_TOO_LARGE,
"payload_too_large",
format!("Request body exceeds limit of {} bytes", limit),
)
.into_response();
}
}
}
}
// Also check actual body size (for cases without Content-Length or streaming)
// The body has already been read at this point in the pipeline
if let Some(body) = &req.body {
if body.len() > limit {
return ApiError::new(
StatusCode::PAYLOAD_TOO_LARGE,
"payload_too_large",
format!("Request body exceeds limit of {} bytes", limit),
)
.into_response();
}
}
// Body is within limits, continue to next middleware/handler
next(req).await
})
}
fn clone_box(&self) -> Box<dyn MiddlewareLayer> {
Box::new(self.clone())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::path_params::PathParams;
use crate::request::Request;
use bytes::Bytes;
use http::{Extensions, Method};
use proptest::prelude::*;
use std::sync::Arc;
/// Create a test request with the given body
fn create_test_request_with_body(body: Bytes) -> Request {
let uri: http::Uri = "/test".parse().unwrap();
let mut builder = http::Request::builder().method(Method::POST).uri(uri);
// Set Content-Length header
builder = builder.header(http::header::CONTENT_LENGTH, body.len().to_string());
let req = builder.body(()).unwrap();
let (parts, _) = req.into_parts();
Request::new(parts, body, Arc::new(Extensions::new()), PathParams::new())
}
/// Create a test request without Content-Length header
fn create_test_request_without_content_length(body: Bytes) -> Request {
let uri: http::Uri = "/test".parse().unwrap();
let builder = http::Request::builder().method(Method::POST).uri(uri);
let req = builder.body(()).unwrap();
let (parts, _) = req.into_parts();
Request::new(parts, body, Arc::new(Extensions::new()), PathParams::new())
}
/// Create a simple handler that returns 200 OK
fn ok_handler() -> BoxedNext {
Arc::new(|_req: Request| {
Box::pin(async {
http::Response::builder()
.status(StatusCode::OK)
.body(http_body_util::Full::new(Bytes::from("ok")))
.unwrap()
}) as Pin<Box<dyn Future<Output = Response> + Send + 'static>>
})
}
// **Feature: phase4-ergonomics-v1, Property 3: Body Size Limit Enforcement**
//
// For any configured body size limit L and any request body B where size(B) > L,
// the system should return a 413 Payload Too Large response.
//
// **Validates: Requirements 2.2, 2.3, 2.4, 2.5**
proptest! {
#![proptest_config(ProptestConfig::with_cases(100))]
#[test]
fn prop_body_size_limit_enforcement(
// Generate limit between 1 and 10KB for testing
limit in 1usize..10240usize,
// Generate body size relative to limit
body_size_factor in 0.5f64..2.0f64,
) {
let rt = tokio::runtime::Runtime::new().unwrap();
rt.block_on(async {
let body_size = ((limit as f64) * body_size_factor) as usize;
let body = Bytes::from(vec![b'x'; body_size]);
let request = create_test_request_with_body(body.clone());
let layer = BodyLimitLayer::new(limit);
let handler = ok_handler();
let response = layer.call(request, handler).await;
if body_size > limit {
// Body exceeds limit - should return 413
prop_assert_eq!(
response.status(),
StatusCode::PAYLOAD_TOO_LARGE,
"Expected 413 for body size {} > limit {}",
body_size,
limit
);
} else {
// Body within limit - should return 200
prop_assert_eq!(
response.status(),
StatusCode::OK,
"Expected 200 for body size {} <= limit {}",
body_size,
limit
);
}
Ok(())
})?;
}
#[test]
fn prop_body_limit_without_content_length_header(
limit in 1usize..10240usize,
body_size_factor in 0.5f64..2.0f64,
) {
let rt = tokio::runtime::Runtime::new().unwrap();
rt.block_on(async {
let body_size = ((limit as f64) * body_size_factor) as usize;
let body = Bytes::from(vec![b'x'; body_size]);
// Create request without Content-Length header
let request = create_test_request_without_content_length(body.clone());
let layer = BodyLimitLayer::new(limit);
let handler = ok_handler();
let response = layer.call(request, handler).await;
if body_size > limit {
// Body exceeds limit - should return 413
prop_assert_eq!(
response.status(),
StatusCode::PAYLOAD_TOO_LARGE,
"Expected 413 for body size {} > limit {} (no Content-Length)",
body_size,
limit
);
} else {
// Body within limit - should return 200
prop_assert_eq!(
response.status(),
StatusCode::OK,
"Expected 200 for body size {} <= limit {} (no Content-Length)",
body_size,
limit
);
}
Ok(())
})?;
}
}
#[tokio::test]
async fn test_body_at_exact_limit() {
let limit = 100;
let body = Bytes::from(vec![b'x'; limit]);
let request = create_test_request_with_body(body);
let layer = BodyLimitLayer::new(limit);
let handler = ok_handler();
let response = layer.call(request, handler).await;
assert_eq!(response.status(), StatusCode::OK);
}
#[tokio::test]
async fn test_body_one_byte_over_limit() {
let limit = 100;
let body = Bytes::from(vec![b'x'; limit + 1]);
let request = create_test_request_with_body(body);
let layer = BodyLimitLayer::new(limit);
let handler = ok_handler();
let response = layer.call(request, handler).await;
assert_eq!(response.status(), StatusCode::PAYLOAD_TOO_LARGE);
}
#[tokio::test]
async fn test_body_one_byte_under_limit() {
let limit = 100;
let body = Bytes::from(vec![b'x'; limit - 1]);
let request = create_test_request_with_body(body);
let layer = BodyLimitLayer::new(limit);
let handler = ok_handler();
let response = layer.call(request, handler).await;
assert_eq!(response.status(), StatusCode::OK);
}
#[tokio::test]
async fn test_empty_body() {
let limit = 100;
let body = Bytes::new();
let request = create_test_request_with_body(body);
let layer = BodyLimitLayer::new(limit);
let handler = ok_handler();
let response = layer.call(request, handler).await;
assert_eq!(response.status(), StatusCode::OK);
}
#[tokio::test]
async fn test_default_limit() {
let layer = BodyLimitLayer::default();
assert_eq!(layer.limit(), DEFAULT_BODY_LIMIT);
}
#[test]
fn test_clone() {
let layer = BodyLimitLayer::new(1024);
let cloned = layer.clone();
assert_eq!(layer.limit(), cloned.limit());
}
}