auth-framework 0.5.0-rc18

A comprehensive, production-ready authentication and authorization framework for Rust applications
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
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
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
//! OAuth 2.0 Authorization Server Implementation
//!
//! This module provides a fully secure OAuth 2.0 authorization server implementation
//! with all critical vulnerabilities addressed and proper validation.

use crate::errors::{AuthError, Result};
use crate::security::secure_utils::constant_time_compare;
use crate::server::oauth::oauth2_enhanced_storage::{
    EnhancedAuthorizationCode, EnhancedClientCredentials, EnhancedTokenStorage, RefreshToken,
};
use crate::tokens::{AuthToken, TokenManager};
use crate::user_context::{SessionStore, UserContext};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::RwLock;

/// OAuth 2.0 grant types
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum GrantType {
    AuthorizationCode,
    RefreshToken,
    ClientCredentials,
    DeviceCode,
    TokenExchange,
}

impl std::fmt::Display for GrantType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            GrantType::AuthorizationCode => write!(f, "authorization_code"),
            GrantType::RefreshToken => write!(f, "refresh_token"),
            GrantType::ClientCredentials => write!(f, "client_credentials"),
            GrantType::DeviceCode => write!(f, "urn:ietf:params:oauth:grant-type:device_code"),
            GrantType::TokenExchange => {
                write!(f, "urn:ietf:params:oauth:grant-type:token-exchange")
            }
        }
    }
}

impl std::str::FromStr for GrantType {
    type Err = AuthError;

    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        match s {
            "authorization_code" => Ok(Self::AuthorizationCode),
            "refresh_token" => Ok(Self::RefreshToken),
            "client_credentials" => Ok(Self::ClientCredentials),
            "urn:ietf:params:oauth:grant-type:device_code" => Ok(Self::DeviceCode),
            "urn:ietf:params:oauth:grant-type:token-exchange" => Ok(Self::TokenExchange),
            other => Err(AuthError::auth_method(
                "oauth2",
                &format!("Unsupported grant type: {other}"),
            )),
        }
    }
}

/// OAuth 2.0 response types
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum ResponseType {
    Code,
    Token,
    IdToken,
}

impl std::fmt::Display for ResponseType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ResponseType::Code => write!(f, "code"),
            ResponseType::Token => write!(f, "token"),
            ResponseType::IdToken => write!(f, "id_token"),
        }
    }
}

impl std::str::FromStr for ResponseType {
    type Err = AuthError;

    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        match s {
            "code" => Ok(Self::Code),
            "token" => Ok(Self::Token),
            "id_token" => Ok(Self::IdToken),
            other => Err(AuthError::auth_method(
                "oauth2",
                &format!("Unsupported response type: {other}"),
            )),
        }
    }
}

/// OAuth 2.0 server configuration
#[derive(Debug, Clone)]
pub struct OAuth2Config {
    /// Authorization server issuer identifier
    pub issuer: String,
    /// Authorization code lifetime
    pub authorization_code_lifetime: Duration,
    /// Access token lifetime
    pub access_token_lifetime: Duration,
    /// Refresh token lifetime
    pub refresh_token_lifetime: Duration,
    /// Device code lifetime
    pub device_code_lifetime: Duration,
    /// Default scope if none specified
    pub default_scope: Option<String>,
    /// Maximum scope lifetime
    pub max_scope_lifetime: Duration,
    /// Require PKCE for public clients
    pub require_pkce: bool,
    /// Enable token introspection
    pub enable_introspection: bool,
    /// Enable token revocation
    pub enable_revocation: bool,
}

impl Default for OAuth2Config {
    fn default() -> Self {
        Self {
            issuer: "https://auth.example.com".to_string(),
            authorization_code_lifetime: Duration::from_secs(600), // 10 minutes
            access_token_lifetime: Duration::from_secs(3600),      // 1 hour
            refresh_token_lifetime: Duration::from_secs(86400 * 7), // 7 days
            device_code_lifetime: Duration::from_secs(600),        // 10 minutes
            default_scope: Some("read".to_string()),
            max_scope_lifetime: Duration::from_secs(86400 * 30), // 30 days
            require_pkce: true,
            enable_introspection: true,
            enable_revocation: true,
        }
    }
}

impl OAuth2Config {
    /// Create a new builder for `OAuth2Config`, starting from defaults.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use auth_framework::oauth2_server::OAuth2Config;
    /// use std::time::Duration;
    ///
    /// let config = OAuth2Config::builder()
    ///     .issuer("https://id.example.com")
    ///     .access_token_lifetime(Duration::from_secs(1800))
    ///     .require_pkce(true)
    ///     .build();
    /// ```
    pub fn builder() -> OAuth2ConfigBuilder {
        OAuth2ConfigBuilder::default()
    }
}

/// A builder for [`OAuth2Config`].
///
/// Obtain via [`OAuth2Config::builder()`]. All fields start with secure
/// defaults; override only what you need.
#[derive(Debug, Clone)]
pub struct OAuth2ConfigBuilder {
    config: OAuth2Config,
}

impl Default for OAuth2ConfigBuilder {
    fn default() -> Self {
        Self {
            config: OAuth2Config::default(),
        }
    }
}

impl OAuth2ConfigBuilder {
    /// Set the authorization server issuer identifier.
    pub fn issuer(mut self, issuer: impl Into<String>) -> Self {
        self.config.issuer = issuer.into();
        self
    }

    /// Set the authorization code lifetime.
    pub fn authorization_code_lifetime(mut self, lifetime: Duration) -> Self {
        self.config.authorization_code_lifetime = lifetime;
        self
    }

    /// Set the access token lifetime.
    pub fn access_token_lifetime(mut self, lifetime: Duration) -> Self {
        self.config.access_token_lifetime = lifetime;
        self
    }

    /// Set the refresh token lifetime.
    pub fn refresh_token_lifetime(mut self, lifetime: Duration) -> Self {
        self.config.refresh_token_lifetime = lifetime;
        self
    }

    /// Set the device code lifetime.
    pub fn device_code_lifetime(mut self, lifetime: Duration) -> Self {
        self.config.device_code_lifetime = lifetime;
        self
    }

    /// Set the default scope granted when none is specified.
    pub fn default_scope(mut self, scope: impl Into<String>) -> Self {
        self.config.default_scope = Some(scope.into());
        self
    }

    /// Set the maximum scope lifetime.
    pub fn max_scope_lifetime(mut self, lifetime: Duration) -> Self {
        self.config.max_scope_lifetime = lifetime;
        self
    }

    /// Set whether PKCE is required for public clients.
    pub fn require_pkce(mut self, require: bool) -> Self {
        self.config.require_pkce = require;
        self
    }

    /// Enable or disable token introspection (RFC 7662).
    pub fn enable_introspection(mut self, enable: bool) -> Self {
        self.config.enable_introspection = enable;
        self
    }

    /// Enable or disable token revocation (RFC 7009).
    pub fn enable_revocation(mut self, enable: bool) -> Self {
        self.config.enable_revocation = enable;
        self
    }

    /// Build the [`OAuth2Config`].
    pub fn build(self) -> OAuth2Config {
        self.config
    }
}

/// Token request structure
///
/// Use the convenience constructors for common grant types instead of filling
/// every field manually:
///
/// ```rust,no_run
/// use auth_framework::server::oauth::oauth2_server::TokenRequest;
///
/// // Authorization code exchange
/// let req = TokenRequest::authorization_code("my_code")
///     .client_id("client123")
///     .client_secret("secret")
///     .redirect_uri("https://app.example.com/cb")
///     .code_verifier("pkce_verifier");
///
/// // Refresh token grant
/// let req = TokenRequest::refresh("my_refresh_token");
///
/// // Client credentials grant
/// let req = TokenRequest::client_credentials("client123", "secret");
/// ```
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct TokenRequest {
    pub grant_type: String,
    /// Client identifier. Optional here because HTTP clients may use HTTP Basic auth
    /// (`Authorization: Basic …`) instead of embedding it in the request body.
    #[serde(default)]
    pub client_id: Option<String>,
    pub client_secret: Option<String>,
    pub code: Option<String>,
    pub redirect_uri: Option<String>,
    pub refresh_token: Option<String>,
    pub scope: Option<String>,
    pub code_verifier: Option<String>,
    pub username: Option<String>,
    pub password: Option<String>,
    pub device_code: Option<String>,
    /// RFC 8707 Resource Indicators — target resource URI(s).
    #[serde(default)]
    pub resource: Option<Vec<String>>,
}

impl TokenRequest {
    /// Create a token request for the **authorization_code** grant.
    pub fn authorization_code(code: impl Into<String>) -> Self {
        Self {
            grant_type: "authorization_code".to_string(),
            code: Some(code.into()),
            ..Default::default()
        }
    }

    /// Create a token request for the **refresh_token** grant.
    pub fn refresh(token: impl Into<String>) -> Self {
        Self {
            grant_type: "refresh_token".to_string(),
            refresh_token: Some(token.into()),
            ..Default::default()
        }
    }

    /// Create a token request for the **client_credentials** grant.
    pub fn client_credentials(
        client_id: impl Into<String>,
        client_secret: impl Into<String>,
    ) -> Self {
        Self {
            grant_type: "client_credentials".to_string(),
            client_id: Some(client_id.into()),
            client_secret: Some(client_secret.into()),
            ..Default::default()
        }
    }

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

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

    /// Set the redirect URI.
    pub fn redirect_uri(mut self, uri: impl Into<String>) -> Self {
        self.redirect_uri = Some(uri.into());
        self
    }

    /// Set the PKCE code verifier.
    pub fn code_verifier(mut self, verifier: impl Into<String>) -> Self {
        self.code_verifier = Some(verifier.into());
        self
    }

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

    /// Set RFC 8707 resource indicators.
    pub fn resource(mut self, uris: Vec<String>) -> Self {
        self.resource = Some(uris);
        self
    }
}

/// Token response structure
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TokenResponse {
    pub access_token: String,
    pub token_type: String,
    pub expires_in: u64,
    pub refresh_token: Option<String>,
    pub scope: Option<String>,
    pub id_token: Option<String>,
}

/// Authorization request structure
///
/// Use [`AuthorizationRequest::new`] for a concise starting point:
///
/// ```rust,no_run
/// use auth_framework::server::oauth::oauth2_server::AuthorizationRequest;
///
/// let req = AuthorizationRequest::new("client123", "code", "https://app.example.com/cb")
///     .scope("openid profile")
///     .state("random_state")
///     .pkce("challenge", "S256");
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuthorizationRequest {
    pub client_id: String,
    pub response_type: String,
    pub redirect_uri: String,
    pub scope: Option<String>,
    pub state: Option<String>,
    pub code_challenge: Option<String>,
    pub code_challenge_method: Option<String>,
    pub nonce: Option<String>,
    /// RFC 8707 Resource Indicators — target resource URI(s).
    #[serde(default)]
    pub resource: Option<Vec<String>>,
}

impl AuthorizationRequest {
    /// Create a new authorization request with the required fields.
    pub fn new(
        client_id: impl Into<String>,
        response_type: impl Into<String>,
        redirect_uri: impl Into<String>,
    ) -> Self {
        Self {
            client_id: client_id.into(),
            response_type: response_type.into(),
            redirect_uri: redirect_uri.into(),
            scope: None,
            state: None,
            code_challenge: None,
            code_challenge_method: None,
            nonce: None,
            resource: None,
        }
    }

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

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

    /// Set the PKCE code challenge and method.
    pub fn pkce(mut self, challenge: impl Into<String>, method: impl Into<String>) -> Self {
        self.code_challenge = Some(challenge.into());
        self.code_challenge_method = Some(method.into());
        self
    }

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

    /// Set RFC 8707 resource indicators.
    pub fn resource(mut self, uris: Vec<String>) -> Self {
        self.resource = Some(uris);
        self
    }
}

/// OAuth 2.0 Authorization Server
pub struct OAuth2Server {
    config: OAuth2Config,
    token_storage: Arc<RwLock<EnhancedTokenStorage>>,
    session_store: Arc<RwLock<SessionStore>>,
    token_manager: Arc<TokenManager>,
}

impl OAuth2Server {
    pub async fn new(config: OAuth2Config, token_manager: Arc<TokenManager>) -> Result<Self> {
        Ok(Self {
            config,
            token_storage: Arc::new(RwLock::new(EnhancedTokenStorage::new())),
            session_store: Arc::new(RwLock::new(SessionStore::new())),
            token_manager,
        })
    }

    /// Register a confidential client with proper secret validation
    pub async fn register_confidential_client(
        &self,
        client_id: String,
        client_secret: &str,
        redirect_uris: Vec<String>,
        allowed_scopes: Vec<String>,
        grant_types: Vec<String>,
    ) -> Result<()> {
        // Validate client secret strength
        if client_secret.len() < 32 {
            return Err(AuthError::auth_method(
                "oauth2",
                "Client secret must be at least 32 characters",
            ));
        }

        let credentials = EnhancedClientCredentials::new_confidential(
            client_id,
            client_secret,
            redirect_uris,
            allowed_scopes,
            grant_types,
        )?;

        let mut storage = self.token_storage.write().await;
        storage.store_client_credentials(credentials).await?;

        Ok(())
    }

    /// Register a public client (PKCE required)
    pub async fn register_public_client(
        &self,
        client_id: String,
        redirect_uris: Vec<String>,
        allowed_scopes: Vec<String>,
        grant_types: Vec<String>,
    ) -> Result<()> {
        let credentials = EnhancedClientCredentials::new_public(
            client_id,
            redirect_uris,
            allowed_scopes,
            grant_types,
        );

        let mut storage = self.token_storage.write().await;
        storage.store_client_credentials(credentials).await?;

        Ok(())
    }

    /// Create authorization code with proper user context
    pub async fn create_authorization_code(
        &self,
        request: AuthorizationRequest,
        user_context: UserContext,
    ) -> Result<EnhancedAuthorizationCode> {
        // Validate client exists and supports authorization code flow
        let storage = self.token_storage.read().await;
        let client = storage
            .get_client_credentials(&request.client_id)
            .await?
            .ok_or_else(|| AuthError::auth_method("oauth2", "Invalid client_id"))?;

        if !client.supports_grant_type("authorization_code") {
            return Err(AuthError::auth_method(
                "oauth2",
                "Client does not support authorization code grant",
            ));
        }

        if !client.redirect_uris.contains(&request.redirect_uri) {
            return Err(AuthError::auth_method("oauth2", "Invalid redirect_uri"));
        }

        // Parse and validate scopes
        let requested_scopes = self.parse_scopes(request.scope.as_deref())?;
        let authorized_scopes = self.authorize_scopes(&client, &user_context, &requested_scopes)?;

        // Create authorization code with proper user context
        let auth_code = EnhancedAuthorizationCode::new(
            client.client_id.clone(),
            user_context.user_id.clone(), // FIXED: Use real user ID from context
            request.redirect_uri,
            authorized_scopes,
            request.code_challenge,
            request.code_challenge_method,
            self.config.authorization_code_lifetime,
        );

        // Store authorization code
        drop(storage);
        let mut storage = self.token_storage.write().await;
        storage.store_authorization_code(auth_code.clone()).await?;

        Ok(auth_code)
    }

    /// Handle token exchange with comprehensive validation
    pub async fn token_exchange(&self, request: TokenRequest) -> Result<TokenResponse> {
        match request.grant_type.as_str() {
            "authorization_code" => self.handle_authorization_code_grant(request).await,
            "refresh_token" => self.handle_refresh_token_grant(request).await,
            "client_credentials" => self.handle_client_credentials_grant(request).await,
            _ => Err(AuthError::auth_method("oauth2", "Unsupported grant type")),
        }
    }

    /// Handle authorization code grant with proper validation
    async fn handle_authorization_code_grant(
        &self,
        request: TokenRequest,
    ) -> Result<TokenResponse> {
        let client_id = request
            .client_id
            .ok_or_else(|| AuthError::auth_method("oauth2", "client_id is required"))?;
        // Validate client credentials FIRST
        let storage = self.token_storage.read().await;
        let _client = storage
            .get_client_credentials(&client_id)
            .await?
            .ok_or_else(|| AuthError::auth_method("oauth2", "Invalid client_id"))?;

        // CRITICAL FIX: Validate client secret properly
        if !storage
            .validate_client_credentials(&client_id, request.client_secret.as_deref())
            .await?
        {
            return Err(AuthError::auth_method(
                "oauth2",
                "Invalid client credentials",
            ));
        }

        // Get and validate authorization code
        let code = request
            .code
            .ok_or_else(|| AuthError::auth_method("oauth2", "Missing authorization code"))?;

        drop(storage);
        let mut storage = self.token_storage.write().await;
        let auth_code = storage
            .consume_authorization_code(&code)
            .await?
            .ok_or_else(|| {
                AuthError::auth_method("oauth2", "Invalid or expired authorization code")
            })?;

        // Validate code belongs to this client
        if auth_code.client_id != client_id {
            return Err(AuthError::auth_method(
                "oauth2",
                "Authorization code does not belong to client",
            ));
        }

        // Validate PKCE if required
        if let Some(challenge) = &auth_code.code_challenge {
            let verifier = request
                .code_verifier
                .ok_or_else(|| AuthError::auth_method("oauth2", "PKCE code verifier required"))?;

            if !self.validate_pkce_challenge(
                challenge,
                &verifier,
                &auth_code.code_challenge_method,
            )? {
                return Err(AuthError::auth_method(
                    "oauth2",
                    "Invalid PKCE code verifier",
                ));
            }
        }

        // Generate tokens with proper user context
        let access_token = self
            .generate_access_token(
                &auth_code.client_id,
                Some(&auth_code.user_id), // FIXED: Use actual user ID from auth code
                &auth_code.scopes,
            )
            .await?;

        // Generate refresh token
        let refresh_token = RefreshToken::new(
            auth_code.client_id.clone(),
            auth_code.user_id.clone(), // FIXED: Use actual user ID
            auth_code.scopes.clone(),  // FIXED: Use authorized scopes from auth code
            self.config.refresh_token_lifetime,
        );

        let refresh_token_id = storage.store_refresh_token(refresh_token).await?;

        Ok(TokenResponse {
            access_token: access_token.access_token,
            token_type: "Bearer".to_string(),
            expires_in: self.config.access_token_lifetime.as_secs(),
            refresh_token: Some(refresh_token_id),
            scope: Some(auth_code.scopes.join(" ")),
            id_token: None,
        })
    }

    /// Handle refresh token grant with proper validation
    async fn handle_refresh_token_grant(&self, request: TokenRequest) -> Result<TokenResponse> {
        let client_id = request
            .client_id
            .ok_or_else(|| AuthError::auth_method("oauth2", "client_id is required"))?;
        // Validate client credentials
        let storage = self.token_storage.read().await;
        if !storage
            .validate_client_credentials(&client_id, request.client_secret.as_deref())
            .await?
        {
            return Err(AuthError::auth_method(
                "oauth2",
                "Invalid client credentials",
            ));
        }

        // Get and validate refresh token
        let refresh_token_id = request
            .refresh_token
            .ok_or_else(|| AuthError::auth_method("oauth2", "Missing refresh token"))?;

        // CRITICAL FIX: Validate refresh token from storage
        let stored_token = storage
            .get_refresh_token(&refresh_token_id)
            .await?
            .ok_or_else(|| AuthError::auth_method("oauth2", "Invalid refresh token"))?;

        if !stored_token.is_valid() {
            return Err(AuthError::auth_method(
                "oauth2",
                "Refresh token is expired or revoked",
            ));
        }

        // Validate token belongs to this client
        if stored_token.client_id != client_id {
            return Err(AuthError::auth_method(
                "oauth2",
                "Refresh token does not belong to client",
            ));
        }

        // Parse requested scopes (must be subset of original)
        let requested_scopes = self.parse_scopes(request.scope.as_deref())?;
        let authorized_scopes = if requested_scopes.is_empty() {
            stored_token.scopes.clone() // FIXED: Use original scopes from token
        } else {
            self.validate_scope_subset(&stored_token.scopes, &requested_scopes)?
        };

        drop(storage);

        // Generate new access token
        let access_token = self
            .generate_access_token(
                &stored_token.client_id,
                Some(&stored_token.user_id), // FIXED: Use actual user ID from token
                &authorized_scopes,
            )
            .await?;

        // Generate new refresh token
        let mut storage = self.token_storage.write().await;
        storage.revoke_refresh_token(&refresh_token_id).await?; // Revoke old token

        let new_refresh_token = RefreshToken::new(
            stored_token.client_id.clone(),
            stored_token.user_id.clone(),
            authorized_scopes.clone(),
            self.config.refresh_token_lifetime,
        );

        let new_refresh_token_id = storage.store_refresh_token(new_refresh_token).await?;

        Ok(TokenResponse {
            access_token: access_token.access_token,
            token_type: "Bearer".to_string(),
            expires_in: self.config.access_token_lifetime.as_secs(),
            refresh_token: Some(new_refresh_token_id),
            scope: Some(authorized_scopes.join(" ")),
            id_token: None,
        })
    }

    /// Handle client credentials grant with proper validation
    async fn handle_client_credentials_grant(
        &self,
        request: TokenRequest,
    ) -> Result<TokenResponse> {
        let client_id = request
            .client_id
            .ok_or_else(|| AuthError::auth_method("oauth2", "client_id is required"))?;
        // Validate client credentials
        let storage = self.token_storage.read().await;
        let client = storage
            .get_client_credentials(&client_id)
            .await?
            .ok_or_else(|| AuthError::auth_method("oauth2", "Invalid client_id"))?;

        // CRITICAL FIX: Validate client secret properly
        if !storage
            .validate_client_credentials(&client_id, request.client_secret.as_deref())
            .await?
        {
            return Err(AuthError::auth_method(
                "oauth2",
                "Invalid client credentials",
            ));
        }

        if !client.supports_grant_type("client_credentials") {
            return Err(AuthError::auth_method(
                "oauth2",
                "Client does not support client credentials grant",
            ));
        }

        // Parse and validate scopes
        let requested_scopes = self.parse_scopes(request.scope.as_deref())?;
        let authorized_scopes = requested_scopes
            .iter()
            .filter(|scope| client.has_scope(scope))
            .cloned()
            .collect::<Vec<_>>();

        if authorized_scopes.is_empty() && !requested_scopes.is_empty() {
            return Err(AuthError::auth_method("oauth2", "No authorized scopes"));
        }

        drop(storage);

        // Generate access token (no user context for client credentials)
        let access_token = self
            .generate_access_token(&client_id, None, &authorized_scopes)
            .await?;

        Ok(TokenResponse {
            access_token: access_token.access_token,
            token_type: "Bearer".to_string(),
            expires_in: self.config.access_token_lifetime.as_secs(),
            refresh_token: None, // No refresh token for client credentials
            scope: Some(authorized_scopes.join(" ")),
            id_token: None,
        })
    }

    /// Generate access token with proper validation
    async fn generate_access_token(
        &self,
        client_id: &str,
        user_id: Option<&str>,
        scopes: &[String],
    ) -> Result<AuthToken> {
        let subject = user_id.unwrap_or(client_id);
        let mut token = self.token_manager.create_auth_token(
            subject,
            crate::types::Scopes::from(
                scopes
                    .iter()
                    .map(|s| s.to_string())
                    .collect::<Vec<String>>(),
            ),
            "oauth2",
            Some(self.config.access_token_lifetime),
        )?;

        // Add client_id claim
        token.add_custom_claim(
            "client_id".to_string(),
            serde_json::Value::String(client_id.to_string()),
        );

        // Add user_id claim if present
        if let Some(uid) = user_id {
            token.add_custom_claim(
                "user_id".to_string(),
                serde_json::Value::String(uid.to_string()),
            );
        }

        Ok(token)
    }

    /// Parse scopes from scope string
    fn parse_scopes(&self, scope_str: Option<&str>) -> Result<Vec<String>> {
        match scope_str {
            Some(scopes) => Ok(scopes.split_whitespace().map(|s| s.to_string()).collect()),
            None => match &self.config.default_scope {
                Some(default) => Ok(vec![default.clone()]),
                None => Ok(vec![]),
            },
        }
    }

    /// Authorize scopes based on client and user permissions
    fn authorize_scopes(
        &self,
        client: &EnhancedClientCredentials,
        user_context: &UserContext,
        requested_scopes: &[String],
    ) -> Result<Vec<String>> {
        let mut authorized = Vec::new();

        for scope in requested_scopes {
            // Check if client is allowed this scope
            if client.has_scope(scope) {
                // Check if user has this scope (if applicable)
                if user_context.has_scope(scope) {
                    authorized.push(scope.clone());
                }
            }
        }

        if authorized.is_empty() && !requested_scopes.is_empty() {
            return Err(AuthError::auth_method("oauth2", "No authorized scopes"));
        }

        Ok(authorized)
    }

    /// Validate that requested scopes are subset of original scopes
    fn validate_scope_subset(
        &self,
        original_scopes: &[String],
        requested_scopes: &[String],
    ) -> Result<Vec<String>> {
        let mut validated = Vec::new();

        for scope in requested_scopes {
            if original_scopes.contains(scope) {
                validated.push(scope.clone());
            } else {
                return Err(AuthError::auth_method(
                    "oauth2",
                    format!("Requested scope '{}' not in original grant", scope),
                ));
            }
        }

        Ok(validated)
    }

    /// Validate PKCE code challenge
    fn validate_pkce_challenge(
        &self,
        challenge: &str,
        verifier: &str,
        method: &Option<String>,
    ) -> Result<bool> {
        let method = method.as_deref().unwrap_or("plain");

        match method {
            "plain" => Ok(constant_time_compare(
                challenge.as_bytes(),
                verifier.as_bytes(),
            )),
            "S256" => {
                use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
                use sha2::{Digest, Sha256};

                let hash = Sha256::digest(verifier.as_bytes());
                let encoded = URL_SAFE_NO_PAD.encode(hash);
                Ok(constant_time_compare(
                    challenge.as_bytes(),
                    encoded.as_bytes(),
                ))
            }
            _ => Err(AuthError::auth_method("oauth2", "Unsupported PKCE method")),
        }
    }

    /// Revoke token (refresh token or access token)
    pub async fn revoke_token(&self, token: &str, client_id: &str) -> Result<bool> {
        let mut storage = self.token_storage.write().await;

        // Validate client is authorized to revoke this token
        if client_id.is_empty() {
            return Err(AuthError::auth_method(
                "oauth2",
                "Client ID is required for token revocation",
            ));
        }

        // Verify client exists by trying to get its credentials
        if storage.get_client_credentials(client_id).await.is_err() {
            return Err(AuthError::auth_method("oauth2", "Invalid client"));
        }

        // Try to revoke as refresh token first
        if storage.validate_refresh_token(token).await? {
            return storage.revoke_refresh_token(token).await;
        }

        // For access tokens, we would need to maintain a revocation list
        // This is a simplified implementation
        Ok(false)
    }

    /// Clean up expired tokens
    pub async fn cleanup_expired_tokens(&self) -> Result<usize> {
        let mut storage = self.token_storage.write().await;
        storage.cleanup_expired_tokens().await
    }

    /// Add user credentials to the server's token storage.
    ///
    /// Use this to register users before calling `authenticate_user`.
    /// In production this is typically called during server setup or via an
    /// administrative API; in tests it provides a way to seed known users
    /// without hardcoding them in the library itself.
    pub async fn add_user_credentials(
        &self,
        creds: crate::server::oauth::oauth2_enhanced_storage::UserCredentials,
    ) -> Result<()> {
        let mut storage = self.token_storage.write().await;
        storage.store_user_credentials(creds).await
    }

    /// Authenticate user and create session
    pub async fn authenticate_user(
        &self,
        username: &str,
        password: &str,
        scopes: Vec<String>,
    ) -> Result<UserContext> {
        // CRITICAL SECURITY FIX: Validate credentials against storage
        let storage = self.token_storage.read().await;

        // Validate username exists and password is correct using storage
        if !self
            .validate_user_credentials_against_storage(&storage, username, password)
            .await?
        {
            return Err(AuthError::auth_method(
                "oauth2",
                "Invalid username or password",
            ));
        }

        // Validate user is authorized for requested scopes
        let authorized_scopes = self
            .validate_user_scopes_against_storage(&storage, username, &scopes)
            .await?;

        drop(storage);

        // Create user context with validated information
        let user_context = UserContext::new(
            self.generate_user_id(username).await?,
            username.to_string(),
            self.get_user_email(username).await?,
        )
        .with_scopes(authorized_scopes);

        let mut session_store = self.session_store.write().await;
        session_store.create_session(user_context.clone());

        Ok(user_context)
    }

    /// Validate user credentials against secure storage
    async fn validate_user_credentials_against_storage(
        &self,
        storage: &EnhancedTokenStorage,
        username: &str,
        password: &str,
    ) -> Result<bool> {
        // Minimum security requirements - but don't return early to prevent timing attacks
        let is_empty = username.is_empty() || password.is_empty();
        let is_too_short = password.len() < 8;

        // Always perform the expensive bcrypt operation to prevent timing attacks
        match storage.get_user_credentials(username).await {
            Ok(Some(stored_credentials)) => {
                // Use bcrypt to verify password against hash
                use bcrypt::verify;
                match verify(password, &stored_credentials.password_hash) {
                    Ok(is_valid) => {
                        // Only return true if all conditions are met
                        Ok(is_valid && !is_empty && !is_too_short)
                    }
                    Err(_) => {
                        // Hash verification failed - fail securely
                        Ok(false)
                    }
                }
            }
            Ok(None) => {
                // User not found - still do dummy bcrypt operation to prevent timing attacks
                use bcrypt::verify;
                let _dummy_result = verify(
                    password,
                    "$2b$12$K2CtDP7zMH7VgxScmHTa/.EUm5nd9.xnZM8Cl/p9RMb5QZaJUHgBm",
                );
                Ok(false)
            }
            Err(_) => {
                // Storage error - still do dummy bcrypt operation to prevent timing attacks
                use bcrypt::verify;
                let _dummy_result = verify(
                    password,
                    "$2b$12$K2CtDP7zMH7VgxScmHTa/.EUm5nd9.xnZM8Cl/p9RMb5QZaJUHgBm",
                );
                Ok(false)
            }
        }
    }

    /// Validate user is authorized for requested scopes using storage
    async fn validate_user_scopes_against_storage(
        &self,
        storage: &EnhancedTokenStorage,
        username: &str,
        requested_scopes: &[String],
    ) -> Result<Vec<String>> {
        // Get user permissions from storage
        let user_permissions = match storage.get_user_permissions(username).await {
            Ok(Some(permissions)) => permissions.scopes,
            Ok(None) => {
                return Err(AuthError::auth_method(
                    "oauth2",
                    "User not found in permission store",
                ));
            }
            Err(_) => {
                return Err(AuthError::auth_method(
                    "oauth2",
                    "Failed to retrieve user permissions",
                ));
            }
        };

        let mut authorized = Vec::new();
        for scope in requested_scopes {
            if user_permissions.contains(scope) {
                authorized.push(scope.clone());
            }
        }

        // If no scopes requested, give default read scope for valid users
        if authorized.is_empty() && !requested_scopes.is_empty() {
            return Err(AuthError::auth_method(
                "oauth2",
                "User not authorized for requested scopes",
            ));
        }

        if authorized.is_empty() {
            // Check if user has at least read permission for default scope
            if user_permissions.contains(&"read".to_string()) {
                authorized.push("read".to_string());
            } else {
                return Err(AuthError::auth_method(
                    "oauth2",
                    "User has no authorized scopes",
                ));
            }
        }

        Ok(authorized)
    }

    /// Generate consistent user ID
    async fn generate_user_id(&self, username: &str) -> Result<String> {
        // In production, this would be the user's UUID from the database
        // For now, create a deterministic but unique ID
        let hash = Sha256::digest(format!("user_id_{}", username).as_bytes());
        let hash_str = format!("{:x}", hash);
        Ok(format!("user_{}", &hash_str[0..16]))
    }

    /// Get user email from user store
    async fn get_user_email(&self, username: &str) -> Result<Option<String>> {
        let storage = self.token_storage.read().await;
        match storage.get_user_credentials(username).await {
            Ok(Some(creds)) => Ok(creds.email),
            // User not found or storage error — return None rather than a fabricated address.
            _ => Ok(None),
        }
    }

    /// Get user context from session
    pub async fn get_user_context(&self, session_id: &str) -> Result<Option<UserContext>> {
        let session_store = self.session_store.read().await;
        Ok(session_store.get_session(session_id).cloned())
    }

    /// Invalidate user session
    pub async fn invalidate_session(&self, session_id: &str) -> Result<bool> {
        let mut session_store = self.session_store.write().await;
        Ok(session_store.invalidate_session(session_id))
    }
}