1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
//! Authentication middleware for Axum request handlers.
use std::sync::Arc;
use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
use serde::{Deserialize, Serialize};
use crate::{
error::{AuthError, Result},
jwt::{Claims, JwtValidator},
};
/// Authenticated user extracted from JWT token
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuthenticatedUser {
/// User ID from token claims
pub user_id: String,
/// Full JWT claims
pub claims: Claims,
}
impl AuthenticatedUser {
/// Get a custom claim from the JWT
#[must_use]
pub fn get_custom_claim(&self, key: &str) -> Option<&serde_json::Value> {
self.claims.get_custom(key)
}
/// Check if user has a specific role
#[must_use]
pub fn has_role(&self, role: &str) -> bool {
if let Some(serde_json::Value::String(user_role)) = self.claims.get_custom("role") {
user_role == role
} else if let Some(serde_json::Value::Array(roles)) = self.claims.get_custom("roles") {
roles.iter().any(|r| {
if let serde_json::Value::String(r_str) = r {
r_str == role
} else {
false
}
})
} else {
false
}
}
}
/// Authentication middleware configuration
pub struct AuthMiddleware {
validator: Arc<JwtValidator>,
public_key: Vec<u8>,
}
impl AuthMiddleware {
/// Create a new authentication middleware
///
/// # Arguments
/// * `validator` - JWT validator
/// * `public_key` - Public key for JWT signature verification
///
/// Note: this type validates a presented Bearer token. The previous
/// `session_store` and `optional` parameters were never consulted (no
/// session-revocation check, no optional-auth handling), so they were removed
/// rather than continue to advertise behavior that did not exist
/// (L-authmw-ignores). Optional/anonymous handling belongs at the request layer;
/// session-revocation checks belong on the refresh-token path.
#[must_use]
pub const fn new(validator: Arc<JwtValidator>, public_key: Vec<u8>) -> Self {
Self {
validator,
public_key,
}
}
/// Validate a Bearer token and extract claims.
///
/// # Errors
///
/// Returns `AuthError::InvalidToken` if the token signature is invalid,
/// expired, or does not match the expected issuer/audience.
/// Returns `AuthError::KeyError` if the public key cannot be used for
/// verification.
// Reason: the awaitable signature is this crate's seam for key material that
// has to be fetched — `fraiseql_jwks::JwksSource` refreshes over the network. Only
// static-public-key path resolves without I/O, and narrowing the signature to
// it would have to be widened again by the first JWKS-backed validator.
#[allow(unknown_lints, clippy::unused_async_trait_impl)]
pub async fn validate_token(&self, token: &str) -> Result<Claims> {
self.validator.validate(token, &self.public_key)
}
}
impl AuthError {
/// Map each error variant to its HTTP response parts.
///
/// SECURITY: Sanitized messages never expose internal details.
#[allow(clippy::cognitive_complexity)] // Reason: exhaustive 1:1 mapping of AuthError variants to HTTP response tuples
fn response_parts(&self) -> (StatusCode, &'static str, String) {
match self {
Self::TokenExpired => {
(StatusCode::UNAUTHORIZED, "token_expired", "Authentication failed".to_string())
},
Self::InvalidSignature => (
StatusCode::UNAUTHORIZED,
"invalid_signature",
"Authentication failed".to_string(),
),
Self::InvalidToken { .. }
| Self::MissingClaim { .. }
| Self::InvalidClaimValue { .. }
// OIDC replay-protection errors and JWT temporal guards: return 401 without
// revealing which specific claim was invalid to avoid oracle attacks.
| Self::MissingNonce
| Self::NonceMismatch
| Self::MissingAuthTime
| Self::SessionTooOld { .. }
| Self::TokenIssuedInFuture
| Self::TokenTooOld
| Self::TokenNotYetValid
// Algorithm-substitution attacks: reject with 401 without revealing which algorithm
// was rejected, to avoid giving an attacker information about the allowed set.
| Self::ForbiddenAlgorithm { .. } => {
(StatusCode::UNAUTHORIZED, "invalid_token", "Authentication failed".to_string())
},
Self::TokenNotFound => {
(StatusCode::UNAUTHORIZED, "token_not_found", "Authentication failed".to_string())
},
Self::SessionRevoked => {
(StatusCode::UNAUTHORIZED, "session_revoked", "Authentication failed".to_string())
},
Self::InvalidState => {
(StatusCode::BAD_REQUEST, "invalid_state", "Authentication failed".to_string())
},
Self::Forbidden { .. } => {
(StatusCode::FORBIDDEN, "forbidden", "Permission denied".to_string())
},
Self::OAuthError { .. } => {
(StatusCode::UNAUTHORIZED, "oauth_error", "Authentication failed".to_string())
},
Self::SessionError { .. } => {
(StatusCode::UNAUTHORIZED, "session_error", "Authentication failed".to_string())
},
Self::DatabaseError { .. }
| Self::ConfigError { .. }
| Self::OidcMetadataError { .. }
| Self::Internal { .. }
| Self::SystemTimeError { .. } => (
StatusCode::INTERNAL_SERVER_ERROR,
"server_error",
"Service temporarily unavailable".to_string(),
),
Self::PkceError { .. } => {
(StatusCode::BAD_REQUEST, "pkce_error", "Authentication failed".to_string())
},
Self::RateLimited { retry_after_secs } => (
StatusCode::TOO_MANY_REQUESTS,
"rate_limited",
format!("Too many requests. Retry after {retry_after_secs} seconds"),
),
// SECURITY: unknown-user and wrong-password collapse to one response so the
// client cannot enumerate registered emails (no user-existence oracle).
Self::InvalidCredentials => (
StatusCode::UNAUTHORIZED,
"invalid_credentials",
"Invalid email or password".to_string(),
),
Self::AccountDisabled => {
(StatusCode::FORBIDDEN, "account_disabled", "This account is disabled".to_string())
},
// Account-wide deactivation (#946), as opposed to `AccountDisabled`, which
// suspends only the local password credential. Reached at session creation —
// i.e. after some credential already succeeded — so naming the state discloses
// nothing to a party that does not already hold a working credential.
Self::AccountDeactivated => (
StatusCode::FORBIDDEN,
"account_deactivated",
"This account has been deactivated".to_string(),
),
Self::EmailAlreadyRegistered => (
StatusCode::CONFLICT,
"email_already_registered",
"An account already exists for this email".to_string(),
),
// Safe to state plainly: reaching this requires having already proved
// control of the address, so it is not an existence oracle (#945).
Self::EmailClaimedByAnotherAccount => (
StatusCode::CONFLICT,
"email_claimed_by_another_account",
"That email address is already verified on another account".to_string(),
),
// The validation reason stays server-side; the client gets a generic message.
Self::InvalidRegistration { .. } => (
StatusCode::BAD_REQUEST,
"invalid_registration",
"Invalid registration details".to_string(),
),
}
}
/// Log security-sensitive error details server-side before returning a sanitized response.
#[allow(clippy::cognitive_complexity)] // Reason: exhaustive match logging security-sensitive details per AuthError variant
fn log_security_details(&self) {
use tracing::warn;
match self {
Self::InvalidToken { reason } => warn!("Invalid token error: {reason}"),
Self::MissingClaim { claim } => warn!("Missing required claim: {claim}"),
Self::InvalidClaimValue { claim, reason } => {
warn!("Invalid claim value for '{claim}': {reason}");
},
Self::Forbidden { message } => warn!("Authorization denied: {message}"),
Self::OAuthError { message } => warn!("OAuth provider error: {message}"),
Self::SessionError { message } => warn!("Session error: {message}"),
Self::DatabaseError { message } => {
warn!("Database error (should not reach client): {message}");
},
Self::ConfigError { message } => {
warn!("Configuration error (should not reach client): {message}");
},
Self::OidcMetadataError { message } => warn!("OIDC metadata error: {message}"),
Self::PkceError { message } => warn!("PKCE error: {message}"),
Self::Internal { message } => {
warn!("Internal error (should not reach client): {message}");
},
Self::SystemTimeError { message } => {
warn!("System time error (should not reach client): {message}");
},
Self::MissingNonce | Self::NonceMismatch => {
warn!("OIDC nonce validation failed: {self}");
},
Self::MissingAuthTime | Self::SessionTooOld { .. } => {
warn!("OIDC auth_time validation failed: {self}");
},
Self::TokenIssuedInFuture | Self::TokenTooOld | Self::TokenNotYetValid => {
warn!("JWT temporal claim validation failed: {self}");
},
Self::ForbiddenAlgorithm { alg } => {
warn!("OIDC algorithm-substitution attack rejected: forbidden algorithm '{alg}'");
},
Self::InvalidRegistration { reason } => warn!("Local signup rejected: {reason}"),
// No additional logging here: the local-password flow audit-logs the precise
// reason (unknown_user / wrong_password / disabled) at the point of failure.
Self::TokenExpired
| Self::InvalidSignature
| Self::TokenNotFound
| Self::SessionRevoked
| Self::InvalidState
| Self::RateLimited { .. }
| Self::InvalidCredentials
| Self::AccountDisabled
| Self::AccountDeactivated
| Self::EmailAlreadyRegistered
| Self::EmailClaimedByAnotherAccount => {},
}
}
}
impl IntoResponse for AuthError {
fn into_response(self) -> Response {
self.log_security_details();
let (status, error_code, sanitized_message) = self.response_parts();
let body = serde_json::json!({
"errors": [{
"message": sanitized_message,
"extensions": {
"code": error_code
}
}]
});
(status, axum::Json(body)).into_response()
}
}