spikard 0.3.6 → 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 (142) hide show
  1. checksums.yaml +4 -4
  2. data/LICENSE +1 -1
  3. data/README.md +674 -659
  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 -386
  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 -221
  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 -0
  24. data/vendor/crates/spikard-bindings-shared/examples/config_extraction.rs +132 -0
  25. data/vendor/crates/spikard-bindings-shared/src/config_extractor.rs +752 -0
  26. data/vendor/crates/spikard-bindings-shared/src/conversion_traits.rs +194 -0
  27. data/vendor/crates/spikard-bindings-shared/src/di_traits.rs +246 -0
  28. data/vendor/crates/spikard-bindings-shared/src/error_response.rs +401 -0
  29. data/vendor/crates/spikard-bindings-shared/src/handler_base.rs +238 -0
  30. data/vendor/crates/spikard-bindings-shared/src/lib.rs +24 -0
  31. data/vendor/crates/spikard-bindings-shared/src/lifecycle_base.rs +292 -0
  32. data/vendor/crates/spikard-bindings-shared/src/lifecycle_executor.rs +616 -0
  33. data/vendor/crates/spikard-bindings-shared/src/response_builder.rs +305 -0
  34. data/vendor/crates/spikard-bindings-shared/src/test_client_base.rs +248 -0
  35. data/vendor/crates/spikard-bindings-shared/src/validation_helpers.rs +351 -0
  36. data/vendor/crates/spikard-bindings-shared/tests/comprehensive_coverage.rs +454 -0
  37. data/vendor/crates/spikard-bindings-shared/tests/error_response_edge_cases.rs +383 -0
  38. data/vendor/crates/spikard-bindings-shared/tests/handler_base_integration.rs +280 -0
  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 -63
  43. data/vendor/crates/spikard-core/src/di/container.rs +702 -726
  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 -538
  47. data/vendor/crates/spikard-core/src/di/graph.rs +506 -545
  48. data/vendor/crates/spikard-core/src/di/mod.rs +192 -192
  49. data/vendor/crates/spikard-core/src/di/resolved.rs +405 -411
  50. data/vendor/crates/spikard-core/src/di/value.rs +281 -283
  51. data/vendor/crates/spikard-core/src/errors.rs +69 -39
  52. data/vendor/crates/spikard-core/src/http.rs +415 -153
  53. data/vendor/crates/spikard-core/src/lib.rs +29 -29
  54. data/vendor/crates/spikard-core/src/lifecycle.rs +1186 -422
  55. data/vendor/crates/spikard-core/src/metadata.rs +389 -0
  56. data/vendor/crates/spikard-core/src/parameters.rs +2525 -722
  57. data/vendor/crates/spikard-core/src/problem.rs +344 -310
  58. data/vendor/crates/spikard-core/src/request_data.rs +1154 -189
  59. data/vendor/crates/spikard-core/src/router.rs +510 -249
  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 -0
  63. data/vendor/crates/spikard-core/src/{validation.rs → validation/mod.rs} +457 -699
  64. data/vendor/crates/spikard-http/Cargo.toml +62 -68
  65. data/vendor/crates/spikard-http/examples/sse-notifications.rs +148 -0
  66. data/vendor/crates/spikard-http/examples/websocket-chat.rs +92 -0
  67. data/vendor/crates/spikard-http/src/auth.rs +296 -247
  68. data/vendor/crates/spikard-http/src/background.rs +1860 -249
  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 -490
  73. data/vendor/crates/spikard-http/src/debug.rs +128 -63
  74. data/vendor/crates/spikard-http/src/di_handler.rs +1668 -423
  75. data/vendor/crates/spikard-http/src/handler_response.rs +901 -190
  76. data/vendor/crates/spikard-http/src/handler_trait.rs +838 -228
  77. data/vendor/crates/spikard-http/src/handler_trait_tests.rs +290 -284
  78. data/vendor/crates/spikard-http/src/lib.rs +534 -529
  79. data/vendor/crates/spikard-http/src/lifecycle/adapter.rs +230 -149
  80. data/vendor/crates/spikard-http/src/lifecycle.rs +1193 -428
  81. data/vendor/crates/spikard-http/src/middleware/mod.rs +560 -285
  82. data/vendor/crates/spikard-http/src/middleware/multipart.rs +912 -86
  83. data/vendor/crates/spikard-http/src/middleware/urlencoded.rs +513 -147
  84. data/vendor/crates/spikard-http/src/middleware/validation.rs +768 -287
  85. data/vendor/crates/spikard-http/src/openapi/mod.rs +309 -309
  86. data/vendor/crates/spikard-http/src/openapi/parameter_extraction.rs +535 -190
  87. data/vendor/crates/spikard-http/src/openapi/schema_conversion.rs +1363 -308
  88. data/vendor/crates/spikard-http/src/openapi/spec_generation.rs +665 -195
  89. data/vendor/crates/spikard-http/src/query_parser.rs +793 -369
  90. data/vendor/crates/spikard-http/src/response.rs +720 -399
  91. data/vendor/crates/spikard-http/src/server/handler.rs +1650 -87
  92. data/vendor/crates/spikard-http/src/server/lifecycle_execution.rs +234 -98
  93. data/vendor/crates/spikard-http/src/server/mod.rs +1593 -805
  94. data/vendor/crates/spikard-http/src/server/request_extraction.rs +789 -119
  95. data/vendor/crates/spikard-http/src/server/routing_factory.rs +629 -0
  96. data/vendor/crates/spikard-http/src/sse.rs +1409 -447
  97. data/vendor/crates/spikard-http/src/testing/form.rs +52 -14
  98. data/vendor/crates/spikard-http/src/testing/multipart.rs +64 -60
  99. data/vendor/crates/spikard-http/src/testing/test_client.rs +311 -285
  100. data/vendor/crates/spikard-http/src/testing.rs +406 -377
  101. data/vendor/crates/spikard-http/src/websocket.rs +1404 -324
  102. data/vendor/crates/spikard-http/tests/background_behavior.rs +832 -0
  103. data/vendor/crates/spikard-http/tests/common/handlers.rs +309 -0
  104. data/vendor/crates/spikard-http/tests/common/mod.rs +26 -0
  105. data/vendor/crates/spikard-http/tests/di_integration.rs +192 -0
  106. data/vendor/crates/spikard-http/tests/doc_snippets.rs +5 -0
  107. data/vendor/crates/spikard-http/tests/lifecycle_execution.rs +1093 -0
  108. data/vendor/crates/spikard-http/tests/multipart_behavior.rs +656 -0
  109. data/vendor/crates/spikard-http/tests/server_config_builder.rs +314 -0
  110. data/vendor/crates/spikard-http/tests/sse_behavior.rs +620 -0
  111. data/vendor/crates/spikard-http/tests/websocket_behavior.rs +663 -0
  112. data/vendor/crates/spikard-rb/Cargo.toml +48 -42
  113. data/vendor/crates/spikard-rb/build.rs +199 -8
  114. data/vendor/crates/spikard-rb/src/background.rs +63 -63
  115. data/vendor/crates/spikard-rb/src/config/mod.rs +5 -0
  116. data/vendor/crates/spikard-rb/src/{config.rs → config/server_config.rs} +285 -294
  117. data/vendor/crates/spikard-rb/src/conversion.rs +554 -453
  118. data/vendor/crates/spikard-rb/src/di/builder.rs +100 -0
  119. data/vendor/crates/spikard-rb/src/{di.rs → di/mod.rs} +375 -409
  120. data/vendor/crates/spikard-rb/src/handler.rs +618 -625
  121. data/vendor/crates/spikard-rb/src/integration/mod.rs +3 -0
  122. data/vendor/crates/spikard-rb/src/lib.rs +1806 -2771
  123. data/vendor/crates/spikard-rb/src/lifecycle.rs +275 -274
  124. data/vendor/crates/spikard-rb/src/metadata/mod.rs +5 -0
  125. data/vendor/crates/spikard-rb/src/metadata/route_extraction.rs +442 -0
  126. data/vendor/crates/spikard-rb/src/runtime/mod.rs +5 -0
  127. data/vendor/crates/spikard-rb/src/runtime/server_runner.rs +324 -0
  128. data/vendor/crates/spikard-rb/src/server.rs +305 -283
  129. data/vendor/crates/spikard-rb/src/sse.rs +231 -231
  130. data/vendor/crates/spikard-rb/src/{test_client.rs → testing/client.rs} +538 -404
  131. data/vendor/crates/spikard-rb/src/testing/mod.rs +7 -0
  132. data/vendor/crates/spikard-rb/src/{test_sse.rs → testing/sse.rs} +143 -143
  133. data/vendor/crates/spikard-rb/src/testing/websocket.rs +608 -0
  134. data/vendor/crates/spikard-rb/src/websocket.rs +377 -233
  135. metadata +60 -13
  136. data/vendor/crates/spikard-http/src/parameters.rs +0 -1
  137. data/vendor/crates/spikard-http/src/problem.rs +0 -1
  138. data/vendor/crates/spikard-http/src/router.rs +0 -1
  139. data/vendor/crates/spikard-http/src/schema_registry.rs +0 -1
  140. data/vendor/crates/spikard-http/src/type_hints.rs +0 -1
  141. data/vendor/crates/spikard-http/src/validation.rs +0 -1
  142. data/vendor/crates/spikard-rb/src/test_websocket.rs +0 -221
@@ -1,247 +1,296 @@
1
- //! Authentication middleware for JWT and API keys.
2
- //!
3
- //! This module provides tower middleware for authenticating requests using:
4
- //! - JWT tokens (via the Authorization header)
5
- //! - API keys (via custom headers)
6
-
7
- use axum::{
8
- body::Body,
9
- extract::Request,
10
- http::{HeaderMap, StatusCode, Uri},
11
- middleware::Next,
12
- response::{IntoResponse, Response},
13
- };
14
- use jsonwebtoken::{Algorithm, DecodingKey, Validation, decode};
15
- use serde::{Deserialize, Serialize};
16
- use std::collections::HashSet;
17
-
18
- use crate::{ApiKeyConfig, JwtConfig, ProblemDetails};
19
-
20
- /// Standard type URI for authentication errors (401)
21
- const TYPE_AUTH_ERROR: &str = "https://spikard.dev/errors/unauthorized";
22
-
23
- /// Standard type URI for configuration errors (500)
24
- const TYPE_CONFIG_ERROR: &str = "https://spikard.dev/errors/configuration-error";
25
-
26
- /// JWT claims structure - can be extended based on needs
27
- #[derive(Debug, Serialize, Deserialize)]
28
- pub struct Claims {
29
- pub sub: String,
30
- pub exp: usize,
31
- #[serde(skip_serializing_if = "Option::is_none")]
32
- pub iat: Option<usize>,
33
- #[serde(skip_serializing_if = "Option::is_none")]
34
- pub nbf: Option<usize>,
35
- #[serde(skip_serializing_if = "Option::is_none")]
36
- pub aud: Option<Vec<String>>,
37
- #[serde(skip_serializing_if = "Option::is_none")]
38
- pub iss: Option<String>,
39
- }
40
-
41
- /// JWT authentication middleware
42
- ///
43
- /// Validates JWT tokens from the Authorization header (Bearer scheme).
44
- /// On success, the validated claims are available to downstream handlers.
45
- /// On failure, returns 401 Unauthorized with RFC 9457 Problem Details.
46
- pub async fn jwt_auth_middleware(
47
- config: JwtConfig,
48
- headers: HeaderMap,
49
- request: Request<Body>,
50
- next: Next,
51
- ) -> Result<Response, Response> {
52
- let auth_header = headers
53
- .get("authorization")
54
- .and_then(|v| v.to_str().ok())
55
- .ok_or_else(|| {
56
- let problem = ProblemDetails::new(
57
- TYPE_AUTH_ERROR,
58
- "Missing or invalid Authorization header",
59
- StatusCode::UNAUTHORIZED,
60
- )
61
- .with_detail("Expected 'Authorization: Bearer <token>'");
62
- (StatusCode::UNAUTHORIZED, axum::Json(problem)).into_response()
63
- })?;
64
-
65
- let token = auth_header.strip_prefix("Bearer ").ok_or_else(|| {
66
- let problem = ProblemDetails::new(
67
- TYPE_AUTH_ERROR,
68
- "Invalid Authorization header format",
69
- StatusCode::UNAUTHORIZED,
70
- )
71
- .with_detail("Authorization header must use Bearer scheme: 'Bearer <token>'");
72
- (StatusCode::UNAUTHORIZED, axum::Json(problem)).into_response()
73
- })?;
74
-
75
- let parts: Vec<&str> = token.split('.').collect();
76
- if parts.len() != 3 {
77
- let problem = ProblemDetails::new(TYPE_AUTH_ERROR, "Malformed JWT token", StatusCode::UNAUTHORIZED)
78
- .with_detail(format!(
79
- "Malformed JWT token: expected 3 parts separated by dots, found {}",
80
- parts.len()
81
- ));
82
- return Err((StatusCode::UNAUTHORIZED, axum::Json(problem)).into_response());
83
- }
84
-
85
- let algorithm = parse_algorithm(&config.algorithm).map_err(|_| {
86
- let problem = ProblemDetails::new(
87
- TYPE_CONFIG_ERROR,
88
- "Invalid JWT configuration",
89
- StatusCode::INTERNAL_SERVER_ERROR,
90
- )
91
- .with_detail(format!("Unsupported algorithm: {}", config.algorithm));
92
- (StatusCode::INTERNAL_SERVER_ERROR, axum::Json(problem)).into_response()
93
- })?;
94
-
95
- let mut validation = Validation::new(algorithm);
96
- if let Some(ref aud) = config.audience {
97
- validation.set_audience(aud);
98
- }
99
- if let Some(ref iss) = config.issuer {
100
- validation.set_issuer(std::slice::from_ref(iss));
101
- }
102
- validation.leeway = config.leeway;
103
- validation.validate_nbf = true;
104
-
105
- let decoding_key = DecodingKey::from_secret(config.secret.as_bytes());
106
- let _token_data = decode::<Claims>(token, &decoding_key, &validation).map_err(|e| {
107
- let detail = match e.kind() {
108
- jsonwebtoken::errors::ErrorKind::ExpiredSignature => "Token has expired".to_string(),
109
- jsonwebtoken::errors::ErrorKind::InvalidToken => "Token is invalid".to_string(),
110
- jsonwebtoken::errors::ErrorKind::InvalidSignature => "Token signature is invalid".to_string(),
111
- jsonwebtoken::errors::ErrorKind::Base64(_) => "Token signature is invalid".to_string(),
112
- jsonwebtoken::errors::ErrorKind::InvalidAudience => "Token audience is invalid".to_string(),
113
- jsonwebtoken::errors::ErrorKind::InvalidIssuer => {
114
- if let Some(ref expected_iss) = config.issuer {
115
- format!("Token issuer is invalid, expected '{}'", expected_iss)
116
- } else {
117
- "Token issuer is invalid".to_string()
118
- }
119
- }
120
- jsonwebtoken::errors::ErrorKind::ImmatureSignature => {
121
- "JWT not valid yet, not before claim is in the future".to_string()
122
- }
123
- _ => format!("Token validation failed: {}", e),
124
- };
125
-
126
- let problem =
127
- ProblemDetails::new(TYPE_AUTH_ERROR, "JWT validation failed", StatusCode::UNAUTHORIZED).with_detail(detail);
128
- (StatusCode::UNAUTHORIZED, axum::Json(problem)).into_response()
129
- })?;
130
-
131
- // TODO: Attach claims to request extensions for handlers to access
132
- Ok(next.run(request).await)
133
- }
134
-
135
- /// Parse JWT algorithm string to jsonwebtoken Algorithm enum
136
- fn parse_algorithm(alg: &str) -> Result<Algorithm, String> {
137
- match alg {
138
- "HS256" => Ok(Algorithm::HS256),
139
- "HS384" => Ok(Algorithm::HS384),
140
- "HS512" => Ok(Algorithm::HS512),
141
- "RS256" => Ok(Algorithm::RS256),
142
- "RS384" => Ok(Algorithm::RS384),
143
- "RS512" => Ok(Algorithm::RS512),
144
- "ES256" => Ok(Algorithm::ES256),
145
- "ES384" => Ok(Algorithm::ES384),
146
- "PS256" => Ok(Algorithm::PS256),
147
- "PS384" => Ok(Algorithm::PS384),
148
- "PS512" => Ok(Algorithm::PS512),
149
- _ => Err(format!("Unsupported algorithm: {}", alg)),
150
- }
151
- }
152
-
153
- /// API Key authentication middleware
154
- ///
155
- /// Validates API keys from a custom header (default: X-API-Key) or query parameter.
156
- /// Checks header first, then query parameter as fallback.
157
- /// On success, the request proceeds to the next handler.
158
- /// On failure, returns 401 Unauthorized with RFC 9457 Problem Details.
159
- pub async fn api_key_auth_middleware(
160
- config: ApiKeyConfig,
161
- headers: HeaderMap,
162
- request: Request<Body>,
163
- next: Next,
164
- ) -> Result<Response, Response> {
165
- let valid_keys: HashSet<String> = config.keys.into_iter().collect();
166
-
167
- let uri = request.uri().clone();
168
-
169
- let api_key_from_header = headers.get(&config.header_name).and_then(|v| v.to_str().ok());
170
-
171
- let api_key = if let Some(key) = api_key_from_header {
172
- Some(key)
173
- } else {
174
- extract_api_key_from_query(&uri)
175
- };
176
-
177
- let api_key = api_key.ok_or_else(|| {
178
- let problem =
179
- ProblemDetails::new(TYPE_AUTH_ERROR, "Missing API key", StatusCode::UNAUTHORIZED).with_detail(format!(
180
- "Expected '{}' header or 'api_key' query parameter with valid API key",
181
- config.header_name
182
- ));
183
- (StatusCode::UNAUTHORIZED, axum::Json(problem)).into_response()
184
- })?;
185
-
186
- if !valid_keys.contains(api_key) {
187
- let problem = ProblemDetails::new(TYPE_AUTH_ERROR, "Invalid API key", StatusCode::UNAUTHORIZED)
188
- .with_detail("The provided API key is not valid");
189
- return Err((StatusCode::UNAUTHORIZED, axum::Json(problem)).into_response());
190
- }
191
-
192
- Ok(next.run(request).await)
193
- }
194
-
195
- /// Extract API key from query parameters
196
- ///
197
- /// Checks for common API key parameter names: api_key, apiKey, key
198
- fn extract_api_key_from_query(uri: &Uri) -> Option<&str> {
199
- let query = uri.query()?;
200
-
201
- for param in query.split('&') {
202
- if let Some((key, value)) = param.split_once('=')
203
- && (key == "api_key" || key == "apiKey" || key == "key")
204
- {
205
- return Some(value);
206
- }
207
- }
208
-
209
- None
210
- }
211
-
212
- #[cfg(test)]
213
- mod tests {
214
- use super::*;
215
-
216
- #[test]
217
- fn test_parse_algorithm() {
218
- assert!(matches!(parse_algorithm("HS256"), Ok(Algorithm::HS256)));
219
- assert!(matches!(parse_algorithm("HS384"), Ok(Algorithm::HS384)));
220
- assert!(matches!(parse_algorithm("HS512"), Ok(Algorithm::HS512)));
221
- assert!(matches!(parse_algorithm("RS256"), Ok(Algorithm::RS256)));
222
- assert!(matches!(parse_algorithm("RS384"), Ok(Algorithm::RS384)));
223
- assert!(matches!(parse_algorithm("RS512"), Ok(Algorithm::RS512)));
224
- assert!(matches!(parse_algorithm("ES256"), Ok(Algorithm::ES256)));
225
- assert!(matches!(parse_algorithm("ES384"), Ok(Algorithm::ES384)));
226
- assert!(matches!(parse_algorithm("PS256"), Ok(Algorithm::PS256)));
227
- assert!(matches!(parse_algorithm("PS384"), Ok(Algorithm::PS384)));
228
- assert!(matches!(parse_algorithm("PS512"), Ok(Algorithm::PS512)));
229
- assert!(parse_algorithm("INVALID").is_err());
230
- }
231
-
232
- #[test]
233
- fn test_claims_serialization() {
234
- let claims = Claims {
235
- sub: "user123".to_string(),
236
- exp: 1234567890,
237
- iat: Some(1234567800),
238
- nbf: None,
239
- aud: Some(vec!["https://api.example.com".to_string()]),
240
- iss: Some("https://auth.example.com".to_string()),
241
- };
242
-
243
- let json = serde_json::to_string(&claims).unwrap();
244
- assert!(json.contains("user123"));
245
- assert!(json.contains("1234567890"));
246
- }
247
- }
1
+ //! Authentication middleware for JWT and API keys.
2
+ //!
3
+ //! This module provides tower middleware for authenticating requests using:
4
+ //! - JWT tokens (via the Authorization header)
5
+ //! - API keys (via custom headers)
6
+
7
+ use axum::{
8
+ body::Body,
9
+ extract::Request,
10
+ http::{HeaderMap, StatusCode, Uri},
11
+ middleware::Next,
12
+ response::{IntoResponse, Response},
13
+ };
14
+ use jsonwebtoken::{Algorithm, DecodingKey, Validation, decode};
15
+ use serde::{Deserialize, Serialize};
16
+ use std::collections::HashSet;
17
+
18
+ use crate::{ApiKeyConfig, JwtConfig, ProblemDetails};
19
+
20
+ /// Standard type URI for authentication errors (401)
21
+ const TYPE_AUTH_ERROR: &str = "https://spikard.dev/errors/unauthorized";
22
+
23
+ /// Standard type URI for configuration errors (500)
24
+ const TYPE_CONFIG_ERROR: &str = "https://spikard.dev/errors/configuration-error";
25
+
26
+ /// JWT claims structure - can be extended based on needs
27
+ #[derive(Debug, Serialize, Deserialize)]
28
+ pub struct Claims {
29
+ pub sub: String,
30
+ pub exp: usize,
31
+ #[serde(skip_serializing_if = "Option::is_none")]
32
+ pub iat: Option<usize>,
33
+ #[serde(skip_serializing_if = "Option::is_none")]
34
+ pub nbf: Option<usize>,
35
+ #[serde(skip_serializing_if = "Option::is_none")]
36
+ pub aud: Option<Vec<String>>,
37
+ #[serde(skip_serializing_if = "Option::is_none")]
38
+ pub iss: Option<String>,
39
+ }
40
+
41
+ /// JWT authentication middleware
42
+ ///
43
+ /// Validates JWT tokens from the Authorization header (Bearer scheme).
44
+ /// On success, the validated claims are available to downstream handlers.
45
+ /// On failure, returns 401 Unauthorized with RFC 9457 Problem Details.
46
+ ///
47
+ /// Coverage: Tested via integration tests (`auth_integration.rs`)
48
+ ///
49
+ /// # Errors
50
+ /// Returns an error response when the Authorization header is missing, malformed,
51
+ /// the token is invalid, or configuration is incorrect.
52
+ #[cfg(not(tarpaulin_include))]
53
+ pub async fn jwt_auth_middleware(
54
+ config: JwtConfig,
55
+ headers: HeaderMap,
56
+ request: Request<Body>,
57
+ next: Next,
58
+ ) -> Result<Response, Response> {
59
+ let auth_header = headers
60
+ .get("authorization")
61
+ .and_then(|v| v.to_str().ok())
62
+ .ok_or_else(|| {
63
+ let problem = ProblemDetails::new(
64
+ TYPE_AUTH_ERROR,
65
+ "Missing or invalid Authorization header",
66
+ StatusCode::UNAUTHORIZED,
67
+ )
68
+ .with_detail("Expected 'Authorization: Bearer <token>'");
69
+ (StatusCode::UNAUTHORIZED, axum::Json(problem)).into_response()
70
+ })?;
71
+
72
+ let token = auth_header.strip_prefix("Bearer ").ok_or_else(|| {
73
+ let problem = ProblemDetails::new(
74
+ TYPE_AUTH_ERROR,
75
+ "Invalid Authorization header format",
76
+ StatusCode::UNAUTHORIZED,
77
+ )
78
+ .with_detail("Authorization header must use Bearer scheme: 'Bearer <token>'");
79
+ (StatusCode::UNAUTHORIZED, axum::Json(problem)).into_response()
80
+ })?;
81
+
82
+ let parts: Vec<&str> = token.split('.').collect();
83
+ if parts.len() != 3 {
84
+ let problem = ProblemDetails::new(TYPE_AUTH_ERROR, "Malformed JWT token", StatusCode::UNAUTHORIZED)
85
+ .with_detail(format!(
86
+ "Malformed JWT token: expected 3 parts separated by dots, found {}",
87
+ parts.len()
88
+ ));
89
+ return Err((StatusCode::UNAUTHORIZED, axum::Json(problem)).into_response());
90
+ }
91
+
92
+ let algorithm = parse_algorithm(&config.algorithm).map_err(|_| {
93
+ let problem = ProblemDetails::new(
94
+ TYPE_CONFIG_ERROR,
95
+ "Invalid JWT configuration",
96
+ StatusCode::INTERNAL_SERVER_ERROR,
97
+ )
98
+ .with_detail(format!("Unsupported algorithm: {}", config.algorithm));
99
+ (StatusCode::INTERNAL_SERVER_ERROR, axum::Json(problem)).into_response()
100
+ })?;
101
+
102
+ let mut validation = Validation::new(algorithm);
103
+ if let Some(ref aud) = config.audience {
104
+ validation.set_audience(aud);
105
+ }
106
+ if let Some(ref iss) = config.issuer {
107
+ validation.set_issuer(std::slice::from_ref(iss));
108
+ }
109
+ validation.leeway = config.leeway;
110
+ validation.validate_nbf = true;
111
+
112
+ let decoding_key = DecodingKey::from_secret(config.secret.as_bytes());
113
+ let _token_data = decode::<Claims>(token, &decoding_key, &validation).map_err(|e| {
114
+ let detail = match e.kind() {
115
+ jsonwebtoken::errors::ErrorKind::ExpiredSignature => "Token has expired".to_string(),
116
+ jsonwebtoken::errors::ErrorKind::InvalidToken => "Token is invalid".to_string(),
117
+ jsonwebtoken::errors::ErrorKind::InvalidSignature | jsonwebtoken::errors::ErrorKind::Base64(_) => {
118
+ "Token signature is invalid".to_string()
119
+ }
120
+ jsonwebtoken::errors::ErrorKind::InvalidAudience => "Token audience is invalid".to_string(),
121
+ jsonwebtoken::errors::ErrorKind::InvalidIssuer => config.issuer.as_ref().map_or_else(
122
+ || "Token issuer is invalid".to_string(),
123
+ |expected_iss| format!("Token issuer is invalid, expected '{expected_iss}'"),
124
+ ),
125
+ jsonwebtoken::errors::ErrorKind::ImmatureSignature => {
126
+ "JWT not valid yet, not before claim is in the future".to_string()
127
+ }
128
+ _ => format!("Token validation failed: {e}"),
129
+ };
130
+
131
+ let problem =
132
+ ProblemDetails::new(TYPE_AUTH_ERROR, "JWT validation failed", StatusCode::UNAUTHORIZED).with_detail(detail);
133
+ (StatusCode::UNAUTHORIZED, axum::Json(problem)).into_response()
134
+ })?;
135
+
136
+ // TODO: Attach claims to request extensions for handlers to access
137
+ Ok(next.run(request).await)
138
+ }
139
+
140
+ /// Parse JWT algorithm string to jsonwebtoken Algorithm enum
141
+ fn parse_algorithm(alg: &str) -> Result<Algorithm, String> {
142
+ match alg {
143
+ "HS256" => Ok(Algorithm::HS256),
144
+ "HS384" => Ok(Algorithm::HS384),
145
+ "HS512" => Ok(Algorithm::HS512),
146
+ "RS256" => Ok(Algorithm::RS256),
147
+ "RS384" => Ok(Algorithm::RS384),
148
+ "RS512" => Ok(Algorithm::RS512),
149
+ "ES256" => Ok(Algorithm::ES256),
150
+ "ES384" => Ok(Algorithm::ES384),
151
+ "PS256" => Ok(Algorithm::PS256),
152
+ "PS384" => Ok(Algorithm::PS384),
153
+ "PS512" => Ok(Algorithm::PS512),
154
+ _ => Err(format!("Unsupported algorithm: {alg}")),
155
+ }
156
+ }
157
+
158
+ /// API Key authentication middleware
159
+ ///
160
+ /// Validates API keys from a custom header (default: X-API-Key) or query parameter.
161
+ /// Checks header first, then query parameter as fallback.
162
+ /// On success, the request proceeds to the next handler.
163
+ /// On failure, returns 401 Unauthorized with RFC 9457 Problem Details.
164
+ ///
165
+ /// Coverage: Tested via integration tests (`auth_integration.rs`)
166
+ ///
167
+ /// # Errors
168
+ /// Returns an error response when the API key is missing or invalid.
169
+ #[cfg(not(tarpaulin_include))]
170
+ pub async fn api_key_auth_middleware(
171
+ config: ApiKeyConfig,
172
+ headers: HeaderMap,
173
+ request: Request<Body>,
174
+ next: Next,
175
+ ) -> Result<Response, Response> {
176
+ let valid_keys: HashSet<String> = config.keys.into_iter().collect();
177
+
178
+ let uri = request.uri().clone();
179
+
180
+ let api_key_from_header = headers.get(&config.header_name).and_then(|v| v.to_str().ok());
181
+
182
+ let api_key = api_key_from_header.map_or_else(|| extract_api_key_from_query(&uri), Some);
183
+
184
+ let api_key = api_key.ok_or_else(|| {
185
+ let problem =
186
+ ProblemDetails::new(TYPE_AUTH_ERROR, "Missing API key", StatusCode::UNAUTHORIZED).with_detail(format!(
187
+ "Expected '{}' header or 'api_key' query parameter with valid API key",
188
+ config.header_name
189
+ ));
190
+ (StatusCode::UNAUTHORIZED, axum::Json(problem)).into_response()
191
+ })?;
192
+
193
+ if !valid_keys.contains(api_key) {
194
+ let problem = ProblemDetails::new(TYPE_AUTH_ERROR, "Invalid API key", StatusCode::UNAUTHORIZED)
195
+ .with_detail("The provided API key is not valid");
196
+ return Err((StatusCode::UNAUTHORIZED, axum::Json(problem)).into_response());
197
+ }
198
+
199
+ Ok(next.run(request).await)
200
+ }
201
+
202
+ /// Extract API key from query parameters
203
+ ///
204
+ /// Checks for common API key parameter names: api_key, apiKey, key
205
+ fn extract_api_key_from_query(uri: &Uri) -> Option<&str> {
206
+ let query = uri.query()?;
207
+
208
+ for param in query.split('&') {
209
+ if let Some((key, value)) = param.split_once('=')
210
+ && (key == "api_key" || key == "apiKey" || key == "key")
211
+ {
212
+ return Some(value);
213
+ }
214
+ }
215
+
216
+ None
217
+ }
218
+
219
+ #[cfg(test)]
220
+ mod tests {
221
+ use super::*;
222
+
223
+ #[test]
224
+ fn test_parse_algorithm() {
225
+ assert!(matches!(parse_algorithm("HS256"), Ok(Algorithm::HS256)));
226
+ assert!(matches!(parse_algorithm("HS384"), Ok(Algorithm::HS384)));
227
+ assert!(matches!(parse_algorithm("HS512"), Ok(Algorithm::HS512)));
228
+ assert!(matches!(parse_algorithm("RS256"), Ok(Algorithm::RS256)));
229
+ assert!(matches!(parse_algorithm("RS384"), Ok(Algorithm::RS384)));
230
+ assert!(matches!(parse_algorithm("RS512"), Ok(Algorithm::RS512)));
231
+ assert!(matches!(parse_algorithm("ES256"), Ok(Algorithm::ES256)));
232
+ assert!(matches!(parse_algorithm("ES384"), Ok(Algorithm::ES384)));
233
+ assert!(matches!(parse_algorithm("PS256"), Ok(Algorithm::PS256)));
234
+ assert!(matches!(parse_algorithm("PS384"), Ok(Algorithm::PS384)));
235
+ assert!(matches!(parse_algorithm("PS512"), Ok(Algorithm::PS512)));
236
+ assert!(parse_algorithm("INVALID").is_err());
237
+ }
238
+
239
+ #[test]
240
+ fn test_claims_serialization() {
241
+ let claims = Claims {
242
+ sub: "user123".to_string(),
243
+ exp: 1234567890,
244
+ iat: Some(1234567800),
245
+ nbf: None,
246
+ aud: Some(vec!["https://api.example.com".to_string()]),
247
+ iss: Some("https://auth.example.com".to_string()),
248
+ };
249
+
250
+ let json = serde_json::to_string(&claims).unwrap();
251
+ assert!(json.contains("user123"));
252
+ assert!(json.contains("1234567890"));
253
+ }
254
+
255
+ #[test]
256
+ fn test_extract_api_key_from_query_api_key() {
257
+ let uri: axum::http::Uri = "/api/endpoint?api_key=secret123".parse().unwrap();
258
+ let result = extract_api_key_from_query(&uri);
259
+ assert_eq!(result, Some("secret123"));
260
+ }
261
+
262
+ #[test]
263
+ fn test_extract_api_key_from_query_api_key_camel_case() {
264
+ let uri: axum::http::Uri = "/api/endpoint?apiKey=mykey456".parse().unwrap();
265
+ let result = extract_api_key_from_query(&uri);
266
+ assert_eq!(result, Some("mykey456"));
267
+ }
268
+
269
+ #[test]
270
+ fn test_extract_api_key_from_query_key() {
271
+ let uri: axum::http::Uri = "/api/endpoint?key=testkey789".parse().unwrap();
272
+ let result = extract_api_key_from_query(&uri);
273
+ assert_eq!(result, Some("testkey789"));
274
+ }
275
+
276
+ #[test]
277
+ fn test_extract_api_key_from_query_no_key() {
278
+ let uri: axum::http::Uri = "/api/endpoint?foo=bar&baz=qux".parse().unwrap();
279
+ let result = extract_api_key_from_query(&uri);
280
+ assert_eq!(result, None);
281
+ }
282
+
283
+ #[test]
284
+ fn test_extract_api_key_from_query_empty_string() {
285
+ let uri: axum::http::Uri = "/api/endpoint".parse().unwrap();
286
+ let result = extract_api_key_from_query(&uri);
287
+ assert_eq!(result, None);
288
+ }
289
+
290
+ #[test]
291
+ fn test_extract_api_key_from_query_multiple_params() {
292
+ let uri: axum::http::Uri = "/api/endpoint?foo=bar&api_key=found&baz=qux".parse().unwrap();
293
+ let result = extract_api_key_from_query(&uri);
294
+ assert_eq!(result, Some("found"));
295
+ }
296
+ }