spikard 0.3.5 → 0.3.6
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.
- checksums.yaml +4 -4
- data/LICENSE +1 -1
- data/README.md +659 -659
- data/ext/spikard_rb/Cargo.toml +17 -17
- data/ext/spikard_rb/extconf.rb +10 -10
- data/ext/spikard_rb/src/lib.rs +6 -6
- data/lib/spikard/app.rb +386 -386
- data/lib/spikard/background.rb +27 -27
- data/lib/spikard/config.rb +396 -396
- data/lib/spikard/converters.rb +13 -13
- data/lib/spikard/handler_wrapper.rb +113 -113
- data/lib/spikard/provide.rb +214 -214
- data/lib/spikard/response.rb +173 -173
- data/lib/spikard/schema.rb +243 -243
- data/lib/spikard/sse.rb +111 -111
- data/lib/spikard/streaming_response.rb +44 -44
- data/lib/spikard/testing.rb +221 -221
- data/lib/spikard/upload_file.rb +131 -131
- data/lib/spikard/version.rb +5 -5
- data/lib/spikard/websocket.rb +59 -59
- data/lib/spikard.rb +43 -43
- data/sig/spikard.rbs +366 -360
- data/vendor/crates/spikard-core/Cargo.toml +40 -40
- data/vendor/crates/spikard-core/src/bindings/mod.rs +3 -3
- data/vendor/crates/spikard-core/src/bindings/response.rs +133 -133
- data/vendor/crates/spikard-core/src/debug.rs +63 -63
- data/vendor/crates/spikard-core/src/di/container.rs +726 -726
- data/vendor/crates/spikard-core/src/di/dependency.rs +273 -273
- data/vendor/crates/spikard-core/src/di/error.rs +118 -118
- data/vendor/crates/spikard-core/src/di/factory.rs +538 -538
- data/vendor/crates/spikard-core/src/di/graph.rs +545 -545
- data/vendor/crates/spikard-core/src/di/mod.rs +192 -192
- data/vendor/crates/spikard-core/src/di/resolved.rs +411 -411
- data/vendor/crates/spikard-core/src/di/value.rs +283 -283
- data/vendor/crates/spikard-core/src/errors.rs +39 -39
- data/vendor/crates/spikard-core/src/http.rs +153 -153
- data/vendor/crates/spikard-core/src/lib.rs +29 -29
- data/vendor/crates/spikard-core/src/lifecycle.rs +422 -422
- data/vendor/crates/spikard-core/src/parameters.rs +722 -722
- data/vendor/crates/spikard-core/src/problem.rs +310 -310
- data/vendor/crates/spikard-core/src/request_data.rs +189 -189
- data/vendor/crates/spikard-core/src/router.rs +249 -249
- data/vendor/crates/spikard-core/src/schema_registry.rs +183 -183
- data/vendor/crates/spikard-core/src/type_hints.rs +304 -304
- data/vendor/crates/spikard-core/src/validation.rs +699 -699
- data/vendor/crates/spikard-http/Cargo.toml +68 -68
- data/vendor/crates/spikard-http/src/auth.rs +247 -247
- data/vendor/crates/spikard-http/src/background.rs +249 -249
- data/vendor/crates/spikard-http/src/bindings/mod.rs +3 -3
- data/vendor/crates/spikard-http/src/bindings/response.rs +1 -1
- data/vendor/crates/spikard-http/src/body_metadata.rs +8 -8
- data/vendor/crates/spikard-http/src/cors.rs +490 -490
- data/vendor/crates/spikard-http/src/debug.rs +63 -63
- data/vendor/crates/spikard-http/src/di_handler.rs +423 -423
- data/vendor/crates/spikard-http/src/handler_response.rs +190 -190
- data/vendor/crates/spikard-http/src/handler_trait.rs +228 -228
- data/vendor/crates/spikard-http/src/handler_trait_tests.rs +284 -284
- data/vendor/crates/spikard-http/src/lib.rs +529 -529
- data/vendor/crates/spikard-http/src/lifecycle/adapter.rs +149 -149
- data/vendor/crates/spikard-http/src/lifecycle.rs +428 -428
- data/vendor/crates/spikard-http/src/middleware/mod.rs +285 -285
- data/vendor/crates/spikard-http/src/middleware/multipart.rs +86 -86
- data/vendor/crates/spikard-http/src/middleware/urlencoded.rs +147 -147
- data/vendor/crates/spikard-http/src/middleware/validation.rs +287 -287
- data/vendor/crates/spikard-http/src/openapi/mod.rs +309 -309
- data/vendor/crates/spikard-http/src/openapi/parameter_extraction.rs +190 -190
- data/vendor/crates/spikard-http/src/openapi/schema_conversion.rs +308 -308
- data/vendor/crates/spikard-http/src/openapi/spec_generation.rs +195 -195
- data/vendor/crates/spikard-http/src/parameters.rs +1 -1
- data/vendor/crates/spikard-http/src/problem.rs +1 -1
- data/vendor/crates/spikard-http/src/query_parser.rs +369 -369
- data/vendor/crates/spikard-http/src/response.rs +399 -399
- data/vendor/crates/spikard-http/src/router.rs +1 -1
- data/vendor/crates/spikard-http/src/schema_registry.rs +1 -1
- data/vendor/crates/spikard-http/src/server/handler.rs +87 -87
- data/vendor/crates/spikard-http/src/server/lifecycle_execution.rs +98 -98
- data/vendor/crates/spikard-http/src/server/mod.rs +805 -805
- data/vendor/crates/spikard-http/src/server/request_extraction.rs +119 -119
- data/vendor/crates/spikard-http/src/sse.rs +447 -447
- data/vendor/crates/spikard-http/src/testing/form.rs +14 -14
- data/vendor/crates/spikard-http/src/testing/multipart.rs +60 -60
- data/vendor/crates/spikard-http/src/testing/test_client.rs +285 -285
- data/vendor/crates/spikard-http/src/testing.rs +377 -377
- data/vendor/crates/spikard-http/src/type_hints.rs +1 -1
- data/vendor/crates/spikard-http/src/validation.rs +1 -1
- data/vendor/crates/spikard-http/src/websocket.rs +324 -324
- data/vendor/crates/spikard-rb/Cargo.toml +42 -42
- data/vendor/crates/spikard-rb/build.rs +8 -8
- data/vendor/crates/spikard-rb/src/background.rs +63 -63
- data/vendor/crates/spikard-rb/src/config.rs +294 -294
- data/vendor/crates/spikard-rb/src/conversion.rs +453 -453
- data/vendor/crates/spikard-rb/src/di.rs +409 -409
- data/vendor/crates/spikard-rb/src/handler.rs +625 -625
- data/vendor/crates/spikard-rb/src/lib.rs +2771 -2771
- data/vendor/crates/spikard-rb/src/lifecycle.rs +274 -274
- data/vendor/crates/spikard-rb/src/server.rs +283 -283
- data/vendor/crates/spikard-rb/src/sse.rs +231 -231
- data/vendor/crates/spikard-rb/src/test_client.rs +404 -404
- data/vendor/crates/spikard-rb/src/test_sse.rs +143 -143
- data/vendor/crates/spikard-rb/src/test_websocket.rs +221 -221
- data/vendor/crates/spikard-rb/src/websocket.rs +233 -233
- metadata +1 -1
|
@@ -1,68 +1,68 @@
|
|
|
1
|
-
[package]
|
|
2
|
-
name = "spikard-http"
|
|
3
|
-
version = "0.3.
|
|
4
|
-
edition = "2024"
|
|
5
|
-
authors = ["Na'aman Hirschfeld <nhirschfeld@gmail.com>"]
|
|
6
|
-
license = "MIT"
|
|
7
|
-
repository = "https://github.com/Goldziher/spikard"
|
|
8
|
-
homepage = "https://github.com/Goldziher/spikard"
|
|
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 = { version = "0.8", features = ["multipart", "ws"] }
|
|
17
|
-
tokio = { version = "1", features = ["full"] }
|
|
18
|
-
tokio-util = "0.7"
|
|
19
|
-
tower = "0.5"
|
|
20
|
-
tower-http = { version = "0.6.7", features = [
|
|
21
|
-
"trace",
|
|
22
|
-
"request-id",
|
|
23
|
-
"compression-gzip",
|
|
24
|
-
"compression-br",
|
|
25
|
-
"timeout",
|
|
26
|
-
"limit",
|
|
27
|
-
"fs",
|
|
28
|
-
"set-header",
|
|
29
|
-
"sensitive-headers",
|
|
30
|
-
] }
|
|
31
|
-
tower_governor = "0.8"
|
|
32
|
-
jsonwebtoken = { version = "10.2", features = ["use_pem", "rust_crypto"] }
|
|
33
|
-
utoipa = { version = "5", features = ["axum_extras", "chrono", "uuid"] }
|
|
34
|
-
utoipa-swagger-ui = { version = "9", features = ["axum"] }
|
|
35
|
-
utoipa-redoc = { version = "6", features = ["axum"] }
|
|
36
|
-
serde = { version = "1.0", features = ["derive"] }
|
|
37
|
-
serde_json = "1.0"
|
|
38
|
-
tracing = "0.1"
|
|
39
|
-
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
|
40
|
-
spikard-core = { path = "../spikard-core", features = ["di"] }
|
|
41
|
-
futures-util = "0.3"
|
|
42
|
-
futures = "0.3"
|
|
43
|
-
jsonschema = { version = "0.37", default-features = false }
|
|
44
|
-
serde_qs = "0.15"
|
|
45
|
-
lazy_static = "1.5"
|
|
46
|
-
regex = "1"
|
|
47
|
-
rustc-hash = "2.1"
|
|
48
|
-
urlencoding = "2.1"
|
|
49
|
-
mime = "0.3"
|
|
50
|
-
jiff = "0.2"
|
|
51
|
-
uuid = "1.18"
|
|
52
|
-
bytes = "1.11"
|
|
53
|
-
http-body-util = "0.1"
|
|
54
|
-
http-body = "1.0"
|
|
55
|
-
axum-test = { version = "18", features = ["ws"] }
|
|
56
|
-
anyhow = "1.0"
|
|
57
|
-
cookie = "0.18"
|
|
58
|
-
base64 = "0.22.1"
|
|
59
|
-
flate2 = "1.1"
|
|
60
|
-
brotli = "8.0"
|
|
61
|
-
|
|
62
|
-
[features]
|
|
63
|
-
default = []
|
|
64
|
-
di = ["spikard-core/di"]
|
|
65
|
-
|
|
66
|
-
[dev-dependencies]
|
|
67
|
-
chrono = "0.4"
|
|
68
|
-
doc-comment = "0.3"
|
|
1
|
+
[package]
|
|
2
|
+
name = "spikard-http"
|
|
3
|
+
version = "0.3.6"
|
|
4
|
+
edition = "2024"
|
|
5
|
+
authors = ["Na'aman Hirschfeld <nhirschfeld@gmail.com>"]
|
|
6
|
+
license = "MIT"
|
|
7
|
+
repository = "https://github.com/Goldziher/spikard"
|
|
8
|
+
homepage = "https://github.com/Goldziher/spikard"
|
|
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 = { version = "0.8", features = ["multipart", "ws"] }
|
|
17
|
+
tokio = { version = "1", features = ["full"] }
|
|
18
|
+
tokio-util = "0.7"
|
|
19
|
+
tower = "0.5"
|
|
20
|
+
tower-http = { version = "0.6.7", features = [
|
|
21
|
+
"trace",
|
|
22
|
+
"request-id",
|
|
23
|
+
"compression-gzip",
|
|
24
|
+
"compression-br",
|
|
25
|
+
"timeout",
|
|
26
|
+
"limit",
|
|
27
|
+
"fs",
|
|
28
|
+
"set-header",
|
|
29
|
+
"sensitive-headers",
|
|
30
|
+
] }
|
|
31
|
+
tower_governor = "0.8"
|
|
32
|
+
jsonwebtoken = { version = "10.2", features = ["use_pem", "rust_crypto"] }
|
|
33
|
+
utoipa = { version = "5", features = ["axum_extras", "chrono", "uuid"] }
|
|
34
|
+
utoipa-swagger-ui = { version = "9", features = ["axum"] }
|
|
35
|
+
utoipa-redoc = { version = "6", features = ["axum"] }
|
|
36
|
+
serde = { version = "1.0", features = ["derive"] }
|
|
37
|
+
serde_json = "1.0"
|
|
38
|
+
tracing = "0.1"
|
|
39
|
+
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
|
40
|
+
spikard-core = { path = "../spikard-core", features = ["di"] }
|
|
41
|
+
futures-util = "0.3"
|
|
42
|
+
futures = "0.3"
|
|
43
|
+
jsonschema = { version = "0.37", default-features = false }
|
|
44
|
+
serde_qs = "0.15"
|
|
45
|
+
lazy_static = "1.5"
|
|
46
|
+
regex = "1"
|
|
47
|
+
rustc-hash = "2.1"
|
|
48
|
+
urlencoding = "2.1"
|
|
49
|
+
mime = "0.3"
|
|
50
|
+
jiff = "0.2"
|
|
51
|
+
uuid = "1.18"
|
|
52
|
+
bytes = "1.11"
|
|
53
|
+
http-body-util = "0.1"
|
|
54
|
+
http-body = "1.0"
|
|
55
|
+
axum-test = { version = "18", features = ["ws"] }
|
|
56
|
+
anyhow = "1.0"
|
|
57
|
+
cookie = "0.18"
|
|
58
|
+
base64 = "0.22.1"
|
|
59
|
+
flate2 = "1.1"
|
|
60
|
+
brotli = "8.0"
|
|
61
|
+
|
|
62
|
+
[features]
|
|
63
|
+
default = []
|
|
64
|
+
di = ["spikard-core/di"]
|
|
65
|
+
|
|
66
|
+
[dev-dependencies]
|
|
67
|
+
chrono = "0.4"
|
|
68
|
+
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
|
+
}
|