spikard 0.5.0 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (135) hide show
  1. checksums.yaml +4 -4
  2. data/LICENSE +1 -1
  3. data/README.md +674 -674
  4. data/ext/spikard_rb/Cargo.toml +17 -17
  5. data/ext/spikard_rb/extconf.rb +13 -10
  6. data/ext/spikard_rb/src/lib.rs +6 -6
  7. data/lib/spikard/app.rb +405 -405
  8. data/lib/spikard/background.rb +27 -27
  9. data/lib/spikard/config.rb +396 -396
  10. data/lib/spikard/converters.rb +13 -13
  11. data/lib/spikard/handler_wrapper.rb +113 -113
  12. data/lib/spikard/provide.rb +214 -214
  13. data/lib/spikard/response.rb +173 -173
  14. data/lib/spikard/schema.rb +243 -243
  15. data/lib/spikard/sse.rb +111 -111
  16. data/lib/spikard/streaming_response.rb +44 -44
  17. data/lib/spikard/testing.rb +256 -256
  18. data/lib/spikard/upload_file.rb +131 -131
  19. data/lib/spikard/version.rb +5 -5
  20. data/lib/spikard/websocket.rb +59 -59
  21. data/lib/spikard.rb +43 -43
  22. data/sig/spikard.rbs +366 -366
  23. data/vendor/crates/spikard-bindings-shared/Cargo.toml +63 -63
  24. data/vendor/crates/spikard-bindings-shared/examples/config_extraction.rs +132 -132
  25. data/vendor/crates/spikard-bindings-shared/src/config_extractor.rs +752 -752
  26. data/vendor/crates/spikard-bindings-shared/src/conversion_traits.rs +194 -194
  27. data/vendor/crates/spikard-bindings-shared/src/di_traits.rs +246 -246
  28. data/vendor/crates/spikard-bindings-shared/src/error_response.rs +401 -401
  29. data/vendor/crates/spikard-bindings-shared/src/handler_base.rs +238 -238
  30. data/vendor/crates/spikard-bindings-shared/src/lib.rs +24 -24
  31. data/vendor/crates/spikard-bindings-shared/src/lifecycle_base.rs +292 -292
  32. data/vendor/crates/spikard-bindings-shared/src/lifecycle_executor.rs +616 -616
  33. data/vendor/crates/spikard-bindings-shared/src/response_builder.rs +305 -305
  34. data/vendor/crates/spikard-bindings-shared/src/test_client_base.rs +248 -248
  35. data/vendor/crates/spikard-bindings-shared/src/validation_helpers.rs +351 -351
  36. data/vendor/crates/spikard-bindings-shared/tests/comprehensive_coverage.rs +454 -454
  37. data/vendor/crates/spikard-bindings-shared/tests/error_response_edge_cases.rs +383 -383
  38. data/vendor/crates/spikard-bindings-shared/tests/handler_base_integration.rs +280 -280
  39. data/vendor/crates/spikard-core/Cargo.toml +40 -40
  40. data/vendor/crates/spikard-core/src/bindings/mod.rs +3 -3
  41. data/vendor/crates/spikard-core/src/bindings/response.rs +133 -133
  42. data/vendor/crates/spikard-core/src/debug.rs +127 -127
  43. data/vendor/crates/spikard-core/src/di/container.rs +702 -702
  44. data/vendor/crates/spikard-core/src/di/dependency.rs +273 -273
  45. data/vendor/crates/spikard-core/src/di/error.rs +118 -118
  46. data/vendor/crates/spikard-core/src/di/factory.rs +534 -534
  47. data/vendor/crates/spikard-core/src/di/graph.rs +506 -506
  48. data/vendor/crates/spikard-core/src/di/mod.rs +192 -192
  49. data/vendor/crates/spikard-core/src/di/resolved.rs +405 -405
  50. data/vendor/crates/spikard-core/src/di/value.rs +281 -281
  51. data/vendor/crates/spikard-core/src/errors.rs +69 -69
  52. data/vendor/crates/spikard-core/src/http.rs +415 -415
  53. data/vendor/crates/spikard-core/src/lib.rs +29 -29
  54. data/vendor/crates/spikard-core/src/lifecycle.rs +1186 -1186
  55. data/vendor/crates/spikard-core/src/metadata.rs +389 -389
  56. data/vendor/crates/spikard-core/src/parameters.rs +2525 -2525
  57. data/vendor/crates/spikard-core/src/problem.rs +344 -344
  58. data/vendor/crates/spikard-core/src/request_data.rs +1154 -1154
  59. data/vendor/crates/spikard-core/src/router.rs +510 -510
  60. data/vendor/crates/spikard-core/src/schema_registry.rs +183 -183
  61. data/vendor/crates/spikard-core/src/type_hints.rs +304 -304
  62. data/vendor/crates/spikard-core/src/validation/error_mapper.rs +696 -688
  63. data/vendor/crates/spikard-core/src/validation/mod.rs +457 -457
  64. data/vendor/crates/spikard-http/Cargo.toml +62 -64
  65. data/vendor/crates/spikard-http/examples/sse-notifications.rs +148 -148
  66. data/vendor/crates/spikard-http/examples/websocket-chat.rs +92 -92
  67. data/vendor/crates/spikard-http/src/auth.rs +296 -296
  68. data/vendor/crates/spikard-http/src/background.rs +1860 -1860
  69. data/vendor/crates/spikard-http/src/bindings/mod.rs +3 -3
  70. data/vendor/crates/spikard-http/src/bindings/response.rs +1 -1
  71. data/vendor/crates/spikard-http/src/body_metadata.rs +8 -8
  72. data/vendor/crates/spikard-http/src/cors.rs +1005 -1005
  73. data/vendor/crates/spikard-http/src/debug.rs +128 -128
  74. data/vendor/crates/spikard-http/src/di_handler.rs +1668 -1668
  75. data/vendor/crates/spikard-http/src/handler_response.rs +901 -901
  76. data/vendor/crates/spikard-http/src/handler_trait.rs +838 -830
  77. data/vendor/crates/spikard-http/src/handler_trait_tests.rs +290 -290
  78. data/vendor/crates/spikard-http/src/lib.rs +534 -534
  79. data/vendor/crates/spikard-http/src/lifecycle/adapter.rs +230 -230
  80. data/vendor/crates/spikard-http/src/lifecycle.rs +1193 -1193
  81. data/vendor/crates/spikard-http/src/middleware/mod.rs +560 -540
  82. data/vendor/crates/spikard-http/src/middleware/multipart.rs +912 -912
  83. data/vendor/crates/spikard-http/src/middleware/urlencoded.rs +513 -513
  84. data/vendor/crates/spikard-http/src/middleware/validation.rs +768 -735
  85. data/vendor/crates/spikard-http/src/openapi/mod.rs +309 -309
  86. data/vendor/crates/spikard-http/src/openapi/parameter_extraction.rs +535 -535
  87. data/vendor/crates/spikard-http/src/openapi/schema_conversion.rs +1363 -1363
  88. data/vendor/crates/spikard-http/src/openapi/spec_generation.rs +665 -665
  89. data/vendor/crates/spikard-http/src/query_parser.rs +793 -793
  90. data/vendor/crates/spikard-http/src/response.rs +720 -720
  91. data/vendor/crates/spikard-http/src/server/handler.rs +1650 -1650
  92. data/vendor/crates/spikard-http/src/server/lifecycle_execution.rs +234 -234
  93. data/vendor/crates/spikard-http/src/server/mod.rs +1593 -1502
  94. data/vendor/crates/spikard-http/src/server/request_extraction.rs +789 -770
  95. data/vendor/crates/spikard-http/src/server/routing_factory.rs +629 -599
  96. data/vendor/crates/spikard-http/src/sse.rs +1409 -1409
  97. data/vendor/crates/spikard-http/src/testing/form.rs +52 -52
  98. data/vendor/crates/spikard-http/src/testing/multipart.rs +64 -60
  99. data/vendor/crates/spikard-http/src/testing/test_client.rs +311 -283
  100. data/vendor/crates/spikard-http/src/testing.rs +406 -377
  101. data/vendor/crates/spikard-http/src/websocket.rs +1404 -1375
  102. data/vendor/crates/spikard-http/tests/background_behavior.rs +832 -832
  103. data/vendor/crates/spikard-http/tests/common/handlers.rs +309 -309
  104. data/vendor/crates/spikard-http/tests/common/mod.rs +26 -26
  105. data/vendor/crates/spikard-http/tests/di_integration.rs +192 -192
  106. data/vendor/crates/spikard-http/tests/doc_snippets.rs +5 -5
  107. data/vendor/crates/spikard-http/tests/lifecycle_execution.rs +1093 -1093
  108. data/vendor/crates/spikard-http/tests/multipart_behavior.rs +656 -656
  109. data/vendor/crates/spikard-http/tests/server_config_builder.rs +314 -314
  110. data/vendor/crates/spikard-http/tests/sse_behavior.rs +620 -620
  111. data/vendor/crates/spikard-http/tests/websocket_behavior.rs +663 -663
  112. data/vendor/crates/spikard-rb/Cargo.toml +48 -48
  113. data/vendor/crates/spikard-rb/build.rs +199 -199
  114. data/vendor/crates/spikard-rb/src/background.rs +63 -63
  115. data/vendor/crates/spikard-rb/src/config/mod.rs +5 -5
  116. data/vendor/crates/spikard-rb/src/config/server_config.rs +285 -285
  117. data/vendor/crates/spikard-rb/src/conversion.rs +554 -554
  118. data/vendor/crates/spikard-rb/src/di/builder.rs +100 -100
  119. data/vendor/crates/spikard-rb/src/di/mod.rs +375 -375
  120. data/vendor/crates/spikard-rb/src/handler.rs +618 -618
  121. data/vendor/crates/spikard-rb/src/integration/mod.rs +3 -3
  122. data/vendor/crates/spikard-rb/src/lib.rs +1806 -1810
  123. data/vendor/crates/spikard-rb/src/lifecycle.rs +275 -275
  124. data/vendor/crates/spikard-rb/src/metadata/mod.rs +5 -5
  125. data/vendor/crates/spikard-rb/src/metadata/route_extraction.rs +442 -447
  126. data/vendor/crates/spikard-rb/src/runtime/mod.rs +5 -5
  127. data/vendor/crates/spikard-rb/src/runtime/server_runner.rs +324 -324
  128. data/vendor/crates/spikard-rb/src/server.rs +305 -308
  129. data/vendor/crates/spikard-rb/src/sse.rs +231 -231
  130. data/vendor/crates/spikard-rb/src/testing/client.rs +538 -551
  131. data/vendor/crates/spikard-rb/src/testing/mod.rs +7 -7
  132. data/vendor/crates/spikard-rb/src/testing/sse.rs +143 -143
  133. data/vendor/crates/spikard-rb/src/testing/websocket.rs +608 -635
  134. data/vendor/crates/spikard-rb/src/websocket.rs +377 -374
  135. metadata +15 -1
@@ -1,540 +1,560 @@
1
- //! HTTP middleware for request validation
2
- //!
3
- //! Provides middleware stack setup, JSON schema validation, multipart/form-data parsing,
4
- //! and URL-encoded form data handling.
5
-
6
- pub mod multipart;
7
- pub mod urlencoded;
8
- pub mod validation;
9
-
10
- use axum::{
11
- body::Body,
12
- extract::State,
13
- extract::{FromRequest, Multipart, Request},
14
- http::StatusCode,
15
- middleware::Next,
16
- response::{IntoResponse, Response},
17
- };
18
- use serde_json::json;
19
- use std::cell::RefCell;
20
- use std::num::NonZeroUsize;
21
-
22
- thread_local! {
23
- static URLENCODED_JSON_CACHE: RefCell<lru::LruCache<bytes::Bytes, bytes::Bytes>> =
24
- RefCell::new(lru::LruCache::new(NonZeroUsize::new(256).expect("non-zero cache size")));
25
- }
26
-
27
- /// Route information for middleware validation
28
- #[derive(Debug, Clone)]
29
- pub struct RouteInfo {
30
- /// Whether this route expects a JSON request body
31
- pub expects_json_body: bool,
32
- }
33
-
34
- /// Request extension carrying the already-collected request body.
35
- ///
36
- /// This avoids double-reading the body stream: middleware can read once for
37
- /// content-length / syntax checks, and request extraction can reuse the bytes.
38
- #[derive(Debug, Clone)]
39
- pub struct PreReadBody(pub bytes::Bytes);
40
-
41
- /// Middleware to validate Content-Type headers and related requirements
42
- ///
43
- /// This middleware performs comprehensive request body validation and transformation:
44
- ///
45
- /// - **Content-Type Validation:** Ensures the request's Content-Type header matches the
46
- /// expected format for the route (if configured).
47
- ///
48
- /// - **Multipart Form Data:** Automatically parses `multipart/form-data` requests and
49
- /// transforms them into JSON format for uniform downstream processing.
50
- ///
51
- /// - **URL-Encoded Forms:** Parses `application/x-www-form-urlencoded` requests and
52
- /// converts them to JSON.
53
- ///
54
- /// - **JSON Validation:** Validates JSON request bodies for well-formedness (when the
55
- /// Content-Type is `application/json`).
56
- ///
57
- /// - **Content-Length:** Validates that the Content-Length header is present and
58
- /// reasonable for POST, PUT, and PATCH requests.
59
- ///
60
- /// # Behavior
61
- ///
62
- /// For request methods POST, PUT, and PATCH:
63
- /// 1. Checks if the route expects a JSON body (via route state)
64
- /// 2. Validates Content-Type headers based on route configuration
65
- /// 3. Parses the request body according to Content-Type:
66
- /// - `multipart/form-data` JSON (form fields as object properties)
67
- /// - `application/x-www-form-urlencoded` JSON (URL parameters as object)
68
- /// - `application/json` Validates JSON syntax
69
- /// 4. Transforms the request to have `Content-Type: application/json`
70
- /// 5. Passes the transformed request to the next middleware
71
- ///
72
- /// For GET, DELETE, and other methods: passes through with minimal validation.
73
- ///
74
- /// # Errors
75
- ///
76
- /// Returns HTTP error responses for:
77
- /// - `400 Bad Request` - Failed to read request body, invalid JSON, malformed forms, invalid Content-Length
78
- /// - `500 Internal Server Error` - Failed to serialize transformed body
79
- ///
80
- /// # Examples
81
- ///
82
- /// ```rust
83
- /// use axum::{middleware::Next, extract::Request};
84
- /// use spikard_http::middleware::validate_content_type_middleware;
85
- ///
86
- /// // This is typically used as middleware in an Axum router:
87
- /// // router.layer(axum::middleware::from_fn(validate_content_type_middleware))
88
- /// ```
89
- ///
90
- /// Coverage: Tested via integration tests (multipart and form parsing tested end-to-end)
91
- #[cfg(not(tarpaulin_include))]
92
- pub async fn validate_content_type_middleware(
93
- State(route_info): State<RouteInfo>,
94
- request: Request,
95
- next: Next,
96
- ) -> Result<Response, Response> {
97
- use axum::body::to_bytes;
98
- use axum::http::Request as HttpRequest;
99
-
100
- let (mut parts, body) = request.into_parts();
101
- let headers = &parts.headers;
102
-
103
- let method = &parts.method;
104
- if method == axum::http::Method::POST || method == axum::http::Method::PUT || method == axum::http::Method::PATCH {
105
- if route_info.expects_json_body {
106
- validation::validate_json_content_type(headers)?;
107
- }
108
-
109
- validation::validate_content_type_headers(headers, 0)?;
110
-
111
- let out_bytes: bytes::Bytes = if let Some(content_type) = headers.get(axum::http::header::CONTENT_TYPE) {
112
- // `validate_content_type_headers()` already enforced basic Content-Type validity for us.
113
- let is_multipart = validation::is_multipart_form_data(content_type);
114
- let is_form_urlencoded = validation::is_form_urlencoded(content_type);
115
-
116
- if is_multipart {
117
- let body_bytes = match to_bytes(body, usize::MAX).await {
118
- Ok(bytes) => bytes,
119
- Err(_) => {
120
- let error_body = json!({
121
- "error": "Failed to read request body"
122
- });
123
- return Err((StatusCode::BAD_REQUEST, axum::Json(error_body)).into_response());
124
- }
125
- };
126
-
127
- validation::validate_content_length(headers, body_bytes.len())?;
128
-
129
- let mut parse_request = HttpRequest::new(Body::from(body_bytes));
130
- *parse_request.headers_mut() = parts.headers.clone();
131
-
132
- let multipart = match Multipart::from_request(parse_request, &()).await {
133
- Ok(mp) => mp,
134
- Err(e) => {
135
- let error_body = json!({
136
- "error": format!("Failed to parse multipart data: {}", e)
137
- });
138
- return Err((StatusCode::BAD_REQUEST, axum::Json(error_body)).into_response());
139
- }
140
- };
141
-
142
- let json_body = match multipart::parse_multipart_to_json(multipart).await {
143
- Ok(json) => json,
144
- Err(e) => {
145
- let error_body = json!({
146
- "error": format!("Failed to process multipart data: {}", e)
147
- });
148
- return Err((StatusCode::BAD_REQUEST, axum::Json(error_body)).into_response());
149
- }
150
- };
151
-
152
- let json_bytes = match serde_json::to_vec(&json_body) {
153
- Ok(bytes) => bytes,
154
- Err(e) => {
155
- let error_body = json!({
156
- "error": format!("Failed to serialize multipart data to JSON: {}", e)
157
- });
158
- return Err((StatusCode::INTERNAL_SERVER_ERROR, axum::Json(error_body)).into_response());
159
- }
160
- };
161
-
162
- parts.headers.insert(
163
- axum::http::header::CONTENT_TYPE,
164
- axum::http::HeaderValue::from_static("application/json"),
165
- );
166
- if let Ok(value) = axum::http::HeaderValue::from_str(&json_bytes.len().to_string()) {
167
- parts.headers.insert(axum::http::header::CONTENT_LENGTH, value);
168
- }
169
- bytes::Bytes::from(json_bytes)
170
- } else if is_form_urlencoded {
171
- let body_bytes = match to_bytes(body, usize::MAX).await {
172
- Ok(bytes) => bytes,
173
- Err(_) => {
174
- let error_body = json!({
175
- "error": "Failed to read request body"
176
- });
177
- return Err((StatusCode::BAD_REQUEST, axum::Json(error_body)).into_response());
178
- }
179
- };
180
-
181
- validation::validate_content_length(headers, body_bytes.len())?;
182
-
183
- parts.headers.insert(
184
- axum::http::header::CONTENT_TYPE,
185
- axum::http::HeaderValue::from_static("application/json"),
186
- );
187
- if let Some(cached) = URLENCODED_JSON_CACHE.with(|cache| cache.borrow_mut().get(&body_bytes).cloned()) {
188
- cached
189
- } else {
190
- let json_body = if body_bytes.is_empty() {
191
- serde_json::json!({})
192
- } else {
193
- match urlencoded::parse_urlencoded_to_json(&body_bytes) {
194
- Ok(json_body) => json_body,
195
- Err(e) => {
196
- let error_body = json!({
197
- "error": format!("Failed to parse URL-encoded form data: {}", e)
198
- });
199
- return Err((StatusCode::BAD_REQUEST, axum::Json(error_body)).into_response());
200
- }
201
- }
202
- };
203
-
204
- let json_bytes = match serde_json::to_vec(&json_body) {
205
- Ok(bytes) => bytes,
206
- Err(e) => {
207
- let error_body = json!({
208
- "error": format!("Failed to serialize URL-encoded form data to JSON: {}", e)
209
- });
210
- return Err((StatusCode::INTERNAL_SERVER_ERROR, axum::Json(error_body)).into_response());
211
- }
212
- };
213
-
214
- let json_bytes = bytes::Bytes::from(json_bytes);
215
- URLENCODED_JSON_CACHE.with(|cache| {
216
- cache.borrow_mut().put(body_bytes.clone(), json_bytes.clone());
217
- });
218
- json_bytes
219
- }
220
- } else {
221
- let body_bytes = match to_bytes(body, usize::MAX).await {
222
- Ok(bytes) => bytes,
223
- Err(_) => {
224
- let error_body = json!({
225
- "error": "Failed to read request body"
226
- });
227
- return Err((StatusCode::BAD_REQUEST, axum::Json(error_body)).into_response());
228
- }
229
- };
230
-
231
- validation::validate_content_length(headers, body_bytes.len())?;
232
-
233
- let should_validate_json = route_info.expects_json_body && validation::is_json_like(content_type);
234
- if should_validate_json
235
- && !body_bytes.is_empty()
236
- && serde_json::from_slice::<serde_json::Value>(&body_bytes).is_err()
237
- {
238
- let error_body = json!({
239
- "detail": "Invalid request format"
240
- });
241
- return Err((StatusCode::BAD_REQUEST, axum::Json(error_body)).into_response());
242
- }
243
-
244
- body_bytes
245
- }
246
- } else {
247
- let body_bytes = match to_bytes(body, usize::MAX).await {
248
- Ok(bytes) => bytes,
249
- Err(_) => {
250
- let error_body = json!({
251
- "error": "Failed to read request body"
252
- });
253
- return Err((StatusCode::BAD_REQUEST, axum::Json(error_body)).into_response());
254
- }
255
- };
256
-
257
- validation::validate_content_length(headers, body_bytes.len())?;
258
- body_bytes
259
- };
260
-
261
- parts.extensions.insert(PreReadBody(out_bytes));
262
-
263
- let request = HttpRequest::from_parts(parts, Body::empty());
264
- Ok(next.run(request).await)
265
- } else {
266
- validation::validate_content_type_headers(headers, 0)?;
267
-
268
- let request = HttpRequest::from_parts(parts, body);
269
- Ok(next.run(request).await)
270
- }
271
- }
272
-
273
- #[cfg(test)]
274
- mod tests {
275
- use super::*;
276
- use axum::body::Body;
277
- use axum::http::Request;
278
-
279
- #[test]
280
- fn test_route_info_creation() {
281
- let info = RouteInfo {
282
- expects_json_body: true,
283
- };
284
- assert!(info.expects_json_body);
285
- }
286
-
287
- #[test]
288
- fn test_route_info_expects_json_body_true() {
289
- let info = RouteInfo {
290
- expects_json_body: true,
291
- };
292
- assert_eq!(info.expects_json_body, true);
293
- }
294
-
295
- #[test]
296
- fn test_route_info_expects_json_body_false() {
297
- let info = RouteInfo {
298
- expects_json_body: false,
299
- };
300
- assert_eq!(info.expects_json_body, false);
301
- }
302
-
303
- #[test]
304
- fn test_request_with_zero_content_length() {
305
- let headers = axum::http::HeaderMap::new();
306
- assert!(headers.get(axum::http::header::CONTENT_LENGTH).is_none());
307
- }
308
-
309
- #[test]
310
- fn test_request_with_very_large_content_length() {
311
- let mut headers = axum::http::HeaderMap::new();
312
- let large_size = usize::MAX - 1;
313
- headers.insert(
314
- axum::http::header::CONTENT_LENGTH,
315
- axum::http::HeaderValue::from_str(&large_size.to_string()).unwrap(),
316
- );
317
- assert!(headers.get(axum::http::header::CONTENT_LENGTH).is_some());
318
- }
319
-
320
- #[test]
321
- fn test_request_body_smaller_than_declared_length() {
322
- let mut headers = axum::http::HeaderMap::new();
323
- headers.insert(
324
- axum::http::header::CONTENT_LENGTH,
325
- axum::http::HeaderValue::from_static("1000"),
326
- );
327
- let result = super::validation::validate_content_length(&headers, 500);
328
- assert!(
329
- result.is_err(),
330
- "Should reject when actual body is smaller than declared"
331
- );
332
- }
333
-
334
- #[test]
335
- fn test_request_body_larger_than_declared_length() {
336
- let mut headers = axum::http::HeaderMap::new();
337
- headers.insert(
338
- axum::http::header::CONTENT_LENGTH,
339
- axum::http::HeaderValue::from_static("500"),
340
- );
341
- let result = super::validation::validate_content_length(&headers, 1000);
342
- assert!(
343
- result.is_err(),
344
- "Should reject when actual body is larger than declared"
345
- );
346
- }
347
-
348
- #[test]
349
- fn test_get_request_no_body_validation() {
350
- let request = Request::builder()
351
- .method(axum::http::Method::GET)
352
- .uri("/api/users")
353
- .body(Body::empty())
354
- .unwrap();
355
-
356
- let (parts, _body) = request.into_parts();
357
- assert_eq!(parts.method, axum::http::Method::GET);
358
- }
359
-
360
- #[test]
361
- fn test_delete_request_no_body_validation() {
362
- let request = Request::builder()
363
- .method(axum::http::Method::DELETE)
364
- .uri("/api/users/1")
365
- .body(Body::empty())
366
- .unwrap();
367
-
368
- let (parts, _body) = request.into_parts();
369
- assert_eq!(parts.method, axum::http::Method::DELETE);
370
- }
371
-
372
- #[test]
373
- fn test_post_request_requires_validation() {
374
- let request = Request::builder()
375
- .method(axum::http::Method::POST)
376
- .uri("/api/users")
377
- .body(Body::empty())
378
- .unwrap();
379
-
380
- let (parts, _body) = request.into_parts();
381
- assert_eq!(parts.method, axum::http::Method::POST);
382
- }
383
-
384
- #[test]
385
- fn test_put_request_requires_validation() {
386
- let request = Request::builder()
387
- .method(axum::http::Method::PUT)
388
- .uri("/api/users/1")
389
- .body(Body::empty())
390
- .unwrap();
391
-
392
- let (parts, _body) = request.into_parts();
393
- assert_eq!(parts.method, axum::http::Method::PUT);
394
- }
395
-
396
- #[test]
397
- fn test_patch_request_requires_validation() {
398
- let request = Request::builder()
399
- .method(axum::http::Method::PATCH)
400
- .uri("/api/users/1")
401
- .body(Body::empty())
402
- .unwrap();
403
-
404
- let (parts, _body) = request.into_parts();
405
- assert_eq!(parts.method, axum::http::Method::PATCH);
406
- }
407
-
408
- #[test]
409
- fn test_content_type_header_case_insensitive() {
410
- let mut headers = axum::http::HeaderMap::new();
411
- headers.insert(
412
- axum::http::header::CONTENT_TYPE,
413
- axum::http::HeaderValue::from_static("application/json"),
414
- );
415
-
416
- assert!(headers.get(axum::http::header::CONTENT_TYPE).is_some());
417
- }
418
-
419
- #[test]
420
- fn test_content_length_header_case_insensitive() {
421
- let mut headers = axum::http::HeaderMap::new();
422
- headers.insert(
423
- axum::http::header::CONTENT_LENGTH,
424
- axum::http::HeaderValue::from_static("100"),
425
- );
426
-
427
- assert!(headers.get(axum::http::header::CONTENT_LENGTH).is_some());
428
- }
429
-
430
- #[test]
431
- fn test_custom_headers_case_preserved() {
432
- let mut headers = axum::http::HeaderMap::new();
433
- let custom_header: axum::http::HeaderName = "X-Custom-Header".parse().unwrap();
434
- headers.insert(custom_header.clone(), axum::http::HeaderValue::from_static("value"));
435
-
436
- assert!(headers.get(&custom_header).is_some());
437
- }
438
-
439
- #[test]
440
- fn test_multipart_boundary_minimal() {
441
- let mut headers = axum::http::HeaderMap::new();
442
- headers.insert(
443
- axum::http::header::CONTENT_TYPE,
444
- axum::http::HeaderValue::from_static("multipart/form-data; boundary=x"),
445
- );
446
-
447
- let result = super::validation::validate_content_type_headers(&headers, 0);
448
- assert!(result.is_ok(), "Minimal boundary should be accepted");
449
- }
450
-
451
- #[test]
452
- fn test_multipart_boundary_with_numbers() {
453
- let mut headers = axum::http::HeaderMap::new();
454
- headers.insert(
455
- axum::http::header::CONTENT_TYPE,
456
- axum::http::HeaderValue::from_static("multipart/form-data; boundary=boundary123456"),
457
- );
458
-
459
- let result = super::validation::validate_content_type_headers(&headers, 0);
460
- assert!(result.is_ok());
461
- }
462
-
463
- #[test]
464
- fn test_multipart_boundary_with_special_chars() {
465
- let mut headers = axum::http::HeaderMap::new();
466
- headers.insert(
467
- axum::http::header::CONTENT_TYPE,
468
- axum::http::HeaderValue::from_static("multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW"),
469
- );
470
-
471
- let result = super::validation::validate_content_type_headers(&headers, 0);
472
- assert!(result.is_ok(), "Boundary with dashes should be accepted");
473
- }
474
-
475
- #[test]
476
- fn test_multipart_empty_boundary() {
477
- let mut headers = axum::http::HeaderMap::new();
478
- headers.insert(
479
- axum::http::header::CONTENT_TYPE,
480
- axum::http::HeaderValue::from_static("multipart/form-data; boundary="),
481
- );
482
-
483
- let _result = super::validation::validate_content_type_headers(&headers, 0);
484
- assert!(headers.get(axum::http::header::CONTENT_TYPE).is_some());
485
- }
486
-
487
- #[test]
488
- fn test_invalid_json_body_detection() {
489
- let invalid_json = r#"{"invalid": json without quotes}"#;
490
- let _mime = "application/json".parse::<mime::Mime>().unwrap();
491
-
492
- let result = serde_json::from_str::<serde_json::Value>(invalid_json);
493
- assert!(result.is_err(), "Invalid JSON should fail parsing");
494
- }
495
-
496
- #[test]
497
- fn test_valid_json_parsing() {
498
- let valid_json = r#"{"key": "value"}"#;
499
- let result = serde_json::from_str::<serde_json::Value>(valid_json);
500
- assert!(result.is_ok(), "Valid JSON should parse successfully");
501
- }
502
-
503
- #[test]
504
- fn test_empty_json_object() {
505
- let empty_json = "{}";
506
- let result = serde_json::from_str::<serde_json::Value>(empty_json);
507
- assert!(result.is_ok());
508
- let value = result.unwrap();
509
- assert!(value.is_object());
510
- assert_eq!(value.as_object().unwrap().len(), 0);
511
- }
512
-
513
- #[test]
514
- fn test_form_data_mime_type() {
515
- let mime = "multipart/form-data; boundary=xyz".parse::<mime::Mime>().unwrap();
516
- assert_eq!(mime.type_(), mime::MULTIPART);
517
- assert_eq!(mime.subtype(), "form-data");
518
- }
519
-
520
- #[test]
521
- fn test_form_urlencoded_mime_type() {
522
- let mime = "application/x-www-form-urlencoded".parse::<mime::Mime>().unwrap();
523
- assert_eq!(mime.type_(), mime::APPLICATION);
524
- assert_eq!(mime.subtype(), "x-www-form-urlencoded");
525
- }
526
-
527
- #[test]
528
- fn test_json_mime_type() {
529
- let mime = "application/json".parse::<mime::Mime>().unwrap();
530
- assert_eq!(mime.type_(), mime::APPLICATION);
531
- assert_eq!(mime.subtype(), mime::JSON);
532
- }
533
-
534
- #[test]
535
- fn test_text_plain_mime_type() {
536
- let mime = "text/plain".parse::<mime::Mime>().unwrap();
537
- assert_eq!(mime.type_(), mime::TEXT);
538
- assert_eq!(mime.subtype(), "plain");
539
- }
540
- }
1
+ //! HTTP middleware for request validation
2
+ //!
3
+ //! Provides middleware stack setup, JSON schema validation, multipart/form-data parsing,
4
+ //! and URL-encoded form data handling.
5
+
6
+ pub mod multipart;
7
+ pub mod urlencoded;
8
+ pub mod validation;
9
+
10
+ use axum::{
11
+ body::Body,
12
+ extract::State,
13
+ extract::{FromRequest, Multipart, Request},
14
+ http::StatusCode,
15
+ middleware::Next,
16
+ response::{IntoResponse, Response},
17
+ };
18
+ use serde_json::json;
19
+ use std::cell::RefCell;
20
+ use std::num::NonZeroUsize;
21
+
22
+ thread_local! {
23
+ static URLENCODED_JSON_CACHE: RefCell<lru::LruCache<bytes::Bytes, bytes::Bytes>> =
24
+ RefCell::new(lru::LruCache::new(NonZeroUsize::new(256).expect("non-zero cache size")));
25
+ }
26
+
27
+ /// Route information for middleware validation
28
+ #[derive(Debug, Clone)]
29
+ pub struct RouteInfo {
30
+ /// Whether this route expects a JSON request body
31
+ pub expects_json_body: bool,
32
+ }
33
+
34
+ /// Request extension carrying the already-collected request body.
35
+ ///
36
+ /// This avoids double-reading the body stream: middleware can read once for
37
+ /// content-length / syntax checks, and request extraction can reuse the bytes.
38
+ #[derive(Debug, Clone)]
39
+ pub struct PreReadBody(pub bytes::Bytes);
40
+
41
+ /// Request extension carrying a pre-parsed JSON body.
42
+ #[derive(Debug, Clone)]
43
+ pub struct PreParsedJson(pub serde_json::Value);
44
+
45
+ /// Middleware to validate Content-Type headers and related requirements
46
+ ///
47
+ /// This middleware performs comprehensive request body validation and transformation:
48
+ ///
49
+ /// - **Content-Type Validation:** Ensures the request's Content-Type header matches the
50
+ /// expected format for the route (if configured).
51
+ ///
52
+ /// - **Multipart Form Data:** Automatically parses `multipart/form-data` requests and
53
+ /// transforms them into JSON format for uniform downstream processing.
54
+ ///
55
+ /// - **URL-Encoded Forms:** Parses `application/x-www-form-urlencoded` requests and
56
+ /// converts them to JSON.
57
+ ///
58
+ /// - **JSON Validation:** Validates JSON request bodies for well-formedness (when the
59
+ /// Content-Type is `application/json`).
60
+ ///
61
+ /// - **Content-Length:** Validates that the Content-Length header is present and
62
+ /// reasonable for POST, PUT, and PATCH requests.
63
+ ///
64
+ /// # Behavior
65
+ ///
66
+ /// For request methods POST, PUT, and PATCH:
67
+ /// 1. Checks if the route expects a JSON body (via route state)
68
+ /// 2. Validates Content-Type headers based on route configuration
69
+ /// 3. Parses the request body according to Content-Type:
70
+ /// - `multipart/form-data` JSON (form fields as object properties)
71
+ /// - `application/x-www-form-urlencoded` → JSON (URL parameters as object)
72
+ /// - `application/json` Validates JSON syntax
73
+ /// 4. Transforms the request to have `Content-Type: application/json`
74
+ /// 5. Passes the transformed request to the next middleware
75
+ ///
76
+ /// For GET, DELETE, and other methods: passes through with minimal validation.
77
+ ///
78
+ /// # Errors
79
+ ///
80
+ /// Returns HTTP error responses for:
81
+ /// - `400 Bad Request` - Failed to read request body, invalid JSON, malformed forms, invalid Content-Length
82
+ /// - `500 Internal Server Error` - Failed to serialize transformed body
83
+ ///
84
+ /// # Examples
85
+ ///
86
+ /// ```rust
87
+ /// use axum::{middleware::Next, extract::Request};
88
+ /// use spikard_http::middleware::validate_content_type_middleware;
89
+ ///
90
+ /// // This is typically used as middleware in an Axum router:
91
+ /// // router.layer(axum::middleware::from_fn(validate_content_type_middleware))
92
+ /// ```
93
+ ///
94
+ /// Coverage: Tested via integration tests (multipart and form parsing tested end-to-end)
95
+ #[cfg(not(tarpaulin_include))]
96
+ pub async fn validate_content_type_middleware(
97
+ State(route_info): State<RouteInfo>,
98
+ request: Request,
99
+ next: Next,
100
+ ) -> Result<Response, Response> {
101
+ use axum::body::to_bytes;
102
+ use axum::http::Request as HttpRequest;
103
+
104
+ let (mut parts, body) = request.into_parts();
105
+ let headers = &parts.headers;
106
+
107
+ let method = &parts.method;
108
+ if method == axum::http::Method::POST || method == axum::http::Method::PUT || method == axum::http::Method::PATCH {
109
+ if route_info.expects_json_body {
110
+ validation::validate_json_content_type(headers)?;
111
+ }
112
+
113
+ let content_kind = validation::validate_content_type_headers_and_classify(headers, 0)?;
114
+
115
+ let mut parsed_json: Option<serde_json::Value> = None;
116
+ let out_bytes: bytes::Bytes = match content_kind {
117
+ Some(validation::ContentTypeKind::Multipart) => {
118
+ let body_bytes = match to_bytes(body, usize::MAX).await {
119
+ Ok(bytes) => bytes,
120
+ Err(_) => {
121
+ let error_body = json!({
122
+ "error": "Failed to read request body"
123
+ });
124
+ return Err((StatusCode::BAD_REQUEST, axum::Json(error_body)).into_response());
125
+ }
126
+ };
127
+
128
+ if headers.get(axum::http::header::CONTENT_LENGTH).is_some() {
129
+ validation::validate_content_length(headers, body_bytes.len())?;
130
+ }
131
+
132
+ let mut parse_request = HttpRequest::new(Body::from(body_bytes));
133
+ *parse_request.headers_mut() = parts.headers.clone();
134
+
135
+ let multipart = match Multipart::from_request(parse_request, &()).await {
136
+ Ok(mp) => mp,
137
+ Err(e) => {
138
+ let error_body = json!({
139
+ "error": format!("Failed to parse multipart data: {}", e)
140
+ });
141
+ return Err((StatusCode::BAD_REQUEST, axum::Json(error_body)).into_response());
142
+ }
143
+ };
144
+
145
+ let json_body = match multipart::parse_multipart_to_json(multipart).await {
146
+ Ok(json) => json,
147
+ Err(e) => {
148
+ let error_body = json!({
149
+ "error": format!("Failed to process multipart data: {}", e)
150
+ });
151
+ return Err((StatusCode::BAD_REQUEST, axum::Json(error_body)).into_response());
152
+ }
153
+ };
154
+
155
+ let json_bytes = match serde_json::to_vec(&json_body) {
156
+ Ok(bytes) => bytes,
157
+ Err(e) => {
158
+ let error_body = json!({
159
+ "error": format!("Failed to serialize multipart data to JSON: {}", e)
160
+ });
161
+ return Err((StatusCode::INTERNAL_SERVER_ERROR, axum::Json(error_body)).into_response());
162
+ }
163
+ };
164
+
165
+ parsed_json = Some(json_body);
166
+ parts.headers.insert(
167
+ axum::http::header::CONTENT_TYPE,
168
+ axum::http::HeaderValue::from_static("application/json"),
169
+ );
170
+ if let Ok(value) = axum::http::HeaderValue::from_str(&json_bytes.len().to_string()) {
171
+ parts.headers.insert(axum::http::header::CONTENT_LENGTH, value);
172
+ }
173
+ bytes::Bytes::from(json_bytes)
174
+ }
175
+ Some(validation::ContentTypeKind::FormUrlencoded) => {
176
+ let body_bytes = match to_bytes(body, usize::MAX).await {
177
+ Ok(bytes) => bytes,
178
+ Err(_) => {
179
+ let error_body = json!({
180
+ "error": "Failed to read request body"
181
+ });
182
+ return Err((StatusCode::BAD_REQUEST, axum::Json(error_body)).into_response());
183
+ }
184
+ };
185
+
186
+ if headers.get(axum::http::header::CONTENT_LENGTH).is_some() {
187
+ validation::validate_content_length(headers, body_bytes.len())?;
188
+ }
189
+
190
+ parts.headers.insert(
191
+ axum::http::header::CONTENT_TYPE,
192
+ axum::http::HeaderValue::from_static("application/json"),
193
+ );
194
+ if let Some(cached) = URLENCODED_JSON_CACHE.with(|cache| cache.borrow_mut().get(&body_bytes).cloned()) {
195
+ cached
196
+ } else {
197
+ let json_body = if body_bytes.is_empty() {
198
+ serde_json::json!({})
199
+ } else {
200
+ match urlencoded::parse_urlencoded_to_json(&body_bytes) {
201
+ Ok(json_body) => json_body,
202
+ Err(e) => {
203
+ let error_body = json!({
204
+ "error": format!("Failed to parse URL-encoded form data: {}", e)
205
+ });
206
+ return Err((StatusCode::BAD_REQUEST, axum::Json(error_body)).into_response());
207
+ }
208
+ }
209
+ };
210
+
211
+ let json_bytes = match serde_json::to_vec(&json_body) {
212
+ Ok(bytes) => bytes,
213
+ Err(e) => {
214
+ let error_body = json!({
215
+ "error": format!("Failed to serialize URL-encoded form data to JSON: {}", e)
216
+ });
217
+ return Err((StatusCode::INTERNAL_SERVER_ERROR, axum::Json(error_body)).into_response());
218
+ }
219
+ };
220
+
221
+ let json_bytes = bytes::Bytes::from(json_bytes);
222
+ parsed_json = Some(json_body);
223
+ URLENCODED_JSON_CACHE.with(|cache| {
224
+ cache.borrow_mut().put(body_bytes.clone(), json_bytes.clone());
225
+ });
226
+ json_bytes
227
+ }
228
+ }
229
+ Some(validation::ContentTypeKind::Json) | Some(validation::ContentTypeKind::Other) => {
230
+ let body_bytes = match to_bytes(body, usize::MAX).await {
231
+ Ok(bytes) => bytes,
232
+ Err(_) => {
233
+ let error_body = json!({
234
+ "error": "Failed to read request body"
235
+ });
236
+ return Err((StatusCode::BAD_REQUEST, axum::Json(error_body)).into_response());
237
+ }
238
+ };
239
+
240
+ if headers.get(axum::http::header::CONTENT_LENGTH).is_some() {
241
+ validation::validate_content_length(headers, body_bytes.len())?;
242
+ }
243
+
244
+ let should_validate_json =
245
+ route_info.expects_json_body && matches!(content_kind, Some(validation::ContentTypeKind::Json));
246
+ if should_validate_json && !body_bytes.is_empty() {
247
+ match serde_json::from_slice::<serde_json::Value>(&body_bytes) {
248
+ Ok(value) => parsed_json = Some(value),
249
+ Err(_) => {
250
+ let error_body = json!({
251
+ "detail": "Invalid request format"
252
+ });
253
+ return Err((StatusCode::BAD_REQUEST, axum::Json(error_body)).into_response());
254
+ }
255
+ }
256
+ }
257
+
258
+ body_bytes
259
+ }
260
+ None => {
261
+ let body_bytes = match to_bytes(body, usize::MAX).await {
262
+ Ok(bytes) => bytes,
263
+ Err(_) => {
264
+ let error_body = json!({
265
+ "error": "Failed to read request body"
266
+ });
267
+ return Err((StatusCode::BAD_REQUEST, axum::Json(error_body)).into_response());
268
+ }
269
+ };
270
+
271
+ if headers.get(axum::http::header::CONTENT_LENGTH).is_some() {
272
+ validation::validate_content_length(headers, body_bytes.len())?;
273
+ }
274
+ body_bytes
275
+ }
276
+ };
277
+
278
+ parts.extensions.insert(PreReadBody(out_bytes));
279
+ if let Some(parsed) = parsed_json {
280
+ parts.extensions.insert(PreParsedJson(parsed));
281
+ }
282
+
283
+ let request = HttpRequest::from_parts(parts, Body::empty());
284
+ Ok(next.run(request).await)
285
+ } else {
286
+ validation::validate_content_type_headers(headers, 0)?;
287
+
288
+ let request = HttpRequest::from_parts(parts, body);
289
+ Ok(next.run(request).await)
290
+ }
291
+ }
292
+
293
+ #[cfg(test)]
294
+ mod tests {
295
+ use super::*;
296
+ use axum::body::Body;
297
+ use axum::http::Request;
298
+
299
+ #[test]
300
+ fn test_route_info_creation() {
301
+ let info = RouteInfo {
302
+ expects_json_body: true,
303
+ };
304
+ assert!(info.expects_json_body);
305
+ }
306
+
307
+ #[test]
308
+ fn test_route_info_expects_json_body_true() {
309
+ let info = RouteInfo {
310
+ expects_json_body: true,
311
+ };
312
+ assert_eq!(info.expects_json_body, true);
313
+ }
314
+
315
+ #[test]
316
+ fn test_route_info_expects_json_body_false() {
317
+ let info = RouteInfo {
318
+ expects_json_body: false,
319
+ };
320
+ assert_eq!(info.expects_json_body, false);
321
+ }
322
+
323
+ #[test]
324
+ fn test_request_with_zero_content_length() {
325
+ let headers = axum::http::HeaderMap::new();
326
+ assert!(headers.get(axum::http::header::CONTENT_LENGTH).is_none());
327
+ }
328
+
329
+ #[test]
330
+ fn test_request_with_very_large_content_length() {
331
+ let mut headers = axum::http::HeaderMap::new();
332
+ let large_size = usize::MAX - 1;
333
+ headers.insert(
334
+ axum::http::header::CONTENT_LENGTH,
335
+ axum::http::HeaderValue::from_str(&large_size.to_string()).unwrap(),
336
+ );
337
+ assert!(headers.get(axum::http::header::CONTENT_LENGTH).is_some());
338
+ }
339
+
340
+ #[test]
341
+ fn test_request_body_smaller_than_declared_length() {
342
+ let mut headers = axum::http::HeaderMap::new();
343
+ headers.insert(
344
+ axum::http::header::CONTENT_LENGTH,
345
+ axum::http::HeaderValue::from_static("1000"),
346
+ );
347
+ let result = super::validation::validate_content_length(&headers, 500);
348
+ assert!(
349
+ result.is_err(),
350
+ "Should reject when actual body is smaller than declared"
351
+ );
352
+ }
353
+
354
+ #[test]
355
+ fn test_request_body_larger_than_declared_length() {
356
+ let mut headers = axum::http::HeaderMap::new();
357
+ headers.insert(
358
+ axum::http::header::CONTENT_LENGTH,
359
+ axum::http::HeaderValue::from_static("500"),
360
+ );
361
+ let result = super::validation::validate_content_length(&headers, 1000);
362
+ assert!(
363
+ result.is_err(),
364
+ "Should reject when actual body is larger than declared"
365
+ );
366
+ }
367
+
368
+ #[test]
369
+ fn test_get_request_no_body_validation() {
370
+ let request = Request::builder()
371
+ .method(axum::http::Method::GET)
372
+ .uri("/api/users")
373
+ .body(Body::empty())
374
+ .unwrap();
375
+
376
+ let (parts, _body) = request.into_parts();
377
+ assert_eq!(parts.method, axum::http::Method::GET);
378
+ }
379
+
380
+ #[test]
381
+ fn test_delete_request_no_body_validation() {
382
+ let request = Request::builder()
383
+ .method(axum::http::Method::DELETE)
384
+ .uri("/api/users/1")
385
+ .body(Body::empty())
386
+ .unwrap();
387
+
388
+ let (parts, _body) = request.into_parts();
389
+ assert_eq!(parts.method, axum::http::Method::DELETE);
390
+ }
391
+
392
+ #[test]
393
+ fn test_post_request_requires_validation() {
394
+ let request = Request::builder()
395
+ .method(axum::http::Method::POST)
396
+ .uri("/api/users")
397
+ .body(Body::empty())
398
+ .unwrap();
399
+
400
+ let (parts, _body) = request.into_parts();
401
+ assert_eq!(parts.method, axum::http::Method::POST);
402
+ }
403
+
404
+ #[test]
405
+ fn test_put_request_requires_validation() {
406
+ let request = Request::builder()
407
+ .method(axum::http::Method::PUT)
408
+ .uri("/api/users/1")
409
+ .body(Body::empty())
410
+ .unwrap();
411
+
412
+ let (parts, _body) = request.into_parts();
413
+ assert_eq!(parts.method, axum::http::Method::PUT);
414
+ }
415
+
416
+ #[test]
417
+ fn test_patch_request_requires_validation() {
418
+ let request = Request::builder()
419
+ .method(axum::http::Method::PATCH)
420
+ .uri("/api/users/1")
421
+ .body(Body::empty())
422
+ .unwrap();
423
+
424
+ let (parts, _body) = request.into_parts();
425
+ assert_eq!(parts.method, axum::http::Method::PATCH);
426
+ }
427
+
428
+ #[test]
429
+ fn test_content_type_header_case_insensitive() {
430
+ let mut headers = axum::http::HeaderMap::new();
431
+ headers.insert(
432
+ axum::http::header::CONTENT_TYPE,
433
+ axum::http::HeaderValue::from_static("application/json"),
434
+ );
435
+
436
+ assert!(headers.get(axum::http::header::CONTENT_TYPE).is_some());
437
+ }
438
+
439
+ #[test]
440
+ fn test_content_length_header_case_insensitive() {
441
+ let mut headers = axum::http::HeaderMap::new();
442
+ headers.insert(
443
+ axum::http::header::CONTENT_LENGTH,
444
+ axum::http::HeaderValue::from_static("100"),
445
+ );
446
+
447
+ assert!(headers.get(axum::http::header::CONTENT_LENGTH).is_some());
448
+ }
449
+
450
+ #[test]
451
+ fn test_custom_headers_case_preserved() {
452
+ let mut headers = axum::http::HeaderMap::new();
453
+ let custom_header: axum::http::HeaderName = "X-Custom-Header".parse().unwrap();
454
+ headers.insert(custom_header.clone(), axum::http::HeaderValue::from_static("value"));
455
+
456
+ assert!(headers.get(&custom_header).is_some());
457
+ }
458
+
459
+ #[test]
460
+ fn test_multipart_boundary_minimal() {
461
+ let mut headers = axum::http::HeaderMap::new();
462
+ headers.insert(
463
+ axum::http::header::CONTENT_TYPE,
464
+ axum::http::HeaderValue::from_static("multipart/form-data; boundary=x"),
465
+ );
466
+
467
+ let result = super::validation::validate_content_type_headers(&headers, 0);
468
+ assert!(result.is_ok(), "Minimal boundary should be accepted");
469
+ }
470
+
471
+ #[test]
472
+ fn test_multipart_boundary_with_numbers() {
473
+ let mut headers = axum::http::HeaderMap::new();
474
+ headers.insert(
475
+ axum::http::header::CONTENT_TYPE,
476
+ axum::http::HeaderValue::from_static("multipart/form-data; boundary=boundary123456"),
477
+ );
478
+
479
+ let result = super::validation::validate_content_type_headers(&headers, 0);
480
+ assert!(result.is_ok());
481
+ }
482
+
483
+ #[test]
484
+ fn test_multipart_boundary_with_special_chars() {
485
+ let mut headers = axum::http::HeaderMap::new();
486
+ headers.insert(
487
+ axum::http::header::CONTENT_TYPE,
488
+ axum::http::HeaderValue::from_static("multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW"),
489
+ );
490
+
491
+ let result = super::validation::validate_content_type_headers(&headers, 0);
492
+ assert!(result.is_ok(), "Boundary with dashes should be accepted");
493
+ }
494
+
495
+ #[test]
496
+ fn test_multipart_empty_boundary() {
497
+ let mut headers = axum::http::HeaderMap::new();
498
+ headers.insert(
499
+ axum::http::header::CONTENT_TYPE,
500
+ axum::http::HeaderValue::from_static("multipart/form-data; boundary="),
501
+ );
502
+
503
+ let _result = super::validation::validate_content_type_headers(&headers, 0);
504
+ assert!(headers.get(axum::http::header::CONTENT_TYPE).is_some());
505
+ }
506
+
507
+ #[test]
508
+ fn test_invalid_json_body_detection() {
509
+ let invalid_json = r#"{"invalid": json without quotes}"#;
510
+ let _mime = "application/json".parse::<mime::Mime>().unwrap();
511
+
512
+ let result = serde_json::from_str::<serde_json::Value>(invalid_json);
513
+ assert!(result.is_err(), "Invalid JSON should fail parsing");
514
+ }
515
+
516
+ #[test]
517
+ fn test_valid_json_parsing() {
518
+ let valid_json = r#"{"key": "value"}"#;
519
+ let result = serde_json::from_str::<serde_json::Value>(valid_json);
520
+ assert!(result.is_ok(), "Valid JSON should parse successfully");
521
+ }
522
+
523
+ #[test]
524
+ fn test_empty_json_object() {
525
+ let empty_json = "{}";
526
+ let result = serde_json::from_str::<serde_json::Value>(empty_json);
527
+ assert!(result.is_ok());
528
+ let value = result.unwrap();
529
+ assert!(value.is_object());
530
+ assert_eq!(value.as_object().unwrap().len(), 0);
531
+ }
532
+
533
+ #[test]
534
+ fn test_form_data_mime_type() {
535
+ let mime = "multipart/form-data; boundary=xyz".parse::<mime::Mime>().unwrap();
536
+ assert_eq!(mime.type_(), mime::MULTIPART);
537
+ assert_eq!(mime.subtype(), "form-data");
538
+ }
539
+
540
+ #[test]
541
+ fn test_form_urlencoded_mime_type() {
542
+ let mime = "application/x-www-form-urlencoded".parse::<mime::Mime>().unwrap();
543
+ assert_eq!(mime.type_(), mime::APPLICATION);
544
+ assert_eq!(mime.subtype(), "x-www-form-urlencoded");
545
+ }
546
+
547
+ #[test]
548
+ fn test_json_mime_type() {
549
+ let mime = "application/json".parse::<mime::Mime>().unwrap();
550
+ assert_eq!(mime.type_(), mime::APPLICATION);
551
+ assert_eq!(mime.subtype(), mime::JSON);
552
+ }
553
+
554
+ #[test]
555
+ fn test_text_plain_mime_type() {
556
+ let mime = "text/plain".parse::<mime::Mime>().unwrap();
557
+ assert_eq!(mime.type_(), mime::TEXT);
558
+ assert_eq!(mime.subtype(), "plain");
559
+ }
560
+ }