spikard 0.3.6 → 0.5.0

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 (113) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +21 -6
  3. data/ext/spikard_rb/Cargo.toml +2 -2
  4. data/lib/spikard/app.rb +33 -14
  5. data/lib/spikard/testing.rb +47 -12
  6. data/lib/spikard/version.rb +1 -1
  7. data/vendor/crates/spikard-bindings-shared/Cargo.toml +63 -0
  8. data/vendor/crates/spikard-bindings-shared/examples/config_extraction.rs +132 -0
  9. data/vendor/crates/spikard-bindings-shared/src/config_extractor.rs +752 -0
  10. data/vendor/crates/spikard-bindings-shared/src/conversion_traits.rs +194 -0
  11. data/vendor/crates/spikard-bindings-shared/src/di_traits.rs +246 -0
  12. data/vendor/crates/spikard-bindings-shared/src/error_response.rs +401 -0
  13. data/vendor/crates/spikard-bindings-shared/src/handler_base.rs +238 -0
  14. data/vendor/crates/spikard-bindings-shared/src/lib.rs +24 -0
  15. data/vendor/crates/spikard-bindings-shared/src/lifecycle_base.rs +292 -0
  16. data/vendor/crates/spikard-bindings-shared/src/lifecycle_executor.rs +616 -0
  17. data/vendor/crates/spikard-bindings-shared/src/response_builder.rs +305 -0
  18. data/vendor/crates/spikard-bindings-shared/src/test_client_base.rs +248 -0
  19. data/vendor/crates/spikard-bindings-shared/src/validation_helpers.rs +351 -0
  20. data/vendor/crates/spikard-bindings-shared/tests/comprehensive_coverage.rs +454 -0
  21. data/vendor/crates/spikard-bindings-shared/tests/error_response_edge_cases.rs +383 -0
  22. data/vendor/crates/spikard-bindings-shared/tests/handler_base_integration.rs +280 -0
  23. data/vendor/crates/spikard-core/Cargo.toml +4 -4
  24. data/vendor/crates/spikard-core/src/debug.rs +64 -0
  25. data/vendor/crates/spikard-core/src/di/container.rs +3 -27
  26. data/vendor/crates/spikard-core/src/di/factory.rs +1 -5
  27. data/vendor/crates/spikard-core/src/di/graph.rs +8 -47
  28. data/vendor/crates/spikard-core/src/di/mod.rs +1 -1
  29. data/vendor/crates/spikard-core/src/di/resolved.rs +1 -7
  30. data/vendor/crates/spikard-core/src/di/value.rs +2 -4
  31. data/vendor/crates/spikard-core/src/errors.rs +30 -0
  32. data/vendor/crates/spikard-core/src/http.rs +262 -0
  33. data/vendor/crates/spikard-core/src/lib.rs +1 -1
  34. data/vendor/crates/spikard-core/src/lifecycle.rs +764 -0
  35. data/vendor/crates/spikard-core/src/metadata.rs +389 -0
  36. data/vendor/crates/spikard-core/src/parameters.rs +1962 -159
  37. data/vendor/crates/spikard-core/src/problem.rs +34 -0
  38. data/vendor/crates/spikard-core/src/request_data.rs +966 -1
  39. data/vendor/crates/spikard-core/src/router.rs +263 -2
  40. data/vendor/crates/spikard-core/src/validation/error_mapper.rs +688 -0
  41. data/vendor/crates/spikard-core/src/{validation.rs → validation/mod.rs} +26 -268
  42. data/vendor/crates/spikard-http/Cargo.toml +12 -16
  43. data/vendor/crates/spikard-http/examples/sse-notifications.rs +148 -0
  44. data/vendor/crates/spikard-http/examples/websocket-chat.rs +92 -0
  45. data/vendor/crates/spikard-http/src/auth.rs +65 -16
  46. data/vendor/crates/spikard-http/src/background.rs +1614 -3
  47. data/vendor/crates/spikard-http/src/cors.rs +515 -0
  48. data/vendor/crates/spikard-http/src/debug.rs +65 -0
  49. data/vendor/crates/spikard-http/src/di_handler.rs +1322 -77
  50. data/vendor/crates/spikard-http/src/handler_response.rs +711 -0
  51. data/vendor/crates/spikard-http/src/handler_trait.rs +607 -5
  52. data/vendor/crates/spikard-http/src/handler_trait_tests.rs +6 -0
  53. data/vendor/crates/spikard-http/src/lib.rs +33 -28
  54. data/vendor/crates/spikard-http/src/lifecycle/adapter.rs +81 -0
  55. data/vendor/crates/spikard-http/src/lifecycle.rs +765 -0
  56. data/vendor/crates/spikard-http/src/middleware/mod.rs +372 -117
  57. data/vendor/crates/spikard-http/src/middleware/multipart.rs +836 -10
  58. data/vendor/crates/spikard-http/src/middleware/urlencoded.rs +409 -43
  59. data/vendor/crates/spikard-http/src/middleware/validation.rs +513 -65
  60. data/vendor/crates/spikard-http/src/openapi/parameter_extraction.rs +345 -0
  61. data/vendor/crates/spikard-http/src/openapi/schema_conversion.rs +1055 -0
  62. data/vendor/crates/spikard-http/src/openapi/spec_generation.rs +473 -3
  63. data/vendor/crates/spikard-http/src/query_parser.rs +455 -31
  64. data/vendor/crates/spikard-http/src/response.rs +321 -0
  65. data/vendor/crates/spikard-http/src/server/handler.rs +1572 -9
  66. data/vendor/crates/spikard-http/src/server/lifecycle_execution.rs +136 -0
  67. data/vendor/crates/spikard-http/src/server/mod.rs +875 -178
  68. data/vendor/crates/spikard-http/src/server/request_extraction.rs +674 -23
  69. data/vendor/crates/spikard-http/src/server/routing_factory.rs +599 -0
  70. data/vendor/crates/spikard-http/src/sse.rs +983 -21
  71. data/vendor/crates/spikard-http/src/testing/form.rs +38 -0
  72. data/vendor/crates/spikard-http/src/testing/test_client.rs +0 -2
  73. data/vendor/crates/spikard-http/src/testing.rs +7 -7
  74. data/vendor/crates/spikard-http/src/websocket.rs +1055 -4
  75. data/vendor/crates/spikard-http/tests/background_behavior.rs +832 -0
  76. data/vendor/crates/spikard-http/tests/common/handlers.rs +309 -0
  77. data/vendor/crates/spikard-http/tests/common/mod.rs +26 -0
  78. data/vendor/crates/spikard-http/tests/di_integration.rs +192 -0
  79. data/vendor/crates/spikard-http/tests/doc_snippets.rs +5 -0
  80. data/vendor/crates/spikard-http/tests/lifecycle_execution.rs +1093 -0
  81. data/vendor/crates/spikard-http/tests/multipart_behavior.rs +656 -0
  82. data/vendor/crates/spikard-http/tests/server_config_builder.rs +314 -0
  83. data/vendor/crates/spikard-http/tests/sse_behavior.rs +620 -0
  84. data/vendor/crates/spikard-http/tests/websocket_behavior.rs +663 -0
  85. data/vendor/crates/spikard-rb/Cargo.toml +10 -4
  86. data/vendor/crates/spikard-rb/build.rs +196 -5
  87. data/vendor/crates/spikard-rb/src/config/mod.rs +5 -0
  88. data/vendor/crates/spikard-rb/src/{config.rs → config/server_config.rs} +100 -109
  89. data/vendor/crates/spikard-rb/src/conversion.rs +121 -20
  90. data/vendor/crates/spikard-rb/src/di/builder.rs +100 -0
  91. data/vendor/crates/spikard-rb/src/{di.rs → di/mod.rs} +12 -46
  92. data/vendor/crates/spikard-rb/src/handler.rs +100 -107
  93. data/vendor/crates/spikard-rb/src/integration/mod.rs +3 -0
  94. data/vendor/crates/spikard-rb/src/lib.rs +467 -1428
  95. data/vendor/crates/spikard-rb/src/lifecycle.rs +1 -0
  96. data/vendor/crates/spikard-rb/src/metadata/mod.rs +5 -0
  97. data/vendor/crates/spikard-rb/src/metadata/route_extraction.rs +447 -0
  98. data/vendor/crates/spikard-rb/src/runtime/mod.rs +5 -0
  99. data/vendor/crates/spikard-rb/src/runtime/server_runner.rs +324 -0
  100. data/vendor/crates/spikard-rb/src/server.rs +47 -22
  101. data/vendor/crates/spikard-rb/src/{test_client.rs → testing/client.rs} +187 -40
  102. data/vendor/crates/spikard-rb/src/testing/mod.rs +7 -0
  103. data/vendor/crates/spikard-rb/src/testing/websocket.rs +635 -0
  104. data/vendor/crates/spikard-rb/src/websocket.rs +178 -37
  105. metadata +46 -13
  106. data/vendor/crates/spikard-http/src/parameters.rs +0 -1
  107. data/vendor/crates/spikard-http/src/problem.rs +0 -1
  108. data/vendor/crates/spikard-http/src/router.rs +0 -1
  109. data/vendor/crates/spikard-http/src/schema_registry.rs +0 -1
  110. data/vendor/crates/spikard-http/src/type_hints.rs +0 -1
  111. data/vendor/crates/spikard-http/src/validation.rs +0 -1
  112. data/vendor/crates/spikard-rb/src/test_websocket.rs +0 -221
  113. /data/vendor/crates/spikard-rb/src/{test_sse.rs → testing/sse.rs} +0 -0
@@ -1,27 +1,167 @@
1
1
  //! JSON schema validation middleware
2
2
 
3
- use crate::problem::{CONTENT_TYPE_PROBLEM_JSON, ProblemDetails};
3
+ use axum::http::HeaderValue;
4
4
  use axum::http::{HeaderMap, StatusCode};
5
5
  use axum::response::{IntoResponse, Response};
6
6
  use serde_json::json;
7
+ use spikard_core::problem::{CONTENT_TYPE_PROBLEM_JSON, ProblemDetails};
7
8
 
8
9
  /// Check if a media type is JSON or has a +json suffix
9
10
  pub fn is_json_content_type(mime: &mime::Mime) -> bool {
10
11
  (mime.type_() == mime::APPLICATION && mime.subtype() == mime::JSON) || mime.suffix() == Some(mime::JSON)
11
12
  }
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
+
13
154
  /// Validate that Content-Type is JSON-compatible when route expects JSON
14
155
  #[allow(clippy::result_large_err)]
15
156
  pub fn validate_json_content_type(headers: &HeaderMap) -> Result<(), Response> {
16
- if let Some(content_type_header) = headers.get(axum::http::header::CONTENT_TYPE)
17
- && let Ok(content_type_str) = content_type_header.to_str()
18
- && let Ok(parsed_mime) = content_type_str.parse::<mime::Mime>()
19
- {
20
- let is_json = (parsed_mime.type_() == mime::APPLICATION && parsed_mime.subtype() == mime::JSON)
21
- || parsed_mime.suffix() == Some(mime::JSON);
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
+ }
22
161
 
23
- let is_form = (parsed_mime.type_() == mime::APPLICATION && parsed_mime.subtype() == "x-www-form-urlencoded")
24
- || (parsed_mime.type_() == mime::MULTIPART && parsed_mime.subtype() == "form-data");
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);
25
165
 
26
166
  if !is_json && !is_form {
27
167
  let problem = ProblemDetails::new(
@@ -47,78 +187,94 @@ pub fn validate_json_content_type(headers: &HeaderMap) -> Result<(), Response> {
47
187
  #[allow(clippy::result_large_err, clippy::collapsible_if)]
48
188
  pub fn validate_content_length(headers: &HeaderMap, actual_size: usize) -> Result<(), Response> {
49
189
  if let Some(content_length_header) = headers.get(axum::http::header::CONTENT_LENGTH) {
50
- if let Ok(content_length_str) = content_length_header.to_str() {
51
- if let Ok(declared_length) = content_length_str.parse::<usize>() {
52
- if declared_length != actual_size {
53
- let problem = ProblemDetails::bad_request(format!(
54
- "Content-Length header ({}) does not match actual body size ({})",
55
- declared_length, actual_size
56
- ));
57
-
58
- let body = problem.to_json().unwrap_or_else(|_| "{}".to_string());
59
- return Err((
60
- StatusCode::BAD_REQUEST,
61
- [(axum::http::header::CONTENT_TYPE, CONTENT_TYPE_PROBLEM_JSON)],
62
- body,
63
- )
64
- .into_response());
65
- }
66
- }
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());
67
206
  }
68
207
  }
69
208
  Ok(())
70
209
  }
71
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
+
72
225
  /// Validate Content-Type header and related requirements
73
226
  #[allow(clippy::result_large_err)]
74
227
  pub fn validate_content_type_headers(headers: &HeaderMap, _declared_body_size: usize) -> Result<(), Response> {
75
- if let Some(content_type_str) = headers
76
- .get(axum::http::header::CONTENT_TYPE)
77
- .and_then(|h| h.to_str().ok())
78
- {
79
- let parsed_mime = match content_type_str.parse::<mime::Mime>() {
80
- Ok(m) => m,
81
- Err(_) => {
82
- let error_body = json!({
83
- "error": format!("Invalid Content-Type header: {}", content_type_str)
84
- });
85
- return Err((StatusCode::BAD_REQUEST, axum::Json(error_body)).into_response());
86
- }
87
- };
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
+ }
88
244
 
89
- let is_json = is_json_content_type(&parsed_mime);
90
- let is_multipart = parsed_mime.type_() == mime::MULTIPART && parsed_mime.subtype() == "form-data";
245
+ let is_json = is_json_like_token(token);
246
+ let is_multipart = is_multipart_form_data_token(token);
91
247
 
92
- if is_multipart && parsed_mime.get_param(mime::BOUNDARY).is_none() {
248
+ if is_multipart && !multipart_has_boundary(content_type) {
93
249
  let error_body = json!({
94
250
  "error": "multipart/form-data requires 'boundary' parameter"
95
251
  });
96
252
  return Err((StatusCode::BAD_REQUEST, axum::Json(error_body)).into_response());
97
253
  }
98
254
 
99
- #[allow(clippy::collapsible_if)]
100
- if is_json {
101
- if let Some(charset) = parsed_mime.get_param(mime::CHARSET).map(|c| c.as_str()) {
102
- if !charset.eq_ignore_ascii_case("utf-8") && !charset.eq_ignore_ascii_case("utf8") {
103
- let problem = ProblemDetails::new(
104
- "https://spikard.dev/errors/unsupported-charset",
105
- "Unsupported Charset",
106
- StatusCode::UNSUPPORTED_MEDIA_TYPE,
107
- )
108
- .with_detail(format!(
109
- "Unsupported charset '{}' for JSON. Only UTF-8 is supported.",
110
- charset
111
- ));
112
-
113
- let body = problem.to_json().unwrap_or_else(|_| "{}".to_string());
114
- return Err((
115
- StatusCode::UNSUPPORTED_MEDIA_TYPE,
116
- [(axum::http::header::CONTENT_TYPE, CONTENT_TYPE_PROBLEM_JSON)],
117
- body,
118
- )
119
- .into_response());
120
- }
121
- }
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());
122
278
  }
123
279
  }
124
280
 
@@ -284,4 +440,296 @@ mod tests {
284
440
  let mime = "application/x-www-form-urlencoded".parse::<mime::Mime>().unwrap();
285
441
  assert!(!is_json_content_type(&mime));
286
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
+ }
287
735
  }