spikard 0.3.0 → 0.3.2

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 (182) 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 -0
  24. data/vendor/crates/spikard-core/src/bindings/mod.rs +3 -0
  25. data/vendor/crates/spikard-core/src/bindings/response.rs +133 -0
  26. data/vendor/crates/spikard-core/src/debug.rs +63 -0
  27. data/vendor/crates/spikard-core/src/di/container.rs +726 -0
  28. data/vendor/crates/spikard-core/src/di/dependency.rs +273 -0
  29. data/vendor/crates/spikard-core/src/di/error.rs +118 -0
  30. data/vendor/crates/spikard-core/src/di/factory.rs +538 -0
  31. data/vendor/crates/spikard-core/src/di/graph.rs +545 -0
  32. data/vendor/crates/spikard-core/src/di/mod.rs +192 -0
  33. data/vendor/crates/spikard-core/src/di/resolved.rs +411 -0
  34. data/vendor/crates/spikard-core/src/di/value.rs +283 -0
  35. data/vendor/crates/spikard-core/src/errors.rs +39 -0
  36. data/vendor/crates/spikard-core/src/http.rs +153 -0
  37. data/vendor/crates/spikard-core/src/lib.rs +29 -0
  38. data/vendor/crates/spikard-core/src/lifecycle.rs +422 -0
  39. data/vendor/crates/spikard-core/src/parameters.rs +722 -0
  40. data/vendor/crates/spikard-core/src/problem.rs +310 -0
  41. data/vendor/crates/spikard-core/src/request_data.rs +189 -0
  42. data/vendor/crates/spikard-core/src/router.rs +249 -0
  43. data/vendor/crates/spikard-core/src/schema_registry.rs +183 -0
  44. data/vendor/crates/spikard-core/src/type_hints.rs +304 -0
  45. data/vendor/crates/spikard-core/src/validation.rs +699 -0
  46. data/vendor/crates/spikard-http/Cargo.toml +58 -0
  47. data/vendor/crates/spikard-http/src/auth.rs +247 -0
  48. data/vendor/crates/spikard-http/src/background.rs +249 -0
  49. data/vendor/crates/spikard-http/src/bindings/mod.rs +3 -0
  50. data/vendor/crates/spikard-http/src/bindings/response.rs +1 -0
  51. data/vendor/crates/spikard-http/src/body_metadata.rs +8 -0
  52. data/vendor/crates/spikard-http/src/cors.rs +490 -0
  53. data/vendor/crates/spikard-http/src/debug.rs +63 -0
  54. data/vendor/crates/spikard-http/src/di_handler.rs +423 -0
  55. data/vendor/crates/spikard-http/src/handler_response.rs +190 -0
  56. data/vendor/crates/spikard-http/src/handler_trait.rs +228 -0
  57. data/vendor/crates/spikard-http/src/handler_trait_tests.rs +284 -0
  58. data/vendor/crates/spikard-http/src/lib.rs +529 -0
  59. data/vendor/crates/spikard-http/src/lifecycle/adapter.rs +149 -0
  60. data/vendor/crates/spikard-http/src/lifecycle.rs +428 -0
  61. data/vendor/crates/spikard-http/src/middleware/mod.rs +285 -0
  62. data/vendor/crates/spikard-http/src/middleware/multipart.rs +86 -0
  63. data/vendor/crates/spikard-http/src/middleware/urlencoded.rs +147 -0
  64. data/vendor/crates/spikard-http/src/middleware/validation.rs +287 -0
  65. data/vendor/crates/spikard-http/src/openapi/mod.rs +309 -0
  66. data/vendor/crates/spikard-http/src/openapi/parameter_extraction.rs +190 -0
  67. data/vendor/crates/spikard-http/src/openapi/schema_conversion.rs +308 -0
  68. data/vendor/crates/spikard-http/src/openapi/spec_generation.rs +195 -0
  69. data/vendor/crates/spikard-http/src/parameters.rs +1 -0
  70. data/vendor/crates/spikard-http/src/problem.rs +1 -0
  71. data/vendor/crates/spikard-http/src/query_parser.rs +369 -0
  72. data/vendor/crates/spikard-http/src/response.rs +399 -0
  73. data/vendor/crates/spikard-http/src/router.rs +1 -0
  74. data/vendor/crates/spikard-http/src/schema_registry.rs +1 -0
  75. data/vendor/crates/spikard-http/src/server/handler.rs +87 -0
  76. data/vendor/crates/spikard-http/src/server/lifecycle_execution.rs +98 -0
  77. data/vendor/crates/spikard-http/src/server/mod.rs +805 -0
  78. data/vendor/crates/spikard-http/src/server/request_extraction.rs +119 -0
  79. data/vendor/crates/spikard-http/src/sse.rs +447 -0
  80. data/vendor/crates/spikard-http/src/testing/form.rs +14 -0
  81. data/vendor/crates/spikard-http/src/testing/multipart.rs +60 -0
  82. data/vendor/crates/spikard-http/src/testing/test_client.rs +285 -0
  83. data/vendor/crates/spikard-http/src/testing.rs +377 -0
  84. data/vendor/crates/spikard-http/src/type_hints.rs +1 -0
  85. data/vendor/crates/spikard-http/src/validation.rs +1 -0
  86. data/vendor/crates/spikard-http/src/websocket.rs +324 -0
  87. data/vendor/crates/spikard-rb/Cargo.toml +42 -0
  88. data/vendor/crates/spikard-rb/build.rs +8 -0
  89. data/vendor/crates/spikard-rb/src/background.rs +63 -0
  90. data/vendor/crates/spikard-rb/src/config.rs +294 -0
  91. data/vendor/crates/spikard-rb/src/conversion.rs +453 -0
  92. data/vendor/crates/spikard-rb/src/di.rs +409 -0
  93. data/vendor/crates/spikard-rb/src/handler.rs +625 -0
  94. data/vendor/crates/spikard-rb/src/lib.rs +2771 -0
  95. data/vendor/crates/spikard-rb/src/lifecycle.rs +274 -0
  96. data/vendor/crates/spikard-rb/src/server.rs +283 -0
  97. data/vendor/crates/spikard-rb/src/sse.rs +231 -0
  98. data/vendor/crates/spikard-rb/src/test_client.rs +404 -0
  99. data/vendor/crates/spikard-rb/src/test_sse.rs +143 -0
  100. data/vendor/crates/spikard-rb/src/test_websocket.rs +221 -0
  101. data/vendor/crates/spikard-rb/src/websocket.rs +233 -0
  102. data/vendor/spikard-core/Cargo.toml +40 -0
  103. data/vendor/spikard-core/src/bindings/mod.rs +3 -0
  104. data/vendor/spikard-core/src/bindings/response.rs +133 -0
  105. data/vendor/spikard-core/src/debug.rs +63 -0
  106. data/vendor/spikard-core/src/di/container.rs +726 -0
  107. data/vendor/spikard-core/src/di/dependency.rs +273 -0
  108. data/vendor/spikard-core/src/di/error.rs +118 -0
  109. data/vendor/spikard-core/src/di/factory.rs +538 -0
  110. data/vendor/spikard-core/src/di/graph.rs +545 -0
  111. data/vendor/spikard-core/src/di/mod.rs +192 -0
  112. data/vendor/spikard-core/src/di/resolved.rs +411 -0
  113. data/vendor/spikard-core/src/di/value.rs +283 -0
  114. data/vendor/spikard-core/src/http.rs +153 -0
  115. data/vendor/spikard-core/src/lib.rs +28 -0
  116. data/vendor/spikard-core/src/lifecycle.rs +422 -0
  117. data/vendor/spikard-core/src/parameters.rs +719 -0
  118. data/vendor/spikard-core/src/problem.rs +310 -0
  119. data/vendor/spikard-core/src/request_data.rs +189 -0
  120. data/vendor/spikard-core/src/router.rs +249 -0
  121. data/vendor/spikard-core/src/schema_registry.rs +183 -0
  122. data/vendor/spikard-core/src/type_hints.rs +304 -0
  123. data/vendor/spikard-core/src/validation.rs +699 -0
  124. data/vendor/spikard-http/Cargo.toml +58 -0
  125. data/vendor/spikard-http/src/auth.rs +247 -0
  126. data/vendor/spikard-http/src/background.rs +249 -0
  127. data/vendor/spikard-http/src/bindings/mod.rs +3 -0
  128. data/vendor/spikard-http/src/bindings/response.rs +1 -0
  129. data/vendor/spikard-http/src/body_metadata.rs +8 -0
  130. data/vendor/spikard-http/src/cors.rs +490 -0
  131. data/vendor/spikard-http/src/debug.rs +63 -0
  132. data/vendor/spikard-http/src/di_handler.rs +423 -0
  133. data/vendor/spikard-http/src/handler_response.rs +190 -0
  134. data/vendor/spikard-http/src/handler_trait.rs +228 -0
  135. data/vendor/spikard-http/src/handler_trait_tests.rs +284 -0
  136. data/vendor/spikard-http/src/lib.rs +529 -0
  137. data/vendor/spikard-http/src/lifecycle/adapter.rs +149 -0
  138. data/vendor/spikard-http/src/lifecycle.rs +428 -0
  139. data/vendor/spikard-http/src/middleware/mod.rs +285 -0
  140. data/vendor/spikard-http/src/middleware/multipart.rs +86 -0
  141. data/vendor/spikard-http/src/middleware/urlencoded.rs +147 -0
  142. data/vendor/spikard-http/src/middleware/validation.rs +287 -0
  143. data/vendor/spikard-http/src/openapi/mod.rs +309 -0
  144. data/vendor/spikard-http/src/openapi/parameter_extraction.rs +190 -0
  145. data/vendor/spikard-http/src/openapi/schema_conversion.rs +308 -0
  146. data/vendor/spikard-http/src/openapi/spec_generation.rs +195 -0
  147. data/vendor/spikard-http/src/parameters.rs +1 -0
  148. data/vendor/spikard-http/src/problem.rs +1 -0
  149. data/vendor/spikard-http/src/query_parser.rs +369 -0
  150. data/vendor/spikard-http/src/response.rs +399 -0
  151. data/vendor/spikard-http/src/router.rs +1 -0
  152. data/vendor/spikard-http/src/schema_registry.rs +1 -0
  153. data/vendor/spikard-http/src/server/handler.rs +80 -0
  154. data/vendor/spikard-http/src/server/lifecycle_execution.rs +98 -0
  155. data/vendor/spikard-http/src/server/mod.rs +805 -0
  156. data/vendor/spikard-http/src/server/request_extraction.rs +119 -0
  157. data/vendor/spikard-http/src/sse.rs +447 -0
  158. data/vendor/spikard-http/src/testing/form.rs +14 -0
  159. data/vendor/spikard-http/src/testing/multipart.rs +60 -0
  160. data/vendor/spikard-http/src/testing/test_client.rs +285 -0
  161. data/vendor/spikard-http/src/testing.rs +377 -0
  162. data/vendor/spikard-http/src/type_hints.rs +1 -0
  163. data/vendor/spikard-http/src/validation.rs +1 -0
  164. data/vendor/spikard-http/src/websocket.rs +324 -0
  165. data/vendor/spikard-rb/Cargo.toml +42 -0
  166. data/vendor/spikard-rb/build.rs +8 -0
  167. data/vendor/spikard-rb/src/background.rs +63 -0
  168. data/vendor/spikard-rb/src/config.rs +294 -0
  169. data/vendor/spikard-rb/src/conversion.rs +392 -0
  170. data/vendor/spikard-rb/src/di.rs +409 -0
  171. data/vendor/spikard-rb/src/handler.rs +534 -0
  172. data/vendor/spikard-rb/src/lib.rs +2020 -0
  173. data/vendor/spikard-rb/src/lifecycle.rs +267 -0
  174. data/vendor/spikard-rb/src/server.rs +283 -0
  175. data/vendor/spikard-rb/src/sse.rs +231 -0
  176. data/vendor/spikard-rb/src/test_client.rs +404 -0
  177. data/vendor/spikard-rb/src/test_sse.rs +143 -0
  178. data/vendor/spikard-rb/src/test_websocket.rs +221 -0
  179. data/vendor/spikard-rb/src/websocket.rs +233 -0
  180. metadata +162 -8
  181. /data/vendor/bundle/ruby/{3.3.0 → 3.4.0}/gems/diff-lcs-1.6.2/mise.toml +0 -0
  182. /data/vendor/bundle/ruby/{3.3.0 → 3.4.0}/gems/rake-compiler-dock-1.10.0/build/buildkitd.toml +0 -0
@@ -0,0 +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"
@@ -0,0 +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
+ }
@@ -0,0 +1,249 @@
1
+ use std::borrow::Cow;
2
+ use std::sync::Arc;
3
+ use std::time::Duration;
4
+
5
+ use futures::FutureExt;
6
+ use futures::future::BoxFuture;
7
+ use tokio::sync::{Semaphore, mpsc};
8
+ use tokio::task::JoinSet;
9
+ use tokio::time::timeout;
10
+ use tokio_util::sync::CancellationToken;
11
+
12
+ /// Configuration for in-process background task execution.
13
+ #[derive(Clone, Debug)]
14
+ pub struct BackgroundTaskConfig {
15
+ pub max_queue_size: usize,
16
+ pub max_concurrent_tasks: usize,
17
+ pub drain_timeout_secs: u64,
18
+ }
19
+
20
+ impl Default for BackgroundTaskConfig {
21
+ fn default() -> Self {
22
+ Self {
23
+ max_queue_size: 1024,
24
+ max_concurrent_tasks: 128,
25
+ drain_timeout_secs: 30,
26
+ }
27
+ }
28
+ }
29
+
30
+ #[derive(Clone, Debug)]
31
+ pub struct BackgroundJobMetadata {
32
+ pub name: Cow<'static, str>,
33
+ pub request_id: Option<String>,
34
+ }
35
+
36
+ impl Default for BackgroundJobMetadata {
37
+ fn default() -> Self {
38
+ Self {
39
+ name: Cow::Borrowed("background_task"),
40
+ request_id: None,
41
+ }
42
+ }
43
+ }
44
+
45
+ pub type BackgroundJobFuture = BoxFuture<'static, Result<(), BackgroundJobError>>;
46
+
47
+ struct BackgroundJob {
48
+ pub future: BackgroundJobFuture,
49
+ pub metadata: BackgroundJobMetadata,
50
+ }
51
+
52
+ impl BackgroundJob {
53
+ fn new<F>(future: F, metadata: BackgroundJobMetadata) -> Self
54
+ where
55
+ F: futures::Future<Output = Result<(), BackgroundJobError>> + Send + 'static,
56
+ {
57
+ Self {
58
+ future: future.boxed(),
59
+ metadata,
60
+ }
61
+ }
62
+ }
63
+
64
+ #[derive(Debug, Clone)]
65
+ pub struct BackgroundJobError {
66
+ pub message: String,
67
+ }
68
+
69
+ impl From<String> for BackgroundJobError {
70
+ fn from(message: String) -> Self {
71
+ Self { message }
72
+ }
73
+ }
74
+
75
+ impl From<&str> for BackgroundJobError {
76
+ fn from(message: &str) -> Self {
77
+ Self {
78
+ message: message.to_string(),
79
+ }
80
+ }
81
+ }
82
+
83
+ #[derive(Debug, Clone)]
84
+ pub enum BackgroundSpawnError {
85
+ QueueFull,
86
+ }
87
+
88
+ impl std::fmt::Display for BackgroundSpawnError {
89
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
90
+ match self {
91
+ BackgroundSpawnError::QueueFull => write!(f, "background task queue is full"),
92
+ }
93
+ }
94
+ }
95
+
96
+ impl std::error::Error for BackgroundSpawnError {}
97
+
98
+ #[derive(Debug)]
99
+ pub struct BackgroundShutdownError;
100
+
101
+ #[derive(Default)]
102
+ struct BackgroundMetrics {
103
+ queued: std::sync::atomic::AtomicU64,
104
+ running: std::sync::atomic::AtomicU64,
105
+ failed: std::sync::atomic::AtomicU64,
106
+ }
107
+
108
+ impl BackgroundMetrics {
109
+ fn inc_queued(&self) {
110
+ self.queued.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
111
+ }
112
+
113
+ fn dec_queued(&self) {
114
+ self.queued.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
115
+ }
116
+
117
+ fn inc_running(&self) {
118
+ self.running.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
119
+ }
120
+
121
+ fn dec_running(&self) {
122
+ self.running.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
123
+ }
124
+
125
+ fn inc_failed(&self) {
126
+ self.failed.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
127
+ }
128
+ }
129
+
130
+ #[derive(Clone)]
131
+ pub struct BackgroundHandle {
132
+ sender: mpsc::Sender<BackgroundJob>,
133
+ metrics: Arc<BackgroundMetrics>,
134
+ }
135
+
136
+ impl BackgroundHandle {
137
+ pub fn spawn<F, Fut>(&self, f: F) -> Result<(), BackgroundSpawnError>
138
+ where
139
+ F: FnOnce() -> Fut,
140
+ Fut: futures::Future<Output = Result<(), BackgroundJobError>> + Send + 'static,
141
+ {
142
+ let future = f();
143
+ self.spawn_with_metadata(future, BackgroundJobMetadata::default())
144
+ }
145
+
146
+ pub fn spawn_with_metadata<Fut>(
147
+ &self,
148
+ future: Fut,
149
+ metadata: BackgroundJobMetadata,
150
+ ) -> Result<(), BackgroundSpawnError>
151
+ where
152
+ Fut: futures::Future<Output = Result<(), BackgroundJobError>> + Send + 'static,
153
+ {
154
+ self.metrics.inc_queued();
155
+ let job = BackgroundJob::new(future, metadata);
156
+ self.sender.try_send(job).map_err(|_| {
157
+ self.metrics.dec_queued();
158
+ BackgroundSpawnError::QueueFull
159
+ })
160
+ }
161
+ }
162
+
163
+ pub struct BackgroundRuntime {
164
+ handle: BackgroundHandle,
165
+ drain_timeout: Duration,
166
+ shutdown_token: CancellationToken,
167
+ join_handle: tokio::task::JoinHandle<()>,
168
+ }
169
+
170
+ impl BackgroundRuntime {
171
+ pub async fn start(config: BackgroundTaskConfig) -> Self {
172
+ let (tx, rx) = mpsc::channel(config.max_queue_size);
173
+ let metrics = Arc::new(BackgroundMetrics::default());
174
+ let handle = BackgroundHandle {
175
+ sender: tx.clone(),
176
+ metrics: metrics.clone(),
177
+ };
178
+ let shutdown_token = CancellationToken::new();
179
+ let semaphore = Arc::new(Semaphore::new(config.max_concurrent_tasks));
180
+ let driver_token = shutdown_token.clone();
181
+
182
+ let join_handle = tokio::spawn(run_executor(rx, semaphore, metrics.clone(), driver_token));
183
+
184
+ Self {
185
+ handle,
186
+ drain_timeout: Duration::from_secs(config.drain_timeout_secs),
187
+ shutdown_token,
188
+ join_handle,
189
+ }
190
+ }
191
+
192
+ pub fn handle(&self) -> BackgroundHandle {
193
+ self.handle.clone()
194
+ }
195
+
196
+ pub async fn shutdown(self) -> Result<(), BackgroundShutdownError> {
197
+ self.shutdown_token.cancel();
198
+ drop(self.handle);
199
+ match timeout(self.drain_timeout, self.join_handle).await {
200
+ Ok(Ok(_)) => Ok(()),
201
+ _ => Err(BackgroundShutdownError),
202
+ }
203
+ }
204
+ }
205
+
206
+ async fn run_executor(
207
+ mut rx: mpsc::Receiver<BackgroundJob>,
208
+ semaphore: Arc<Semaphore>,
209
+ metrics: Arc<BackgroundMetrics>,
210
+ token: CancellationToken,
211
+ ) {
212
+ let mut join_set = JoinSet::new();
213
+
214
+ loop {
215
+ tokio::select! {
216
+ _ = token.cancelled() => {
217
+ break;
218
+ }
219
+ maybe_job = rx.recv() => {
220
+ match maybe_job {
221
+ Some(job) => {
222
+ metrics.dec_queued();
223
+ let semaphore = semaphore.clone();
224
+ let metrics_clone = metrics.clone();
225
+ join_set.spawn(async move {
226
+ let BackgroundJob { future, metadata } = job;
227
+ match semaphore.acquire_owned().await {
228
+ Ok(_permit) => {
229
+ metrics_clone.inc_running();
230
+ if let Err(err) = future.await {
231
+ metrics_clone.inc_failed();
232
+ tracing::error!(target = "spikard::background", task = %metadata.name, error = %err.message, "background task failed");
233
+ }
234
+ metrics_clone.dec_running();
235
+ }
236
+ Err(_) => {
237
+ tracing::warn!(target = "spikard::background", "failed to acquire semaphore permit for background task");
238
+ }
239
+ }
240
+ });
241
+ }
242
+ None => break,
243
+ }
244
+ }
245
+ }
246
+ }
247
+
248
+ while join_set.join_next().await.is_some() {}
249
+ }
@@ -0,0 +1,3 @@
1
+ pub mod response;
2
+
3
+ pub use response::{RawResponse, StaticAsset};
@@ -0,0 +1 @@
1
+ pub use spikard_core::bindings::response::*;
@@ -0,0 +1,8 @@
1
+ //! Shared metadata stored on `http::Response` extensions.
2
+
3
+ /// Extension type storing the original, uncompressed response body size in bytes.
4
+ ///
5
+ /// Middleware (like compression) can inspect this to make deterministic decisions
6
+ /// even when the final body length would otherwise require buffering.
7
+ #[derive(Debug, Clone, Copy)]
8
+ pub struct ResponseBodySize(pub usize);