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,296 +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
- ///
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
- }
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
+ }