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_jwt_token(
565                subject,
566                vec!["openid".to_string()],
567                Some(Duration::from_secs(3600)),
568            )
569            .map_err(|e| AuthError::auth_method("oidc", format!("JWT creation failed: {}", e)))?;
570
571        Ok(token)
572    }
573
574    /// Validate an authorization request for OIDC
575    pub async fn validate_authorization_request(
576        &self,
577        request: &OidcAuthorizationRequest,
578    ) -> Result<AuthorizationValidationResult> {
579        // Check if 'openid' scope is present
580        if !request.scope.split_whitespace().any(|s| s == "openid") {
581            return Err(AuthError::auth_method(
582                "oidc",
583                "Missing required 'openid' scope",
584            ));
585        }
586
587        // SEC-H2: Require state parameter (CSRF protection per OAuth 2.0 §10.12)
588        match &request.state {
589            None => {
590                return Err(AuthError::auth_method(
591                    "oidc",
592                    "Missing required 'state' parameter",
593                ));
594            }
595            Some(s) if s.is_empty() => {
596                return Err(AuthError::auth_method(
597                    "oidc",
598                    "The 'state' parameter must not be empty",
599                ));
600            }
601            _ => {}
602        }
603
604        // Validate response_type
605        if !self
606            .config
607            .response_types_supported
608            .contains(&request.response_type)
609        {
610            return Err(AuthError::auth_method(
611                "oidc",
612                format!("Unsupported response_type: {}", request.response_type),
613            ));
614        }
615
616        // SEC-M8: Block implicit grant response types (OAuth 2.1 compliance).
617        // Response types containing "token" without "code" are implicit grants.
618        {
619            let rt = &request.response_type;
620            if rt.split_whitespace().any(|part| part == "token")
621                && !rt.split_whitespace().any(|part| part == "code")
622            {
623                return Err(AuthError::auth_method(
624                    "oidc",
625                    "Implicit grant (response_type containing 'token' without 'code') is not permitted",
626                ));
627            }
628        }
629
630        // Validate client_id
631        if request.client_id.is_empty() {
632            return Err(AuthError::auth_method("oidc", "Missing client_id"));
633        }
634
635        // Check client exists in registry and validate redirect_uri + scopes
636        if let Some(client_registry) = &self.client_registry {
637            if client_registry
638                .get_client(&request.client_id)
639                .await?
640                .is_none()
641            {
642                return Err(AuthError::auth_method("oidc", "Invalid client_id"));
643            }
644
645            // Validate redirect_uri against registered URIs
646            if !client_registry
647                .validate_redirect_uri(&request.client_id, &request.redirect_uri)
648                .await?
649            {
650                return Err(AuthError::auth_method(
651                    "oidc",
652                    "Invalid redirect_uri for client",
653                ));
654            }
655
656            // SEC-M4: Validate requested scopes against client's authorized scopes
657            for scope in request.scope.split_whitespace() {
658                if !client_registry
659                    .validate_scope(&request.client_id, scope)
660                    .await?
661                {
662                    return Err(AuthError::auth_method(
663                        "oidc",
664                        format!("Client is not authorized for scope '{}'", scope),
665                    ));
666                }
667            }
668        } else {
669            // SEC-H3: Without a client registry, we cannot verify the redirect_uri
670            // belongs to a legitimate client. Reject all requests to prevent open
671            // redirect attacks.
672            return Err(AuthError::auth_method(
673                "oidc",
674                "Client registry is required for authorization requests",
675            ));
676        }
677
678        // SEC-M4: Validate all requested scopes against server's supported scopes
679        for scope in request.scope.split_whitespace() {
680            if !self.config.scopes_supported.contains(&scope.to_string()) {
681                return Err(AuthError::auth_method(
682                    "oidc",
683                    format!("Unsupported scope '{}'", scope),
684                ));
685            }
686        }
687
688        Ok(AuthorizationValidationResult {
689            valid: true,
690            client_id: request.client_id.clone(),
691            redirect_uri: request.redirect_uri.clone(),
692            scope: request.scope.clone(),
693            state: request.state.clone(),
694            nonce: request.nonce.clone(),
695            max_age: request.max_age,
696            response_type: request.response_type.clone(),
697        })
698    }
699
700    /// Get user information for the UserInfo endpoint
701    pub async fn get_userinfo(&self, access_token: &str) -> Result<UserInfo> {
702        // Validate access token
703        let token_claims = self
704            .token_manager
705            .validate_jwt_token(access_token)
706            .map_err(|e| AuthError::auth_method("oidc", format!("Invalid access token: {}", e)))?;
707
708        // Extract subject from token
709        let subject = &token_claims.sub;
710
711        // Get user information from storage
712        let user_key = format!("user:{}", subject);
713        if let Some(user_data) = self.storage.get_kv(&user_key).await? {
714            let user_str = std::str::from_utf8(&user_data).unwrap_or("{}");
715            let user_profile: HashMap<String, Value> =
716                serde_json::from_str(user_str).unwrap_or_default();
717
718            Ok(UserInfo {
719                sub: subject.clone(),
720                name: user_profile
721                    .get("name")
722                    .and_then(|v| v.as_str())
723                    .map(|s| s.to_string()),
724                given_name: user_profile
725                    .get("given_name")
726                    .and_then(|v| v.as_str())
727                    .map(|s| s.to_string()),
728                family_name: user_profile
729                    .get("family_name")
730                    .and_then(|v| v.as_str())
731                    .map(|s| s.to_string()),
732                middle_name: user_profile
733                    .get("middle_name")
734                    .and_then(|v| v.as_str())
735                    .map(|s| s.to_string()),
736                nickname: user_profile
737                    .get("nickname")
738                    .and_then(|v| v.as_str())
739                    .map(|s| s.to_string()),
740                preferred_username: user_profile
741                    .get("preferred_username")
742                    .and_then(|v| v.as_str())
743                    .map(|s| s.to_string()),
744                profile: user_profile
745                    .get("profile")
746                    .and_then(|v| v.as_str())
747                    .map(|s| s.to_string()),
748                picture: user_profile
749                    .get("picture")
750                    .and_then(|v| v.as_str())
751                    .map(|s| s.to_string()),
752                website: user_profile
753                    .get("website")
754                    .and_then(|v| v.as_str())
755                    .map(|s| s.to_string()),
756                email: user_profile
757                    .get("email")
758                    .and_then(|v| v.as_str())
759                    .map(|s| s.to_string()),
760                email_verified: user_profile.get("email_verified").and_then(|v| v.as_bool()),
761                gender: user_profile
762                    .get("gender")
763                    .and_then(|v| v.as_str())
764                    .map(|s| s.to_string()),
765                birthdate: user_profile
766                    .get("birthdate")
767                    .and_then(|v| v.as_str())
768                    .map(|s| s.to_string()),
769                zoneinfo: user_profile
770                    .get("zoneinfo")
771                    .and_then(|v| v.as_str())
772                    .map(|s| s.to_string()),
773                locale: user_profile
774                    .get("locale")
775                    .and_then(|v| v.as_str())
776                    .map(|s| s.to_string()),
777                phone_number: user_profile
778                    .get("phone_number")
779                    .and_then(|v| v.as_str())
780                    .map(|s| s.to_string()),
781                phone_number_verified: user_profile
782                    .get("phone_number_verified")
783                    .and_then(|v| v.as_bool()),
784                address: user_profile
785                    .get("address")
786                    .and_then(|addr| addr.as_object())
787                    .map(|addr_obj| Address {
788                        formatted: addr_obj
789                            .get("formatted")
790                            .and_then(|v| v.as_str())
791                            .map(|s| s.to_string()),
792                        street_address: addr_obj
793                            .get("street_address")
794                            .and_then(|v| v.as_str())
795                            .map(|s| s.to_string()),
796                        locality: addr_obj
797                            .get("locality")
798                            .and_then(|v| v.as_str())
799                            .map(|s| s.to_string()),
800                        region: addr_obj
801                            .get("region")
802                            .and_then(|v| v.as_str())
803                            .map(|s| s.to_string()),
804                        postal_code: addr_obj
805                            .get("postal_code")
806                            .and_then(|v| v.as_str())
807                            .map(|s| s.to_string()),
808                        country: addr_obj
809                            .get("country")
810                            .and_then(|v| v.as_str())
811                            .map(|s| s.to_string()),
812                    }),
813                updated_at: user_profile.get("updated_at").and_then(|v| v.as_u64()),
814                additional_claims: user_profile
815                    .into_iter()
816                    .filter(|(k, _)| {
817                        ![
818                            "sub",
819                            "name",
820                            "given_name",
821                            "family_name",
822                            "middle_name",
823                            "nickname",
824                            "preferred_username",
825                            "profile",
826                            "picture",
827                            "website",
828                            "email",
829                            "email_verified",
830                            "gender",
831                            "birthdate",
832                            "zoneinfo",
833                            "locale",
834                            "phone_number",
835                            "phone_number_verified",
836                            "address",
837                            "updated_at",
838                        ]
839                        .contains(&k.as_str())
840                    })
841                    .collect(),
842            })
843        } else {
844            // Return minimal user info with only the subject claim when no stored profile exists
845            Ok(UserInfo {
846                sub: subject.clone(),
847                name: None,
848                given_name: None,
849                family_name: None,
850                middle_name: None,
851                nickname: None,
852                preferred_username: Some(subject.clone()),
853                profile: None,
854                picture: None,
855                website: None,
856                email: None,
857                email_verified: None,
858                gender: None,
859                birthdate: None,
860                zoneinfo: None,
861                locale: None,
862                phone_number: None,
863                phone_number_verified: None,
864                address: None,
865                updated_at: None,
866                additional_claims: HashMap::new(),
867            })
868        }
869    }
870
871    /// Handle logout request
872    pub async fn handle_logout(
873        &self,
874        id_token_hint: Option<&str>,
875        post_logout_redirect_uri: Option<&str>,
876        state: Option<&str>,
877    ) -> Result<LogoutResponse> {
878        // Validate ID token hint if provided
879        if let Some(id_token) = id_token_hint {
880            let claims = self
881                .token_manager
882                .validate_jwt_token(id_token)
883                .map_err(|e| AuthError::auth_method("oidc", format!("Invalid ID token: {}", e)))?;
884
885            // Invalidate all sessions for the user identified in the token
886            let user_sessions = self
887                .storage
888                .list_user_sessions(&claims.sub)
889                .await
890                .map_err(|e| AuthError::internal(format!("Failed to list user sessions: {}", e)))?;
891
892            for session in user_sessions {
893                self.storage
894                    .delete_session(&session.session_id)
895                    .await
896                    .map_err(|e| AuthError::internal(format!("Failed to delete session: {}", e)))?;
897            }
898        }
899
900        // Validate post_logout_redirect_uri against registered URIs
901        if let Some(post_logout_uri) = post_logout_redirect_uri {
902            // Extract client_id from the ID token if available
903            if let Some(id_token) = id_token_hint {
904                let claims = self
905                    .token_manager
906                    .validate_jwt_token(id_token)
907                    .map_err(|e| {
908                        AuthError::auth_method("oidc", format!("Invalid ID token: {}", e))
909                    })?;
910
911                if let Some(aud) = claims.aud.split_whitespace().next() {
912                    // Validate that the post-logout redirect URI is registered for this client
913                    if !self
914                        .is_post_logout_uri_registered(aud, post_logout_uri)
915                        .await?
916                    {
917                        return Err(AuthError::validation(
918                            "post_logout_redirect_uri not registered for client",
919                        ));
920                    }
921                }
922            } else {
923                // If no ID token provided, we cannot validate the client association
924                // In a production system, you might want to require ID token for validation
925                return Err(AuthError::validation(
926                    "id_token_hint required for post_logout_redirect_uri validation",
927                ));
928            }
929        }
930
931        Ok(LogoutResponse {
932            post_logout_redirect_uri: post_logout_redirect_uri.map(|uri| uri.to_string()),
933            state: state.map(|s| s.to_string()),
934        })
935    }
936
937    /// Check if a post-logout redirect URI is registered for a client
938    async fn is_post_logout_uri_registered(&self, client_id: &str, uri: &str) -> Result<bool> {
939        // SECURITY CRITICAL: Validate redirect URI against registered URIs
940
941        // Basic security: only allow https URIs (except localhost for development)
942        if !uri.starts_with("https://")
943            && !uri.starts_with("http://localhost")
944            && !uri.starts_with("http://127.0.0.1")
945        {
946            tracing::warn!(
947                "Rejected post-logout redirect URI with invalid scheme: {}",
948                uri
949            );
950            return Ok(false);
951        }
952
953        // Enhanced security: Validate against registered URIs
954        match self.get_client_registered_post_logout_uris(client_id).await {
955            Ok(registered_uris) => {
956                let is_registered = registered_uris.contains(&uri.to_string());
957                if !is_registered {
958                    tracing::warn!(
959                        "Rejected unregistered post-logout redirect URI for client {}: {}",
960                        client_id,
961                        uri
962                    );
963                }
964                Ok(is_registered)
965            }
966            Err(_) => {
967                // When client lookup fails, reject all redirect URIs to prevent
968                // open-redirect attacks. Even loopback URIs are rejected here because
969                // `http://localhost.evil.com` would match a naive prefix check.
970                tracing::error!(
971                    "Rejected redirect URI — client lookup failed for {}: {}",
972                    client_id,
973                    uri
974                );
975                Ok(false)
976            }
977        }
978    }
979
980    /// Get registered post-logout redirect URIs for a client
981    async fn get_client_registered_post_logout_uris(&self, client_id: &str) -> Result<Vec<String>> {
982        // Look up post-logout redirect URIs from client registry storage
983        if let Some(client_registry) = &self.client_registry
984            && let Some(client) = client_registry.get_client(client_id).await?
985        {
986            // Post-logout redirect URIs are stored in client metadata
987            if let Some(uris) = client.metadata.get("post_logout_redirect_uris")
988                && let Some(arr) = uris.as_array()
989            {
990                return Ok(arr
991                    .iter()
992                    .filter_map(|v| v.as_str().map(|s| s.to_string()))
993                    .collect());
994            }
995        }
996        // Unknown client or no registry — return empty list so all redirect URIs
997        // are rejected, preventing open-redirect attacks.
998        Ok(Vec::new())
999    }
1000
1001    /// Generate JWK Set for the .well-known/jwks.json endpoint
1002    pub fn generate_jwks(&self) -> Result<JwkSet> {
1003        let keys = self
1004            .token_manager
1005            .export_public_jwks()?
1006            .into_iter()
1007            .map(|key| Jwk {
1008                kty: "RSA".to_string(),
1009                use_: Some("sig".to_string()),
1010                key_ops: Some(vec!["verify".to_string()]),
1011                alg: Some(algorithm_to_string(&key.algorithm)),
1012                kid: Some(key.kid),
1013                n: key.n,
1014                e: key.e,
1015                additional_params: HashMap::new(),
1016            })
1017            .collect();
1018
1019        Ok(JwkSet { keys })
1020    }
1021}
1022
1023/// OIDC Authorization Request
1024#[derive(Debug, Clone, Serialize, Deserialize)]
1025pub struct OidcAuthorizationRequest {
1026    pub response_type: String,
1027    pub client_id: String,
1028    pub redirect_uri: String,
1029    pub scope: String,
1030    pub state: Option<String>,
1031    pub nonce: Option<String>,
1032    pub max_age: Option<u64>,
1033    pub ui_locales: Option<String>,
1034    pub claims_locales: Option<String>,
1035    pub id_token_hint: Option<String>,
1036    pub login_hint: Option<String>,
1037    pub acr_values: Option<String>,
1038    pub claims: Option<String>,
1039    pub request: Option<String>,
1040    pub request_uri: Option<String>,
1041}
1042
1043impl OidcAuthorizationRequest {
1044    /// Create a builder with the required `client_id` and `redirect_uri`.
1045    ///
1046    /// Defaults: `response_type = "code"`, `scope = "openid"`.
1047    pub fn builder(
1048        client_id: impl Into<String>,
1049        redirect_uri: impl Into<String>,
1050    ) -> OidcAuthorizationRequestBuilder {
1051        OidcAuthorizationRequestBuilder::new(client_id, redirect_uri)
1052    }
1053}
1054
1055/// Fluent builder for [`OidcAuthorizationRequest`].
1056///
1057/// # Example
1058///
1059/// ```rust
1060/// use auth_framework::server::oidc::core::OidcAuthorizationRequest;
1061///
1062/// let req = OidcAuthorizationRequest::builder("my-client", "https://app.example/callback")
1063///     .scope("openid profile email")
1064///     .state("random_state")
1065///     .nonce("random_nonce")
1066///     .build();
1067///
1068/// assert_eq!(req.client_id, "my-client");
1069/// assert_eq!(req.scope, "openid profile email");
1070/// ```
1071pub struct OidcAuthorizationRequestBuilder {
1072    req: OidcAuthorizationRequest,
1073}
1074
1075impl OidcAuthorizationRequestBuilder {
1076    fn new(client_id: impl Into<String>, redirect_uri: impl Into<String>) -> Self {
1077        Self {
1078            req: OidcAuthorizationRequest {
1079                response_type: "code".to_string(),
1080                client_id: client_id.into(),
1081                redirect_uri: redirect_uri.into(),
1082                scope: "openid".to_string(),
1083                state: None,
1084                nonce: None,
1085                max_age: None,
1086                ui_locales: None,
1087                claims_locales: None,
1088                id_token_hint: None,
1089                login_hint: None,
1090                acr_values: None,
1091                claims: None,
1092                request: None,
1093                request_uri: None,
1094            },
1095        }
1096    }
1097
1098    /// Set the OAuth2 response type (default: `"code"`).
1099    pub fn response_type(mut self, rt: impl Into<String>) -> Self {
1100        self.req.response_type = rt.into();
1101        self
1102    }
1103
1104    /// Set the requested scopes (default: `"openid"`).
1105    pub fn scope(mut self, scope: impl Into<String>) -> Self {
1106        self.req.scope = scope.into();
1107        self
1108    }
1109
1110    /// Set the state parameter for CSRF protection.
1111    pub fn state(mut self, state: impl Into<String>) -> Self {
1112        self.req.state = Some(state.into());
1113        self
1114    }
1115
1116    /// Set the nonce for ID token replay protection.
1117    pub fn nonce(mut self, nonce: impl Into<String>) -> Self {
1118        self.req.nonce = Some(nonce.into());
1119        self
1120    }
1121
1122    /// Set the maximum authentication age in seconds.
1123    pub fn max_age(mut self, seconds: u64) -> Self {
1124        self.req.max_age = Some(seconds);
1125        self
1126    }
1127
1128    /// Provide a login hint (e.g. email or username).
1129    pub fn login_hint(mut self, hint: impl Into<String>) -> Self {
1130        self.req.login_hint = Some(hint.into());
1131        self
1132    }
1133
1134    /// Set the id_token_hint for session management.
1135    pub fn id_token_hint(mut self, hint: impl Into<String>) -> Self {
1136        self.req.id_token_hint = Some(hint.into());
1137        self
1138    }
1139
1140    /// Set the ACR values.
1141    pub fn acr_values(mut self, values: impl Into<String>) -> Self {
1142        self.req.acr_values = Some(values.into());
1143        self
1144    }
1145
1146    /// Consume the builder and produce the request.
1147    pub fn build(self) -> OidcAuthorizationRequest {
1148        self.req
1149    }
1150}
1151
1152/// Authorization validation result
1153#[derive(Debug, Clone)]
1154pub struct AuthorizationValidationResult {
1155    pub valid: bool,
1156    pub client_id: String,
1157    pub redirect_uri: String,
1158    pub scope: String,
1159    pub state: Option<String>,
1160    pub nonce: Option<String>,
1161    pub max_age: Option<u64>,
1162    pub response_type: String,
1163}
1164
1165/// ID Token Claims
1166#[derive(Debug, Clone, Serialize, Deserialize)]
1167pub struct IdTokenClaims {
1168    /// Issuer
1169    pub iss: String,
1170    /// Subject
1171    pub sub: String,
1172    /// Audience
1173    pub aud: Vec<String>,
1174    /// Expiration time
1175    pub exp: u64,
1176    /// Issued at
1177    pub iat: u64,
1178    /// Authentication time
1179    #[serde(skip_serializing_if = "Option::is_none")]
1180    pub auth_time: Option<u64>,
1181    /// Nonce
1182    #[serde(skip_serializing_if = "Option::is_none")]
1183    pub nonce: Option<String>,
1184    /// Additional claims
1185    #[serde(flatten)]
1186    pub additional_claims: HashMap<String, Value>,
1187}
1188
1189/// UserInfo response
1190#[derive(Debug, Clone, Serialize, Deserialize)]
1191pub struct UserInfo {
1192    pub sub: String,
1193    #[serde(skip_serializing_if = "Option::is_none")]
1194    pub name: Option<String>,
1195    #[serde(skip_serializing_if = "Option::is_none")]
1196    pub given_name: Option<String>,
1197    #[serde(skip_serializing_if = "Option::is_none")]
1198    pub family_name: Option<String>,
1199    #[serde(skip_serializing_if = "Option::is_none")]
1200    pub middle_name: Option<String>,
1201    #[serde(skip_serializing_if = "Option::is_none")]
1202    pub nickname: Option<String>,
1203    #[serde(skip_serializing_if = "Option::is_none")]
1204    pub preferred_username: Option<String>,
1205    #[serde(skip_serializing_if = "Option::is_none")]
1206    pub profile: Option<String>,
1207    #[serde(skip_serializing_if = "Option::is_none")]
1208    pub picture: Option<String>,
1209    #[serde(skip_serializing_if = "Option::is_none")]
1210    pub website: Option<String>,
1211    #[serde(skip_serializing_if = "Option::is_none")]
1212    pub email: Option<String>,
1213    #[serde(skip_serializing_if = "Option::is_none")]
1214    pub email_verified: Option<bool>,
1215    #[serde(skip_serializing_if = "Option::is_none")]
1216    pub gender: Option<String>,
1217    #[serde(skip_serializing_if = "Option::is_none")]
1218    pub birthdate: Option<String>,
1219    #[serde(skip_serializing_if = "Option::is_none")]
1220    pub zoneinfo: Option<String>,
1221    #[serde(skip_serializing_if = "Option::is_none")]
1222    pub locale: Option<String>,
1223    #[serde(skip_serializing_if = "Option::is_none")]
1224    pub phone_number: Option<String>,
1225    #[serde(skip_serializing_if = "Option::is_none")]
1226    pub phone_number_verified: Option<bool>,
1227    #[serde(skip_serializing_if = "Option::is_none")]
1228    pub address: Option<Address>,
1229    #[serde(skip_serializing_if = "Option::is_none")]
1230    pub updated_at: Option<u64>,
1231    #[serde(flatten)]
1232    pub additional_claims: HashMap<String, Value>,
1233}
1234
1235/// Address claim
1236#[derive(Debug, Clone, Serialize, Deserialize)]
1237pub struct Address {
1238    #[serde(skip_serializing_if = "Option::is_none")]
1239    pub formatted: Option<String>,
1240    #[serde(skip_serializing_if = "Option::is_none")]
1241    pub street_address: Option<String>,
1242    #[serde(skip_serializing_if = "Option::is_none")]
1243    pub locality: Option<String>,
1244    #[serde(skip_serializing_if = "Option::is_none")]
1245    pub region: Option<String>,
1246    #[serde(skip_serializing_if = "Option::is_none")]
1247    pub postal_code: Option<String>,
1248    #[serde(skip_serializing_if = "Option::is_none")]
1249    pub country: Option<String>,
1250}
1251
1252/// OIDC Discovery Document
1253#[derive(Debug, Clone, Serialize, Deserialize)]
1254pub struct OidcDiscoveryDocument {
1255    pub issuer: String,
1256    pub authorization_endpoint: String,
1257    pub token_endpoint: String,
1258    pub userinfo_endpoint: String,
1259    pub jwks_uri: String,
1260    #[serde(skip_serializing_if = "Option::is_none")]
1261    pub registration_endpoint: Option<String>,
1262    pub scopes_supported: Vec<String>,
1263    pub response_types_supported: Vec<String>,
1264    #[serde(skip_serializing_if = "Option::is_none")]
1265    pub response_modes_supported: Option<Vec<String>>,
1266    #[serde(skip_serializing_if = "Option::is_none")]
1267    pub grant_types_supported: Option<Vec<String>>,
1268    pub subject_types_supported: Vec<SubjectType>,
1269    pub id_token_signing_alg_values_supported: Vec<String>,
1270    #[serde(skip_serializing_if = "Option::is_none")]
1271    pub userinfo_signing_alg_values_supported: Option<Vec<String>>,
1272    #[serde(skip_serializing_if = "Option::is_none")]
1273    pub token_endpoint_auth_methods_supported: Option<Vec<String>>,
1274    #[serde(skip_serializing_if = "Option::is_none")]
1275    pub claims_supported: Option<Vec<String>>,
1276    #[serde(skip_serializing_if = "Option::is_none")]
1277    pub claims_parameter_supported: Option<bool>,
1278    #[serde(skip_serializing_if = "Option::is_none")]
1279    pub request_parameter_supported: Option<bool>,
1280    #[serde(skip_serializing_if = "Option::is_none")]
1281    pub request_uri_parameter_supported: Option<bool>,
1282    #[serde(skip_serializing_if = "Option::is_none")]
1283    pub code_challenge_methods_supported: Option<Vec<String>>,
1284}
1285
1286/// JWK Set
1287#[derive(Debug, Clone, Serialize, Deserialize)]
1288pub struct JwkSet {
1289    pub keys: Vec<Jwk>,
1290}
1291
1292/// JSON Web Key
1293#[derive(Debug, Clone, Serialize, Deserialize)]
1294pub struct Jwk {
1295    pub kty: String,
1296    #[serde(rename = "use", skip_serializing_if = "Option::is_none")]
1297    pub use_: Option<String>,
1298    #[serde(skip_serializing_if = "Option::is_none")]
1299    pub key_ops: Option<Vec<String>>,
1300    #[serde(skip_serializing_if = "Option::is_none")]
1301    pub alg: Option<String>,
1302    #[serde(skip_serializing_if = "Option::is_none")]
1303    pub kid: Option<String>,
1304    pub n: String,
1305    pub e: String,
1306    #[serde(flatten)]
1307    pub additional_params: HashMap<String, Value>,
1308}
1309
1310/// Logout response
1311#[derive(Debug, Clone)]
1312pub struct LogoutResponse {
1313    pub post_logout_redirect_uri: Option<String>,
1314    pub state: Option<String>,
1315}
1316
1317/// Helper function to convert Algorithm to string
1318fn algorithm_to_string(alg: &Algorithm) -> String {
1319    match alg {
1320        Algorithm::HS256 => "HS256".to_string(),
1321        Algorithm::HS384 => "HS384".to_string(),
1322        Algorithm::HS512 => "HS512".to_string(),
1323        Algorithm::ES256 => "ES256".to_string(),
1324        Algorithm::ES384 => "ES384".to_string(),
1325        Algorithm::RS256 => "RS256".to_string(),
1326        Algorithm::RS384 => "RS384".to_string(),
1327        Algorithm::RS512 => "RS512".to_string(),
1328        Algorithm::PS256 => "PS256".to_string(),
1329        Algorithm::PS384 => "PS384".to_string(),
1330        Algorithm::PS512 => "PS512".to_string(),
1331        Algorithm::EdDSA => "EdDSA".to_string(),
1332    }
1333}
1334
1335#[cfg(test)]
1336mod tests {
1337    use super::*;
1338    use crate::storage::MemoryStorage;
1339
1340    async fn create_test_oidc_provider() -> OidcProvider<MemoryStorage> {
1341        let config = OidcConfig::default();
1342        let token_manager = Arc::new(TokenManager::new_hmac(
1343            b"test_secret_key_32_bytes_long!!!!",
1344            "test_issuer",
1345            "test_audience",
1346        ));
1347        let storage = Arc::new(MemoryStorage::new());
1348
1349        // Register a test client so that the fail-closed client registry check passes
1350        let client_registry = Arc::new(
1351            crate::server::core::client_registry::ClientRegistry::new(
1352                storage.clone() as Arc<dyn crate::storage::AuthStorage>
1353            )
1354            .await
1355            .unwrap(),
1356        );
1357        let test_client = crate::client::ClientConfig {
1358            client_id: "test_client".to_string(),
1359            client_secret: Some("test_secret".to_string()),
1360            client_type: crate::client::ClientType::Confidential,
1361            redirect_uris: vec!["https://client.example.com/callback".to_string()].into(),
1362            authorized_scopes: vec![
1363                "openid".to_string(),
1364                "profile".to_string(),
1365                "email".to_string(),
1366            ]
1367            .into(),
1368            authorized_grant_types: vec!["authorization_code".to_string()].into(),
1369            authorized_response_types: vec!["code".to_string()].into(),
1370            client_name: Some("Test Client".to_string()),
1371            client_description: None,
1372            metadata: std::collections::HashMap::new(),
1373        };
1374        client_registry.register_client(test_client).await.unwrap();
1375
1376        let mut provider = OidcProvider::new(config, token_manager, storage)
1377            .await
1378            .unwrap();
1379        provider.set_client_registry(client_registry);
1380        provider
1381    }
1382
1383    #[tokio::test]
1384    async fn test_oidc_provider_creation() {
1385        let provider = create_test_oidc_provider().await;
1386        assert_eq!(provider.config.issuer, "https://auth.example.com");
1387        assert!(
1388            provider
1389                .config
1390                .scopes_supported
1391                .contains(&"openid".to_string())
1392        );
1393    }
1394
1395    #[tokio::test]
1396    async fn test_discovery_document() {
1397        let provider = create_test_oidc_provider().await;
1398        let discovery = provider.discovery_document().unwrap();
1399
1400        assert_eq!(discovery.issuer, "https://auth.example.com");
1401        assert_eq!(
1402            discovery.authorization_endpoint,
1403            "https://auth.example.com/oidc/authorize"
1404        );
1405        assert!(discovery.scopes_supported.contains(&"openid".to_string()));
1406        assert!(
1407            discovery
1408                .response_types_supported
1409                .contains(&"code".to_string())
1410        );
1411    }
1412
1413    #[tokio::test]
1414    async fn test_authorization_request_validation() {
1415        let provider = create_test_oidc_provider().await;
1416
1417        let valid_request = OidcAuthorizationRequest {
1418            response_type: "code".to_string(),
1419            client_id: "test_client".to_string(),
1420            redirect_uri: "https://client.example.com/callback".to_string(),
1421            scope: "openid profile email".to_string(),
1422            state: Some("abc123".to_string()),
1423            nonce: Some("xyz789".to_string()),
1424            max_age: None,
1425            ui_locales: None,
1426            claims_locales: None,
1427            id_token_hint: None,
1428            login_hint: None,
1429            acr_values: None,
1430            claims: None,
1431            request: None,
1432            request_uri: None,
1433        };
1434
1435        let result = provider
1436            .validate_authorization_request(&valid_request)
1437            .await
1438            .unwrap();
1439        assert!(result.valid);
1440        assert_eq!(result.client_id, "test_client");
1441        assert_eq!(result.scope, "openid profile email");
1442    }
1443
1444    #[tokio::test]
1445    async fn test_authorization_request_missing_openid_scope() {
1446        let provider = create_test_oidc_provider().await;
1447
1448        let invalid_request = OidcAuthorizationRequest {
1449            response_type: "code".to_string(),
1450            client_id: "test_client".to_string(),
1451            redirect_uri: "https://client.example.com/callback".to_string(),
1452            scope: "profile email".to_string(), // Missing 'openid'
1453            state: Some("abc123".to_string()),
1454            nonce: Some("xyz789".to_string()),
1455            max_age: None,
1456            ui_locales: None,
1457            claims_locales: None,
1458            id_token_hint: None,
1459            login_hint: None,
1460            acr_values: None,
1461            claims: None,
1462            request: None,
1463            request_uri: None,
1464        };
1465
1466        let result = provider
1467            .validate_authorization_request(&invalid_request)
1468            .await;
1469        assert!(result.is_err());
1470    }
1471
1472    #[tokio::test]
1473    async fn test_id_token_creation() {
1474        let provider = create_test_oidc_provider().await;
1475
1476        let auth_time = SystemTime::now();
1477        let mut claims = HashMap::new();
1478        claims.insert("name".to_string(), Value::String("John Doe".to_string()));
1479        claims.insert(
1480            "email".to_string(),
1481            Value::String("john@example.com".to_string()),
1482        );
1483
1484        use crate::server::oidc::core::IdTokenRequest;
1485        let id_token = provider
1486            .create_id_token(
1487                IdTokenRequest::new("user123", "client456")
1488                    .with_nonce("nonce789")
1489                    .with_auth_time(auth_time)
1490                    .with_claims(&claims),
1491            )
1492            .await
1493            .unwrap();
1494
1495        assert!(!id_token.is_empty());
1496        assert!(id_token.contains('.'));
1497    }
1498
1499    #[tokio::test]
1500    async fn test_jwks_generation() {
1501        let provider = create_test_oidc_provider().await;
1502        let jwks = provider.generate_jwks().unwrap();
1503
1504        assert!(jwks.keys.is_empty());
1505    }
1506
1507    #[tokio::test]
1508    async fn test_logout_handling() {
1509        let provider = create_test_oidc_provider().await;
1510
1511        // Test logout without post_logout_redirect_uri (should work without id_token_hint)
1512        let logout_response = provider
1513            .handle_logout(None, None, Some("state123"))
1514            .await
1515            .unwrap();
1516
1517        assert_eq!(logout_response.post_logout_redirect_uri, None);
1518        assert_eq!(logout_response.state, Some("state123".to_string()));
1519    }
1520
1521    #[test]
1522    fn test_subject_type_serialization() {
1523        let public = SubjectType::Public;
1524        let pairwise = SubjectType::Pairwise;
1525
1526        let public_json = serde_json::to_string(&public).unwrap();
1527        let pairwise_json = serde_json::to_string(&pairwise).unwrap();
1528
1529        assert_eq!(public_json, "\"public\"");
1530        assert_eq!(pairwise_json, "\"pairwise\"");
1531    }
1532
1533    #[test]
1534    fn test_algorithm_to_string_conversion() {
1535        assert_eq!(algorithm_to_string(&Algorithm::RS256), "RS256");
1536        assert_eq!(algorithm_to_string(&Algorithm::ES256), "ES256");
1537        assert_eq!(algorithm_to_string(&Algorithm::HS256), "HS256");
1538        assert_eq!(algorithm_to_string(&Algorithm::EdDSA), "EdDSA");
1539    }
1540
1541    #[test]
1542    fn test_oidc_config_default() {
1543        let config = OidcConfig::default();
1544        assert_eq!(config.issuer, "https://auth.example.com");
1545        assert!(config.scopes_supported.contains(&"openid".to_string()));
1546        assert!(config.claims_supported.contains(&"sub".to_string()));
1547        assert_eq!(config.subject_types_supported, vec![SubjectType::Public]);
1548    }
1549}