spikard 0.3.2 → 0.3.3

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 (180) hide show
  1. checksums.yaml +4 -4
  2. data/LICENSE +1 -1
  3. data/README.md +659 -659
  4. data/ext/spikard_rb/Cargo.toml +17 -17
  5. data/ext/spikard_rb/extconf.rb +10 -10
  6. data/ext/spikard_rb/src/lib.rs +6 -6
  7. data/lib/spikard/app.rb +386 -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 +221 -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 +360 -360
  23. data/vendor/crates/spikard-core/Cargo.toml +40 -40
  24. data/vendor/crates/spikard-core/src/bindings/mod.rs +3 -3
  25. data/vendor/crates/spikard-core/src/bindings/response.rs +133 -133
  26. data/vendor/crates/spikard-core/src/debug.rs +63 -63
  27. data/vendor/crates/spikard-core/src/di/container.rs +726 -726
  28. data/vendor/crates/spikard-core/src/di/dependency.rs +273 -273
  29. data/vendor/crates/spikard-core/src/di/error.rs +118 -118
  30. data/vendor/crates/spikard-core/src/di/factory.rs +538 -538
  31. data/vendor/crates/spikard-core/src/di/graph.rs +545 -545
  32. data/vendor/crates/spikard-core/src/di/mod.rs +192 -192
  33. data/vendor/crates/spikard-core/src/di/resolved.rs +411 -411
  34. data/vendor/crates/spikard-core/src/di/value.rs +283 -283
  35. data/vendor/crates/spikard-core/src/errors.rs +39 -39
  36. data/vendor/crates/spikard-core/src/http.rs +153 -153
  37. data/vendor/crates/spikard-core/src/lib.rs +29 -29
  38. data/vendor/crates/spikard-core/src/lifecycle.rs +422 -422
  39. data/vendor/crates/spikard-core/src/parameters.rs +722 -722
  40. data/vendor/crates/spikard-core/src/problem.rs +310 -310
  41. data/vendor/crates/spikard-core/src/request_data.rs +189 -189
  42. data/vendor/crates/spikard-core/src/router.rs +249 -249
  43. data/vendor/crates/spikard-core/src/schema_registry.rs +183 -183
  44. data/vendor/crates/spikard-core/src/type_hints.rs +304 -304
  45. data/vendor/crates/spikard-core/src/validation.rs +699 -699
  46. data/vendor/crates/spikard-http/Cargo.toml +58 -58
  47. data/vendor/crates/spikard-http/src/auth.rs +247 -247
  48. data/vendor/crates/spikard-http/src/background.rs +249 -249
  49. data/vendor/crates/spikard-http/src/bindings/mod.rs +3 -3
  50. data/vendor/crates/spikard-http/src/bindings/response.rs +1 -1
  51. data/vendor/crates/spikard-http/src/body_metadata.rs +8 -8
  52. data/vendor/crates/spikard-http/src/cors.rs +490 -490
  53. data/vendor/crates/spikard-http/src/debug.rs +63 -63
  54. data/vendor/crates/spikard-http/src/di_handler.rs +423 -423
  55. data/vendor/crates/spikard-http/src/handler_response.rs +190 -190
  56. data/vendor/crates/spikard-http/src/handler_trait.rs +228 -228
  57. data/vendor/crates/spikard-http/src/handler_trait_tests.rs +284 -284
  58. data/vendor/crates/spikard-http/src/lib.rs +529 -529
  59. data/vendor/crates/spikard-http/src/lifecycle/adapter.rs +149 -149
  60. data/vendor/crates/spikard-http/src/lifecycle.rs +428 -428
  61. data/vendor/crates/spikard-http/src/middleware/mod.rs +285 -285
  62. data/vendor/crates/spikard-http/src/middleware/multipart.rs +86 -86
  63. data/vendor/crates/spikard-http/src/middleware/urlencoded.rs +147 -147
  64. data/vendor/crates/spikard-http/src/middleware/validation.rs +287 -287
  65. data/vendor/crates/spikard-http/src/openapi/mod.rs +309 -309
  66. data/vendor/crates/spikard-http/src/openapi/parameter_extraction.rs +190 -190
  67. data/vendor/crates/spikard-http/src/openapi/schema_conversion.rs +308 -308
  68. data/vendor/crates/spikard-http/src/openapi/spec_generation.rs +195 -195
  69. data/vendor/crates/spikard-http/src/parameters.rs +1 -1
  70. data/vendor/crates/spikard-http/src/problem.rs +1 -1
  71. data/vendor/crates/spikard-http/src/query_parser.rs +369 -369
  72. data/vendor/crates/spikard-http/src/response.rs +399 -399
  73. data/vendor/crates/spikard-http/src/router.rs +1 -1
  74. data/vendor/crates/spikard-http/src/schema_registry.rs +1 -1
  75. data/vendor/crates/spikard-http/src/server/handler.rs +87 -87
  76. data/vendor/crates/spikard-http/src/server/lifecycle_execution.rs +98 -98
  77. data/vendor/crates/spikard-http/src/server/mod.rs +805 -805
  78. data/vendor/crates/spikard-http/src/server/request_extraction.rs +119 -119
  79. data/vendor/crates/spikard-http/src/sse.rs +447 -447
  80. data/vendor/crates/spikard-http/src/testing/form.rs +14 -14
  81. data/vendor/crates/spikard-http/src/testing/multipart.rs +60 -60
  82. data/vendor/crates/spikard-http/src/testing/test_client.rs +285 -285
  83. data/vendor/crates/spikard-http/src/testing.rs +377 -377
  84. data/vendor/crates/spikard-http/src/type_hints.rs +1 -1
  85. data/vendor/crates/spikard-http/src/validation.rs +1 -1
  86. data/vendor/crates/spikard-http/src/websocket.rs +324 -324
  87. data/vendor/crates/spikard-rb/Cargo.toml +42 -42
  88. data/vendor/crates/spikard-rb/build.rs +8 -8
  89. data/vendor/crates/spikard-rb/src/background.rs +63 -63
  90. data/vendor/crates/spikard-rb/src/config.rs +294 -294
  91. data/vendor/crates/spikard-rb/src/conversion.rs +453 -453
  92. data/vendor/crates/spikard-rb/src/di.rs +409 -409
  93. data/vendor/crates/spikard-rb/src/handler.rs +625 -625
  94. data/vendor/crates/spikard-rb/src/lib.rs +2771 -2771
  95. data/vendor/crates/spikard-rb/src/lifecycle.rs +274 -274
  96. data/vendor/crates/spikard-rb/src/server.rs +283 -283
  97. data/vendor/crates/spikard-rb/src/sse.rs +231 -231
  98. data/vendor/crates/spikard-rb/src/test_client.rs +404 -404
  99. data/vendor/crates/spikard-rb/src/test_sse.rs +143 -143
  100. data/vendor/crates/spikard-rb/src/test_websocket.rs +221 -221
  101. data/vendor/crates/spikard-rb/src/websocket.rs +233 -233
  102. data/vendor/spikard-core/Cargo.toml +40 -40
  103. data/vendor/spikard-core/src/bindings/mod.rs +3 -3
  104. data/vendor/spikard-core/src/bindings/response.rs +133 -133
  105. data/vendor/spikard-core/src/debug.rs +63 -63
  106. data/vendor/spikard-core/src/di/container.rs +726 -726
  107. data/vendor/spikard-core/src/di/dependency.rs +273 -273
  108. data/vendor/spikard-core/src/di/error.rs +118 -118
  109. data/vendor/spikard-core/src/di/factory.rs +538 -538
  110. data/vendor/spikard-core/src/di/graph.rs +545 -545
  111. data/vendor/spikard-core/src/di/mod.rs +192 -192
  112. data/vendor/spikard-core/src/di/resolved.rs +411 -411
  113. data/vendor/spikard-core/src/di/value.rs +283 -283
  114. data/vendor/spikard-core/src/http.rs +153 -153
  115. data/vendor/spikard-core/src/lib.rs +28 -28
  116. data/vendor/spikard-core/src/lifecycle.rs +422 -422
  117. data/vendor/spikard-core/src/parameters.rs +719 -719
  118. data/vendor/spikard-core/src/problem.rs +310 -310
  119. data/vendor/spikard-core/src/request_data.rs +189 -189
  120. data/vendor/spikard-core/src/router.rs +249 -249
  121. data/vendor/spikard-core/src/schema_registry.rs +183 -183
  122. data/vendor/spikard-core/src/type_hints.rs +304 -304
  123. data/vendor/spikard-core/src/validation.rs +699 -699
  124. data/vendor/spikard-http/Cargo.toml +58 -58
  125. data/vendor/spikard-http/src/auth.rs +247 -247
  126. data/vendor/spikard-http/src/background.rs +249 -249
  127. data/vendor/spikard-http/src/bindings/mod.rs +3 -3
  128. data/vendor/spikard-http/src/bindings/response.rs +1 -1
  129. data/vendor/spikard-http/src/body_metadata.rs +8 -8
  130. data/vendor/spikard-http/src/cors.rs +490 -490
  131. data/vendor/spikard-http/src/debug.rs +63 -63
  132. data/vendor/spikard-http/src/di_handler.rs +423 -423
  133. data/vendor/spikard-http/src/handler_response.rs +190 -190
  134. data/vendor/spikard-http/src/handler_trait.rs +228 -228
  135. data/vendor/spikard-http/src/handler_trait_tests.rs +284 -284
  136. data/vendor/spikard-http/src/lib.rs +529 -529
  137. data/vendor/spikard-http/src/lifecycle/adapter.rs +149 -149
  138. data/vendor/spikard-http/src/lifecycle.rs +428 -428
  139. data/vendor/spikard-http/src/middleware/mod.rs +285 -285
  140. data/vendor/spikard-http/src/middleware/multipart.rs +86 -86
  141. data/vendor/spikard-http/src/middleware/urlencoded.rs +147 -147
  142. data/vendor/spikard-http/src/middleware/validation.rs +287 -287
  143. data/vendor/spikard-http/src/openapi/mod.rs +309 -309
  144. data/vendor/spikard-http/src/openapi/parameter_extraction.rs +190 -190
  145. data/vendor/spikard-http/src/openapi/schema_conversion.rs +308 -308
  146. data/vendor/spikard-http/src/openapi/spec_generation.rs +195 -195
  147. data/vendor/spikard-http/src/parameters.rs +1 -1
  148. data/vendor/spikard-http/src/problem.rs +1 -1
  149. data/vendor/spikard-http/src/query_parser.rs +369 -369
  150. data/vendor/spikard-http/src/response.rs +399 -399
  151. data/vendor/spikard-http/src/router.rs +1 -1
  152. data/vendor/spikard-http/src/schema_registry.rs +1 -1
  153. data/vendor/spikard-http/src/server/handler.rs +80 -80
  154. data/vendor/spikard-http/src/server/lifecycle_execution.rs +98 -98
  155. data/vendor/spikard-http/src/server/mod.rs +805 -805
  156. data/vendor/spikard-http/src/server/request_extraction.rs +119 -119
  157. data/vendor/spikard-http/src/sse.rs +447 -447
  158. data/vendor/spikard-http/src/testing/form.rs +14 -14
  159. data/vendor/spikard-http/src/testing/multipart.rs +60 -60
  160. data/vendor/spikard-http/src/testing/test_client.rs +285 -285
  161. data/vendor/spikard-http/src/testing.rs +377 -377
  162. data/vendor/spikard-http/src/type_hints.rs +1 -1
  163. data/vendor/spikard-http/src/validation.rs +1 -1
  164. data/vendor/spikard-http/src/websocket.rs +324 -324
  165. data/vendor/spikard-rb/Cargo.toml +42 -42
  166. data/vendor/spikard-rb/build.rs +8 -8
  167. data/vendor/spikard-rb/src/background.rs +63 -63
  168. data/vendor/spikard-rb/src/config.rs +294 -294
  169. data/vendor/spikard-rb/src/conversion.rs +392 -392
  170. data/vendor/spikard-rb/src/di.rs +409 -409
  171. data/vendor/spikard-rb/src/handler.rs +534 -534
  172. data/vendor/spikard-rb/src/lib.rs +2020 -2020
  173. data/vendor/spikard-rb/src/lifecycle.rs +267 -267
  174. data/vendor/spikard-rb/src/server.rs +283 -283
  175. data/vendor/spikard-rb/src/sse.rs +231 -231
  176. data/vendor/spikard-rb/src/test_client.rs +404 -404
  177. data/vendor/spikard-rb/src/test_sse.rs +143 -143
  178. data/vendor/spikard-rb/src/test_websocket.rs +221 -221
  179. data/vendor/spikard-rb/src/websocket.rs +233 -233
  180. metadata +1 -1
@@ -1,58 +1,58 @@
1
- [package]
2
- name = "spikard-http"
3
- version.workspace = true
4
- edition.workspace = true
5
- authors.workspace = true
6
- license.workspace = true
7
- repository.workspace = true
8
- homepage.workspace = true
9
- description = "High-performance HTTP server for Spikard with tower-http middleware stack"
10
- keywords = ["http", "server", "axum", "tower", "middleware"]
11
- categories = ["web-programming::http-server", "web-programming"]
12
- documentation = "https://docs.rs/spikard-http"
13
- readme = "README.md"
14
-
15
- [dependencies]
16
- axum = { workspace = true, features = ["multipart", "ws"] }
17
- tokio.workspace = true
18
- tokio-util = "0.7"
19
- tower.workspace = true
20
- tower-http.workspace = true
21
- tower_governor.workspace = true
22
- jsonwebtoken.workspace = true
23
- utoipa.workspace = true
24
- utoipa-swagger-ui.workspace = true
25
- utoipa-redoc.workspace = true
26
- serde.workspace = true
27
- serde_json.workspace = true
28
- tracing.workspace = true
29
- tracing-subscriber.workspace = true
30
- spikard-core.workspace = true
31
- futures-util = "0.3"
32
- futures = "0.3"
33
- jsonschema.workspace = true
34
- serde_qs = "0.15"
35
- lazy_static = "1.5"
36
- regex = "1"
37
- rustc-hash = "2.1"
38
- urlencoding = "2.1"
39
- mime = "0.3"
40
- jiff = "0.2"
41
- uuid = "1.18"
42
- bytes = "1.11"
43
- http-body-util = "0.1"
44
- http-body = "1.0"
45
- axum-test = { version = "18", features = ["ws"] }
46
- anyhow = "1.0"
47
- cookie = "0.18"
48
- base64 = "0.22.1"
49
- flate2 = "1.1"
50
- brotli = "8.0"
51
-
52
- [features]
53
- default = []
54
- di = ["spikard-core/di"]
55
-
56
- [dev-dependencies]
57
- chrono = "0.4"
58
- doc-comment = "0.3"
1
+ [package]
2
+ name = "spikard-http"
3
+ version.workspace = true
4
+ edition.workspace = true
5
+ authors.workspace = true
6
+ license.workspace = true
7
+ repository.workspace = true
8
+ homepage.workspace = true
9
+ description = "High-performance HTTP server for Spikard with tower-http middleware stack"
10
+ keywords = ["http", "server", "axum", "tower", "middleware"]
11
+ categories = ["web-programming::http-server", "web-programming"]
12
+ documentation = "https://docs.rs/spikard-http"
13
+ readme = "README.md"
14
+
15
+ [dependencies]
16
+ axum = { workspace = true, features = ["multipart", "ws"] }
17
+ tokio.workspace = true
18
+ tokio-util = "0.7"
19
+ tower.workspace = true
20
+ tower-http.workspace = true
21
+ tower_governor.workspace = true
22
+ jsonwebtoken.workspace = true
23
+ utoipa.workspace = true
24
+ utoipa-swagger-ui.workspace = true
25
+ utoipa-redoc.workspace = true
26
+ serde.workspace = true
27
+ serde_json.workspace = true
28
+ tracing.workspace = true
29
+ tracing-subscriber.workspace = true
30
+ spikard-core.workspace = true
31
+ futures-util = "0.3"
32
+ futures = "0.3"
33
+ jsonschema.workspace = true
34
+ serde_qs = "0.15"
35
+ lazy_static = "1.5"
36
+ regex = "1"
37
+ rustc-hash = "2.1"
38
+ urlencoding = "2.1"
39
+ mime = "0.3"
40
+ jiff = "0.2"
41
+ uuid = "1.18"
42
+ bytes = "1.11"
43
+ http-body-util = "0.1"
44
+ http-body = "1.0"
45
+ axum-test = { version = "18", features = ["ws"] }
46
+ anyhow = "1.0"
47
+ cookie = "0.18"
48
+ base64 = "0.22.1"
49
+ flate2 = "1.1"
50
+ brotli = "8.0"
51
+
52
+ [features]
53
+ default = []
54
+ di = ["spikard-core/di"]
55
+
56
+ [dev-dependencies]
57
+ chrono = "0.4"
58
+ doc-comment = "0.3"
@@ -1,247 +1,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
- 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
+ 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
+ }