turbomcp-auth 3.0.12

OAuth 2.1 and authentication for TurboMCP with MCP protocol compliance
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
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
//! Unified Authentication Context
//!
//! This module provides the canonical `AuthContext` type used across TurboMCP.
//! It serves as both the internal authentication representation AND the JWT claims structure.
//!
//! # Design Principles
//!
//! - **Single Source of Truth**: ONE auth context type, used everywhere
//! - **Standards-Compliant**: RFC 7519 (JWT), OAuth 2.1, RFC 9449 (DPoP)
//! - **Feature-Gated**: Zero-cost abstractions - no overhead for unused features
//! - **Extensible**: Custom claims via metadata HashMap

use std::collections::HashMap;
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use serde::{Deserialize, Serialize};
use serde_json::Value;

// Import from existing types module to avoid duplication
pub use crate::types::{TokenInfo, UserInfo};

/// Validation configuration for AuthContext
#[derive(Debug, Clone)]
pub struct ValidationConfig {
    /// Expected issuer (iss claim)
    pub issuer: Option<String>,
    /// Expected audience (aud claim)
    pub audience: Option<String>,
    /// Clock skew tolerance for exp/nbf validation
    pub leeway: Duration,
    /// Validate expiration (exp claim)
    pub validate_exp: bool,
    /// Validate not-before (nbf claim)
    pub validate_nbf: bool,
}

impl Default for ValidationConfig {
    fn default() -> Self {
        Self {
            issuer: None,
            audience: None,
            leeway: Duration::from_secs(60), // 60 second clock skew tolerance
            validate_exp: true,
            validate_nbf: true,
        }
    }
}

/// Unified authentication context containing user identity, claims, and session metadata.
///
/// This type serves as both:
/// - The internal authentication representation
/// - The JWT claims structure (via `to_jwt_claims` / `from_jwt_claims`)
///
/// # Standard JWT Claims (RFC 7519)
///
/// - `sub`: Subject (user ID)
/// - `iss`: Issuer (who issued the token)
/// - `aud`: Audience (who the token is for)
/// - `exp`: Expiration time (Unix timestamp)
/// - `iat`: Issued at (Unix timestamp)
/// - `nbf`: Not before (Unix timestamp)
/// - `jti`: JWT ID (unique identifier)
///
/// # Extended Claims
///
/// - `user`: Full user information
/// - `roles`: RBAC roles
/// - `permissions`: Fine-grained permissions
/// - `scopes`: OAuth scopes
/// - `request_id`: Request identifier for replay protection (NOT session-based)
/// - `provider`: Auth provider identifier
/// - `metadata`: Custom claims
///
/// # Example
///
/// ```rust,ignore
/// use turbomcp_auth::context::{AuthContext, AuthContextBuilder};
///
/// let ctx = AuthContext::builder()
///     .subject("user123")
///     .user(user_info)
///     .roles(vec!["admin".into(), "user".into()])
///     .permissions(vec!["read:posts".into(), "write:posts".into()])
///     .build();
///
/// // Check authorization
/// if ctx.has_role("admin") && ctx.has_permission("write:posts") {
///     // Allow action
/// }
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuthContext {
    // ═══════════════════════════════════════════════════
    // STANDARD JWT CLAIMS (RFC 7519)
    // ═══════════════════════════════════════════════════
    /// Subject (typically user ID)
    pub sub: String,

    /// Issuer (who issued this token)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub iss: Option<String>,

    /// Audience (who this token is for)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub aud: Option<String>,

    /// Expiration time (Unix timestamp)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub exp: Option<u64>,

    /// Issued at (Unix timestamp)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub iat: Option<u64>,

    /// Not before (Unix timestamp)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub nbf: Option<u64>,

    /// JWT ID (unique identifier)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub jti: Option<String>,

    // ═══════════════════════════════════════════════════
    // EXTENDED IDENTITY CLAIMS
    // ═══════════════════════════════════════════════════
    /// Full user information
    pub user: UserInfo,

    /// RBAC roles (e.g., ["admin", "user"])
    #[serde(default)]
    pub roles: Vec<String>,

    /// Fine-grained permissions (e.g., ["read:posts", "write:posts"])
    #[serde(default)]
    pub permissions: Vec<String>,

    /// OAuth scopes (e.g., ["openid", "email", "profile"])
    #[serde(default)]
    pub scopes: Vec<String>,

    // ═══════════════════════════════════════════════════
    // REQUEST & TOKEN METADATA
    // ═══════════════════════════════════════════════════
    /// Request ID for nonce/replay protection (MCP compliant - NOT session-based)
    ///
    /// Per MCP security requirements, servers MUST NOT use sessions for authentication.
    /// This field is for request-level binding (DPoP nonces, one-time tokens, etc.),
    /// not session management. Each request must include valid credentials.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub request_id: Option<String>,

    /// When authentication occurred
    #[serde(with = "systemtime_serde")]
    pub authenticated_at: SystemTime,

    /// When this context expires (may differ from JWT exp)
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        with = "systemtime_serde_opt"
    )]
    pub expires_at: Option<SystemTime>,

    /// Token information (access + refresh tokens)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub token: Option<TokenInfo>,

    /// Auth provider (e.g., "oauth2:google", "api_key", "jwt:internal")
    pub provider: String,

    // ═══════════════════════════════════════════════════
    // DPOP BINDING (RFC 9449) - Feature-gated
    // ═══════════════════════════════════════════════════
    #[cfg(feature = "dpop")]
    #[serde(skip_serializing_if = "Option::is_none")]
    /// DPoP JWK thumbprint for token binding
    pub dpop_jkt: Option<String>,

    // ═══════════════════════════════════════════════════
    // CUSTOM CLAIMS (extensibility)
    // ═══════════════════════════════════════════════════
    /// Custom metadata (tenant_id, org_id, etc.)
    #[serde(flatten)]
    pub metadata: HashMap<String, Value>,
}

// ═══════════════════════════════════════════════════════════
// SYSTEMTIME SERDE HELPERS
// ═══════════════════════════════════════════════════════════

mod systemtime_serde {
    use super::*;
    use serde::{Deserializer, Serializer};

    pub fn serialize<S>(time: &SystemTime, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let since_epoch = time
            .duration_since(UNIX_EPOCH)
            .map_err(serde::ser::Error::custom)?;
        serializer.serialize_u64(since_epoch.as_secs())
    }

    pub fn deserialize<'de, D>(deserializer: D) -> Result<SystemTime, D::Error>
    where
        D: Deserializer<'de>,
    {
        let secs = u64::deserialize(deserializer)?;
        Ok(UNIX_EPOCH + Duration::from_secs(secs))
    }
}

mod systemtime_serde_opt {
    use super::*;
    use serde::{Deserializer, Serializer};

    pub fn serialize<S>(time: &Option<SystemTime>, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match time {
            Some(t) => {
                let since_epoch = t
                    .duration_since(UNIX_EPOCH)
                    .map_err(serde::ser::Error::custom)?;
                serializer.serialize_some(&since_epoch.as_secs())
            }
            None => serializer.serialize_none(),
        }
    }

    pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<SystemTime>, D::Error>
    where
        D: Deserializer<'de>,
    {
        let opt: Option<u64> = Option::deserialize(deserializer)?;
        Ok(opt.map(|secs| UNIX_EPOCH + Duration::from_secs(secs)))
    }
}

// ═══════════════════════════════════════════════════════════
// AUTHCONTEXT IMPLEMENTATION
// ═══════════════════════════════════════════════════════════

impl AuthContext {
    /// Create builder for constructing auth context
    pub fn builder() -> AuthContextBuilder {
        AuthContextBuilder::default()
    }

    // ═══════════════════════════════════════════════════
    // JWT SERIALIZATION (for token generation)
    // ═══════════════════════════════════════════════════

    /// Convert to JWT claims (for signing)
    ///
    /// Serializes the entire AuthContext into a JSON value suitable for JWT encoding.
    /// Standard JWT claims (sub, iss, aud, exp, iat, nbf, jti) are included at the top level.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let claims = auth_ctx.to_jwt_claims();
    /// let token = jwt_encoder.encode(&claims)?;
    /// ```
    pub fn to_jwt_claims(&self) -> Value {
        serde_json::to_value(self).expect("AuthContext serialization should never fail")
    }

    /// Create from JWT claims (after validation)
    ///
    /// Deserializes a validated JWT claims object into an AuthContext.
    ///
    /// # Errors
    ///
    /// Returns error if:
    /// - Required fields are missing (sub, user, provider)
    /// - Field types don't match expected types
    /// - Invalid timestamps
    pub fn from_jwt_claims(claims: Value) -> Result<Self, AuthError> {
        serde_json::from_value(claims).map_err(|e| AuthError::InvalidClaims(e.to_string()))
    }

    // ═══════════════════════════════════════════════════
    // VALIDATION METHODS
    // ═══════════════════════════════════════════════════

    /// Check if token is expired
    ///
    /// Uses `expires_at` field if present, otherwise falls back to `exp` claim.
    pub fn is_expired(&self) -> bool {
        // First check expires_at (internal expiration)
        if let Some(expires_at) = self.expires_at
            && SystemTime::now() > expires_at
        {
            return true;
        }

        // Fall back to exp claim (JWT expiration)
        if let Some(exp) = self.exp {
            let exp_time = UNIX_EPOCH + Duration::from_secs(exp);
            if SystemTime::now() > exp_time {
                return true;
            }
        }

        false
    }

    /// Validate all fields (exp, nbf, aud, iss)
    ///
    /// Performs comprehensive validation according to RFC 7519.
    ///
    /// # Errors
    ///
    /// Returns error if:
    /// - Token is expired (with leeway)
    /// - Token not yet valid (nbf with leeway)
    /// - Audience mismatch
    /// - Issuer mismatch
    pub fn validate(&self, config: &ValidationConfig) -> Result<(), AuthError> {
        let now = SystemTime::now();

        // Validate expiration (exp)
        if config.validate_exp
            && let Some(exp) = self.exp
        {
            let exp_time = UNIX_EPOCH + Duration::from_secs(exp);
            let exp_with_leeway = exp_time + config.leeway;
            if now > exp_with_leeway {
                return Err(AuthError::TokenExpired);
            }
        }

        // Validate not-before (nbf)
        if config.validate_nbf
            && let Some(nbf) = self.nbf
        {
            let nbf_time = UNIX_EPOCH + Duration::from_secs(nbf);
            if nbf_time > now + config.leeway {
                return Err(AuthError::TokenNotYetValid);
            }
        }

        // Validate audience (aud)
        if let Some(ref expected_aud) = config.audience {
            match &self.aud {
                Some(aud) if aud == expected_aud => {}
                _ => return Err(AuthError::InvalidAudience),
            }
        }

        // Validate issuer (iss)
        if let Some(ref expected_iss) = config.issuer {
            match &self.iss {
                Some(iss) if iss == expected_iss => {}
                _ => return Err(AuthError::InvalidIssuer),
            }
        }

        Ok(())
    }

    // ═══════════════════════════════════════════════════
    // AUTHORIZATION HELPERS
    // ═══════════════════════════════════════════════════

    /// Check if user has specific role
    pub fn has_role(&self, role: &str) -> bool {
        self.roles.iter().any(|r| r == role)
    }

    /// Check if user has any of the roles
    pub fn has_any_role(&self, roles: &[&str]) -> bool {
        roles.iter().any(|r| self.has_role(r))
    }

    /// Check if user has all of the roles
    pub fn has_all_roles(&self, roles: &[&str]) -> bool {
        roles.iter().all(|r| self.has_role(r))
    }

    /// Check if user has specific permission
    pub fn has_permission(&self, perm: &str) -> bool {
        self.permissions.iter().any(|p| p == perm)
    }

    /// Check if user has any of the permissions
    pub fn has_any_permission(&self, perms: &[&str]) -> bool {
        perms.iter().any(|p| self.has_permission(p))
    }

    /// Check if user has all of the permissions
    pub fn has_all_permissions(&self, perms: &[&str]) -> bool {
        perms.iter().all(|p| self.has_permission(p))
    }

    /// Check if token has specific scope
    pub fn has_scope(&self, scope: &str) -> bool {
        self.scopes.iter().any(|s| s == scope)
    }

    /// Check if token has any of the scopes
    pub fn has_any_scope(&self, scopes: &[&str]) -> bool {
        scopes.iter().any(|s| self.has_scope(s))
    }

    /// Check if token has all of the scopes
    pub fn has_all_scopes(&self, scopes: &[&str]) -> bool {
        scopes.iter().all(|s| self.has_scope(s))
    }

    /// Get custom metadata value
    ///
    /// Deserializes a custom metadata field into the specified type.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// if let Some(tenant_id) = auth_ctx.get_metadata::<String>("tenant_id") {
    ///     println!("Tenant: {}", tenant_id);
    /// }
    /// ```
    pub fn get_metadata<T: serde::de::DeserializeOwned>(&self, key: &str) -> Option<T> {
        self.metadata
            .get(key)
            .and_then(|v| serde_json::from_value(v.clone()).ok())
    }

    // ═══════════════════════════════════════════════════
    // DPOP SUPPORT (feature-gated)
    // ═══════════════════════════════════════════════════

    #[cfg(feature = "dpop")]
    /// Validate DPoP proof (RFC 9449)
    ///
    /// Verifies that the DPoP proof matches the bound JWK thumbprint.
    pub fn validate_dpop_proof(&self, proof: &DpopProof) -> Result<(), AuthError> {
        match &self.dpop_jkt {
            Some(jkt) if jkt == &proof.jkt => Ok(()),
            Some(_) => Err(AuthError::DpopMismatch),
            None => Err(AuthError::DpopRequired),
        }
    }

    #[cfg(feature = "dpop")]
    /// Check if DPoP binding is required
    ///
    /// Returns true if the token was issued with DPoP binding (dpop_jkt is set).
    /// Callers MUST invoke `validate_dpop_binding()` when this returns true.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// if auth_ctx.requires_dpop() {
    ///     // Extract DPoP proof from HTTP headers
    ///     let dpop_header = request.header("DPoP")?;
    ///     let proof = parse_dpop_proof(dpop_header)?;
    ///     let jkt = compute_jkt_from_proof(&proof)?;
    ///
    ///     // Validate binding
    ///     auth_ctx.validate_dpop_binding(&jkt)?;
    /// }
    /// ```
    pub fn requires_dpop(&self) -> bool {
        self.dpop_jkt.is_some()
    }

    #[cfg(feature = "dpop")]
    /// Validate DPoP binding by comparing JWK thumbprints
    ///
    /// This method checks if a DPoP proof's JWK thumbprint matches the bound
    /// thumbprint from token issuance. Callers MUST extract the DPoP proof from
    /// HTTP headers and compute the JWK thumbprint before calling this method.
    ///
    /// # Arguments
    ///
    /// * `proof_thumbprint` - JWK thumbprint (jkt) computed from the DPoP proof
    ///
    /// # Errors
    ///
    /// Returns error if:
    /// - Token requires DPoP but no binding is set (should never happen)
    /// - Proof thumbprint doesn't match the bound thumbprint
    ///
    /// # Security Note
    ///
    /// DPoP proof validation (signature, nonce, timestamp) is NOT performed by
    /// this method. The actual DPoP proof comes from HTTP headers which the auth
    /// provider doesn't have direct access to. This method only validates the
    /// binding between the token and the proof's public key.
    ///
    /// Callers are responsible for:
    /// 1. Extracting DPoP proof from HTTP "DPoP" header
    /// 2. Validating proof signature, nonce, timestamp (use turbomcp-dpop crate)
    /// 3. Computing JWK thumbprint from proof's public key
    /// 4. Calling this method to validate the binding
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use turbomcp_auth::context::AuthContext;
    /// use turbomcp_dpop::DpopProof;
    ///
    /// // After validating the DPoP proof from HTTP headers
    /// let proof = DpopProof::parse_and_validate(dpop_header, http_method, http_uri)?;
    /// let jkt = proof.compute_jkt()?;
    ///
    /// // Validate binding
    /// auth_ctx.validate_dpop_binding(&jkt)?;
    /// ```
    pub fn validate_dpop_binding(&self, proof_thumbprint: &str) -> Result<(), AuthError> {
        match &self.dpop_jkt {
            Some(bound_jkt) if bound_jkt == proof_thumbprint => Ok(()),
            Some(bound_jkt) => {
                // Thumbprint mismatch - token was bound to a different key
                tracing::warn!(
                    expected = bound_jkt,
                    received = proof_thumbprint,
                    "DPoP binding validation failed: thumbprint mismatch"
                );
                Err(AuthError::DpopMismatch)
            }
            None => {
                // Token doesn't require DPoP (dpop_jkt not set)
                tracing::error!(
                    "validate_dpop_binding called but token has no DPoP binding (dpop_jkt not set)"
                );
                Err(AuthError::DpopRequired)
            }
        }
    }
}

// ═══════════════════════════════════════════════════════════
// BUILDER PATTERN
// ═══════════════════════════════════════════════════════════

/// Builder for constructing `AuthContext`
///
/// Provides a fluent API for building auth contexts with validation.
///
/// # Example
///
/// ```rust,ignore
/// use turbomcp_auth::context::AuthContext;
///
/// let ctx = AuthContext::builder()
///     .subject("user123")
///     .user(user_info)
///     .roles(vec!["admin".into()])
///     .permissions(vec!["read:posts".into()])
///     .provider("oauth2:google")
///     .build();
/// ```
#[derive(Default)]
pub struct AuthContextBuilder {
    sub: Option<String>,
    iss: Option<String>,
    aud: Option<String>,
    exp: Option<u64>,
    iat: Option<u64>,
    nbf: Option<u64>,
    jti: Option<String>,
    user: Option<UserInfo>,
    roles: Vec<String>,
    permissions: Vec<String>,
    scopes: Vec<String>,
    request_id: Option<String>,
    authenticated_at: Option<SystemTime>,
    expires_at: Option<SystemTime>,
    token: Option<TokenInfo>,
    provider: Option<String>,
    #[cfg(feature = "dpop")]
    dpop_jkt: Option<String>,
    metadata: HashMap<String, Value>,
}

impl AuthContextBuilder {
    /// Set subject (user ID)
    pub fn subject(mut self, sub: impl Into<String>) -> Self {
        self.sub = Some(sub.into());
        self
    }

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

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

    /// Set expiration (Unix timestamp)
    pub fn exp(mut self, exp: u64) -> Self {
        self.exp = Some(exp);
        self
    }

    /// Set issued at (Unix timestamp)
    pub fn iat(mut self, iat: u64) -> Self {
        self.iat = Some(iat);
        self
    }

    /// Set not before (Unix timestamp)
    pub fn nbf(mut self, nbf: u64) -> Self {
        self.nbf = Some(nbf);
        self
    }

    /// Set JWT ID
    pub fn jti(mut self, jti: impl Into<String>) -> Self {
        self.jti = Some(jti.into());
        self
    }

    /// Set user information
    pub fn user(mut self, user: UserInfo) -> Self {
        self.user = Some(user);
        self
    }

    /// Set roles
    pub fn roles(mut self, roles: Vec<String>) -> Self {
        self.roles = roles;
        self
    }

    /// Add a single role
    pub fn role(mut self, role: impl Into<String>) -> Self {
        self.roles.push(role.into());
        self
    }

    /// Set permissions
    pub fn permissions(mut self, permissions: Vec<String>) -> Self {
        self.permissions = permissions;
        self
    }

    /// Add a single permission
    pub fn permission(mut self, permission: impl Into<String>) -> Self {
        self.permissions.push(permission.into());
        self
    }

    /// Set scopes
    pub fn scopes(mut self, scopes: Vec<String>) -> Self {
        self.scopes = scopes;
        self
    }

    /// Add a single scope
    pub fn scope(mut self, scope: impl Into<String>) -> Self {
        self.scopes.push(scope.into());
        self
    }

    /// Set request ID for nonce/replay protection
    ///
    /// This is used for request-level binding (DPoP nonces, one-time request tokens),
    /// NOT for session management. MCP requires stateless authentication where each
    /// request includes valid credentials.
    pub fn request_id(mut self, request_id: impl Into<String>) -> Self {
        self.request_id = Some(request_id.into());
        self
    }

    /// Set authenticated at timestamp
    pub fn authenticated_at(mut self, authenticated_at: SystemTime) -> Self {
        self.authenticated_at = Some(authenticated_at);
        self
    }

    /// Set expires at timestamp
    pub fn expires_at(mut self, expires_at: SystemTime) -> Self {
        self.expires_at = Some(expires_at);
        self
    }

    /// Set token information
    pub fn token(mut self, token: TokenInfo) -> Self {
        self.token = Some(token);
        self
    }

    /// Set auth provider
    pub fn provider(mut self, provider: impl Into<String>) -> Self {
        self.provider = Some(provider.into());
        self
    }

    /// Set DPoP JWK thumbprint (requires dpop feature)
    #[cfg(feature = "dpop")]
    pub fn dpop_jkt(mut self, jkt: impl Into<String>) -> Self {
        self.dpop_jkt = Some(jkt.into());
        self
    }

    /// Add custom metadata
    pub fn metadata(mut self, key: impl Into<String>, value: Value) -> Self {
        self.metadata.insert(key.into(), value);
        self
    }

    /// Build the `AuthContext`
    ///
    /// # Errors
    ///
    /// Returns error if required fields are missing:
    /// - `sub` (subject)
    /// - `user` (user information)
    /// - `provider` (auth provider)
    pub fn build(self) -> Result<AuthContext, AuthError> {
        let sub = self.sub.ok_or(AuthError::MissingField("sub"))?;
        let user = self.user.ok_or(AuthError::MissingField("user"))?;
        let provider = self.provider.ok_or(AuthError::MissingField("provider"))?;
        let authenticated_at = self.authenticated_at.unwrap_or_else(SystemTime::now);

        Ok(AuthContext {
            sub,
            iss: self.iss,
            aud: self.aud,
            exp: self.exp,
            iat: self.iat,
            nbf: self.nbf,
            jti: self.jti,
            user,
            roles: self.roles,
            permissions: self.permissions,
            scopes: self.scopes,
            request_id: self.request_id,
            authenticated_at,
            expires_at: self.expires_at,
            token: self.token,
            provider,
            #[cfg(feature = "dpop")]
            dpop_jkt: self.dpop_jkt,
            metadata: self.metadata,
        })
    }
}

// ═══════════════════════════════════════════════════════════
// ERROR TYPES
// ═══════════════════════════════════════════════════════════

/// Authentication errors
#[derive(Debug, thiserror::Error)]
pub enum AuthError {
    #[error("Invalid claims: {0}")]
    InvalidClaims(String),

    #[error("Token expired")]
    TokenExpired,

    #[error("Token not yet valid")]
    TokenNotYetValid,

    #[error("Invalid audience")]
    InvalidAudience,

    #[error("Invalid issuer")]
    InvalidIssuer,

    #[error("Missing required field: {0}")]
    MissingField(&'static str),

    #[cfg(feature = "dpop")]
    #[error("DPoP proof mismatch")]
    DpopMismatch,

    #[cfg(feature = "dpop")]
    #[error("DPoP proof required but not provided")]
    DpopRequired,
}

// ═══════════════════════════════════════════════════════════
// DPOP TYPES (feature-gated)
// ═══════════════════════════════════════════════════════════

#[cfg(feature = "dpop")]
/// DPoP proof for token binding (RFC 9449)
pub struct DpopProof {
    /// JWK thumbprint
    pub jkt: String,
}

// ═══════════════════════════════════════════════════════════
// TESTS
// ═══════════════════════════════════════════════════════════

#[cfg(test)]
mod tests {
    use super::*;

    fn create_test_user() -> UserInfo {
        UserInfo {
            id: "user123".to_string(),
            username: "testuser".to_string(),
            email: Some("test@example.com".to_string()),
            display_name: Some("Test User".to_string()),
            avatar_url: None,
            metadata: HashMap::new(),
        }
    }

    #[test]
    fn test_builder_minimal() {
        let user = create_test_user();
        let ctx = AuthContext::builder()
            .subject("user123")
            .user(user)
            .provider("test")
            .build()
            .unwrap();

        assert_eq!(ctx.sub, "user123");
        assert_eq!(ctx.provider, "test");
        assert!(ctx.roles.is_empty());
        assert!(ctx.permissions.is_empty());
    }

    #[test]
    fn test_builder_full() {
        let user = create_test_user();
        let ctx = AuthContext::builder()
            .subject("user123")
            .iss("test-issuer")
            .aud("test-audience")
            .user(user)
            .roles(vec!["admin".to_string(), "user".to_string()])
            .permissions(vec!["read:posts".to_string()])
            .scopes(vec!["openid".to_string(), "email".to_string()])
            .provider("oauth2:test")
            .build()
            .unwrap();

        assert_eq!(ctx.sub, "user123");
        assert_eq!(ctx.iss, Some("test-issuer".to_string()));
        assert_eq!(ctx.aud, Some("test-audience".to_string()));
        assert_eq!(ctx.roles.len(), 2);
        assert_eq!(ctx.permissions.len(), 1);
        assert_eq!(ctx.scopes.len(), 2);
    }

    #[test]
    fn test_is_expired() {
        let user = create_test_user();

        // Not expired (future expiration)
        let future = SystemTime::now() + Duration::from_secs(3600);
        let ctx = AuthContext::builder()
            .subject("user123")
            .user(user.clone())
            .provider("test")
            .expires_at(future)
            .build()
            .unwrap();
        assert!(!ctx.is_expired());

        // Expired (past expiration)
        let past = SystemTime::now() - Duration::from_secs(3600);
        let ctx = AuthContext::builder()
            .subject("user123")
            .user(user)
            .provider("test")
            .expires_at(past)
            .build()
            .unwrap();
        assert!(ctx.is_expired());
    }

    #[test]
    fn test_has_role() {
        let user = create_test_user();
        let ctx = AuthContext::builder()
            .subject("user123")
            .user(user)
            .provider("test")
            .roles(vec!["admin".to_string(), "user".to_string()])
            .build()
            .unwrap();

        assert!(ctx.has_role("admin"));
        assert!(ctx.has_role("user"));
        assert!(!ctx.has_role("superuser"));
    }

    #[test]
    fn test_has_any_role() {
        let user = create_test_user();
        let ctx = AuthContext::builder()
            .subject("user123")
            .user(user)
            .provider("test")
            .roles(vec!["admin".to_string(), "user".to_string()])
            .build()
            .unwrap();

        assert!(ctx.has_any_role(&["admin", "superuser"]));
        assert!(ctx.has_any_role(&["user", "guest"]));
        assert!(!ctx.has_any_role(&["superuser", "guest"]));
    }

    #[test]
    fn test_has_all_roles() {
        let user = create_test_user();
        let ctx = AuthContext::builder()
            .subject("user123")
            .user(user)
            .provider("test")
            .roles(vec!["admin".to_string(), "user".to_string()])
            .build()
            .unwrap();

        assert!(ctx.has_all_roles(&["admin", "user"]));
        assert!(ctx.has_all_roles(&["admin"]));
        assert!(!ctx.has_all_roles(&["admin", "user", "superuser"]));
    }

    #[test]
    fn test_has_permission() {
        let user = create_test_user();
        let ctx = AuthContext::builder()
            .subject("user123")
            .user(user)
            .provider("test")
            .permissions(vec!["read:posts".to_string(), "write:posts".to_string()])
            .build()
            .unwrap();

        assert!(ctx.has_permission("read:posts"));
        assert!(ctx.has_permission("write:posts"));
        assert!(!ctx.has_permission("delete:posts"));
    }

    #[test]
    fn test_has_scope() {
        let user = create_test_user();
        let ctx = AuthContext::builder()
            .subject("user123")
            .user(user)
            .provider("test")
            .scopes(vec!["openid".to_string(), "email".to_string()])
            .build()
            .unwrap();

        assert!(ctx.has_scope("openid"));
        assert!(ctx.has_scope("email"));
        assert!(!ctx.has_scope("profile"));
    }

    #[test]
    fn test_jwt_serialization() {
        let user = create_test_user();
        let ctx = AuthContext::builder()
            .subject("user123")
            .iss("test-issuer")
            .user(user)
            .provider("test")
            .roles(vec!["admin".to_string()])
            .build()
            .unwrap();

        // Serialize to JWT claims
        let claims = ctx.to_jwt_claims();
        assert!(claims.is_object());

        // Deserialize back
        let ctx2 = AuthContext::from_jwt_claims(claims).unwrap();
        assert_eq!(ctx2.sub, ctx.sub);
        assert_eq!(ctx2.iss, ctx.iss);
        assert_eq!(ctx2.roles, ctx.roles);
    }

    #[test]
    fn test_validation_expired() {
        let user = create_test_user();
        let past_timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs()
            - 3600;

        let ctx = AuthContext::builder()
            .subject("user123")
            .user(user)
            .provider("test")
            .exp(past_timestamp)
            .build()
            .unwrap();

        let config = ValidationConfig::default();
        let result = ctx.validate(&config);
        assert!(matches!(result, Err(AuthError::TokenExpired)));
    }

    #[test]
    fn test_validation_not_yet_valid() {
        let user = create_test_user();
        let future_timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs()
            + 3600;

        let ctx = AuthContext::builder()
            .subject("user123")
            .user(user)
            .provider("test")
            .nbf(future_timestamp)
            .build()
            .unwrap();

        let config = ValidationConfig::default();
        let result = ctx.validate(&config);
        assert!(matches!(result, Err(AuthError::TokenNotYetValid)));
    }

    #[test]
    fn test_validation_audience() {
        let user = create_test_user();
        let ctx = AuthContext::builder()
            .subject("user123")
            .user(user)
            .provider("test")
            .aud("wrong-audience")
            .build()
            .unwrap();

        let config = ValidationConfig {
            audience: Some("expected-audience".to_string()),
            ..Default::default()
        };

        let result = ctx.validate(&config);
        assert!(matches!(result, Err(AuthError::InvalidAudience)));
    }

    #[test]
    fn test_metadata() {
        let user = create_test_user();
        let ctx = AuthContext::builder()
            .subject("user123")
            .user(user)
            .provider("test")
            .metadata("tenant_id", Value::String("tenant123".to_string()))
            .metadata("org_id", Value::Number(42.into()))
            .build()
            .unwrap();

        let tenant_id: Option<String> = ctx.get_metadata("tenant_id");
        assert_eq!(tenant_id, Some("tenant123".to_string()));

        let org_id: Option<i64> = ctx.get_metadata("org_id");
        assert_eq!(org_id, Some(42));

        let missing: Option<String> = ctx.get_metadata("missing");
        assert_eq!(missing, None);
    }
}