Skip to main content

auth_framework/server/oidc/
core.rs

1//! OpenID Connect Provider Implementation (OIDC 1.0)
2//!
3//! This module implements a complete OpenID Connect Provider based on:
4//! - OpenID Connect Core 1.0 specification
5//! - OpenID Connect Discovery 1.0
6//! - OpenID Connect Dynamic Client Registration 1.0
7//! - JSON Web Token (JWT) Profile for OAuth 2.0 Client Authentication and Authorization Grants
8
9use crate::errors::{AuthError, Result};
10use crate::oauth2_server::OAuth2Server;
11use crate::server::core::client_registry::ClientRegistry;
12use crate::storage::AuthStorage;
13use crate::tokens::TokenManager;
14use jsonwebtoken::{Algorithm, Header};
15use serde::{Deserialize, Serialize};
16use serde_json::Value;
17use std::collections::HashMap;
18use std::fmt;
19use std::sync::Arc;
20use std::time::{Duration, SystemTime, UNIX_EPOCH};
21
22/// OpenID Connect Provider configuration
23#[derive(Debug, Clone)]
24pub struct OidcConfig {
25    /// Issuer identifier (must be HTTPS URL)
26    pub issuer: String,
27
28    /// OAuth 2.0 base configuration
29    pub oauth2_config: crate::oauth2_server::OAuth2Config,
30
31    /// JWK Set URI
32    pub jwks_uri: String,
33
34    /// UserInfo endpoint URI
35    pub userinfo_endpoint: String,
36
37    /// Supported response types
38    pub response_types_supported: Vec<String>,
39
40    /// Supported subject identifier types
41    pub subject_types_supported: Vec<SubjectType>,
42
43    /// Supported ID token signing algorithms
44    pub id_token_signing_alg_values_supported: Vec<Algorithm>,
45
46    /// Supported scopes
47    pub scopes_supported: Vec<String>,
48
49    /// Supported claims
50    pub claims_supported: Vec<String>,
51
52    /// Whether claims parameter is supported
53    pub claims_parameter_supported: bool,
54
55    /// Whether request parameter is supported
56    pub request_parameter_supported: bool,
57
58    /// Whether request_uri parameter is supported
59    pub request_uri_parameter_supported: bool,
60
61    /// ID token expiration time
62    pub id_token_expiry: Duration,
63
64    /// Maximum age for authentication
65    pub max_age_supported: Option<Duration>,
66}
67
68impl Default for OidcConfig {
69    fn default() -> Self {
70        Self {
71            issuer: "https://auth.example.com".to_string(),
72            oauth2_config: crate::oauth2_server::OAuth2Config::default(),
73            jwks_uri: "https://auth.example.com/.well-known/jwks.json".to_string(),
74            userinfo_endpoint: "https://auth.example.com/oidc/userinfo".to_string(),
75            response_types_supported: vec![
76                "code".to_string(),
77                "id_token".to_string(),
78                "id_token token".to_string(),
79                "code id_token".to_string(),
80                "code token".to_string(),
81                "code id_token token".to_string(),
82            ],
83            subject_types_supported: vec![SubjectType::Public],
84            id_token_signing_alg_values_supported: vec![
85                Algorithm::RS256,
86                Algorithm::ES256,
87                Algorithm::HS256,
88            ],
89            scopes_supported: vec![
90                "openid".to_string(),
91                "profile".to_string(),
92                "email".to_string(),
93                "address".to_string(),
94                "phone".to_string(),
95                "offline_access".to_string(),
96            ],
97            claims_supported: vec![
98                "sub".to_string(),
99                "name".to_string(),
100                "given_name".to_string(),
101                "family_name".to_string(),
102                "middle_name".to_string(),
103                "nickname".to_string(),
104                "preferred_username".to_string(),
105                "profile".to_string(),
106                "picture".to_string(),
107                "website".to_string(),
108                "email".to_string(),
109                "email_verified".to_string(),
110                "gender".to_string(),
111                "birthdate".to_string(),
112                "zoneinfo".to_string(),
113                "locale".to_string(),
114                "phone_number".to_string(),
115                "phone_number_verified".to_string(),
116                "address".to_string(),
117                "updated_at".to_string(),
118            ],
119            claims_parameter_supported: true,
120            request_parameter_supported: true,
121            request_uri_parameter_supported: true,
122            id_token_expiry: Duration::from_secs(3600), // 1 hour
123            max_age_supported: Some(Duration::from_secs(86400)), // 24 hours
124        }
125    }
126}
127
128impl OidcConfig {
129    /// Create a new builder for `OidcConfig`, starting from defaults.
130    ///
131    /// # Example
132    ///
133    /// ```rust,no_run
134    /// use auth_framework::server::oidc::core::OidcConfig;
135    /// use std::time::Duration;
136    ///
137    /// let config = OidcConfig::builder()
138    ///     .issuer("https://id.example.com")
139    ///     .id_token_expiry(Duration::from_secs(1800))
140    ///     .build();
141    /// ```
142    pub fn builder() -> OidcConfigBuilder {
143        OidcConfigBuilder::default()
144    }
145}
146
147/// A builder for [`OidcConfig`].
148///
149/// Obtain via [`OidcConfig::builder()`]. All fields start with sensible
150/// defaults; override only what you need.
151#[derive(Debug, Clone, Default)]
152pub struct OidcConfigBuilder {
153    config: OidcConfig,
154}
155
156impl OidcConfigBuilder {
157    /// Set the issuer identifier (must be an HTTPS URL in production).
158    ///
159    /// # Example
160    /// ```rust,ignore
161    /// let config = OidcConfigBuilder::default()
162    ///     .issuer("https://auth.example.com")
163    ///     .build();
164    /// ```
165    pub fn issuer(mut self, issuer: impl Into<String>) -> Self {
166        self.config.issuer = issuer.into();
167        self
168    }
169
170    /// Set the underlying OAuth 2.0 configuration.
171    ///
172    /// # Example
173    /// ```rust,ignore
174    /// let config = OidcConfigBuilder::default()
175    ///     .oauth2_config(OAuth2Config::default())
176    ///     .build();
177    /// ```
178    pub fn oauth2_config(mut self, config: crate::oauth2_server::OAuth2Config) -> Self {
179        self.config.oauth2_config = config;
180        self
181    }
182
183    /// Set the JWK Set URI.
184    ///
185    /// # Example
186    /// ```rust,ignore
187    /// let config = OidcConfigBuilder::default()
188    ///     .jwks_uri("https://auth.example.com/.well-known/jwks.json")
189    ///     .build();
190    /// ```
191    pub fn jwks_uri(mut self, uri: impl Into<String>) -> Self {
192        self.config.jwks_uri = uri.into();
193        self
194    }
195
196    /// Set the UserInfo endpoint URI.
197    ///
198    /// # Example
199    /// ```rust,ignore
200    /// let config = OidcConfigBuilder::default()
201    ///     .userinfo_endpoint("https://auth.example.com/userinfo")
202    ///     .build();
203    /// ```
204    pub fn userinfo_endpoint(mut self, uri: impl Into<String>) -> Self {
205        self.config.userinfo_endpoint = uri.into();
206        self
207    }
208
209    /// Set the supported response types.
210    ///
211    /// # Example
212    /// ```rust,ignore
213    /// let config = OidcConfigBuilder::default()
214    ///     .response_types_supported(vec!["code".into(), "id_token".into()])
215    ///     .build();
216    /// ```
217    pub fn response_types_supported(mut self, types: Vec<String>) -> Self {
218        self.config.response_types_supported = types;
219        self
220    }
221
222    /// Set the supported subject identifier types.
223    ///
224    /// # Example
225    /// ```rust,ignore
226    /// let config = OidcConfigBuilder::default()
227    ///     .subject_types_supported(vec![SubjectType::Public])
228    ///     .build();
229    /// ```
230    pub fn subject_types_supported(mut self, types: Vec<SubjectType>) -> Self {
231        self.config.subject_types_supported = types;
232        self
233    }
234
235    /// Set the supported ID token signing algorithms.
236    ///
237    /// # Example
238    /// ```rust,ignore
239    /// let config = OidcConfigBuilder::default()
240    ///     .id_token_signing_alg_values_supported(vec![Algorithm::RS256])
241    ///     .build();
242    /// ```
243    pub fn id_token_signing_alg_values_supported(mut self, algs: Vec<Algorithm>) -> Self {
244        self.config.id_token_signing_alg_values_supported = algs;
245        self
246    }
247
248    /// Set the supported scopes.
249    ///
250    /// # Example
251    /// ```rust,ignore
252    /// let config = OidcConfigBuilder::default()
253    ///     .scopes_supported(vec!["openid".into(), "profile".into(), "email".into()])
254    ///     .build();
255    /// ```
256    pub fn scopes_supported(mut self, scopes: Vec<String>) -> Self {
257        self.config.scopes_supported = scopes;
258        self
259    }
260
261    /// Set the supported claims.
262    ///
263    /// # Example
264    /// ```rust,ignore
265    /// let config = OidcConfigBuilder::default()
266    ///     .claims_supported(vec!["sub".into(), "name".into(), "email".into()])
267    ///     .build();
268    /// ```
269    pub fn claims_supported(mut self, claims: Vec<String>) -> Self {
270        self.config.claims_supported = claims;
271        self
272    }
273
274    /// Set whether the claims parameter is supported.
275    ///
276    /// # Example
277    /// ```rust,ignore
278    /// let config = OidcConfigBuilder::default()
279    ///     .claims_parameter_supported(true)
280    ///     .build();
281    /// ```
282    pub fn claims_parameter_supported(mut self, supported: bool) -> Self {
283        self.config.claims_parameter_supported = supported;
284        self
285    }
286
287    /// Set whether the request parameter is supported.
288    ///
289    /// # Example
290    /// ```rust,ignore
291    /// let config = OidcConfigBuilder::default()
292    ///     .request_parameter_supported(true)
293    ///     .build();
294    /// ```
295    pub fn request_parameter_supported(mut self, supported: bool) -> Self {
296        self.config.request_parameter_supported = supported;
297        self
298    }
299
300    /// Set whether the request_uri parameter is supported.
301    ///
302    /// # Example
303    /// ```rust,ignore
304    /// let config = OidcConfigBuilder::default()
305    ///     .request_uri_parameter_supported(false)
306    ///     .build();
307    /// ```
308    pub fn request_uri_parameter_supported(mut self, supported: bool) -> Self {
309        self.config.request_uri_parameter_supported = supported;
310        self
311    }
312
313    /// Set the ID token expiration duration.
314    ///
315    /// # Example
316    /// ```rust,ignore
317    /// use std::time::Duration;
318    /// let config = OidcConfigBuilder::default()
319    ///     .id_token_expiry(Duration::from_secs(3600))
320    ///     .build();
321    /// ```
322    pub fn id_token_expiry(mut self, expiry: Duration) -> Self {
323        self.config.id_token_expiry = expiry;
324        self
325    }
326
327    /// Set the maximum age for authentication.
328    ///
329    /// # Example
330    /// ```rust,ignore
331    /// use std::time::Duration;
332    /// let config = OidcConfigBuilder::default()
333    ///     .max_age_supported(Duration::from_secs(86400))
334    ///     .build();
335    /// ```
336    pub fn max_age_supported(mut self, max_age: Duration) -> Self {
337        self.config.max_age_supported = Some(max_age);
338        self
339    }
340
341    /// Build the [`OidcConfig`].
342    ///
343    /// # Example
344    /// ```rust,ignore
345    /// let config = OidcConfigBuilder::default()
346    ///     .issuer("https://auth.example.com")
347    ///     .scopes_supported(vec!["openid".into(), "profile".into()])
348    ///     .id_token_expiry(Duration::from_secs(3600))
349    ///     .build();
350    /// ```
351    pub fn build(self) -> OidcConfig {
352        self.config
353    }
354}
355
356/// Subject identifier types
357#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
358#[serde(rename_all = "lowercase")]
359pub enum SubjectType {
360    /// Public subject identifier
361    Public,
362    /// Pairwise subject identifier
363    Pairwise,
364}
365
366/// OpenID Connect Provider
367pub struct OidcProvider<S: AuthStorage + ?Sized> {
368    config: OidcConfig,
369    oauth2_server: OAuth2Server,
370    token_manager: Arc<TokenManager>,
371    storage: Arc<S>,
372    client_registry: Option<Arc<ClientRegistry>>,
373}
374
375impl<S: AuthStorage + ?Sized> fmt::Debug for OidcProvider<S> {
376    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
377        f.debug_struct("OidcProvider")
378            .field("config", &self.config)
379            .field("oauth2_server", &"<OAuth2Server>")
380            .field("token_manager", &"<TokenManager>")
381            .field("storage", &"<AuthStorage>")
382            .field("client_registry", &self.client_registry.is_some())
383            .finish()
384    }
385}
386
387impl<S: ?Sized + AuthStorage> OidcProvider<S> {
388    /// Create a new OIDC Provider
389    pub async fn new(
390        config: OidcConfig,
391        token_manager: Arc<TokenManager>,
392        storage: Arc<S>,
393    ) -> Result<Self> {
394        let oauth2_server =
395            OAuth2Server::new(config.oauth2_config.clone(), token_manager.clone()).await?;
396
397        Ok(Self {
398            config,
399            oauth2_server,
400            token_manager,
401            storage,
402            client_registry: None,
403        })
404    }
405
406    /// Get the underlying OAuth 2.0 server
407    pub fn oauth2_server(&self) -> &OAuth2Server {
408        &self.oauth2_server
409    }
410
411    /// Set the client registry for validation
412    pub fn set_client_registry(&mut self, client_registry: Arc<ClientRegistry>) {
413        self.client_registry = Some(client_registry);
414    }
415
416    /// Get OIDC configuration
417    pub fn config(&self) -> &OidcConfig {
418        &self.config
419    }
420
421    /// Generate OpenID Connect Discovery document
422    pub fn discovery_document(&self) -> Result<OidcDiscoveryDocument> {
423        Ok(OidcDiscoveryDocument {
424            issuer: self.config.issuer.clone(),
425            authorization_endpoint: format!("{}/oidc/authorize", self.config.issuer),
426            token_endpoint: format!("{}/oidc/token", self.config.issuer),
427            userinfo_endpoint: self.config.userinfo_endpoint.clone(),
428            jwks_uri: self.config.jwks_uri.clone(),
429            registration_endpoint: Some(format!("{}/oidc/register", self.config.issuer)),
430            scopes_supported: self.config.scopes_supported.clone(),
431            response_types_supported: self.config.response_types_supported.clone(),
432            response_modes_supported: Some(vec![
433                "query".to_string(),
434                "fragment".to_string(),
435                "form_post".to_string(),
436            ]),
437            grant_types_supported: Some(vec![
438                "authorization_code".to_string(),
439                "refresh_token".to_string(),
440                "client_credentials".to_string(),
441            ]),
442            subject_types_supported: self.config.subject_types_supported.clone(),
443            id_token_signing_alg_values_supported: self
444                .config
445                .id_token_signing_alg_values_supported
446                .iter()
447                .map(algorithm_to_string)
448                .collect(),
449            userinfo_signing_alg_values_supported: Some(vec![
450                "RS256".to_string(),
451                "ES256".to_string(),
452                "HS256".to_string(),
453            ]),
454            token_endpoint_auth_methods_supported: Some(vec![
455                "client_secret_basic".to_string(),
456                "client_secret_post".to_string(),
457                "client_secret_jwt".to_string(),
458                "private_key_jwt".to_string(),
459            ]),
460            claims_supported: Some(self.config.claims_supported.clone()),
461            claims_parameter_supported: Some(self.config.claims_parameter_supported),
462            request_parameter_supported: Some(self.config.request_parameter_supported),
463            request_uri_parameter_supported: Some(self.config.request_uri_parameter_supported),
464            code_challenge_methods_supported: Some(vec!["S256".to_string()]),
465        })
466    }
467}
468
469/// Request parameters for creating an ID token.
470///
471/// Use [`IdTokenRequest::new`] to construct with the required `subject` and
472/// `client_id`, then chain optional setters for `nonce`, `auth_time`, and
473/// extra `claims`.
474///
475/// # Example
476///
477/// ```rust,no_run
478/// # use auth_framework::server::oidc::core::IdTokenRequest;
479/// let request = IdTokenRequest::new("user123", "client456")
480///     .with_nonce("abc");
481/// ```
482#[derive(Debug, Clone, Default)]
483pub struct IdTokenRequest<'a> {
484    pub subject: &'a str,
485    pub client_id: &'a str,
486    pub nonce: Option<&'a str>,
487    pub auth_time: Option<SystemTime>,
488    pub claims: Option<&'a HashMap<String, Value>>,
489}
490
491impl<'a> IdTokenRequest<'a> {
492    /// Create a new ID token request with required subject and client_id.
493    pub fn new(subject: &'a str, client_id: &'a str) -> Self {
494        Self {
495            subject,
496            client_id,
497            nonce: None,
498            auth_time: None,
499            claims: None,
500        }
501    }
502
503    /// Set the nonce value for replay protection.
504    pub fn with_nonce(mut self, nonce: &'a str) -> Self {
505        self.nonce = Some(nonce);
506        self
507    }
508
509    /// Set the authentication time.
510    pub fn with_auth_time(mut self, auth_time: SystemTime) -> Self {
511        self.auth_time = Some(auth_time);
512        self
513    }
514
515    /// Set additional claims to include in the ID token.
516    pub fn with_claims(mut self, claims: &'a HashMap<String, Value>) -> Self {
517        self.claims = Some(claims);
518        self
519    }
520}
521
522impl<S: AuthStorage + ?Sized> OidcProvider<S> {
523    /// Create an ID token from a request.
524    pub async fn create_id_token(&self, request: IdTokenRequest<'_>) -> Result<String> {
525        let subject = request.subject;
526        let client_id = request.client_id;
527        let nonce = request.nonce;
528        let auth_time = request.auth_time;
529        let claims = request.claims;
530        let now = SystemTime::now()
531            .duration_since(UNIX_EPOCH)
532            .map_err(|e| AuthError::auth_method("oidc", format!("Time error: {}", e)))?
533            .as_secs();
534
535        let exp = now + self.config.id_token_expiry.as_secs();
536
537        let mut id_token_claims = IdTokenClaims {
538            iss: self.config.issuer.clone(),
539            sub: subject.to_string(),
540            aud: vec![client_id.to_string()],
541            exp,
542            iat: now,
543            auth_time: auth_time
544                .and_then(|t| t.duration_since(UNIX_EPOCH).ok().map(|d| d.as_secs())),
545            nonce: nonce.map(|n| n.to_string()),
546            additional_claims: claims.cloned().unwrap_or_default(),
547        };
548
549        // Add standard claims if provided
550        if let Some(claims) = claims {
551            for (key, value) in claims {
552                if self.config.claims_supported.contains(key) {
553                    id_token_claims
554                        .additional_claims
555                        .insert(key.clone(), value.clone());
556                }
557            }
558        }
559
560        // Create JWT
561        let _header = Header::new(Algorithm::RS256);
562        let token = self
563            .token_manager
564            .create_typed_jwt_token(
565                subject,
566                vec!["openid".to_string()],
567                Some(Duration::from_secs(3600)),
568                "id_token",
569            )
570            .map_err(|e| AuthError::auth_method("oidc", format!("JWT creation failed: {}", e)))?;
571
572        Ok(token)
573    }
574
575    /// Validate an authorization request for OIDC
576    pub async fn validate_authorization_request(
577        &self,
578        request: &OidcAuthorizationRequest,
579    ) -> Result<AuthorizationValidationResult> {
580        // Check if 'openid' scope is present
581        if !request.scope.split_whitespace().any(|s| s == "openid") {
582            return Err(AuthError::auth_method(
583                "oidc",
584                "Missing required 'openid' scope",
585            ));
586        }
587
588        // SEC-H2: Require state parameter (CSRF protection per OAuth 2.0 §10.12)
589        match &request.state {
590            None => {
591                return Err(AuthError::auth_method(
592                    "oidc",
593                    "Missing required 'state' parameter",
594                ));
595            }
596            Some(s) if s.is_empty() => {
597                return Err(AuthError::auth_method(
598                    "oidc",
599                    "The 'state' parameter must not be empty",
600                ));
601            }
602            _ => {}
603        }
604
605        // Validate response_type
606        if !self
607            .config
608            .response_types_supported
609            .contains(&request.response_type)
610        {
611            return Err(AuthError::auth_method(
612                "oidc",
613                format!("Unsupported response_type: {}", request.response_type),
614            ));
615        }
616
617        // SEC-M8: Block implicit grant response types (OAuth 2.1 compliance).
618        // Response types containing "token" without "code" are implicit grants.
619        {
620            let rt = &request.response_type;
621            if rt.split_whitespace().any(|part| part == "token")
622                && !rt.split_whitespace().any(|part| part == "code")
623            {
624                return Err(AuthError::auth_method(
625                    "oidc",
626                    "Implicit grant (response_type containing 'token' without 'code') is not permitted",
627                ));
628            }
629        }
630
631        // Validate client_id
632        if request.client_id.is_empty() {
633            return Err(AuthError::auth_method("oidc", "Missing client_id"));
634        }
635
636        // Check client exists in registry and validate redirect_uri + scopes
637        if let Some(client_registry) = &self.client_registry {
638            if client_registry
639                .get_client(&request.client_id)
640                .await?
641                .is_none()
642            {
643                return Err(AuthError::auth_method("oidc", "Invalid client_id"));
644            }
645
646            // Validate redirect_uri against registered URIs
647            if !client_registry
648                .validate_redirect_uri(&request.client_id, &request.redirect_uri)
649                .await?
650            {
651                return Err(AuthError::auth_method(
652                    "oidc",
653                    "Invalid redirect_uri for client",
654                ));
655            }
656
657            // SEC-M4: Validate requested scopes against client's authorized scopes
658            for scope in request.scope.split_whitespace() {
659                if !client_registry
660                    .validate_scope(&request.client_id, scope)
661                    .await?
662                {
663                    return Err(AuthError::auth_method(
664                        "oidc",
665                        format!("Client is not authorized for scope '{}'", scope),
666                    ));
667                }
668            }
669        } else {
670            // SEC-H3: Without a client registry, we cannot verify the redirect_uri
671            // belongs to a legitimate client. Reject all requests to prevent open
672            // redirect attacks.
673            return Err(AuthError::auth_method(
674                "oidc",
675                "Client registry is required for authorization requests",
676            ));
677        }
678
679        // SEC-M4: Validate all requested scopes against server's supported scopes
680        for scope in request.scope.split_whitespace() {
681            if !self.config.scopes_supported.contains(&scope.to_string()) {
682                return Err(AuthError::auth_method(
683                    "oidc",
684                    format!("Unsupported scope '{}'", scope),
685                ));
686            }
687        }
688
689        Ok(AuthorizationValidationResult {
690            valid: true,
691            client_id: request.client_id.clone(),
692            redirect_uri: request.redirect_uri.clone(),
693            scope: request.scope.clone(),
694            state: request.state.clone(),
695            nonce: request.nonce.clone(),
696            max_age: request.max_age,
697            response_type: request.response_type.clone(),
698        })
699    }
700
701    /// Get user information for the UserInfo endpoint
702    pub async fn get_userinfo(&self, access_token: &str) -> Result<UserInfo> {
703        // Validate access token
704        let token_claims = self
705            .token_manager
706            .validate_jwt_token(access_token)
707            .map_err(|e| AuthError::auth_method("oidc", format!("Invalid access token: {}", e)))?;
708        if token_claims.token_use().is_some() {
709            return Err(AuthError::auth_method(
710                "oidc",
711                "Invalid access token: only an access token can be used here",
712            ));
713        }
714        // Revoked tokens (logout / revocation) are refused; an unreadable list fails closed.
715        match self
716            .storage
717            .get_kv(&format!("revoked_token:{}", token_claims.jti))
718            .await
719        {
720            Ok(None) => {}
721            Ok(Some(_)) => {
722                return Err(AuthError::auth_method(
723                    "oidc",
724                    "Invalid access token: it has been revoked",
725                ));
726            }
727            Err(e) => {
728                tracing::error!("Could not check token revocation list: {}", e);
729                return Err(AuthError::auth_method(
730                    "oidc",
731                    "Unable to verify access token status",
732                ));
733            }
734        }
735
736        // The account must exist and be active (a signature proves who minted the token, not
737        // that its subject is still a live account).
738        match self
739            .storage
740            .get_kv(&format!("user:{}", token_claims.sub))
741            .await
742        {
743            Ok(Some(bytes)) => {
744                let record: serde_json::Value = serde_json::from_slice(&bytes)
745                    .map_err(|_| AuthError::auth_method("oidc", "Unable to verify the account"))?;
746                if record["active"].as_bool() == Some(false) {
747                    return Err(AuthError::auth_method(
748                        "oidc",
749                        "The account has been deactivated",
750                    ));
751                }
752            }
753            Ok(None) => {
754                return Err(AuthError::auth_method("oidc", "Unknown account"));
755            }
756            Err(e) => {
757                tracing::error!("Could not read the account record: {}", e);
758                return Err(AuthError::auth_method(
759                    "oidc",
760                    "Unable to verify the account",
761                ));
762            }
763        }
764
765        // Extract subject from token
766        let subject = &token_claims.sub;
767
768        // Get user information from storage
769        let user_key = format!("user:{}", subject);
770        if let Some(user_data) = self.storage.get_kv(&user_key).await? {
771            let user_str = std::str::from_utf8(&user_data).unwrap_or("{}");
772            let user_profile: HashMap<String, Value> =
773                serde_json::from_str(user_str).unwrap_or_default();
774
775            Ok(UserInfo {
776                sub: subject.clone(),
777                name: user_profile
778                    .get("name")
779                    .and_then(|v| v.as_str())
780                    .map(|s| s.to_string()),
781                given_name: user_profile
782                    .get("given_name")
783                    .and_then(|v| v.as_str())
784                    .map(|s| s.to_string()),
785                family_name: user_profile
786                    .get("family_name")
787                    .and_then(|v| v.as_str())
788                    .map(|s| s.to_string()),
789                middle_name: user_profile
790                    .get("middle_name")
791                    .and_then(|v| v.as_str())
792                    .map(|s| s.to_string()),
793                nickname: user_profile
794                    .get("nickname")
795                    .and_then(|v| v.as_str())
796                    .map(|s| s.to_string()),
797                preferred_username: user_profile
798                    .get("preferred_username")
799                    .and_then(|v| v.as_str())
800                    .map(|s| s.to_string()),
801                profile: user_profile
802                    .get("profile")
803                    .and_then(|v| v.as_str())
804                    .map(|s| s.to_string()),
805                picture: user_profile
806                    .get("picture")
807                    .and_then(|v| v.as_str())
808                    .map(|s| s.to_string()),
809                website: user_profile
810                    .get("website")
811                    .and_then(|v| v.as_str())
812                    .map(|s| s.to_string()),
813                email: user_profile
814                    .get("email")
815                    .and_then(|v| v.as_str())
816                    .map(|s| s.to_string()),
817                email_verified: user_profile.get("email_verified").and_then(|v| v.as_bool()),
818                gender: user_profile
819                    .get("gender")
820                    .and_then(|v| v.as_str())
821                    .map(|s| s.to_string()),
822                birthdate: user_profile
823                    .get("birthdate")
824                    .and_then(|v| v.as_str())
825                    .map(|s| s.to_string()),
826                zoneinfo: user_profile
827                    .get("zoneinfo")
828                    .and_then(|v| v.as_str())
829                    .map(|s| s.to_string()),
830                locale: user_profile
831                    .get("locale")
832                    .and_then(|v| v.as_str())
833                    .map(|s| s.to_string()),
834                phone_number: user_profile
835                    .get("phone_number")
836                    .and_then(|v| v.as_str())
837                    .map(|s| s.to_string()),
838                phone_number_verified: user_profile
839                    .get("phone_number_verified")
840                    .and_then(|v| v.as_bool()),
841                address: user_profile
842                    .get("address")
843                    .and_then(|addr| addr.as_object())
844                    .map(|addr_obj| Address {
845                        formatted: addr_obj
846                            .get("formatted")
847                            .and_then(|v| v.as_str())
848                            .map(|s| s.to_string()),
849                        street_address: addr_obj
850                            .get("street_address")
851                            .and_then(|v| v.as_str())
852                            .map(|s| s.to_string()),
853                        locality: addr_obj
854                            .get("locality")
855                            .and_then(|v| v.as_str())
856                            .map(|s| s.to_string()),
857                        region: addr_obj
858                            .get("region")
859                            .and_then(|v| v.as_str())
860                            .map(|s| s.to_string()),
861                        postal_code: addr_obj
862                            .get("postal_code")
863                            .and_then(|v| v.as_str())
864                            .map(|s| s.to_string()),
865                        country: addr_obj
866                            .get("country")
867                            .and_then(|v| v.as_str())
868                            .map(|s| s.to_string()),
869                    }),
870                updated_at: user_profile.get("updated_at").and_then(|v| v.as_u64()),
871                additional_claims: user_profile
872                    .into_iter()
873                    .filter(|(k, _)| {
874                        ![
875                            "sub",
876                            "name",
877                            "given_name",
878                            "family_name",
879                            "middle_name",
880                            "nickname",
881                            "preferred_username",
882                            "profile",
883                            "picture",
884                            "website",
885                            "email",
886                            "email_verified",
887                            "gender",
888                            "birthdate",
889                            "zoneinfo",
890                            "locale",
891                            "phone_number",
892                            "phone_number_verified",
893                            "address",
894                            "updated_at",
895                        ]
896                        .contains(&k.as_str())
897                    })
898                    .collect(),
899            })
900        } else {
901            // Return minimal user info with only the subject claim when no stored profile exists
902            Ok(UserInfo {
903                sub: subject.clone(),
904                name: None,
905                given_name: None,
906                family_name: None,
907                middle_name: None,
908                nickname: None,
909                preferred_username: Some(subject.clone()),
910                profile: None,
911                picture: None,
912                website: None,
913                email: None,
914                email_verified: None,
915                gender: None,
916                birthdate: None,
917                zoneinfo: None,
918                locale: None,
919                phone_number: None,
920                phone_number_verified: None,
921                address: None,
922                updated_at: None,
923                additional_claims: HashMap::new(),
924            })
925        }
926    }
927
928    /// Handle logout request
929    pub async fn handle_logout(
930        &self,
931        id_token_hint: Option<&str>,
932        post_logout_redirect_uri: Option<&str>,
933        state: Option<&str>,
934    ) -> Result<LogoutResponse> {
935        // Validate ID token hint if provided
936        if let Some(id_token) = id_token_hint {
937            let claims = self
938                .token_manager
939                .validate_jwt_token(id_token)
940                .map_err(|e| AuthError::auth_method("oidc", format!("Invalid ID token: {}", e)))?;
941
942            // Invalidate all sessions for the user identified in the token
943            let user_sessions = self
944                .storage
945                .list_user_sessions(&claims.sub)
946                .await
947                .map_err(|e| AuthError::internal(format!("Failed to list user sessions: {}", e)))?;
948
949            for session in user_sessions {
950                self.storage
951                    .delete_session(&session.session_id)
952                    .await
953                    .map_err(|e| AuthError::internal(format!("Failed to delete session: {}", e)))?;
954            }
955        }
956
957        // Validate post_logout_redirect_uri against registered URIs
958        if let Some(post_logout_uri) = post_logout_redirect_uri {
959            // Extract client_id from the ID token if available
960            if let Some(id_token) = id_token_hint {
961                let claims = self
962                    .token_manager
963                    .validate_jwt_token(id_token)
964                    .map_err(|e| {
965                        AuthError::auth_method("oidc", format!("Invalid ID token: {}", e))
966                    })?;
967
968                if let Some(aud) = claims.aud.split_whitespace().next() {
969                    // Validate that the post-logout redirect URI is registered for this client
970                    if !self
971                        .is_post_logout_uri_registered(aud, post_logout_uri)
972                        .await?
973                    {
974                        return Err(AuthError::validation(
975                            "post_logout_redirect_uri not registered for client",
976                        ));
977                    }
978                }
979            } else {
980                // If no ID token provided, we cannot validate the client association
981                // In a production system, you might want to require ID token for validation
982                return Err(AuthError::validation(
983                    "id_token_hint required for post_logout_redirect_uri validation",
984                ));
985            }
986        }
987
988        Ok(LogoutResponse {
989            post_logout_redirect_uri: post_logout_redirect_uri.map(|uri| uri.to_string()),
990            state: state.map(|s| s.to_string()),
991        })
992    }
993
994    /// Check if a post-logout redirect URI is registered for a client
995    async fn is_post_logout_uri_registered(&self, client_id: &str, uri: &str) -> Result<bool> {
996        // SECURITY CRITICAL: Validate redirect URI against registered URIs
997
998        // Basic security: only allow https URIs (except localhost for development)
999        if !uri.starts_with("https://")
1000            && !uri.starts_with("http://localhost")
1001            && !uri.starts_with("http://127.0.0.1")
1002        {
1003            tracing::warn!(
1004                "Rejected post-logout redirect URI with invalid scheme: {}",
1005                uri
1006            );
1007            return Ok(false);
1008        }
1009
1010        // Enhanced security: Validate against registered URIs
1011        match self.get_client_registered_post_logout_uris(client_id).await {
1012            Ok(registered_uris) => {
1013                let is_registered = registered_uris.contains(&uri.to_string());
1014                if !is_registered {
1015                    tracing::warn!(
1016                        "Rejected unregistered post-logout redirect URI for client {}: {}",
1017                        client_id,
1018                        uri
1019                    );
1020                }
1021                Ok(is_registered)
1022            }
1023            Err(_) => {
1024                // When client lookup fails, reject all redirect URIs to prevent
1025                // open-redirect attacks. Even loopback URIs are rejected here because
1026                // `http://localhost.evil.com` would match a naive prefix check.
1027                tracing::error!(
1028                    "Rejected redirect URI — client lookup failed for {}: {}",
1029                    client_id,
1030                    uri
1031                );
1032                Ok(false)
1033            }
1034        }
1035    }
1036
1037    /// Get registered post-logout redirect URIs for a client
1038    async fn get_client_registered_post_logout_uris(&self, client_id: &str) -> Result<Vec<String>> {
1039        // Look up post-logout redirect URIs from client registry storage
1040        if let Some(client_registry) = &self.client_registry
1041            && let Some(client) = client_registry.get_client(client_id).await?
1042        {
1043            // Post-logout redirect URIs are stored in client metadata
1044            if let Some(uris) = client.metadata.get("post_logout_redirect_uris")
1045                && let Some(arr) = uris.as_array()
1046            {
1047                return Ok(arr
1048                    .iter()
1049                    .filter_map(|v| v.as_str().map(|s| s.to_string()))
1050                    .collect());
1051            }
1052        }
1053        // Unknown client or no registry — return empty list so all redirect URIs
1054        // are rejected, preventing open-redirect attacks.
1055        Ok(Vec::new())
1056    }
1057
1058    /// Generate JWK Set for the .well-known/jwks.json endpoint
1059    pub fn generate_jwks(&self) -> Result<JwkSet> {
1060        let keys = self
1061            .token_manager
1062            .export_public_jwks()?
1063            .into_iter()
1064            .map(|key| Jwk {
1065                kty: "RSA".to_string(),
1066                use_: Some("sig".to_string()),
1067                key_ops: Some(vec!["verify".to_string()]),
1068                alg: Some(algorithm_to_string(&key.algorithm)),
1069                kid: Some(key.kid),
1070                n: key.n,
1071                e: key.e,
1072                additional_params: HashMap::new(),
1073            })
1074            .collect();
1075
1076        Ok(JwkSet { keys })
1077    }
1078}
1079
1080/// OIDC Authorization Request
1081#[derive(Clone, Serialize, Deserialize)]
1082pub struct OidcAuthorizationRequest {
1083    pub response_type: String,
1084    pub client_id: String,
1085    pub redirect_uri: String,
1086    pub scope: String,
1087    pub state: Option<String>,
1088    pub nonce: Option<String>,
1089    pub max_age: Option<u64>,
1090    pub ui_locales: Option<String>,
1091    pub claims_locales: Option<String>,
1092    pub id_token_hint: Option<String>,
1093    pub login_hint: Option<String>,
1094    pub acr_values: Option<String>,
1095    pub claims: Option<String>,
1096    pub request: Option<String>,
1097    pub request_uri: Option<String>,
1098}
1099
1100impl std::fmt::Debug for OidcAuthorizationRequest {
1101    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1102        let mut d = f.debug_struct("OidcAuthorizationRequest");
1103        d.field("response_type", &self.response_type);
1104        d.field("client_id", &self.client_id);
1105        d.field("redirect_uri", &self.redirect_uri);
1106        d.field("scope", &self.scope);
1107        d.field("state", &self.state);
1108        d.field("nonce", &self.nonce);
1109        d.field("max_age", &self.max_age);
1110        d.field("ui_locales", &self.ui_locales);
1111        d.field("claims_locales", &self.claims_locales);
1112        d.field(
1113            "id_token_hint",
1114            &crate::utils::redact::redacted(&self.id_token_hint),
1115        );
1116        d.field("login_hint", &self.login_hint);
1117        d.field("acr_values", &self.acr_values);
1118        d.field("claims", &self.claims);
1119        d.field("request", &crate::utils::redact::redacted(&self.request));
1120        d.field(
1121            "request_uri",
1122            &crate::utils::redact::redacted(&self.request_uri),
1123        );
1124        d.finish()
1125    }
1126}
1127
1128impl OidcAuthorizationRequest {
1129    /// Create a builder with the required `client_id` and `redirect_uri`.
1130    ///
1131    /// Defaults: `response_type = "code"`, `scope = "openid"`.
1132    pub fn builder(
1133        client_id: impl Into<String>,
1134        redirect_uri: impl Into<String>,
1135    ) -> OidcAuthorizationRequestBuilder {
1136        OidcAuthorizationRequestBuilder::new(client_id, redirect_uri)
1137    }
1138}
1139
1140/// Fluent builder for [`OidcAuthorizationRequest`].
1141///
1142/// # Example
1143///
1144/// ```rust
1145/// use auth_framework::server::oidc::core::OidcAuthorizationRequest;
1146///
1147/// let req = OidcAuthorizationRequest::builder("my-client", "https://app.example/callback")
1148///     .scope("openid profile email")
1149///     .state("random_state")
1150///     .nonce("random_nonce")
1151///     .build();
1152///
1153/// assert_eq!(req.client_id, "my-client");
1154/// assert_eq!(req.scope, "openid profile email");
1155/// ```
1156pub struct OidcAuthorizationRequestBuilder {
1157    req: OidcAuthorizationRequest,
1158}
1159
1160impl OidcAuthorizationRequestBuilder {
1161    fn new(client_id: impl Into<String>, redirect_uri: impl Into<String>) -> Self {
1162        Self {
1163            req: OidcAuthorizationRequest {
1164                response_type: "code".to_string(),
1165                client_id: client_id.into(),
1166                redirect_uri: redirect_uri.into(),
1167                scope: "openid".to_string(),
1168                state: None,
1169                nonce: None,
1170                max_age: None,
1171                ui_locales: None,
1172                claims_locales: None,
1173                id_token_hint: None,
1174                login_hint: None,
1175                acr_values: None,
1176                claims: None,
1177                request: None,
1178                request_uri: None,
1179            },
1180        }
1181    }
1182
1183    /// Set the OAuth2 response type (default: `"code"`).
1184    pub fn response_type(mut self, rt: impl Into<String>) -> Self {
1185        self.req.response_type = rt.into();
1186        self
1187    }
1188
1189    /// Set the requested scopes (default: `"openid"`).
1190    pub fn scope(mut self, scope: impl Into<String>) -> Self {
1191        self.req.scope = scope.into();
1192        self
1193    }
1194
1195    /// Set the state parameter for CSRF protection.
1196    pub fn state(mut self, state: impl Into<String>) -> Self {
1197        self.req.state = Some(state.into());
1198        self
1199    }
1200
1201    /// Set the nonce for ID token replay protection.
1202    pub fn nonce(mut self, nonce: impl Into<String>) -> Self {
1203        self.req.nonce = Some(nonce.into());
1204        self
1205    }
1206
1207    /// Set the maximum authentication age in seconds.
1208    pub fn max_age(mut self, seconds: u64) -> Self {
1209        self.req.max_age = Some(seconds);
1210        self
1211    }
1212
1213    /// Provide a login hint (e.g. email or username).
1214    pub fn login_hint(mut self, hint: impl Into<String>) -> Self {
1215        self.req.login_hint = Some(hint.into());
1216        self
1217    }
1218
1219    /// Set the id_token_hint for session management.
1220    pub fn id_token_hint(mut self, hint: impl Into<String>) -> Self {
1221        self.req.id_token_hint = Some(hint.into());
1222        self
1223    }
1224
1225    /// Set the ACR values.
1226    pub fn acr_values(mut self, values: impl Into<String>) -> Self {
1227        self.req.acr_values = Some(values.into());
1228        self
1229    }
1230
1231    /// Consume the builder and produce the request.
1232    pub fn build(self) -> OidcAuthorizationRequest {
1233        self.req
1234    }
1235}
1236
1237/// Authorization validation result
1238#[derive(Debug, Clone)]
1239pub struct AuthorizationValidationResult {
1240    pub valid: bool,
1241    pub client_id: String,
1242    pub redirect_uri: String,
1243    pub scope: String,
1244    pub state: Option<String>,
1245    pub nonce: Option<String>,
1246    pub max_age: Option<u64>,
1247    pub response_type: String,
1248}
1249
1250/// ID Token Claims
1251#[derive(Debug, Clone, Serialize, Deserialize)]
1252pub struct IdTokenClaims {
1253    /// Issuer
1254    pub iss: String,
1255    /// Subject
1256    pub sub: String,
1257    /// Audience
1258    pub aud: Vec<String>,
1259    /// Expiration time
1260    pub exp: u64,
1261    /// Issued at
1262    pub iat: u64,
1263    /// Authentication time
1264    #[serde(skip_serializing_if = "Option::is_none")]
1265    pub auth_time: Option<u64>,
1266    /// Nonce
1267    #[serde(skip_serializing_if = "Option::is_none")]
1268    pub nonce: Option<String>,
1269    /// Additional claims
1270    #[serde(flatten)]
1271    pub additional_claims: HashMap<String, Value>,
1272}
1273
1274/// UserInfo response
1275#[derive(Debug, Clone, Serialize, Deserialize)]
1276pub struct UserInfo {
1277    pub sub: String,
1278    #[serde(skip_serializing_if = "Option::is_none")]
1279    pub name: Option<String>,
1280    #[serde(skip_serializing_if = "Option::is_none")]
1281    pub given_name: Option<String>,
1282    #[serde(skip_serializing_if = "Option::is_none")]
1283    pub family_name: Option<String>,
1284    #[serde(skip_serializing_if = "Option::is_none")]
1285    pub middle_name: Option<String>,
1286    #[serde(skip_serializing_if = "Option::is_none")]
1287    pub nickname: Option<String>,
1288    #[serde(skip_serializing_if = "Option::is_none")]
1289    pub preferred_username: Option<String>,
1290    #[serde(skip_serializing_if = "Option::is_none")]
1291    pub profile: Option<String>,
1292    #[serde(skip_serializing_if = "Option::is_none")]
1293    pub picture: Option<String>,
1294    #[serde(skip_serializing_if = "Option::is_none")]
1295    pub website: Option<String>,
1296    #[serde(skip_serializing_if = "Option::is_none")]
1297    pub email: Option<String>,
1298    #[serde(skip_serializing_if = "Option::is_none")]
1299    pub email_verified: Option<bool>,
1300    #[serde(skip_serializing_if = "Option::is_none")]
1301    pub gender: Option<String>,
1302    #[serde(skip_serializing_if = "Option::is_none")]
1303    pub birthdate: Option<String>,
1304    #[serde(skip_serializing_if = "Option::is_none")]
1305    pub zoneinfo: Option<String>,
1306    #[serde(skip_serializing_if = "Option::is_none")]
1307    pub locale: Option<String>,
1308    #[serde(skip_serializing_if = "Option::is_none")]
1309    pub phone_number: Option<String>,
1310    #[serde(skip_serializing_if = "Option::is_none")]
1311    pub phone_number_verified: Option<bool>,
1312    #[serde(skip_serializing_if = "Option::is_none")]
1313    pub address: Option<Address>,
1314    #[serde(skip_serializing_if = "Option::is_none")]
1315    pub updated_at: Option<u64>,
1316    #[serde(flatten)]
1317    pub additional_claims: HashMap<String, Value>,
1318}
1319
1320/// Address claim
1321#[derive(Debug, Clone, Serialize, Deserialize)]
1322pub struct Address {
1323    #[serde(skip_serializing_if = "Option::is_none")]
1324    pub formatted: Option<String>,
1325    #[serde(skip_serializing_if = "Option::is_none")]
1326    pub street_address: Option<String>,
1327    #[serde(skip_serializing_if = "Option::is_none")]
1328    pub locality: Option<String>,
1329    #[serde(skip_serializing_if = "Option::is_none")]
1330    pub region: Option<String>,
1331    #[serde(skip_serializing_if = "Option::is_none")]
1332    pub postal_code: Option<String>,
1333    #[serde(skip_serializing_if = "Option::is_none")]
1334    pub country: Option<String>,
1335}
1336
1337/// OIDC Discovery Document
1338#[derive(Debug, Clone, Serialize, Deserialize)]
1339pub struct OidcDiscoveryDocument {
1340    pub issuer: String,
1341    pub authorization_endpoint: String,
1342    pub token_endpoint: String,
1343    pub userinfo_endpoint: String,
1344    pub jwks_uri: String,
1345    #[serde(skip_serializing_if = "Option::is_none")]
1346    pub registration_endpoint: Option<String>,
1347    pub scopes_supported: Vec<String>,
1348    pub response_types_supported: Vec<String>,
1349    #[serde(skip_serializing_if = "Option::is_none")]
1350    pub response_modes_supported: Option<Vec<String>>,
1351    #[serde(skip_serializing_if = "Option::is_none")]
1352    pub grant_types_supported: Option<Vec<String>>,
1353    pub subject_types_supported: Vec<SubjectType>,
1354    pub id_token_signing_alg_values_supported: Vec<String>,
1355    #[serde(skip_serializing_if = "Option::is_none")]
1356    pub userinfo_signing_alg_values_supported: Option<Vec<String>>,
1357    #[serde(skip_serializing_if = "Option::is_none")]
1358    pub token_endpoint_auth_methods_supported: Option<Vec<String>>,
1359    #[serde(skip_serializing_if = "Option::is_none")]
1360    pub claims_supported: Option<Vec<String>>,
1361    #[serde(skip_serializing_if = "Option::is_none")]
1362    pub claims_parameter_supported: Option<bool>,
1363    #[serde(skip_serializing_if = "Option::is_none")]
1364    pub request_parameter_supported: Option<bool>,
1365    #[serde(skip_serializing_if = "Option::is_none")]
1366    pub request_uri_parameter_supported: Option<bool>,
1367    #[serde(skip_serializing_if = "Option::is_none")]
1368    pub code_challenge_methods_supported: Option<Vec<String>>,
1369}
1370
1371/// JWK Set
1372#[derive(Debug, Clone, Serialize, Deserialize)]
1373pub struct JwkSet {
1374    pub keys: Vec<Jwk>,
1375}
1376
1377/// JSON Web Key
1378#[derive(Debug, Clone, Serialize, Deserialize)]
1379pub struct Jwk {
1380    pub kty: String,
1381    #[serde(rename = "use", skip_serializing_if = "Option::is_none")]
1382    pub use_: Option<String>,
1383    #[serde(skip_serializing_if = "Option::is_none")]
1384    pub key_ops: Option<Vec<String>>,
1385    #[serde(skip_serializing_if = "Option::is_none")]
1386    pub alg: Option<String>,
1387    #[serde(skip_serializing_if = "Option::is_none")]
1388    pub kid: Option<String>,
1389    pub n: String,
1390    pub e: String,
1391    #[serde(flatten)]
1392    pub additional_params: HashMap<String, Value>,
1393}
1394
1395/// Logout response
1396#[derive(Debug, Clone)]
1397pub struct LogoutResponse {
1398    pub post_logout_redirect_uri: Option<String>,
1399    pub state: Option<String>,
1400}
1401
1402/// Helper function to convert Algorithm to string
1403fn algorithm_to_string(alg: &Algorithm) -> String {
1404    match alg {
1405        Algorithm::HS256 => "HS256".to_string(),
1406        Algorithm::HS384 => "HS384".to_string(),
1407        Algorithm::HS512 => "HS512".to_string(),
1408        Algorithm::ES256 => "ES256".to_string(),
1409        Algorithm::ES384 => "ES384".to_string(),
1410        Algorithm::RS256 => "RS256".to_string(),
1411        Algorithm::RS384 => "RS384".to_string(),
1412        Algorithm::RS512 => "RS512".to_string(),
1413        Algorithm::PS256 => "PS256".to_string(),
1414        Algorithm::PS384 => "PS384".to_string(),
1415        Algorithm::PS512 => "PS512".to_string(),
1416        Algorithm::EdDSA => "EdDSA".to_string(),
1417        // `Algorithm` is `#[non_exhaustive]`; fall back to its `Debug` name for one added later.
1418        other => format!("{other:?}"),
1419    }
1420}
1421
1422#[cfg(test)]
1423mod tests {
1424    use super::*;
1425    use crate::storage::MemoryStorage;
1426
1427    /// The JOSE name of every algorithm this crate knows, as it appears in discovery documents.
1428    #[test]
1429    fn algorithm_names_are_the_jose_names() {
1430        for (alg, want) in [
1431            (Algorithm::HS256, "HS256"),
1432            (Algorithm::HS384, "HS384"),
1433            (Algorithm::HS512, "HS512"),
1434            (Algorithm::ES256, "ES256"),
1435            (Algorithm::ES384, "ES384"),
1436            (Algorithm::RS256, "RS256"),
1437            (Algorithm::RS384, "RS384"),
1438            (Algorithm::RS512, "RS512"),
1439            (Algorithm::PS256, "PS256"),
1440            (Algorithm::PS384, "PS384"),
1441            (Algorithm::PS512, "PS512"),
1442            (Algorithm::EdDSA, "EdDSA"),
1443        ] {
1444            assert_eq!(algorithm_to_string(&alg), want);
1445        }
1446    }
1447
1448    #[tokio::test]
1449    async fn userinfo_refuses_a_deactivated_or_unknown_account() {
1450        let provider = create_test_oidc_provider().await;
1451        let tm = provider.token_manager.clone();
1452        let token_for = |sub: &str| {
1453            tm.create_jwt_token(
1454                sub,
1455                vec!["openid".into()],
1456                Some(std::time::Duration::from_secs(600)),
1457            )
1458            .unwrap()
1459        };
1460        provider
1461            .storage
1462            .store_kv(
1463                "user:gone",
1464                serde_json::json!({"id": "gone", "active": false})
1465                    .to_string()
1466                    .as_bytes(),
1467                None,
1468            )
1469            .await
1470            .unwrap();
1471        let err = provider
1472            .get_userinfo(&token_for("gone"))
1473            .await
1474            .unwrap_err()
1475            .to_string();
1476        assert!(err.to_lowercase().contains("deactivated"), "{err}");
1477        let err = provider
1478            .get_userinfo(&token_for("never-registered"))
1479            .await
1480            .unwrap_err()
1481            .to_string();
1482        assert!(err.to_lowercase().contains("unknown account"), "{err}");
1483    }
1484
1485    #[tokio::test]
1486    async fn userinfo_refuses_revoked_and_refresh_tokens() {
1487        let provider = create_test_oidc_provider().await;
1488        let tm = provider.token_manager.clone();
1489        let access = tm
1490            .create_jwt_token(
1491                "user_x",
1492                vec!["openid".into()],
1493                Some(std::time::Duration::from_secs(600)),
1494            )
1495            .unwrap();
1496        let refresh = tm
1497            .create_refresh_jwt_token("user_x", Some(std::time::Duration::from_secs(600)))
1498            .unwrap();
1499        assert!(
1500            provider.get_userinfo(&refresh).await.is_err(),
1501            "refresh JWT"
1502        );
1503
1504        let jti = tm.validate_jwt_token(&access).unwrap().jti;
1505        provider
1506            .storage
1507            .store_kv(&format!("revoked_token:{jti}"), b"revoked", None)
1508            .await
1509            .unwrap();
1510        let err = provider
1511            .get_userinfo(&access)
1512            .await
1513            .unwrap_err()
1514            .to_string();
1515        assert!(err.contains("revoked"), "{err}");
1516    }
1517
1518    async fn create_test_oidc_provider() -> OidcProvider<MemoryStorage> {
1519        let config = OidcConfig::default();
1520        let token_manager = Arc::new(TokenManager::new_hmac(
1521            b"test_secret_key_32_bytes_long!!!!",
1522            "test_issuer",
1523            "test_audience",
1524        ));
1525        let storage = Arc::new(MemoryStorage::new());
1526
1527        // Register a test client so that the fail-closed client registry check passes
1528        let client_registry = Arc::new(
1529            crate::server::core::client_registry::ClientRegistry::new(
1530                storage.clone() as Arc<dyn crate::storage::AuthStorage>
1531            )
1532            .await
1533            .unwrap(),
1534        );
1535        let test_client = crate::client::ClientConfig {
1536            client_id: "test_client".to_string(),
1537            client_secret: Some("test_secret".to_string()),
1538            client_type: crate::client::ClientType::Confidential,
1539            redirect_uris: vec!["https://client.example.com/callback".to_string()].into(),
1540            authorized_scopes: vec![
1541                "openid".to_string(),
1542                "profile".to_string(),
1543                "email".to_string(),
1544            ]
1545            .into(),
1546            authorized_grant_types: vec!["authorization_code".to_string()].into(),
1547            authorized_response_types: vec!["code".to_string()].into(),
1548            client_name: Some("Test Client".to_string()),
1549            client_description: None,
1550            metadata: std::collections::HashMap::new(),
1551        };
1552        client_registry.register_client(test_client).await.unwrap();
1553
1554        let mut provider = OidcProvider::new(config, token_manager, storage)
1555            .await
1556            .unwrap();
1557        provider.set_client_registry(client_registry);
1558        provider
1559    }
1560
1561    #[tokio::test]
1562    async fn test_oidc_provider_creation() {
1563        let provider = create_test_oidc_provider().await;
1564        assert_eq!(provider.config.issuer, "https://auth.example.com");
1565        assert!(
1566            provider
1567                .config
1568                .scopes_supported
1569                .contains(&"openid".to_string())
1570        );
1571    }
1572
1573    #[tokio::test]
1574    async fn test_discovery_document() {
1575        let provider = create_test_oidc_provider().await;
1576        let discovery = provider.discovery_document().unwrap();
1577
1578        assert_eq!(discovery.issuer, "https://auth.example.com");
1579        assert_eq!(
1580            discovery.authorization_endpoint,
1581            "https://auth.example.com/oidc/authorize"
1582        );
1583        assert!(discovery.scopes_supported.contains(&"openid".to_string()));
1584        assert!(
1585            discovery
1586                .response_types_supported
1587                .contains(&"code".to_string())
1588        );
1589    }
1590
1591    #[tokio::test]
1592    async fn test_authorization_request_validation() {
1593        let provider = create_test_oidc_provider().await;
1594
1595        let valid_request = OidcAuthorizationRequest {
1596            response_type: "code".to_string(),
1597            client_id: "test_client".to_string(),
1598            redirect_uri: "https://client.example.com/callback".to_string(),
1599            scope: "openid profile email".to_string(),
1600            state: Some("abc123".to_string()),
1601            nonce: Some("xyz789".to_string()),
1602            max_age: None,
1603            ui_locales: None,
1604            claims_locales: None,
1605            id_token_hint: None,
1606            login_hint: None,
1607            acr_values: None,
1608            claims: None,
1609            request: None,
1610            request_uri: None,
1611        };
1612
1613        let result = provider
1614            .validate_authorization_request(&valid_request)
1615            .await
1616            .unwrap();
1617        assert!(result.valid);
1618        assert_eq!(result.client_id, "test_client");
1619        assert_eq!(result.scope, "openid profile email");
1620    }
1621
1622    #[tokio::test]
1623    async fn test_authorization_request_missing_openid_scope() {
1624        let provider = create_test_oidc_provider().await;
1625
1626        let invalid_request = OidcAuthorizationRequest {
1627            response_type: "code".to_string(),
1628            client_id: "test_client".to_string(),
1629            redirect_uri: "https://client.example.com/callback".to_string(),
1630            scope: "profile email".to_string(), // Missing 'openid'
1631            state: Some("abc123".to_string()),
1632            nonce: Some("xyz789".to_string()),
1633            max_age: None,
1634            ui_locales: None,
1635            claims_locales: None,
1636            id_token_hint: None,
1637            login_hint: None,
1638            acr_values: None,
1639            claims: None,
1640            request: None,
1641            request_uri: None,
1642        };
1643
1644        let result = provider
1645            .validate_authorization_request(&invalid_request)
1646            .await;
1647        assert!(result.is_err());
1648    }
1649
1650    #[tokio::test]
1651    async fn test_id_token_creation() {
1652        let provider = create_test_oidc_provider().await;
1653
1654        let auth_time = SystemTime::now();
1655        let mut claims = HashMap::new();
1656        claims.insert("name".to_string(), Value::String("John Doe".to_string()));
1657        claims.insert(
1658            "email".to_string(),
1659            Value::String("john@example.com".to_string()),
1660        );
1661
1662        use crate::server::oidc::core::IdTokenRequest;
1663        let id_token = provider
1664            .create_id_token(
1665                IdTokenRequest::new("user123", "client456")
1666                    .with_nonce("nonce789")
1667                    .with_auth_time(auth_time)
1668                    .with_claims(&claims),
1669            )
1670            .await
1671            .unwrap();
1672
1673        assert!(!id_token.is_empty());
1674        assert!(id_token.contains('.'));
1675    }
1676
1677    #[tokio::test]
1678    async fn an_id_token_is_not_an_access_token() {
1679        use crate::server::oidc::core::IdTokenRequest;
1680        let provider = create_test_oidc_provider().await;
1681        let id_token = provider
1682            .create_id_token(IdTokenRequest::new("user123", "client456"))
1683            .await
1684            .unwrap();
1685        // it is a valid JWT of this server ...
1686        assert!(provider.token_manager.validate_jwt_token(&id_token).is_ok());
1687        // ... but not something that authenticates a request
1688        let storage = MemoryStorage::new();
1689        assert!(
1690            crate::auth::validate_access_jwt_with(
1691                &provider.token_manager,
1692                &storage,
1693                &id_token,
1694                false,
1695                false
1696            )
1697            .await
1698            .is_err(),
1699            "an ID token must not be accepted as an access token"
1700        );
1701        // control: a genuine access token for the same subject is
1702        let access = provider
1703            .token_manager
1704            .create_jwt_token("user123", vec!["openid".into()], None)
1705            .unwrap();
1706        assert!(
1707            crate::auth::validate_access_jwt_with(
1708                &provider.token_manager,
1709                &storage,
1710                &access,
1711                false,
1712                false
1713            )
1714            .await
1715            .is_ok()
1716        );
1717    }
1718
1719    #[tokio::test]
1720    async fn test_jwks_generation() {
1721        let provider = create_test_oidc_provider().await;
1722        let jwks = provider.generate_jwks().unwrap();
1723
1724        assert!(jwks.keys.is_empty());
1725    }
1726
1727    #[tokio::test]
1728    async fn test_logout_handling() {
1729        let provider = create_test_oidc_provider().await;
1730
1731        // Test logout without post_logout_redirect_uri (should work without id_token_hint)
1732        let logout_response = provider
1733            .handle_logout(None, None, Some("state123"))
1734            .await
1735            .unwrap();
1736
1737        assert_eq!(logout_response.post_logout_redirect_uri, None);
1738        assert_eq!(logout_response.state, Some("state123".to_string()));
1739    }
1740
1741    #[test]
1742    fn test_subject_type_serialization() {
1743        let public = SubjectType::Public;
1744        let pairwise = SubjectType::Pairwise;
1745
1746        let public_json = serde_json::to_string(&public).unwrap();
1747        let pairwise_json = serde_json::to_string(&pairwise).unwrap();
1748
1749        assert_eq!(public_json, "\"public\"");
1750        assert_eq!(pairwise_json, "\"pairwise\"");
1751    }
1752
1753    #[test]
1754    fn test_algorithm_to_string_conversion() {
1755        assert_eq!(algorithm_to_string(&Algorithm::RS256), "RS256");
1756        assert_eq!(algorithm_to_string(&Algorithm::ES256), "ES256");
1757        assert_eq!(algorithm_to_string(&Algorithm::HS256), "HS256");
1758        assert_eq!(algorithm_to_string(&Algorithm::EdDSA), "EdDSA");
1759    }
1760
1761    #[test]
1762    fn test_oidc_config_default() {
1763        let config = OidcConfig::default();
1764        assert_eq!(config.issuer, "https://auth.example.com");
1765        assert!(config.scopes_supported.contains(&"openid".to_string()));
1766        assert!(config.claims_supported.contains(&"sub".to_string()));
1767        assert_eq!(config.subject_types_supported, vec![SubjectType::Public]);
1768    }
1769}