forge-runtime 0.9.0

Runtime executors and gateway for the Forge framework
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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
use std::sync::Arc;

use axum::{
    body::Body,
    extract::{Request, State},
    http::{StatusCode, header},
    middleware::Next,
    response::{IntoResponse, Json, Response},
};
use forge_core::auth::Claims;
use forge_core::config::JwtAlgorithm as CoreJwtAlgorithm;
use forge_core::function::AuthContext;
use jsonwebtoken::{Algorithm, DecodingKey, Validation, dangerous, decode, encode};
use tracing::debug;

use super::jwks::JwksClient;

/// Authentication configuration for the runtime.
#[derive(Debug, Clone)]
pub struct AuthConfig {
    /// JWT secret for HMAC algorithms (HS256, HS384, HS512).
    pub jwt_secret: Option<String>,
    /// JWT algorithm.
    pub algorithm: JwtAlgorithm,
    /// JWKS client for RSA algorithms.
    pub jwks_client: Option<Arc<JwksClient>>,
    /// Expected token issuer (iss claim).
    pub issuer: Option<String>,
    /// Expected audience (aud claim).
    pub audience: Option<String>,
    /// Skip signature verification (DEV MODE ONLY - NEVER USE IN PRODUCTION).
    /// This field is intentionally not public. Use `dev_mode()` constructor which
    /// includes a runtime guard against production use.
    pub(crate) skip_verification: bool,
}

impl Default for AuthConfig {
    fn default() -> Self {
        Self {
            jwt_secret: None,
            algorithm: JwtAlgorithm::HS256,
            jwks_client: None,
            issuer: None,
            audience: None,
            skip_verification: false,
        }
    }
}

impl AuthConfig {
    /// Create auth config from forge core config.
    pub fn from_forge_config(
        config: &forge_core::config::AuthConfig,
    ) -> Result<Self, super::jwks::JwksError> {
        let algorithm = JwtAlgorithm::from(config.jwt_algorithm);

        let jwks_client = config
            .jwks_url
            .as_ref()
            .map(|url| JwksClient::new(url.clone(), config.jwks_cache_ttl_secs).map(Arc::new))
            .transpose()?;

        Ok(Self {
            jwt_secret: config.jwt_secret.clone(),
            algorithm,
            jwks_client,
            issuer: config.jwt_issuer.clone(),
            audience: config.jwt_audience.clone(),
            skip_verification: false,
        })
    }

    /// Create a new auth config with the given HMAC secret.
    pub fn with_secret(secret: impl Into<String>) -> Self {
        Self {
            jwt_secret: Some(secret.into()),
            ..Default::default()
        }
    }

    /// Create a dev mode config that skips signature verification.
    /// WARNING: Only use this for development and testing!
    ///
    /// Returns a production-safe config (verification enabled, no secret) if
    /// `FORGE_ENV` is set to `"production"`, preventing accidental misuse.
    pub fn dev_mode() -> Self {
        if std::env::var("FORGE_ENV")
            .map(|v| v.eq_ignore_ascii_case("production"))
            .unwrap_or(false)
        {
            tracing::error!(
                "AuthConfig::dev_mode() called with FORGE_ENV=production. \
                 Returning default config with verification enabled."
            );
            return Self::default();
        }
        Self {
            jwt_secret: None,
            algorithm: JwtAlgorithm::HS256,
            jwks_client: None,
            issuer: None,
            audience: None,
            skip_verification: true,
        }
    }

    /// Check if this config uses HMAC (symmetric) algorithms.
    pub fn is_hmac(&self) -> bool {
        matches!(
            self.algorithm,
            JwtAlgorithm::HS256 | JwtAlgorithm::HS384 | JwtAlgorithm::HS512
        )
    }

    /// Check if this config uses RSA (asymmetric) algorithms.
    pub fn is_rsa(&self) -> bool {
        matches!(
            self.algorithm,
            JwtAlgorithm::RS256 | JwtAlgorithm::RS384 | JwtAlgorithm::RS512
        )
    }
}

/// Supported JWT algorithms.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum JwtAlgorithm {
    #[default]
    HS256,
    HS384,
    HS512,
    RS256,
    RS384,
    RS512,
}

impl From<JwtAlgorithm> for Algorithm {
    fn from(alg: JwtAlgorithm) -> Self {
        match alg {
            JwtAlgorithm::HS256 => Algorithm::HS256,
            JwtAlgorithm::HS384 => Algorithm::HS384,
            JwtAlgorithm::HS512 => Algorithm::HS512,
            JwtAlgorithm::RS256 => Algorithm::RS256,
            JwtAlgorithm::RS384 => Algorithm::RS384,
            JwtAlgorithm::RS512 => Algorithm::RS512,
        }
    }
}

impl From<CoreJwtAlgorithm> for JwtAlgorithm {
    fn from(alg: CoreJwtAlgorithm) -> Self {
        match alg {
            CoreJwtAlgorithm::HS256 => JwtAlgorithm::HS256,
            CoreJwtAlgorithm::HS384 => JwtAlgorithm::HS384,
            CoreJwtAlgorithm::HS512 => JwtAlgorithm::HS512,
            CoreJwtAlgorithm::RS256 => JwtAlgorithm::RS256,
            CoreJwtAlgorithm::RS384 => JwtAlgorithm::RS384,
            CoreJwtAlgorithm::RS512 => JwtAlgorithm::RS512,
        }
    }
}

/// Token issuer for HMAC-based JWT signing.
///
/// Created from the auth config when an HMAC algorithm is configured.
/// Passed into MutationContext so handlers can call `ctx.issue_token()`.
#[derive(Clone)]
pub struct HmacTokenIssuer {
    secret: String,
    algorithm: Algorithm,
}

impl HmacTokenIssuer {
    /// Create a token issuer from auth config, if HMAC auth is configured.
    pub fn from_config(config: &AuthConfig) -> Option<Self> {
        if !config.is_hmac() {
            return None;
        }
        let secret = config.jwt_secret.as_ref()?.clone();
        if secret.is_empty() {
            return None;
        }
        if secret.len() < 32 {
            tracing::warn!(
                secret_len = secret.len(),
                "JWT secret is shorter than 32 bytes. This weakens HMAC security \
                 and may allow brute-force attacks. Use a cryptographically random \
                 secret of at least 32 bytes (e.g. `openssl rand -base64 32`)."
            );
        }
        Some(Self {
            secret,
            algorithm: config.algorithm.into(),
        })
    }
}

impl forge_core::TokenIssuer for HmacTokenIssuer {
    fn sign(&self, claims: &Claims) -> forge_core::Result<String> {
        let header = jsonwebtoken::Header::new(self.algorithm);
        encode(
            &header,
            claims,
            &jsonwebtoken::EncodingKey::from_secret(self.secret.as_bytes()),
        )
        .map_err(|e| forge_core::ForgeError::Internal(format!("token signing error: {e}")))
    }
}

/// Authentication middleware.
#[derive(Clone)]
pub struct AuthMiddleware {
    config: Arc<AuthConfig>,
    /// Pre-computed HMAC decoding key (for performance).
    hmac_key: Option<DecodingKey>,
}

impl std::fmt::Debug for AuthMiddleware {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AuthMiddleware")
            .field("config", &self.config)
            .field("hmac_key", &self.hmac_key.is_some())
            .finish()
    }
}

impl AuthMiddleware {
    /// Create a new auth middleware.
    pub fn new(config: AuthConfig) -> Self {
        if config.skip_verification {
            tracing::warn!("JWT signature verification is DISABLED. Do not use in production.");
        }

        // Pre-compute HMAC key if using HMAC algorithm
        let hmac_key = if config.skip_verification {
            None
        } else if config.is_hmac() {
            config
                .jwt_secret
                .as_ref()
                .filter(|s| !s.is_empty())
                .map(|secret| DecodingKey::from_secret(secret.as_bytes()))
        } else {
            None
        };

        Self {
            config: Arc::new(config),
            hmac_key,
        }
    }

    /// Create a middleware that allows all requests (development mode).
    /// WARNING: This skips signature verification! Never use in production.
    pub fn permissive() -> Self {
        Self::new(AuthConfig::dev_mode())
    }

    /// Get the config.
    pub fn config(&self) -> &AuthConfig {
        &self.config
    }

    /// Validate a JWT token and extract claims.
    pub async fn validate_token_async(&self, token: &str) -> Result<Claims, AuthError> {
        if self.config.skip_verification {
            return self.decode_without_verification(token);
        }

        if self.config.is_hmac() {
            self.validate_hmac(token)
        } else {
            self.validate_rsa(token).await
        }
    }

    /// Validate HMAC-signed token.
    fn validate_hmac(&self, token: &str) -> Result<Claims, AuthError> {
        let key = self.hmac_key.as_ref().ok_or_else(|| {
            AuthError::InvalidToken("JWT secret not configured for HMAC".to_string())
        })?;

        self.decode_and_validate(token, key)
    }

    /// Validate RSA-signed token using JWKS.
    async fn validate_rsa(&self, token: &str) -> Result<Claims, AuthError> {
        let jwks = self.config.jwks_client.as_ref().ok_or_else(|| {
            AuthError::InvalidToken("JWKS URL not configured for RSA".to_string())
        })?;

        // Extract key ID from token header
        let header = jsonwebtoken::decode_header(token)
            .map_err(|e| AuthError::InvalidToken(format!("Invalid token header: {}", e)))?;

        debug!(kid = ?header.kid, alg = ?header.alg, "Validating RSA token");

        // Get key from JWKS
        let key = if let Some(kid) = header.kid {
            jwks.get_key(&kid).await.map_err(|e| {
                AuthError::InvalidToken(format!("Failed to get key '{}': {}", kid, e))
            })?
        } else {
            jwks.get_any_key()
                .await
                .map_err(|e| AuthError::InvalidToken(format!("Failed to get JWKS key: {}", e)))?
        };

        self.decode_and_validate(token, &key)
    }

    /// Decode and validate token with the given key.
    fn decode_and_validate(&self, token: &str, key: &DecodingKey) -> Result<Claims, AuthError> {
        let mut validation = Validation::new(self.config.algorithm.into());

        // Configure validation
        validation.validate_exp = true;
        validation.validate_nbf = true;
        validation.leeway = 60; // 60 seconds clock skew tolerance

        // Require exp and sub claims
        validation.set_required_spec_claims(&["exp", "sub"]);

        // Validate issuer if configured
        if let Some(ref issuer) = self.config.issuer {
            validation.set_issuer(&[issuer]);
        }

        // Validate audience if configured
        if let Some(ref audience) = self.config.audience {
            validation.set_audience(&[audience]);
        } else {
            validation.validate_aud = false;
        }

        let token_data =
            decode::<Claims>(token, key, &validation).map_err(|e| self.map_jwt_error(e))?;

        Ok(token_data.claims)
    }

    /// Map jsonwebtoken errors to AuthError.
    fn map_jwt_error(&self, e: jsonwebtoken::errors::Error) -> AuthError {
        match e.kind() {
            jsonwebtoken::errors::ErrorKind::ExpiredSignature => AuthError::TokenExpired,
            jsonwebtoken::errors::ErrorKind::InvalidSignature => {
                AuthError::InvalidToken("Invalid signature".to_string())
            }
            jsonwebtoken::errors::ErrorKind::InvalidToken => {
                AuthError::InvalidToken("Invalid token format".to_string())
            }
            jsonwebtoken::errors::ErrorKind::MissingRequiredClaim(claim) => {
                AuthError::InvalidToken(format!("Missing required claim: {}", claim))
            }
            jsonwebtoken::errors::ErrorKind::InvalidIssuer => {
                AuthError::InvalidToken("Invalid issuer".to_string())
            }
            jsonwebtoken::errors::ErrorKind::InvalidAudience => {
                AuthError::InvalidToken("Invalid audience".to_string())
            }
            _ => AuthError::InvalidToken(e.to_string()),
        }
    }

    /// Decode JWT token without signature verification (DEV MODE ONLY).
    fn decode_without_verification(&self, token: &str) -> Result<Claims, AuthError> {
        let token_data =
            dangerous::insecure_decode::<Claims>(token).map_err(|e| match e.kind() {
                jsonwebtoken::errors::ErrorKind::InvalidToken => {
                    AuthError::InvalidToken("Invalid token format".to_string())
                }
                _ => AuthError::InvalidToken(e.to_string()),
            })?;

        // Still check expiration in dev mode
        if token_data.claims.is_expired() {
            return Err(AuthError::TokenExpired);
        }

        Ok(token_data.claims)
    }
}

/// Authentication errors.
#[derive(Debug, Clone, thiserror::Error)]
pub enum AuthError {
    #[error("Missing authorization header")]
    MissingHeader,
    #[error("Invalid authorization header format")]
    InvalidHeader,
    #[error("Invalid token: {0}")]
    InvalidToken(String),
    #[error("Token expired")]
    TokenExpired,
}

/// Pull client IP + user-agent from a request for auth-failure signal emission.
fn extract_auth_diag(req: &Request<Body>) -> (Option<String>, Option<String>) {
    let ip = crate::gateway::extract_client_ip(req.headers());
    let ua = crate::gateway::extract_header(req.headers(), "user-agent");
    (ip, ua)
}

/// Emit a diagnostic signal event for an authentication failure. Used by
/// dashboards to monitor attack patterns and by operators to debug client
/// token issues.
fn emit_auth_failure(
    reason: &str,
    detail: &str,
    path: &str,
    client_ip: Option<String>,
    user_agent: Option<String>,
) {
    let is_bot = crate::signals::bot::is_bot(user_agent.as_deref());
    crate::signals::emit_diagnostic(
        "auth.failed",
        serde_json::json!({
            "reason": reason,
            "detail": detail,
            "path": path,
        }),
        client_ip,
        user_agent,
        None,
        None,
        is_bot,
    );
}

/// Extract token from request headers.
pub fn extract_token(req: &Request<Body>) -> Result<Option<String>, AuthError> {
    let Some(header_value) = req.headers().get(axum::http::header::AUTHORIZATION) else {
        return Ok(None);
    };

    let header = header_value
        .to_str()
        .map_err(|_| AuthError::InvalidHeader)?;
    let token = header
        .strip_prefix("Bearer ")
        .ok_or(AuthError::InvalidHeader)?
        .trim();

    if token.is_empty() {
        return Err(AuthError::InvalidHeader);
    }

    Ok(Some(token.to_string()))
}

/// Extract auth context from token (async, supports both HMAC and RSA/JWKS).
pub async fn extract_auth_context_async(
    token: Option<String>,
    middleware: &AuthMiddleware,
) -> Result<AuthContext, AuthError> {
    match token {
        Some(token) => middleware
            .validate_token_async(&token)
            .await
            .map(build_auth_context_from_claims),
        None => Ok(AuthContext::unauthenticated()),
    }
}

/// Build auth context from validated claims.
///
/// This handles both UUID and non-UUID subjects properly:
/// - UUID subjects: uses `authenticated()` with the parsed UUID
/// - Non-UUID subjects: uses `authenticated_without_uuid()` and stores raw subject in claims
pub fn build_auth_context_from_claims(claims: Claims) -> AuthContext {
    // Try to parse subject as UUID first (before moving claims)
    let user_id = claims.user_id();

    // Build custom claims with raw subject included, filtering out reserved JWT claims
    let mut custom_claims = claims.sanitized_custom();
    custom_claims.insert("sub".to_string(), serde_json::Value::String(claims.sub));

    match user_id {
        Some(uuid) => {
            // Subject is a valid UUID
            AuthContext::authenticated(uuid, claims.roles, custom_claims)
        }
        None => {
            // Subject is not a UUID (e.g., Firebase uid, Clerk user_xxx, email)
            // Still authenticated, but user_id() will return None
            AuthContext::authenticated_without_uuid(claims.roles, custom_claims)
        }
    }
}

/// Authentication middleware function.
pub async fn auth_middleware(
    State(middleware): State<Arc<AuthMiddleware>>,
    req: Request<Body>,
    next: Next,
) -> Response {
    let token = match extract_token(&req) {
        Ok(token) => token,
        Err(e) => {
            let (ip, ua) = extract_auth_diag(&req);
            tracing::warn!(error = %e, "Invalid authorization header");
            emit_auth_failure("invalid_header", &e.to_string(), req.uri().path(), ip, ua);
            return (
                StatusCode::UNAUTHORIZED,
                Json(serde_json::json!({
                    "success": false,
                    "error": { "code": "UNAUTHORIZED", "message": "Invalid authorization header" }
                })),
            )
                .into_response();
        }
    };
    tracing::trace!(
        token_present = token.is_some(),
        "Auth middleware processing request"
    );

    let auth_context = match extract_auth_context_async(token, &middleware).await {
        Ok(auth_context) => auth_context,
        Err(e) => {
            let (ip, ua) = extract_auth_diag(&req);
            let reason = match &e {
                AuthError::TokenExpired => "token_expired",
                AuthError::InvalidToken(_) => "invalid_token",
                AuthError::MissingHeader => "missing_token",
                AuthError::InvalidHeader => "invalid_header",
            };
            tracing::warn!(error = %e, "Token validation failed");
            emit_auth_failure(reason, &e.to_string(), req.uri().path(), ip, ua);
            return (
                StatusCode::UNAUTHORIZED,
                Json(serde_json::json!({
                    "success": false,
                    "error": { "code": "UNAUTHORIZED", "message": "Invalid authentication token" }
                })),
            )
                .into_response();
        }
    };
    tracing::trace!(
        authenticated = auth_context.is_authenticated(),
        "Auth context created"
    );

    // Set OAuth session cookie when user is authenticated and HMAC secret
    // is available. This identifies the user on the OAuth authorize page
    // (same backend origin) without needing cross-origin localStorage.
    // Requires CORS Access-Control-Allow-Credentials: true and frontend
    // fetch with credentials: 'include' for the Set-Cookie to stick.
    let should_set_cookie =
        auth_context.is_authenticated() && middleware.config.jwt_secret.is_some();

    let req_is_https = req
        .headers()
        .get("x-forwarded-proto")
        .and_then(|v| v.to_str().ok())
        .map(|s| s == "https")
        .unwrap_or(false);

    // Skip cookie if one already exists (avoids resigning on every request)
    let has_session_cookie = req
        .headers()
        .get(header::COOKIE)
        .and_then(|v| v.to_str().ok())
        .map(|c| c.contains("forge_session="))
        .unwrap_or(false);

    let should_set_cookie = should_set_cookie && !has_session_cookie;

    let mut req = req;
    req.extensions_mut().insert(auth_context.clone());

    let mut response = next.run(req).await;

    if should_set_cookie
        && let Some(subject) = auth_context.subject()
        && let Some(secret) = &middleware.config.jwt_secret
    {
        let cookie_value = sign_session_cookie(subject, secret);
        let secure_flag = if req_is_https { "; Secure" } else { "" };
        let cookie = format!(
            "forge_session={cookie_value}; Path=/_api/oauth/; HttpOnly; SameSite=Lax; Max-Age=86400{secure_flag}"
        );
        if let Ok(val) = axum::http::HeaderValue::from_str(&cookie) {
            response.headers_mut().append(header::SET_COOKIE, val);
        }
    }

    response
}

/// OAuth session cookie format: `subject.expiry_unix.hmac_signature`
/// The cookie identifies a user for the OAuth consent page without requiring
/// localStorage (which doesn't work cross-origin in dev).
pub fn sign_session_cookie(subject: &str, secret: &str) -> String {
    use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
    use hmac::{Hmac, Mac};
    use sha2::Sha256;

    let expiry = chrono::Utc::now().timestamp() + 86400; // 24h
    let payload = format!("{subject}.{expiry}");

    let mut mac =
        Hmac::<Sha256>::new_from_slice(secret.as_bytes()).expect("HMAC accepts any key length");
    mac.update(payload.as_bytes());
    let sig = URL_SAFE_NO_PAD.encode(mac.finalize().into_bytes());

    format!("{payload}.{sig}")
}

/// Verify and extract the subject from a session cookie.
/// Returns None if expired, tampered, or malformed.
pub fn verify_session_cookie(cookie_value: &str, secret: &str) -> Option<String> {
    use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
    use hmac::{Hmac, Mac};
    use sha2::Sha256;

    let parts: Vec<&str> = cookie_value.rsplitn(2, '.').collect();
    if parts.len() != 2 {
        return None;
    }
    let sig_encoded = parts.first()?;
    let payload = parts.get(1)?; // "subject.expiry"

    // Verify signature (HMAC verify_slice is constant-time)
    let sig_bytes = URL_SAFE_NO_PAD.decode(sig_encoded).ok()?;
    let mut mac = Hmac::<Sha256>::new_from_slice(secret.as_bytes()).ok()?;
    mac.update(payload.as_bytes());
    mac.verify_slice(&sig_bytes).ok()?;

    // Extract subject and expiry
    let dot_pos = payload.rfind('.')?;
    let subject = &payload[..dot_pos];
    let expiry_str = &payload[dot_pos + 1..];
    let expiry: i64 = expiry_str.parse().ok()?;

    if chrono::Utc::now().timestamp() > expiry {
        return None;
    }

    Some(subject.to_string())
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::indexing_slicing, clippy::panic)]
mod tests {
    use super::*;
    use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
    use hmac::{Hmac, Mac};
    use jsonwebtoken::{EncodingKey, Header, encode};
    use sha2::Sha256;

    fn create_test_claims(expired: bool) -> Claims {
        use forge_core::auth::ClaimsBuilder;

        let mut builder = ClaimsBuilder::new().subject("test-user-id").role("user");

        if expired {
            builder = builder.duration_secs(-3600); // Expired 1 hour ago
        } else {
            builder = builder.duration_secs(3600); // Valid for 1 hour
        }

        builder.build().unwrap()
    }

    fn create_test_token(claims: &Claims, secret: &str) -> String {
        encode(
            &Header::default(),
            claims,
            &EncodingKey::from_secret(secret.as_bytes()),
        )
        .unwrap()
    }

    fn session_cookie_with_expiry(subject: &str, secret: &str, expiry: i64) -> String {
        let payload = format!("{subject}.{expiry}");
        let mut mac =
            Hmac::<Sha256>::new_from_slice(secret.as_bytes()).expect("HMAC accepts any key");
        mac.update(payload.as_bytes());
        let sig = URL_SAFE_NO_PAD.encode(mac.finalize().into_bytes());
        format!("{payload}.{sig}")
    }

    #[test]
    fn test_auth_config_default() {
        let config = AuthConfig::default();
        assert_eq!(config.algorithm, JwtAlgorithm::HS256);
        assert!(!config.skip_verification);
    }

    #[test]
    fn test_auth_config_dev_mode() {
        let config = AuthConfig::dev_mode();
        assert!(config.skip_verification);
    }

    #[test]
    fn test_auth_middleware_permissive() {
        let middleware = AuthMiddleware::permissive();
        assert!(middleware.config.skip_verification);
    }

    #[tokio::test]
    async fn test_valid_token_with_correct_secret() {
        let secret = "test-secret-key";
        let config = AuthConfig::with_secret(secret);
        let middleware = AuthMiddleware::new(config);

        let claims = create_test_claims(false);
        let token = create_test_token(&claims, secret);

        let result = middleware.validate_token_async(&token).await;
        assert!(result.is_ok());
        let validated_claims = result.unwrap();
        assert_eq!(validated_claims.sub, "test-user-id");
    }

    #[tokio::test]
    async fn test_valid_token_with_wrong_secret() {
        let config = AuthConfig::with_secret("correct-secret");
        let middleware = AuthMiddleware::new(config);

        let claims = create_test_claims(false);
        let token = create_test_token(&claims, "wrong-secret");

        let result = middleware.validate_token_async(&token).await;
        assert!(result.is_err());
        match result {
            Err(AuthError::InvalidToken(_)) => {}
            _ => panic!("Expected InvalidToken error"),
        }
    }

    #[tokio::test]
    async fn test_expired_token() {
        let secret = "test-secret";
        let config = AuthConfig::with_secret(secret);
        let middleware = AuthMiddleware::new(config);

        let claims = create_test_claims(true); // Expired
        let token = create_test_token(&claims, secret);

        let result = middleware.validate_token_async(&token).await;
        assert!(result.is_err());
        match result {
            Err(AuthError::TokenExpired) => {}
            _ => panic!("Expected TokenExpired error"),
        }
    }

    #[tokio::test]
    async fn test_tampered_token() {
        let secret = "test-secret";
        let config = AuthConfig::with_secret(secret);
        let middleware = AuthMiddleware::new(config);

        let claims = create_test_claims(false);
        let mut token = create_test_token(&claims, secret);

        // Tamper with the token by modifying a character in the signature
        if let Some(last_char) = token.pop() {
            let replacement = if last_char == 'a' { 'b' } else { 'a' };
            token.push(replacement);
        }

        let result = middleware.validate_token_async(&token).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_dev_mode_skips_signature() {
        let config = AuthConfig::dev_mode();
        let middleware = AuthMiddleware::new(config);

        // Create token with any secret
        let claims = create_test_claims(false);
        let token = create_test_token(&claims, "any-secret");

        // Should still validate in dev mode
        let result = middleware.validate_token_async(&token).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_dev_mode_still_checks_expiration() {
        let config = AuthConfig::dev_mode();
        let middleware = AuthMiddleware::new(config);

        let claims = create_test_claims(true); // Expired
        let token = create_test_token(&claims, "any-secret");

        let result = middleware.validate_token_async(&token).await;
        assert!(result.is_err());
        match result {
            Err(AuthError::TokenExpired) => {}
            _ => panic!("Expected TokenExpired error even in dev mode"),
        }
    }

    #[tokio::test]
    async fn test_invalid_token_format() {
        let config = AuthConfig::with_secret("secret");
        let middleware = AuthMiddleware::new(config);

        let result = middleware.validate_token_async("not-a-valid-jwt").await;
        assert!(result.is_err());
        match result {
            Err(AuthError::InvalidToken(_)) => {}
            _ => panic!("Expected InvalidToken error"),
        }
    }

    #[test]
    fn test_algorithm_conversion() {
        // HMAC algorithms
        assert_eq!(Algorithm::from(JwtAlgorithm::HS256), Algorithm::HS256);
        assert_eq!(Algorithm::from(JwtAlgorithm::HS384), Algorithm::HS384);
        assert_eq!(Algorithm::from(JwtAlgorithm::HS512), Algorithm::HS512);
        // RSA algorithms
        assert_eq!(Algorithm::from(JwtAlgorithm::RS256), Algorithm::RS256);
        assert_eq!(Algorithm::from(JwtAlgorithm::RS384), Algorithm::RS384);
        assert_eq!(Algorithm::from(JwtAlgorithm::RS512), Algorithm::RS512);
    }

    #[test]
    fn test_is_hmac_and_is_rsa() {
        let hmac_config = AuthConfig::with_secret("test");
        assert!(hmac_config.is_hmac());
        assert!(!hmac_config.is_rsa());

        let rsa_config = AuthConfig {
            algorithm: JwtAlgorithm::RS256,
            ..Default::default()
        };
        assert!(!rsa_config.is_hmac());
        assert!(rsa_config.is_rsa());
    }

    #[test]
    fn test_extract_token_rejects_non_bearer_header() {
        let req = Request::builder()
            .header(axum::http::header::AUTHORIZATION, "Basic abc")
            .body(Body::empty())
            .unwrap();

        let result = extract_token(&req);
        assert!(matches!(result, Err(AuthError::InvalidHeader)));
    }

    #[test]
    fn test_build_auth_context_from_non_uuid_claims_preserves_subject() {
        let claims = Claims::builder()
            .subject("clerk_user_123")
            .role("member")
            .claim("tenant_id", serde_json::json!("tenant-1"))
            .build()
            .unwrap();

        let auth = build_auth_context_from_claims(claims);
        assert!(auth.is_authenticated());
        assert!(auth.user_id().is_none());
        assert_eq!(auth.subject(), Some("clerk_user_123"));
        assert_eq!(auth.principal_id(), Some("clerk_user_123".to_string()));
        assert!(auth.has_role("member"));
        assert_eq!(
            auth.claim("sub"),
            Some(&serde_json::json!("clerk_user_123"))
        );
    }

    #[test]
    fn test_verify_session_cookie_round_trip_and_tamper_detection() {
        let cookie = sign_session_cookie("user-123", "session-secret");

        assert_eq!(
            verify_session_cookie(&cookie, "session-secret"),
            Some("user-123".to_string())
        );

        let mut tampered = cookie.clone();
        if let Some(last_char) = tampered.pop() {
            tampered.push(if last_char == 'a' { 'b' } else { 'a' });
        }

        assert_eq!(verify_session_cookie(&tampered, "session-secret"), None);
        assert_eq!(verify_session_cookie(&cookie, "wrong-secret"), None);
    }

    #[test]
    fn test_verify_session_cookie_rejects_expired_cookie() {
        let expired_cookie = session_cookie_with_expiry(
            "user-123",
            "session-secret",
            chrono::Utc::now().timestamp() - 1,
        );

        assert_eq!(
            verify_session_cookie(&expired_cookie, "session-secret"),
            None
        );
    }

    #[tokio::test]
    async fn test_extract_auth_context_async_invalid_token_errors() {
        let middleware = AuthMiddleware::new(AuthConfig::with_secret("secret"));
        let result = extract_auth_context_async(Some("bad.token".to_string()), &middleware).await;
        assert!(matches!(result, Err(AuthError::InvalidToken(_))));
    }
}