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