rust-webx-host 1.2.0

rust-webx HTTP layer: Host builder, middleware pipeline, Trie-based router, hyper integration
Documentation
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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
//! JWT authentication module for the rust-webx framework.
//!
//! Provides `JwtAuth` —an `IAuthenticationHandler` implementation that reads
//! a Bearer token from the `Authorization` header and validates it using
//! the `jsonwebtoken` crate.
//!
//! # Issuance and revocation (WEBX-2)
//!
//! Minting and invalidation are ports, so application code does not need its
//! own signing or session code:
//!
//! * [`JwtTokenIssuer`] implements `ITokenIssuer` and is registered
//!   automatically by `HostBuilder::add_authentication()` from `Jwt.Secret`.
//!   A login handler injects `Arc<dyn ITokenIssuer>` and calls
//!   [`ITokenIssuer::issue`].
//! * `.use_session_store(store)` registers an `ISessionStore`; the auth
//!   middleware then rejects a token whose `jti` was revoked. Revocation is
//!   opt-in: without a store the middleware only verifies signatures.
//!
//! ```ignore
//! // login: issue and remember the jti (or give it to the client)
//! let issued = token_issuer.issue(TokenClaims::new(&user.id)).await?;
//! // logout: revoke it; the next request with that token is 401
//! session_store.revoke(&issued.jti).await?;
//! ```
//!
//! # Example
//!
//! ```ignore
//! use webx_host::auth_jwt::{JwtAuth, jwt_middleware};
//! use jsonwebtoken::{DecodingKey, Validation};
//!
//! let auth = JwtAuth::new(
//!     DecodingKey::from_secret(b"my-secret"),
//!     Validation::default(),
//! );
//! let middleware = jwt_middleware(Arc::new(auth));
//! ```

use jsonwebtoken::{decode, encode, DecodingKey, EncodingKey, Header, Validation};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::ops::ControlFlow;
use std::sync::{Arc, OnceLock};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use webx_core::auth::{IAuthenticationHandler, IClaims};
use webx_core::error::{Error, Result};
use webx_core::http::IHttpContext;
use webx_core::middleware::IMiddleware;
use webx_core::security::{ISessionStore, ITokenIssuer, IssuedToken, TokenClaims};

// ---------------------------------------------------------------------------
// JwtClaims —IClaims implementation backed by JWT payload
// ---------------------------------------------------------------------------

/// Claims extracted from a JWT token.
///
/// By default, looks for `sub`, `roles`, and `permissions` claims.
/// All other claims are accessible via `claims()` as stringified values.
pub struct JwtClaims {
    sub: String,
    roles: Vec<String>,
    permissions: Vec<String>,
    /// Pre-flattened raw claims map for the `claims()` method.
    raw: HashMap<String, String>,
}

/// Intermediate deserialization target. After deserialization we convert
/// into `JwtClaims` which stores pre-computed data for `IClaims`.
#[derive(Debug, Deserialize, Serialize)]
struct RawClaims {
    #[serde(default)]
    sub: String,
    #[serde(default)]
    roles: Vec<String>,
    #[serde(default)]
    permissions: Vec<String>,
    #[serde(flatten)]
    extra: HashMap<String, serde_json::Value>,
}

impl JwtClaims {
    /// Create empty claims with just a subject.
    pub fn new(subject: impl Into<String>) -> Self {
        let sub = subject.into();
        let mut raw = HashMap::new();
        raw.insert("sub".to_string(), sub.clone());
        Self {
            sub,
            roles: Vec::new(),
            permissions: Vec::new(),
            raw,
        }
    }
}

impl From<RawClaims> for JwtClaims {
    fn from(rc: RawClaims) -> Self {
        let mut raw = HashMap::new();
        raw.insert("sub".to_string(), rc.sub.clone());
        for (k, v) in &rc.extra {
            match v {
                serde_json::Value::String(s) => {
                    raw.insert(k.clone(), s.clone());
                }
                other => {
                    raw.insert(k.clone(), other.to_string());
                }
            }
        }
        Self {
            sub: rc.sub,
            roles: rc.roles,
            permissions: rc.permissions,
            raw,
        }
    }
}

impl IClaims for JwtClaims {
    fn subject(&self) -> &str {
        &self.sub
    }

    fn roles(&self) -> &[String] {
        &self.roles
    }

    fn permissions(&self) -> &[String] {
        &self.permissions
    }

    fn claims(&self) -> &HashMap<String, String> {
        &self.raw
    }

    fn clone_box(&self) -> Box<dyn IClaims> {
        Box::new(Self {
            sub: self.sub.clone(),
            roles: self.roles.clone(),
            permissions: self.permissions.clone(),
            raw: self.raw.clone(),
        })
    }
}

// ---------------------------------------------------------------------------
// JwtAuth —IAuthenticationHandler implementation
// ---------------------------------------------------------------------------

/// JWT-based authentication handler.
///
/// Reads the `Authorization: Bearer <token>` header, decodes and validates
/// the JWT, and returns the resulting claims. Only a **valid** token produces
/// claims: a missing header, a non-`Bearer` scheme or a token that fails
/// validation all yield `Ok(None)` — the request simply continues as anonymous.
pub struct JwtAuth {
    decoding_key: DecodingKey,
    validation: Validation,
}

impl JwtAuth {
    /// Create a new JWT authenticator.
    pub fn new(decoding_key: DecodingKey, validation: Validation) -> Self {
        Self {
            decoding_key,
            validation,
        }
    }
}

#[async_trait::async_trait]
impl IAuthenticationHandler for JwtAuth {
    async fn authenticate(&self, ctx: &mut dyn IHttpContext) -> Result<Option<Box<dyn IClaims>>> {
        // Extract token synchronously —avoids holding &dyn IHttpContext
        // across any async boundary, keeping the future Send.
        let header = match ctx.request().header("authorization") {
            Some(h) => h,
            None => return Ok(None),
        };

        // RFC 6750: scheme is case-insensitive
        let token = if header.len() >= 7 && header[..7].eq_ignore_ascii_case("Bearer ") {
            header[7..].trim().to_string()
        } else {
            return Ok(None);
        };

        if token.is_empty() {
            return Ok(None);
        }

        // A rejected token means "not authenticated", not "reject the request":
        // the request continues as anonymous and the endpoint decides. This is
        // what keeps a public endpoint (login, health, docs) reachable while a
        // client still holds an expired token, instead of dead-locking it with a
        // 401 on every call. Protected endpoints respond 401 further down the
        // pipeline (`#[authorize]` rules or a required `#[fromclaim]` identity),
        // through the single unauthorized writer (detail "authentication
        // required" + `WWW-Authenticate`).
        let token_data = match decode::<RawClaims>(&token, &self.decoding_key, &self.validation) {
            Ok(data) => data,
            Err(e) => {
                // The decoder's message is for operators, not for the client
                // (it names InvalidToken/ExpiredSignature/InvalidAlgorithm/...).
                tracing::debug!(reason = %e, "JWT rejected");
                return Ok(None);
            }
        };

        let claims: JwtClaims = token_data.claims.into();
        Ok(Some(Box::new(claims)))
    }
}

// ---------------------------------------------------------------------------
// JwtTokenIssuer —ITokenIssuer implementation (default token minting)
// ---------------------------------------------------------------------------

/// Default token lifetime used by [`JwtTokenIssuer::from_secret`] when the
/// caller does not pass one explicitly.
///
/// The host does **not** use this constant: `add_authentication()` builds the
/// issuer from the `Jwt.ExpirationMinutes` appsettings key (default 60 minutes).
pub const DEFAULT_TOKEN_LIFETIME: Duration = Duration::from_secs(3600);

fn unix_now() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|elapsed| elapsed.as_secs())
        .unwrap_or_default()
}

/// JWT token issuer — the default [`ITokenIssuer`].
///
/// **HS256 only.** The token is signed with `HS256` and verified by this
/// crate's `JwtAuth`, whose `Validation::default()` also expects `HS256`, so
/// issuer and verifier agree out of the box. Asymmetric algorithms (RSA/EC)
/// are not supported by this type: using one requires *both* a custom
/// [`ITokenIssuer`] and a custom [`IAuthenticationHandler`] (the host's
/// `jwt_middleware` always verifies with `Validation::default()`).
///
/// Mints a token carrying `sub`, `roles`, `permissions`, the caller's extra
/// claims, and the framework-managed `jti` / `iat` / `exp`. The `jti` is what
/// [`ISessionStore::revoke`] later invalidates, so a login endpoint only needs:
///
/// ```ignore
/// let issued = issuer.issue(TokenClaims::new(&user.id)).await?;
/// sessions.revoke(&issued.jti).await?; // logout
/// ```
///
/// `HostBuilder::add_authentication()` registers one from the configured
/// `Jwt.Secret` / `Jwt.ExpirationMinutes`; register a custom [`ITokenIssuer`] in
/// DI to replace it.
pub struct JwtTokenIssuer {
    encoding_key: EncodingKey,
    default_lifetime: Duration,
    issuer: Option<String>,
    audience: Option<String>,
}

impl JwtTokenIssuer {
    /// Build an HS256 issuer from a shared secret — the same secret
    /// `JwtAuth` verifies with.
    ///
    /// `default_lifetime` applies when [`TokenClaims::expires_in`] is `None`;
    /// `DEFAULT_TOKEN_LIFETIME` (1 hour) is the framework default.
    pub fn from_secret(secret: impl AsRef<[u8]>, default_lifetime: Duration) -> Self {
        Self {
            encoding_key: EncodingKey::from_secret(secret.as_ref()),
            default_lifetime,
            issuer: None,
            audience: None,
        }
    }

    /// Set the `iss` claim.
    pub fn with_issuer(mut self, issuer: impl Into<String>) -> Self {
        self.issuer = Some(issuer.into());
        self
    }

    /// Set the `aud` claim.
    pub fn with_audience(mut self, audience: impl Into<String>) -> Self {
        self.audience = Some(audience.into());
        self
    }
}

#[async_trait::async_trait]
impl ITokenIssuer for JwtTokenIssuer {
    async fn issue(&self, claims: TokenClaims) -> Result<IssuedToken> {
        let subject = claims.subject.trim();
        if subject.is_empty() {
            return Err(Error::Validation(
                "token subject must not be empty".to_string(),
            ));
        }

        let lifetime = claims.expires_in.unwrap_or(self.default_lifetime);
        let issued_at = unix_now();
        let expires_at_unix_secs = issued_at.saturating_add(lifetime.as_secs());
        let jti = uuid::Uuid::new_v4().to_string();

        // Extra claims first: reserved claims must win, otherwise a caller could
        // override `sub`/`exp`/`jti` through `TokenClaims::extra`.
        let mut payload = serde_json::Map::new();
        for (key, value) in &claims.extra {
            payload.insert(key.clone(), serde_json::Value::String(value.clone()));
        }
        payload.insert("sub".into(), serde_json::json!(subject));
        payload.insert("roles".into(), serde_json::json!(claims.roles));
        payload.insert("permissions".into(), serde_json::json!(claims.permissions));
        payload.insert("jti".into(), serde_json::json!(jti));
        payload.insert("iat".into(), serde_json::json!(issued_at));
        payload.insert("exp".into(), serde_json::json!(expires_at_unix_secs));
        if let Some(issuer) = &self.issuer {
            payload.insert("iss".into(), serde_json::json!(issuer));
        }
        if let Some(audience) = &self.audience {
            payload.insert("aud".into(), serde_json::json!(audience));
        }

        // `Header::default()` is `HS256` — the only algorithm this issuer
        // promises, and the one `JwtAuth` verifies.
        let token = encode(
            &Header::default(),
            &serde_json::Value::Object(payload),
            &self.encoding_key,
        )
        .map_err(|error| Error::Internal(format!("JWT signing failed: {error}")))?;

        Ok(IssuedToken {
            token,
            jti,
            expires_at_unix_secs,
        })
    }
}

// ---------------------------------------------------------------------------
// Middleware
// ---------------------------------------------------------------------------

/// Authentication middleware: verify the token, then reject revoked tokens.
struct AuthMiddleware {
    handler: Arc<dyn IAuthenticationHandler>,
    /// `None` = signature verification only (1.1 behaviour).
    session_store: Option<Arc<dyn ISessionStore>>,
}

#[async_trait::async_trait]
impl IMiddleware for AuthMiddleware {
    async fn invoke(&self, ctx: &mut dyn IHttpContext) -> Result<ControlFlow<()>> {
        if let Some(claims) = self.handler.authenticate(ctx).await? {
            if let Some(store) = &self.session_store {
                // A token without `jti` cannot be matched against a revocation
                // record; it keeps its `exp`-based lifetime (no re-reject).
                if let Some(jti) = claims.jti() {
                    if store.is_revoked(jti).await? {
                        // Revoked credentials are a credentials problem, not an
                        // anonymous request: fail here so the host writes its
                        // single 401 (problem+json + `WWW-Authenticate`).
                        return Err(Error::Unauthorized("token has been revoked".to_string()));
                    }
                }
            }
            // IHttpContext extends IClaimsExt, so set_claims is available directly.
            ctx.set_claims(claims);
        }
        Ok(ControlFlow::Continue(()))
    }
}

/// Create a JWT authentication middleware from an authentication handler.
///
/// Reads the Bearer token from `Authorization` header, validates it, and
/// stores the resulting claims in the HTTP context for downstream use.
pub fn jwt_middleware(handler: Arc<dyn IAuthenticationHandler>) -> impl IMiddleware {
    AuthMiddleware {
        handler,
        session_store: None,
    }
}

/// Create a JWT authentication middleware that also rejects revoked tokens.
///
/// After the signature check, the token's `jti` is looked up in `session_store`;
/// a revoked token is answered with the framework's 401 (problem+json +
/// `WWW-Authenticate`) before the endpoint runs. Tokens without a `jti` pass
/// through unchanged.
///
/// **Advanced entry point** — only for a hand-assembled middleware pipeline.
/// A regular host enables revocation with
/// [`HostBuilder::use_session_store`](crate::server::HostBuilder::use_session_store),
/// which registers the store and wires this middleware itself.
pub fn jwt_middleware_with_revocation(
    handler: Arc<dyn IAuthenticationHandler>,
    session_store: Arc<dyn ISessionStore>,
) -> impl IMiddleware {
    AuthMiddleware {
        handler,
        session_store: Some(session_store),
    }
}

// ---------------------------------------------------------------------------
// Global JWT encoding secret (for token creation in handlers)
// ---------------------------------------------------------------------------

static JWT_ENCODING_SECRET: OnceLock<String> = OnceLock::new();

/// Initialize the global JWT encoding secret from the configured secret.
/// This is called automatically by `.add_authentication()` on the `HostBuilder`,
/// but can also be called manually if needed.
///
/// Idempotent: subsequent calls are no-ops (the first secret wins).
pub fn init_jwt_secret(secret: &str) {
    let _ = JWT_ENCODING_SECRET.set(secret.to_owned());
}

/// Retrieve the global JWT encoding secret previously set via [`init_jwt_secret`].
///
/// # Panics
/// Panics if [`init_jwt_secret`] has not been called yet.
pub fn jwt_secret() -> &'static str {
    JWT_ENCODING_SECRET
        .get()
        .expect("init_jwt_secret must be called before jwt_secret")
}