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,735 +1,768 @@
1
- //! JSON schema validation middleware
2
-
3
- use axum::http::HeaderValue;
4
- use axum::http::{HeaderMap, StatusCode};
5
- use axum::response::{IntoResponse, Response};
6
- use serde_json::json;
7
- use spikard_core::problem::{CONTENT_TYPE_PROBLEM_JSON, ProblemDetails};
8
-
9
- /// Check if a media type is JSON or has a +json suffix
10
- pub fn is_json_content_type(mime: &mime::Mime) -> bool {
11
- (mime.type_() == mime::APPLICATION && mime.subtype() == mime::JSON) || mime.suffix() == Some(mime::JSON)
12
- }
13
-
14
- fn trim_ascii_whitespace(bytes: &[u8]) -> &[u8] {
15
- let mut start = 0usize;
16
- let mut end = bytes.len();
17
- while start < end && (bytes[start] == b' ' || bytes[start] == b'\t') {
18
- start += 1;
19
- }
20
- while end > start && (bytes[end - 1] == b' ' || bytes[end - 1] == b'\t') {
21
- end -= 1;
22
- }
23
- &bytes[start..end]
24
- }
25
-
26
- fn token_before_semicolon(bytes: &[u8]) -> &[u8] {
27
- let mut i = 0usize;
28
- while i < bytes.len() {
29
- let b = bytes[i];
30
- if b == b';' {
31
- break;
32
- }
33
- i += 1;
34
- }
35
- trim_ascii_whitespace(&bytes[..i])
36
- }
37
-
38
- #[inline]
39
- fn is_json_like_token(token: &[u8]) -> bool {
40
- if token.eq_ignore_ascii_case(b"application/json") {
41
- return true;
42
- }
43
- // vendor JSON: application/vnd.foo+json
44
- token.len() >= 5 && token[token.len() - 5..].eq_ignore_ascii_case(b"+json")
45
- }
46
-
47
- #[inline]
48
- fn is_multipart_form_data_token(token: &[u8]) -> bool {
49
- token.eq_ignore_ascii_case(b"multipart/form-data")
50
- }
51
-
52
- #[inline]
53
- fn is_form_urlencoded_token(token: &[u8]) -> bool {
54
- token.eq_ignore_ascii_case(b"application/x-www-form-urlencoded")
55
- }
56
-
57
- fn is_valid_content_type_token(token: &[u8]) -> bool {
58
- // Minimal fast validation:
59
- // - exactly one '/' separating type and subtype
60
- // - no whitespace
61
- // - type and subtype are non-empty
62
- if token.is_empty() {
63
- return false;
64
- }
65
- let mut slash_pos: Option<usize> = None;
66
- for (idx, &b) in token.iter().enumerate() {
67
- if b == b' ' || b == b'\t' {
68
- return false;
69
- }
70
- if b == b'/' {
71
- if slash_pos.is_some() {
72
- return false;
73
- }
74
- slash_pos = Some(idx);
75
- }
76
- }
77
- match slash_pos {
78
- None => false,
79
- Some(0) => false,
80
- Some(pos) if pos + 1 >= token.len() => false,
81
- Some(_) => true,
82
- }
83
- }
84
-
85
- fn ascii_contains_ignore_case(haystack: &[u8], needle: &[u8]) -> bool {
86
- if needle.is_empty() {
87
- return true;
88
- }
89
- if haystack.len() < needle.len() {
90
- return false;
91
- }
92
- haystack.windows(needle.len()).any(|w| w.eq_ignore_ascii_case(needle))
93
- }
94
-
95
- /// Fast classification: does this Content-Type represent JSON (application/json or +json)?
96
- pub fn is_json_like(content_type: &HeaderValue) -> bool {
97
- let token = token_before_semicolon(content_type.as_bytes());
98
- is_json_like_token(token)
99
- }
100
-
101
- /// Fast classification for already-extracted header strings.
102
- ///
103
- /// This is used in hot paths where headers are stored as `String` values in `RequestData`.
104
- pub fn is_json_like_str(content_type: &str) -> bool {
105
- let token = token_before_semicolon(content_type.as_bytes());
106
- is_json_like_token(token)
107
- }
108
-
109
- /// Fast classification: is this Content-Type multipart/form-data?
110
- pub fn is_multipart_form_data(content_type: &HeaderValue) -> bool {
111
- let token = token_before_semicolon(content_type.as_bytes());
112
- is_multipart_form_data_token(token)
113
- }
114
-
115
- /// Fast classification: is this Content-Type application/x-www-form-urlencoded?
116
- pub fn is_form_urlencoded(content_type: &HeaderValue) -> bool {
117
- let token = token_before_semicolon(content_type.as_bytes());
118
- is_form_urlencoded_token(token)
119
- }
120
-
121
- fn multipart_has_boundary(content_type: &HeaderValue) -> bool {
122
- ascii_contains_ignore_case(content_type.as_bytes(), b"boundary=")
123
- }
124
-
125
- fn json_charset_value(content_type: &HeaderValue) -> Option<&[u8]> {
126
- let bytes = content_type.as_bytes();
127
- if !ascii_contains_ignore_case(bytes, b"charset=") {
128
- return None;
129
- }
130
-
131
- // Extract first charset token after "charset=" up to ';' or whitespace.
132
- let mut i = 0usize;
133
- while i + 8 <= bytes.len() {
134
- if bytes[i..i + 8].eq_ignore_ascii_case(b"charset=") {
135
- let mut j = i + 8;
136
- while j < bytes.len() && (bytes[j] == b' ' || bytes[j] == b'\t') {
137
- j += 1;
138
- }
139
- let start = j;
140
- while j < bytes.len() {
141
- let b = bytes[j];
142
- if b == b';' || b == b' ' || b == b'\t' {
143
- break;
144
- }
145
- j += 1;
146
- }
147
- return Some(&bytes[start..j]);
148
- }
149
- i += 1;
150
- }
151
- None
152
- }
153
-
154
- /// Validate that Content-Type is JSON-compatible when route expects JSON
155
- #[allow(clippy::result_large_err)]
156
- pub fn validate_json_content_type(headers: &HeaderMap) -> Result<(), Response> {
157
- if let Some(content_type_header) = headers.get(axum::http::header::CONTENT_TYPE) {
158
- if content_type_header.to_str().is_err() {
159
- return Ok(());
160
- }
161
-
162
- let token = token_before_semicolon(content_type_header.as_bytes());
163
- let is_json = is_json_like_token(token);
164
- let is_form = is_form_urlencoded_token(token) || is_multipart_form_data_token(token);
165
-
166
- if !is_json && !is_form {
167
- let problem = ProblemDetails::new(
168
- "https://spikard.dev/errors/unsupported-media-type",
169
- "Unsupported Media Type",
170
- StatusCode::UNSUPPORTED_MEDIA_TYPE,
171
- )
172
- .with_detail("Unsupported media type");
173
-
174
- let body = problem.to_json().unwrap_or_else(|_| "{}".to_string());
175
- return Err((
176
- StatusCode::UNSUPPORTED_MEDIA_TYPE,
177
- [(axum::http::header::CONTENT_TYPE, CONTENT_TYPE_PROBLEM_JSON)],
178
- body,
179
- )
180
- .into_response());
181
- }
182
- }
183
- Ok(())
184
- }
185
-
186
- /// Validate Content-Length header matches actual body size
187
- #[allow(clippy::result_large_err, clippy::collapsible_if)]
188
- pub fn validate_content_length(headers: &HeaderMap, actual_size: usize) -> Result<(), Response> {
189
- if let Some(content_length_header) = headers.get(axum::http::header::CONTENT_LENGTH) {
190
- let Some(declared_length) = parse_ascii_usize(content_length_header.as_bytes()) else {
191
- return Ok(());
192
- };
193
- if declared_length != actual_size {
194
- let problem = ProblemDetails::bad_request(format!(
195
- "Content-Length header ({}) does not match actual body size ({})",
196
- declared_length, actual_size
197
- ));
198
-
199
- let body = problem.to_json().unwrap_or_else(|_| "{}".to_string());
200
- return Err((
201
- StatusCode::BAD_REQUEST,
202
- [(axum::http::header::CONTENT_TYPE, CONTENT_TYPE_PROBLEM_JSON)],
203
- body,
204
- )
205
- .into_response());
206
- }
207
- }
208
- Ok(())
209
- }
210
-
211
- fn parse_ascii_usize(bytes: &[u8]) -> Option<usize> {
212
- if bytes.is_empty() {
213
- return None;
214
- }
215
- let mut value: usize = 0;
216
- for &b in bytes {
217
- if !b.is_ascii_digit() {
218
- return None;
219
- }
220
- value = value.saturating_mul(10).saturating_add((b - b'0') as usize);
221
- }
222
- Some(value)
223
- }
224
-
225
- /// Validate Content-Type header and related requirements
226
- #[allow(clippy::result_large_err)]
227
- pub fn validate_content_type_headers(headers: &HeaderMap, _declared_body_size: usize) -> Result<(), Response> {
228
- if let Some(content_type) = headers.get(axum::http::header::CONTENT_TYPE) {
229
- if !content_type.as_bytes().is_ascii() && content_type.to_str().is_err() {
230
- // Keep legacy behavior: invalid bytes should fail fast.
231
- let error_body = json!({
232
- "error": "Invalid Content-Type header"
233
- });
234
- return Err((StatusCode::BAD_REQUEST, axum::Json(error_body)).into_response());
235
- }
236
-
237
- let token = token_before_semicolon(content_type.as_bytes());
238
- if !is_valid_content_type_token(token) {
239
- let error_body = json!({
240
- "error": "Invalid Content-Type header"
241
- });
242
- return Err((StatusCode::BAD_REQUEST, axum::Json(error_body)).into_response());
243
- }
244
-
245
- let is_json = is_json_like_token(token);
246
- let is_multipart = is_multipart_form_data_token(token);
247
-
248
- if is_multipart && !multipart_has_boundary(content_type) {
249
- let error_body = json!({
250
- "error": "multipart/form-data requires 'boundary' parameter"
251
- });
252
- return Err((StatusCode::BAD_REQUEST, axum::Json(error_body)).into_response());
253
- }
254
-
255
- if is_json
256
- && let Some(charset) = json_charset_value(content_type)
257
- && !charset.eq_ignore_ascii_case(b"utf-8")
258
- && !charset.eq_ignore_ascii_case(b"utf8")
259
- {
260
- let charset_str = String::from_utf8_lossy(charset);
261
- let problem = ProblemDetails::new(
262
- "https://spikard.dev/errors/unsupported-charset",
263
- "Unsupported Charset",
264
- StatusCode::UNSUPPORTED_MEDIA_TYPE,
265
- )
266
- .with_detail(format!(
267
- "Unsupported charset '{}' for JSON. Only UTF-8 is supported.",
268
- charset_str
269
- ));
270
-
271
- let body = problem.to_json().unwrap_or_else(|_| "{}".to_string());
272
- return Err((
273
- StatusCode::UNSUPPORTED_MEDIA_TYPE,
274
- [(axum::http::header::CONTENT_TYPE, CONTENT_TYPE_PROBLEM_JSON)],
275
- body,
276
- )
277
- .into_response());
278
- }
279
- }
280
-
281
- Ok(())
282
- }
283
-
284
- #[cfg(test)]
285
- mod tests {
286
- use super::*;
287
- use axum::http::HeaderValue;
288
-
289
- #[test]
290
- fn validate_content_length_accepts_matching_sizes() {
291
- let mut headers = HeaderMap::new();
292
- headers.insert(axum::http::header::CONTENT_LENGTH, HeaderValue::from_static("5"));
293
-
294
- assert!(validate_content_length(&headers, 5).is_ok());
295
- }
296
-
297
- #[test]
298
- fn validate_content_length_rejects_mismatched_sizes() {
299
- let mut headers = HeaderMap::new();
300
- headers.insert(axum::http::header::CONTENT_LENGTH, HeaderValue::from_static("10"));
301
-
302
- let err = validate_content_length(&headers, 4).expect_err("expected mismatch");
303
- assert_eq!(err.status(), StatusCode::BAD_REQUEST);
304
- assert_eq!(
305
- err.headers()
306
- .get(axum::http::header::CONTENT_TYPE)
307
- .and_then(|value| value.to_str().ok()),
308
- Some(CONTENT_TYPE_PROBLEM_JSON)
309
- );
310
- }
311
-
312
- #[test]
313
- fn test_multipart_without_boundary() {
314
- let mut headers = HeaderMap::new();
315
- headers.insert(
316
- axum::http::header::CONTENT_TYPE,
317
- HeaderValue::from_static("multipart/form-data"),
318
- );
319
-
320
- let result = validate_content_type_headers(&headers, 0);
321
- assert!(result.is_err());
322
- }
323
-
324
- #[test]
325
- fn test_multipart_with_boundary() {
326
- let mut headers = HeaderMap::new();
327
- headers.insert(
328
- axum::http::header::CONTENT_TYPE,
329
- HeaderValue::from_static("multipart/form-data; boundary=----WebKitFormBoundary"),
330
- );
331
-
332
- let result = validate_content_type_headers(&headers, 0);
333
- assert!(result.is_ok());
334
- }
335
-
336
- #[test]
337
- fn test_json_with_utf16_charset() {
338
- let mut headers = HeaderMap::new();
339
- headers.insert(
340
- axum::http::header::CONTENT_TYPE,
341
- HeaderValue::from_static("application/json; charset=utf-16"),
342
- );
343
-
344
- let result = validate_content_type_headers(&headers, 0);
345
- assert!(result.is_err());
346
- }
347
-
348
- #[test]
349
- fn test_json_with_utf8_charset() {
350
- let mut headers = HeaderMap::new();
351
- headers.insert(
352
- axum::http::header::CONTENT_TYPE,
353
- HeaderValue::from_static("application/json; charset=utf-8"),
354
- );
355
-
356
- let result = validate_content_type_headers(&headers, 0);
357
- assert!(result.is_ok());
358
- }
359
-
360
- #[test]
361
- fn test_json_without_charset() {
362
- let mut headers = HeaderMap::new();
363
- headers.insert(
364
- axum::http::header::CONTENT_TYPE,
365
- HeaderValue::from_static("application/json"),
366
- );
367
-
368
- let result = validate_content_type_headers(&headers, 0);
369
- assert!(result.is_ok());
370
- }
371
-
372
- #[test]
373
- fn test_vendor_json_accepted() {
374
- let mut headers = HeaderMap::new();
375
- headers.insert(
376
- axum::http::header::CONTENT_TYPE,
377
- HeaderValue::from_static("application/vnd.api+json"),
378
- );
379
-
380
- let result = validate_content_type_headers(&headers, 0);
381
- assert!(result.is_ok());
382
- }
383
-
384
- #[test]
385
- fn test_problem_json_accepted() {
386
- let mut headers = HeaderMap::new();
387
- headers.insert(
388
- axum::http::header::CONTENT_TYPE,
389
- HeaderValue::from_static("application/problem+json"),
390
- );
391
-
392
- let result = validate_content_type_headers(&headers, 0);
393
- assert!(result.is_ok());
394
- }
395
-
396
- #[test]
397
- fn test_vendor_json_with_utf16_charset_rejected() {
398
- let mut headers = HeaderMap::new();
399
- headers.insert(
400
- axum::http::header::CONTENT_TYPE,
401
- HeaderValue::from_static("application/vnd.api+json; charset=utf-16"),
402
- );
403
-
404
- let result = validate_content_type_headers(&headers, 0);
405
- assert!(result.is_err());
406
- }
407
-
408
- #[test]
409
- fn test_vendor_json_with_utf8_charset_accepted() {
410
- let mut headers = HeaderMap::new();
411
- headers.insert(
412
- axum::http::header::CONTENT_TYPE,
413
- HeaderValue::from_static("application/vnd.api+json; charset=utf-8"),
414
- );
415
-
416
- let result = validate_content_type_headers(&headers, 0);
417
- assert!(result.is_ok());
418
- }
419
-
420
- #[test]
421
- fn test_is_json_content_type() {
422
- let mime = "application/json".parse::<mime::Mime>().unwrap();
423
- assert!(is_json_content_type(&mime));
424
-
425
- let mime = "application/vnd.api+json".parse::<mime::Mime>().unwrap();
426
- assert!(is_json_content_type(&mime));
427
-
428
- let mime = "application/problem+json".parse::<mime::Mime>().unwrap();
429
- assert!(is_json_content_type(&mime));
430
-
431
- let mime = "application/hal+json".parse::<mime::Mime>().unwrap();
432
- assert!(is_json_content_type(&mime));
433
-
434
- let mime = "text/plain".parse::<mime::Mime>().unwrap();
435
- assert!(!is_json_content_type(&mime));
436
-
437
- let mime = "application/xml".parse::<mime::Mime>().unwrap();
438
- assert!(!is_json_content_type(&mime));
439
-
440
- let mime = "application/x-www-form-urlencoded".parse::<mime::Mime>().unwrap();
441
- assert!(!is_json_content_type(&mime));
442
- }
443
-
444
- #[test]
445
- fn test_json_with_utf8_uppercase_charset() {
446
- let mut headers = HeaderMap::new();
447
- headers.insert(
448
- axum::http::header::CONTENT_TYPE,
449
- HeaderValue::from_static("application/json; charset=UTF-8"),
450
- );
451
-
452
- let result = validate_content_type_headers(&headers, 0);
453
- assert!(result.is_ok(), "UTF-8 in uppercase should be accepted");
454
- }
455
-
456
- #[test]
457
- fn test_json_with_utf8_no_hyphen_charset() {
458
- let mut headers = HeaderMap::new();
459
- headers.insert(
460
- axum::http::header::CONTENT_TYPE,
461
- HeaderValue::from_static("application/json; charset=utf8"),
462
- );
463
-
464
- let result = validate_content_type_headers(&headers, 0);
465
- assert!(result.is_ok(), "utf8 without hyphen should be accepted");
466
- }
467
-
468
- #[test]
469
- fn test_json_with_iso88591_charset_rejected() {
470
- let mut headers = HeaderMap::new();
471
- headers.insert(
472
- axum::http::header::CONTENT_TYPE,
473
- HeaderValue::from_static("application/json; charset=iso-8859-1"),
474
- );
475
-
476
- let result = validate_content_type_headers(&headers, 0);
477
- assert!(result.is_err(), "iso-8859-1 should be rejected for JSON");
478
- }
479
-
480
- #[test]
481
- fn test_json_with_utf32_charset_rejected() {
482
- let mut headers = HeaderMap::new();
483
- headers.insert(
484
- axum::http::header::CONTENT_TYPE,
485
- HeaderValue::from_static("application/json; charset=utf-32"),
486
- );
487
-
488
- let result = validate_content_type_headers(&headers, 0);
489
- assert!(result.is_err(), "UTF-32 should be rejected for JSON");
490
- }
491
-
492
- #[test]
493
- fn test_multipart_with_boundary_and_charset() {
494
- let mut headers = HeaderMap::new();
495
- headers.insert(
496
- axum::http::header::CONTENT_TYPE,
497
- HeaderValue::from_static("multipart/form-data; boundary=abc123; charset=utf-8"),
498
- );
499
-
500
- let result = validate_content_type_headers(&headers, 0);
501
- assert!(
502
- result.is_ok(),
503
- "multipart with boundary should accept charset parameter"
504
- );
505
- }
506
-
507
- #[test]
508
- fn test_validate_content_length_no_header() {
509
- let headers = HeaderMap::new();
510
-
511
- let result = validate_content_length(&headers, 1024);
512
- assert!(result.is_ok(), "Missing Content-Length header should pass");
513
- }
514
-
515
- #[test]
516
- fn test_validate_content_length_zero_bytes() {
517
- let mut headers = HeaderMap::new();
518
- headers.insert(axum::http::header::CONTENT_LENGTH, HeaderValue::from_static("0"));
519
-
520
- assert!(validate_content_length(&headers, 0).is_ok());
521
- }
522
-
523
- #[test]
524
- fn test_validate_content_length_large_body() {
525
- let mut headers = HeaderMap::new();
526
- let large_size = 1024 * 1024 * 100;
527
- headers.insert(
528
- axum::http::header::CONTENT_LENGTH,
529
- HeaderValue::from_str(&large_size.to_string()).unwrap(),
530
- );
531
-
532
- assert!(validate_content_length(&headers, large_size).is_ok());
533
- }
534
-
535
- #[test]
536
- fn test_validate_content_length_invalid_header_format() {
537
- let mut headers = HeaderMap::new();
538
- headers.insert(
539
- axum::http::header::CONTENT_LENGTH,
540
- HeaderValue::from_static("not-a-number"),
541
- );
542
-
543
- let result = validate_content_length(&headers, 100);
544
- assert!(
545
- result.is_ok(),
546
- "Invalid Content-Length format should be skipped gracefully"
547
- );
548
- }
549
-
550
- #[test]
551
- fn test_invalid_content_type_format() {
552
- let mut headers = HeaderMap::new();
553
- headers.insert(
554
- axum::http::header::CONTENT_TYPE,
555
- HeaderValue::from_static("not/a/valid/type"),
556
- );
557
-
558
- let result = validate_content_type_headers(&headers, 0);
559
- assert!(result.is_err(), "Invalid mime type format should be rejected");
560
- }
561
-
562
- #[test]
563
- fn test_unsupported_content_type_xml() {
564
- let mut headers = HeaderMap::new();
565
- headers.insert(
566
- axum::http::header::CONTENT_TYPE,
567
- HeaderValue::from_static("application/xml"),
568
- );
569
-
570
- let result = validate_content_type_headers(&headers, 0);
571
- assert!(
572
- result.is_ok(),
573
- "XML should pass header validation (routing layer rejects if needed)"
574
- );
575
- }
576
-
577
- #[test]
578
- fn test_unsupported_content_type_plain_text() {
579
- let mut headers = HeaderMap::new();
580
- headers.insert(axum::http::header::CONTENT_TYPE, HeaderValue::from_static("text/plain"));
581
-
582
- let result = validate_content_type_headers(&headers, 0);
583
- assert!(result.is_ok(), "Plain text should pass header validation");
584
- }
585
-
586
- #[test]
587
- fn test_content_type_with_boundary_missing_boundary_param() {
588
- let mut headers = HeaderMap::new();
589
- headers.insert(
590
- axum::http::header::CONTENT_TYPE,
591
- HeaderValue::from_static("multipart/form-data; charset=utf-8"),
592
- );
593
-
594
- let result = validate_content_type_headers(&headers, 0);
595
- assert!(
596
- result.is_err(),
597
- "multipart/form-data without boundary parameter should be rejected"
598
- );
599
- }
600
-
601
- #[test]
602
- fn test_content_type_form_urlencoded() {
603
- let mut headers = HeaderMap::new();
604
- headers.insert(
605
- axum::http::header::CONTENT_TYPE,
606
- HeaderValue::from_static("application/x-www-form-urlencoded"),
607
- );
608
-
609
- let result = validate_content_type_headers(&headers, 0);
610
- assert!(result.is_ok(), "form-urlencoded should be accepted");
611
- }
612
-
613
- #[test]
614
- fn test_is_json_content_type_with_hal_json() {
615
- let mime = "application/hal+json".parse::<mime::Mime>().unwrap();
616
- assert!(is_json_content_type(&mime), "HAL+JSON should be recognized as JSON");
617
- }
618
-
619
- #[test]
620
- fn test_is_json_content_type_with_ld_json() {
621
- let mime = "application/ld+json".parse::<mime::Mime>().unwrap();
622
- assert!(is_json_content_type(&mime), "LD+JSON should be recognized as JSON");
623
- }
624
-
625
- #[test]
626
- fn test_is_json_content_type_rejects_json_patch() {
627
- let mime = "application/json-patch+json".parse::<mime::Mime>().unwrap();
628
- assert!(is_json_content_type(&mime), "JSON-Patch should be recognized as JSON");
629
- }
630
-
631
- #[test]
632
- fn test_is_json_content_type_rejects_html() {
633
- let mime = "text/html".parse::<mime::Mime>().unwrap();
634
- assert!(!is_json_content_type(&mime), "HTML should not be JSON");
635
- }
636
-
637
- #[test]
638
- fn test_is_json_content_type_rejects_csv() {
639
- let mime = "text/csv".parse::<mime::Mime>().unwrap();
640
- assert!(!is_json_content_type(&mime), "CSV should not be JSON");
641
- }
642
-
643
- #[test]
644
- fn test_is_json_content_type_rejects_image_png() {
645
- let mime = "image/png".parse::<mime::Mime>().unwrap();
646
- assert!(!is_json_content_type(&mime), "PNG should not be JSON");
647
- }
648
-
649
- #[test]
650
- fn test_validate_json_content_type_missing_header() {
651
- let headers = HeaderMap::new();
652
- let result = validate_json_content_type(&headers);
653
- assert!(
654
- result.is_ok(),
655
- "Missing Content-Type for JSON route should be OK (routing layer handles)"
656
- );
657
- }
658
-
659
- #[test]
660
- fn test_validate_json_content_type_accepts_form_urlencoded() {
661
- let mut headers = HeaderMap::new();
662
- headers.insert(
663
- axum::http::header::CONTENT_TYPE,
664
- HeaderValue::from_static("application/x-www-form-urlencoded"),
665
- );
666
-
667
- let result = validate_json_content_type(&headers);
668
- assert!(result.is_ok(), "Form-urlencoded should be accepted for JSON routes");
669
- }
670
-
671
- #[test]
672
- fn test_validate_json_content_type_accepts_multipart() {
673
- let mut headers = HeaderMap::new();
674
- headers.insert(
675
- axum::http::header::CONTENT_TYPE,
676
- HeaderValue::from_static("multipart/form-data; boundary=abc123"),
677
- );
678
-
679
- let result = validate_json_content_type(&headers);
680
- assert!(result.is_ok(), "Multipart should be accepted for JSON routes");
681
- }
682
-
683
- #[test]
684
- fn test_validate_json_content_type_rejects_xml() {
685
- let mut headers = HeaderMap::new();
686
- headers.insert(
687
- axum::http::header::CONTENT_TYPE,
688
- HeaderValue::from_static("application/xml"),
689
- );
690
-
691
- let result = validate_json_content_type(&headers);
692
- assert!(result.is_err(), "XML should be rejected for JSON-expecting routes");
693
- assert_eq!(
694
- result.unwrap_err().status(),
695
- StatusCode::UNSUPPORTED_MEDIA_TYPE,
696
- "Should return 415 Unsupported Media Type"
697
- );
698
- }
699
-
700
- #[test]
701
- fn test_content_type_with_multiple_parameters() {
702
- let mut headers = HeaderMap::new();
703
- headers.insert(
704
- axum::http::header::CONTENT_TYPE,
705
- HeaderValue::from_static("application/json; charset=utf-8; boundary=xyz"),
706
- );
707
-
708
- let result = validate_content_type_headers(&headers, 0);
709
- assert!(result.is_ok(), "Multiple parameters should be parsed correctly");
710
- }
711
-
712
- #[test]
713
- fn test_content_type_with_quoted_parameter() {
714
- let mut headers = HeaderMap::new();
715
- headers.insert(
716
- axum::http::header::CONTENT_TYPE,
717
- HeaderValue::from_static(r#"multipart/form-data; boundary="----WebKitFormBoundary""#),
718
- );
719
-
720
- let result = validate_content_type_headers(&headers, 0);
721
- assert!(result.is_ok(), "Quoted boundary parameter should be handled");
722
- }
723
-
724
- #[test]
725
- fn test_content_type_case_insensitive_type() {
726
- let mut headers = HeaderMap::new();
727
- headers.insert(
728
- axum::http::header::CONTENT_TYPE,
729
- HeaderValue::from_static("Application/JSON"),
730
- );
731
-
732
- let result = validate_content_type_headers(&headers, 0);
733
- assert!(result.is_ok(), "Content-Type type/subtype should be case-insensitive");
734
- }
735
- }
1
+ //! JSON schema validation middleware
2
+
3
+ use axum::http::HeaderValue;
4
+ use axum::http::{HeaderMap, StatusCode};
5
+ use axum::response::{IntoResponse, Response};
6
+ use serde_json::json;
7
+ use spikard_core::problem::{CONTENT_TYPE_PROBLEM_JSON, ProblemDetails};
8
+
9
+ /// Check if a media type is JSON or has a +json suffix
10
+ pub fn is_json_content_type(mime: &mime::Mime) -> bool {
11
+ (mime.type_() == mime::APPLICATION && mime.subtype() == mime::JSON) || mime.suffix() == Some(mime::JSON)
12
+ }
13
+
14
+ fn trim_ascii_whitespace(bytes: &[u8]) -> &[u8] {
15
+ let mut start = 0usize;
16
+ let mut end = bytes.len();
17
+ while start < end && (bytes[start] == b' ' || bytes[start] == b'\t') {
18
+ start += 1;
19
+ }
20
+ while end > start && (bytes[end - 1] == b' ' || bytes[end - 1] == b'\t') {
21
+ end -= 1;
22
+ }
23
+ &bytes[start..end]
24
+ }
25
+
26
+ fn token_before_semicolon(bytes: &[u8]) -> &[u8] {
27
+ let mut i = 0usize;
28
+ while i < bytes.len() {
29
+ let b = bytes[i];
30
+ if b == b';' {
31
+ break;
32
+ }
33
+ i += 1;
34
+ }
35
+ trim_ascii_whitespace(&bytes[..i])
36
+ }
37
+
38
+ #[inline]
39
+ fn is_json_like_token(token: &[u8]) -> bool {
40
+ if token.eq_ignore_ascii_case(b"application/json") {
41
+ return true;
42
+ }
43
+ // vendor JSON: application/vnd.foo+json
44
+ token.len() >= 5 && token[token.len() - 5..].eq_ignore_ascii_case(b"+json")
45
+ }
46
+
47
+ #[inline]
48
+ fn is_multipart_form_data_token(token: &[u8]) -> bool {
49
+ token.eq_ignore_ascii_case(b"multipart/form-data")
50
+ }
51
+
52
+ #[inline]
53
+ fn is_form_urlencoded_token(token: &[u8]) -> bool {
54
+ token.eq_ignore_ascii_case(b"application/x-www-form-urlencoded")
55
+ }
56
+
57
+ fn is_valid_content_type_token(token: &[u8]) -> bool {
58
+ // Minimal fast validation:
59
+ // - exactly one '/' separating type and subtype
60
+ // - no whitespace
61
+ // - type and subtype are non-empty
62
+ if token.is_empty() {
63
+ return false;
64
+ }
65
+ let mut slash_pos: Option<usize> = None;
66
+ for (idx, &b) in token.iter().enumerate() {
67
+ if b == b' ' || b == b'\t' {
68
+ return false;
69
+ }
70
+ if b == b'/' {
71
+ if slash_pos.is_some() {
72
+ return false;
73
+ }
74
+ slash_pos = Some(idx);
75
+ }
76
+ }
77
+ match slash_pos {
78
+ None => false,
79
+ Some(0) => false,
80
+ Some(pos) if pos + 1 >= token.len() => false,
81
+ Some(_) => true,
82
+ }
83
+ }
84
+
85
+ fn ascii_contains_ignore_case(haystack: &[u8], needle: &[u8]) -> bool {
86
+ if needle.is_empty() {
87
+ return true;
88
+ }
89
+ if haystack.len() < needle.len() {
90
+ return false;
91
+ }
92
+ haystack.windows(needle.len()).any(|w| w.eq_ignore_ascii_case(needle))
93
+ }
94
+
95
+ /// Fast classification: does this Content-Type represent JSON (application/json or +json)?
96
+ pub fn is_json_like(content_type: &HeaderValue) -> bool {
97
+ let token = token_before_semicolon(content_type.as_bytes());
98
+ is_json_like_token(token)
99
+ }
100
+
101
+ /// Fast classification for already-extracted header strings.
102
+ ///
103
+ /// This is used in hot paths where headers are stored as `String` values in `RequestData`.
104
+ pub fn is_json_like_str(content_type: &str) -> bool {
105
+ let token = token_before_semicolon(content_type.as_bytes());
106
+ is_json_like_token(token)
107
+ }
108
+
109
+ /// Fast classification: is this Content-Type multipart/form-data?
110
+ pub fn is_multipart_form_data(content_type: &HeaderValue) -> bool {
111
+ let token = token_before_semicolon(content_type.as_bytes());
112
+ is_multipart_form_data_token(token)
113
+ }
114
+
115
+ /// Fast classification: is this Content-Type application/x-www-form-urlencoded?
116
+ pub fn is_form_urlencoded(content_type: &HeaderValue) -> bool {
117
+ let token = token_before_semicolon(content_type.as_bytes());
118
+ is_form_urlencoded_token(token)
119
+ }
120
+
121
+ /// Classify Content-Type header values after validation.
122
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
123
+ pub enum ContentTypeKind {
124
+ Json,
125
+ Multipart,
126
+ FormUrlencoded,
127
+ Other,
128
+ }
129
+
130
+ fn multipart_has_boundary(content_type: &HeaderValue) -> bool {
131
+ ascii_contains_ignore_case(content_type.as_bytes(), b"boundary=")
132
+ }
133
+
134
+ fn json_charset_value(content_type: &HeaderValue) -> Option<&[u8]> {
135
+ let bytes = content_type.as_bytes();
136
+ if !ascii_contains_ignore_case(bytes, b"charset=") {
137
+ return None;
138
+ }
139
+
140
+ // Extract first charset token after "charset=" up to ';' or whitespace.
141
+ let mut i = 0usize;
142
+ while i + 8 <= bytes.len() {
143
+ if bytes[i..i + 8].eq_ignore_ascii_case(b"charset=") {
144
+ let mut j = i + 8;
145
+ while j < bytes.len() && (bytes[j] == b' ' || bytes[j] == b'\t') {
146
+ j += 1;
147
+ }
148
+ let start = j;
149
+ while j < bytes.len() {
150
+ let b = bytes[j];
151
+ if b == b';' || b == b' ' || b == b'\t' {
152
+ break;
153
+ }
154
+ j += 1;
155
+ }
156
+ return Some(&bytes[start..j]);
157
+ }
158
+ i += 1;
159
+ }
160
+ None
161
+ }
162
+
163
+ /// Validate that Content-Type is JSON-compatible when route expects JSON
164
+ #[allow(clippy::result_large_err)]
165
+ pub fn validate_json_content_type(headers: &HeaderMap) -> Result<(), Response> {
166
+ if let Some(content_type_header) = headers.get(axum::http::header::CONTENT_TYPE) {
167
+ if content_type_header.to_str().is_err() {
168
+ return Ok(());
169
+ }
170
+
171
+ let token = token_before_semicolon(content_type_header.as_bytes());
172
+ let is_json = is_json_like_token(token);
173
+ let is_form = is_form_urlencoded_token(token) || is_multipart_form_data_token(token);
174
+
175
+ if !is_json && !is_form {
176
+ let problem = ProblemDetails::new(
177
+ "https://spikard.dev/errors/unsupported-media-type",
178
+ "Unsupported Media Type",
179
+ StatusCode::UNSUPPORTED_MEDIA_TYPE,
180
+ )
181
+ .with_detail("Unsupported media type");
182
+ let body = problem.to_json().unwrap_or_else(|_| "{}".to_string());
183
+ return Err((
184
+ StatusCode::UNSUPPORTED_MEDIA_TYPE,
185
+ [(axum::http::header::CONTENT_TYPE, CONTENT_TYPE_PROBLEM_JSON)],
186
+ body,
187
+ )
188
+ .into_response());
189
+ }
190
+ }
191
+ Ok(())
192
+ }
193
+
194
+ /// Validate Content-Length header matches actual body size
195
+ #[allow(clippy::result_large_err, clippy::collapsible_if)]
196
+ pub fn validate_content_length(headers: &HeaderMap, actual_size: usize) -> Result<(), Response> {
197
+ if let Some(content_length_header) = headers.get(axum::http::header::CONTENT_LENGTH) {
198
+ let Some(declared_length) = parse_ascii_usize(content_length_header.as_bytes()) else {
199
+ return Ok(());
200
+ };
201
+ if declared_length != actual_size {
202
+ let problem = ProblemDetails::new(
203
+ "https://spikard.dev/errors/content-length-mismatch",
204
+ "Content-Length header mismatch",
205
+ StatusCode::BAD_REQUEST,
206
+ )
207
+ .with_detail("Content-Length header does not match actual body size");
208
+ let body = problem.to_json().unwrap_or_else(|_| {
209
+ json!({"error": "Content-Length header does not match actual body size"}).to_string()
210
+ });
211
+ return Err((
212
+ StatusCode::BAD_REQUEST,
213
+ [(axum::http::header::CONTENT_TYPE, CONTENT_TYPE_PROBLEM_JSON)],
214
+ body,
215
+ )
216
+ .into_response());
217
+ }
218
+ }
219
+ Ok(())
220
+ }
221
+
222
+ fn parse_ascii_usize(bytes: &[u8]) -> Option<usize> {
223
+ if bytes.is_empty() {
224
+ return None;
225
+ }
226
+ let mut value: usize = 0;
227
+ for &b in bytes {
228
+ if !b.is_ascii_digit() {
229
+ return None;
230
+ }
231
+ value = value.saturating_mul(10).saturating_add((b - b'0') as usize);
232
+ }
233
+ Some(value)
234
+ }
235
+
236
+ /// Validate Content-Type header and related requirements
237
+ #[allow(clippy::result_large_err)]
238
+ pub fn validate_content_type_headers(headers: &HeaderMap, _declared_body_size: usize) -> Result<(), Response> {
239
+ validate_content_type_headers_and_classify(headers, _declared_body_size).map(|_| ())
240
+ }
241
+
242
+ /// Validate Content-Type and return its classification (if present).
243
+ #[allow(clippy::result_large_err)]
244
+ pub fn validate_content_type_headers_and_classify(
245
+ headers: &HeaderMap,
246
+ _declared_body_size: usize,
247
+ ) -> Result<Option<ContentTypeKind>, Response> {
248
+ let Some(content_type) = headers.get(axum::http::header::CONTENT_TYPE) else {
249
+ return Ok(None);
250
+ };
251
+
252
+ if !content_type.as_bytes().is_ascii() && content_type.to_str().is_err() {
253
+ // Keep legacy behavior: invalid bytes should fail fast.
254
+ let error_body = json!({
255
+ "error": "Invalid Content-Type header"
256
+ });
257
+ return Err((StatusCode::BAD_REQUEST, axum::Json(error_body)).into_response());
258
+ }
259
+
260
+ let token = token_before_semicolon(content_type.as_bytes());
261
+ if !is_valid_content_type_token(token) {
262
+ let error_body = json!({
263
+ "error": "Invalid Content-Type header"
264
+ });
265
+ return Err((StatusCode::BAD_REQUEST, axum::Json(error_body)).into_response());
266
+ }
267
+
268
+ let is_json = is_json_like_token(token);
269
+ let is_multipart = is_multipart_form_data_token(token);
270
+ let is_form = is_form_urlencoded_token(token);
271
+
272
+ if is_multipart && !multipart_has_boundary(content_type) {
273
+ let error_body = json!({
274
+ "error": "multipart/form-data requires 'boundary' parameter"
275
+ });
276
+ return Err((StatusCode::BAD_REQUEST, axum::Json(error_body)).into_response());
277
+ }
278
+
279
+ if is_json
280
+ && let Some(charset) = json_charset_value(content_type)
281
+ && !charset.eq_ignore_ascii_case(b"utf-8")
282
+ && !charset.eq_ignore_ascii_case(b"utf8")
283
+ {
284
+ let charset_str = String::from_utf8_lossy(charset);
285
+ let problem = ProblemDetails::new(
286
+ "https://spikard.dev/errors/unsupported-charset",
287
+ "Unsupported Charset",
288
+ StatusCode::UNSUPPORTED_MEDIA_TYPE,
289
+ )
290
+ .with_detail(format!(
291
+ "Unsupported charset '{}' for JSON. Only UTF-8 is supported.",
292
+ charset_str
293
+ ));
294
+
295
+ let body = problem.to_json().unwrap_or_else(|_| "{}".to_string());
296
+ return Err((
297
+ StatusCode::UNSUPPORTED_MEDIA_TYPE,
298
+ [(axum::http::header::CONTENT_TYPE, CONTENT_TYPE_PROBLEM_JSON)],
299
+ body,
300
+ )
301
+ .into_response());
302
+ }
303
+
304
+ let kind = if is_json {
305
+ ContentTypeKind::Json
306
+ } else if is_multipart {
307
+ ContentTypeKind::Multipart
308
+ } else if is_form {
309
+ ContentTypeKind::FormUrlencoded
310
+ } else {
311
+ ContentTypeKind::Other
312
+ };
313
+
314
+ Ok(Some(kind))
315
+ }
316
+
317
+ #[cfg(test)]
318
+ mod tests {
319
+ use super::*;
320
+ use axum::http::HeaderValue;
321
+
322
+ #[test]
323
+ fn validate_content_length_accepts_matching_sizes() {
324
+ let mut headers = HeaderMap::new();
325
+ headers.insert(axum::http::header::CONTENT_LENGTH, HeaderValue::from_static("5"));
326
+
327
+ assert!(validate_content_length(&headers, 5).is_ok());
328
+ }
329
+
330
+ #[test]
331
+ fn validate_content_length_rejects_mismatched_sizes() {
332
+ let mut headers = HeaderMap::new();
333
+ headers.insert(axum::http::header::CONTENT_LENGTH, HeaderValue::from_static("10"));
334
+
335
+ let err = validate_content_length(&headers, 4).expect_err("expected mismatch");
336
+ assert_eq!(err.status(), StatusCode::BAD_REQUEST);
337
+ assert_eq!(
338
+ err.headers()
339
+ .get(axum::http::header::CONTENT_TYPE)
340
+ .and_then(|value| value.to_str().ok()),
341
+ Some(CONTENT_TYPE_PROBLEM_JSON)
342
+ );
343
+ }
344
+
345
+ #[test]
346
+ fn test_multipart_without_boundary() {
347
+ let mut headers = HeaderMap::new();
348
+ headers.insert(
349
+ axum::http::header::CONTENT_TYPE,
350
+ HeaderValue::from_static("multipart/form-data"),
351
+ );
352
+
353
+ let result = validate_content_type_headers(&headers, 0);
354
+ assert!(result.is_err());
355
+ }
356
+
357
+ #[test]
358
+ fn test_multipart_with_boundary() {
359
+ let mut headers = HeaderMap::new();
360
+ headers.insert(
361
+ axum::http::header::CONTENT_TYPE,
362
+ HeaderValue::from_static("multipart/form-data; boundary=----WebKitFormBoundary"),
363
+ );
364
+
365
+ let result = validate_content_type_headers(&headers, 0);
366
+ assert!(result.is_ok());
367
+ }
368
+
369
+ #[test]
370
+ fn test_json_with_utf16_charset() {
371
+ let mut headers = HeaderMap::new();
372
+ headers.insert(
373
+ axum::http::header::CONTENT_TYPE,
374
+ HeaderValue::from_static("application/json; charset=utf-16"),
375
+ );
376
+
377
+ let result = validate_content_type_headers(&headers, 0);
378
+ assert!(result.is_err());
379
+ }
380
+
381
+ #[test]
382
+ fn test_json_with_utf8_charset() {
383
+ let mut headers = HeaderMap::new();
384
+ headers.insert(
385
+ axum::http::header::CONTENT_TYPE,
386
+ HeaderValue::from_static("application/json; charset=utf-8"),
387
+ );
388
+
389
+ let result = validate_content_type_headers(&headers, 0);
390
+ assert!(result.is_ok());
391
+ }
392
+
393
+ #[test]
394
+ fn test_json_without_charset() {
395
+ let mut headers = HeaderMap::new();
396
+ headers.insert(
397
+ axum::http::header::CONTENT_TYPE,
398
+ HeaderValue::from_static("application/json"),
399
+ );
400
+
401
+ let result = validate_content_type_headers(&headers, 0);
402
+ assert!(result.is_ok());
403
+ }
404
+
405
+ #[test]
406
+ fn test_vendor_json_accepted() {
407
+ let mut headers = HeaderMap::new();
408
+ headers.insert(
409
+ axum::http::header::CONTENT_TYPE,
410
+ HeaderValue::from_static("application/vnd.api+json"),
411
+ );
412
+
413
+ let result = validate_content_type_headers(&headers, 0);
414
+ assert!(result.is_ok());
415
+ }
416
+
417
+ #[test]
418
+ fn test_problem_json_accepted() {
419
+ let mut headers = HeaderMap::new();
420
+ headers.insert(
421
+ axum::http::header::CONTENT_TYPE,
422
+ HeaderValue::from_static("application/problem+json"),
423
+ );
424
+
425
+ let result = validate_content_type_headers(&headers, 0);
426
+ assert!(result.is_ok());
427
+ }
428
+
429
+ #[test]
430
+ fn test_vendor_json_with_utf16_charset_rejected() {
431
+ let mut headers = HeaderMap::new();
432
+ headers.insert(
433
+ axum::http::header::CONTENT_TYPE,
434
+ HeaderValue::from_static("application/vnd.api+json; charset=utf-16"),
435
+ );
436
+
437
+ let result = validate_content_type_headers(&headers, 0);
438
+ assert!(result.is_err());
439
+ }
440
+
441
+ #[test]
442
+ fn test_vendor_json_with_utf8_charset_accepted() {
443
+ let mut headers = HeaderMap::new();
444
+ headers.insert(
445
+ axum::http::header::CONTENT_TYPE,
446
+ HeaderValue::from_static("application/vnd.api+json; charset=utf-8"),
447
+ );
448
+
449
+ let result = validate_content_type_headers(&headers, 0);
450
+ assert!(result.is_ok());
451
+ }
452
+
453
+ #[test]
454
+ fn test_is_json_content_type() {
455
+ let mime = "application/json".parse::<mime::Mime>().unwrap();
456
+ assert!(is_json_content_type(&mime));
457
+
458
+ let mime = "application/vnd.api+json".parse::<mime::Mime>().unwrap();
459
+ assert!(is_json_content_type(&mime));
460
+
461
+ let mime = "application/problem+json".parse::<mime::Mime>().unwrap();
462
+ assert!(is_json_content_type(&mime));
463
+
464
+ let mime = "application/hal+json".parse::<mime::Mime>().unwrap();
465
+ assert!(is_json_content_type(&mime));
466
+
467
+ let mime = "text/plain".parse::<mime::Mime>().unwrap();
468
+ assert!(!is_json_content_type(&mime));
469
+
470
+ let mime = "application/xml".parse::<mime::Mime>().unwrap();
471
+ assert!(!is_json_content_type(&mime));
472
+
473
+ let mime = "application/x-www-form-urlencoded".parse::<mime::Mime>().unwrap();
474
+ assert!(!is_json_content_type(&mime));
475
+ }
476
+
477
+ #[test]
478
+ fn test_json_with_utf8_uppercase_charset() {
479
+ let mut headers = HeaderMap::new();
480
+ headers.insert(
481
+ axum::http::header::CONTENT_TYPE,
482
+ HeaderValue::from_static("application/json; charset=UTF-8"),
483
+ );
484
+
485
+ let result = validate_content_type_headers(&headers, 0);
486
+ assert!(result.is_ok(), "UTF-8 in uppercase should be accepted");
487
+ }
488
+
489
+ #[test]
490
+ fn test_json_with_utf8_no_hyphen_charset() {
491
+ let mut headers = HeaderMap::new();
492
+ headers.insert(
493
+ axum::http::header::CONTENT_TYPE,
494
+ HeaderValue::from_static("application/json; charset=utf8"),
495
+ );
496
+
497
+ let result = validate_content_type_headers(&headers, 0);
498
+ assert!(result.is_ok(), "utf8 without hyphen should be accepted");
499
+ }
500
+
501
+ #[test]
502
+ fn test_json_with_iso88591_charset_rejected() {
503
+ let mut headers = HeaderMap::new();
504
+ headers.insert(
505
+ axum::http::header::CONTENT_TYPE,
506
+ HeaderValue::from_static("application/json; charset=iso-8859-1"),
507
+ );
508
+
509
+ let result = validate_content_type_headers(&headers, 0);
510
+ assert!(result.is_err(), "iso-8859-1 should be rejected for JSON");
511
+ }
512
+
513
+ #[test]
514
+ fn test_json_with_utf32_charset_rejected() {
515
+ let mut headers = HeaderMap::new();
516
+ headers.insert(
517
+ axum::http::header::CONTENT_TYPE,
518
+ HeaderValue::from_static("application/json; charset=utf-32"),
519
+ );
520
+
521
+ let result = validate_content_type_headers(&headers, 0);
522
+ assert!(result.is_err(), "UTF-32 should be rejected for JSON");
523
+ }
524
+
525
+ #[test]
526
+ fn test_multipart_with_boundary_and_charset() {
527
+ let mut headers = HeaderMap::new();
528
+ headers.insert(
529
+ axum::http::header::CONTENT_TYPE,
530
+ HeaderValue::from_static("multipart/form-data; boundary=abc123; charset=utf-8"),
531
+ );
532
+
533
+ let result = validate_content_type_headers(&headers, 0);
534
+ assert!(
535
+ result.is_ok(),
536
+ "multipart with boundary should accept charset parameter"
537
+ );
538
+ }
539
+
540
+ #[test]
541
+ fn test_validate_content_length_no_header() {
542
+ let headers = HeaderMap::new();
543
+
544
+ let result = validate_content_length(&headers, 1024);
545
+ assert!(result.is_ok(), "Missing Content-Length header should pass");
546
+ }
547
+
548
+ #[test]
549
+ fn test_validate_content_length_zero_bytes() {
550
+ let mut headers = HeaderMap::new();
551
+ headers.insert(axum::http::header::CONTENT_LENGTH, HeaderValue::from_static("0"));
552
+
553
+ assert!(validate_content_length(&headers, 0).is_ok());
554
+ }
555
+
556
+ #[test]
557
+ fn test_validate_content_length_large_body() {
558
+ let mut headers = HeaderMap::new();
559
+ let large_size = 1024 * 1024 * 100;
560
+ headers.insert(
561
+ axum::http::header::CONTENT_LENGTH,
562
+ HeaderValue::from_str(&large_size.to_string()).unwrap(),
563
+ );
564
+
565
+ assert!(validate_content_length(&headers, large_size).is_ok());
566
+ }
567
+
568
+ #[test]
569
+ fn test_validate_content_length_invalid_header_format() {
570
+ let mut headers = HeaderMap::new();
571
+ headers.insert(
572
+ axum::http::header::CONTENT_LENGTH,
573
+ HeaderValue::from_static("not-a-number"),
574
+ );
575
+
576
+ let result = validate_content_length(&headers, 100);
577
+ assert!(
578
+ result.is_ok(),
579
+ "Invalid Content-Length format should be skipped gracefully"
580
+ );
581
+ }
582
+
583
+ #[test]
584
+ fn test_invalid_content_type_format() {
585
+ let mut headers = HeaderMap::new();
586
+ headers.insert(
587
+ axum::http::header::CONTENT_TYPE,
588
+ HeaderValue::from_static("not/a/valid/type"),
589
+ );
590
+
591
+ let result = validate_content_type_headers(&headers, 0);
592
+ assert!(result.is_err(), "Invalid mime type format should be rejected");
593
+ }
594
+
595
+ #[test]
596
+ fn test_unsupported_content_type_xml() {
597
+ let mut headers = HeaderMap::new();
598
+ headers.insert(
599
+ axum::http::header::CONTENT_TYPE,
600
+ HeaderValue::from_static("application/xml"),
601
+ );
602
+
603
+ let result = validate_content_type_headers(&headers, 0);
604
+ assert!(
605
+ result.is_ok(),
606
+ "XML should pass header validation (routing layer rejects if needed)"
607
+ );
608
+ }
609
+
610
+ #[test]
611
+ fn test_unsupported_content_type_plain_text() {
612
+ let mut headers = HeaderMap::new();
613
+ headers.insert(axum::http::header::CONTENT_TYPE, HeaderValue::from_static("text/plain"));
614
+
615
+ let result = validate_content_type_headers(&headers, 0);
616
+ assert!(result.is_ok(), "Plain text should pass header validation");
617
+ }
618
+
619
+ #[test]
620
+ fn test_content_type_with_boundary_missing_boundary_param() {
621
+ let mut headers = HeaderMap::new();
622
+ headers.insert(
623
+ axum::http::header::CONTENT_TYPE,
624
+ HeaderValue::from_static("multipart/form-data; charset=utf-8"),
625
+ );
626
+
627
+ let result = validate_content_type_headers(&headers, 0);
628
+ assert!(
629
+ result.is_err(),
630
+ "multipart/form-data without boundary parameter should be rejected"
631
+ );
632
+ }
633
+
634
+ #[test]
635
+ fn test_content_type_form_urlencoded() {
636
+ let mut headers = HeaderMap::new();
637
+ headers.insert(
638
+ axum::http::header::CONTENT_TYPE,
639
+ HeaderValue::from_static("application/x-www-form-urlencoded"),
640
+ );
641
+
642
+ let result = validate_content_type_headers(&headers, 0);
643
+ assert!(result.is_ok(), "form-urlencoded should be accepted");
644
+ }
645
+
646
+ #[test]
647
+ fn test_is_json_content_type_with_hal_json() {
648
+ let mime = "application/hal+json".parse::<mime::Mime>().unwrap();
649
+ assert!(is_json_content_type(&mime), "HAL+JSON should be recognized as JSON");
650
+ }
651
+
652
+ #[test]
653
+ fn test_is_json_content_type_with_ld_json() {
654
+ let mime = "application/ld+json".parse::<mime::Mime>().unwrap();
655
+ assert!(is_json_content_type(&mime), "LD+JSON should be recognized as JSON");
656
+ }
657
+
658
+ #[test]
659
+ fn test_is_json_content_type_rejects_json_patch() {
660
+ let mime = "application/json-patch+json".parse::<mime::Mime>().unwrap();
661
+ assert!(is_json_content_type(&mime), "JSON-Patch should be recognized as JSON");
662
+ }
663
+
664
+ #[test]
665
+ fn test_is_json_content_type_rejects_html() {
666
+ let mime = "text/html".parse::<mime::Mime>().unwrap();
667
+ assert!(!is_json_content_type(&mime), "HTML should not be JSON");
668
+ }
669
+
670
+ #[test]
671
+ fn test_is_json_content_type_rejects_csv() {
672
+ let mime = "text/csv".parse::<mime::Mime>().unwrap();
673
+ assert!(!is_json_content_type(&mime), "CSV should not be JSON");
674
+ }
675
+
676
+ #[test]
677
+ fn test_is_json_content_type_rejects_image_png() {
678
+ let mime = "image/png".parse::<mime::Mime>().unwrap();
679
+ assert!(!is_json_content_type(&mime), "PNG should not be JSON");
680
+ }
681
+
682
+ #[test]
683
+ fn test_validate_json_content_type_missing_header() {
684
+ let headers = HeaderMap::new();
685
+ let result = validate_json_content_type(&headers);
686
+ assert!(
687
+ result.is_ok(),
688
+ "Missing Content-Type for JSON route should be OK (routing layer handles)"
689
+ );
690
+ }
691
+
692
+ #[test]
693
+ fn test_validate_json_content_type_accepts_form_urlencoded() {
694
+ let mut headers = HeaderMap::new();
695
+ headers.insert(
696
+ axum::http::header::CONTENT_TYPE,
697
+ HeaderValue::from_static("application/x-www-form-urlencoded"),
698
+ );
699
+
700
+ let result = validate_json_content_type(&headers);
701
+ assert!(result.is_ok(), "Form-urlencoded should be accepted for JSON routes");
702
+ }
703
+
704
+ #[test]
705
+ fn test_validate_json_content_type_accepts_multipart() {
706
+ let mut headers = HeaderMap::new();
707
+ headers.insert(
708
+ axum::http::header::CONTENT_TYPE,
709
+ HeaderValue::from_static("multipart/form-data; boundary=abc123"),
710
+ );
711
+
712
+ let result = validate_json_content_type(&headers);
713
+ assert!(result.is_ok(), "Multipart should be accepted for JSON routes");
714
+ }
715
+
716
+ #[test]
717
+ fn test_validate_json_content_type_rejects_xml() {
718
+ let mut headers = HeaderMap::new();
719
+ headers.insert(
720
+ axum::http::header::CONTENT_TYPE,
721
+ HeaderValue::from_static("application/xml"),
722
+ );
723
+
724
+ let result = validate_json_content_type(&headers);
725
+ assert!(result.is_err(), "XML should be rejected for JSON-expecting routes");
726
+ assert_eq!(
727
+ result.unwrap_err().status(),
728
+ StatusCode::UNSUPPORTED_MEDIA_TYPE,
729
+ "Should return 415 Unsupported Media Type"
730
+ );
731
+ }
732
+
733
+ #[test]
734
+ fn test_content_type_with_multiple_parameters() {
735
+ let mut headers = HeaderMap::new();
736
+ headers.insert(
737
+ axum::http::header::CONTENT_TYPE,
738
+ HeaderValue::from_static("application/json; charset=utf-8; boundary=xyz"),
739
+ );
740
+
741
+ let result = validate_content_type_headers(&headers, 0);
742
+ assert!(result.is_ok(), "Multiple parameters should be parsed correctly");
743
+ }
744
+
745
+ #[test]
746
+ fn test_content_type_with_quoted_parameter() {
747
+ let mut headers = HeaderMap::new();
748
+ headers.insert(
749
+ axum::http::header::CONTENT_TYPE,
750
+ HeaderValue::from_static(r#"multipart/form-data; boundary="----WebKitFormBoundary""#),
751
+ );
752
+
753
+ let result = validate_content_type_headers(&headers, 0);
754
+ assert!(result.is_ok(), "Quoted boundary parameter should be handled");
755
+ }
756
+
757
+ #[test]
758
+ fn test_content_type_case_insensitive_type() {
759
+ let mut headers = HeaderMap::new();
760
+ headers.insert(
761
+ axum::http::header::CONTENT_TYPE,
762
+ HeaderValue::from_static("Application/JSON"),
763
+ );
764
+
765
+ let result = validate_content_type_headers(&headers, 0);
766
+ assert!(result.is_ok(), "Content-Type type/subtype should be case-insensitive");
767
+ }
768
+ }