1use 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#[derive(Debug, Clone)]
24pub struct OidcConfig {
25 pub issuer: String,
27
28 pub oauth2_config: crate::oauth2_server::OAuth2Config,
30
31 pub jwks_uri: String,
33
34 pub userinfo_endpoint: String,
36
37 pub response_types_supported: Vec<String>,
39
40 pub subject_types_supported: Vec<SubjectType>,
42
43 pub id_token_signing_alg_values_supported: Vec<Algorithm>,
45
46 pub scopes_supported: Vec<String>,
48
49 pub claims_supported: Vec<String>,
51
52 pub claims_parameter_supported: bool,
54
55 pub request_parameter_supported: bool,
57
58 pub request_uri_parameter_supported: bool,
60
61 pub id_token_expiry: Duration,
63
64 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), max_age_supported: Some(Duration::from_secs(86400)), }
125 }
126}
127
128impl OidcConfig {
129 pub fn builder() -> OidcConfigBuilder {
143 OidcConfigBuilder::default()
144 }
145}
146
147#[derive(Debug, Clone, Default)]
152pub struct OidcConfigBuilder {
153 config: OidcConfig,
154}
155
156impl OidcConfigBuilder {
157 pub fn issuer(mut self, issuer: impl Into<String>) -> Self {
166 self.config.issuer = issuer.into();
167 self
168 }
169
170 pub fn oauth2_config(mut self, config: crate::oauth2_server::OAuth2Config) -> Self {
179 self.config.oauth2_config = config;
180 self
181 }
182
183 pub fn jwks_uri(mut self, uri: impl Into<String>) -> Self {
192 self.config.jwks_uri = uri.into();
193 self
194 }
195
196 pub fn userinfo_endpoint(mut self, uri: impl Into<String>) -> Self {
205 self.config.userinfo_endpoint = uri.into();
206 self
207 }
208
209 pub fn response_types_supported(mut self, types: Vec<String>) -> Self {
218 self.config.response_types_supported = types;
219 self
220 }
221
222 pub fn subject_types_supported(mut self, types: Vec<SubjectType>) -> Self {
231 self.config.subject_types_supported = types;
232 self
233 }
234
235 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 pub fn scopes_supported(mut self, scopes: Vec<String>) -> Self {
257 self.config.scopes_supported = scopes;
258 self
259 }
260
261 pub fn claims_supported(mut self, claims: Vec<String>) -> Self {
270 self.config.claims_supported = claims;
271 self
272 }
273
274 pub fn claims_parameter_supported(mut self, supported: bool) -> Self {
283 self.config.claims_parameter_supported = supported;
284 self
285 }
286
287 pub fn request_parameter_supported(mut self, supported: bool) -> Self {
296 self.config.request_parameter_supported = supported;
297 self
298 }
299
300 pub fn request_uri_parameter_supported(mut self, supported: bool) -> Self {
309 self.config.request_uri_parameter_supported = supported;
310 self
311 }
312
313 pub fn id_token_expiry(mut self, expiry: Duration) -> Self {
323 self.config.id_token_expiry = expiry;
324 self
325 }
326
327 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 pub fn build(self) -> OidcConfig {
352 self.config
353 }
354}
355
356#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
358#[serde(rename_all = "lowercase")]
359pub enum SubjectType {
360 Public,
362 Pairwise,
364}
365
366pub 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 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 pub fn oauth2_server(&self) -> &OAuth2Server {
408 &self.oauth2_server
409 }
410
411 pub fn set_client_registry(&mut self, client_registry: Arc<ClientRegistry>) {
413 self.client_registry = Some(client_registry);
414 }
415
416 pub fn config(&self) -> &OidcConfig {
418 &self.config
419 }
420
421 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#[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 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 pub fn with_nonce(mut self, nonce: &'a str) -> Self {
505 self.nonce = Some(nonce);
506 self
507 }
508
509 pub fn with_auth_time(mut self, auth_time: SystemTime) -> Self {
511 self.auth_time = Some(auth_time);
512 self
513 }
514
515 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 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 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 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 pub async fn validate_authorization_request(
576 &self,
577 request: &OidcAuthorizationRequest,
578 ) -> Result<AuthorizationValidationResult> {
579 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 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 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 {
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 if request.client_id.is_empty() {
632 return Err(AuthError::auth_method("oidc", "Missing client_id"));
633 }
634
635 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 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 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 return Err(AuthError::auth_method(
673 "oidc",
674 "Client registry is required for authorization requests",
675 ));
676 }
677
678 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 pub async fn get_userinfo(&self, access_token: &str) -> Result<UserInfo> {
702 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 let subject = &token_claims.sub;
710
711 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 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 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 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 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 if let Some(post_logout_uri) = post_logout_redirect_uri {
902 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 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 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 async fn is_post_logout_uri_registered(&self, client_id: &str, uri: &str) -> Result<bool> {
939 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 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 tracing::error!(
971 "Rejected redirect URI — client lookup failed for {}: {}",
972 client_id,
973 uri
974 );
975 Ok(false)
976 }
977 }
978 }
979
980 async fn get_client_registered_post_logout_uris(&self, client_id: &str) -> Result<Vec<String>> {
982 if let Some(client_registry) = &self.client_registry
984 && let Some(client) = client_registry.get_client(client_id).await?
985 {
986 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 Ok(Vec::new())
999 }
1000
1001 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#[derive(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 std::fmt::Debug for OidcAuthorizationRequest {
1044 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1045 let mut d = f.debug_struct("OidcAuthorizationRequest");
1046 d.field("response_type", &self.response_type);
1047 d.field("client_id", &self.client_id);
1048 d.field("redirect_uri", &self.redirect_uri);
1049 d.field("scope", &self.scope);
1050 d.field("state", &self.state);
1051 d.field("nonce", &self.nonce);
1052 d.field("max_age", &self.max_age);
1053 d.field("ui_locales", &self.ui_locales);
1054 d.field("claims_locales", &self.claims_locales);
1055 d.field(
1056 "id_token_hint",
1057 &crate::utils::redact::redacted(&self.id_token_hint),
1058 );
1059 d.field("login_hint", &self.login_hint);
1060 d.field("acr_values", &self.acr_values);
1061 d.field("claims", &self.claims);
1062 d.field("request", &crate::utils::redact::redacted(&self.request));
1063 d.field(
1064 "request_uri",
1065 &crate::utils::redact::redacted(&self.request_uri),
1066 );
1067 d.finish()
1068 }
1069}
1070
1071impl OidcAuthorizationRequest {
1072 pub fn builder(
1076 client_id: impl Into<String>,
1077 redirect_uri: impl Into<String>,
1078 ) -> OidcAuthorizationRequestBuilder {
1079 OidcAuthorizationRequestBuilder::new(client_id, redirect_uri)
1080 }
1081}
1082
1083pub struct OidcAuthorizationRequestBuilder {
1100 req: OidcAuthorizationRequest,
1101}
1102
1103impl OidcAuthorizationRequestBuilder {
1104 fn new(client_id: impl Into<String>, redirect_uri: impl Into<String>) -> Self {
1105 Self {
1106 req: OidcAuthorizationRequest {
1107 response_type: "code".to_string(),
1108 client_id: client_id.into(),
1109 redirect_uri: redirect_uri.into(),
1110 scope: "openid".to_string(),
1111 state: None,
1112 nonce: None,
1113 max_age: None,
1114 ui_locales: None,
1115 claims_locales: None,
1116 id_token_hint: None,
1117 login_hint: None,
1118 acr_values: None,
1119 claims: None,
1120 request: None,
1121 request_uri: None,
1122 },
1123 }
1124 }
1125
1126 pub fn response_type(mut self, rt: impl Into<String>) -> Self {
1128 self.req.response_type = rt.into();
1129 self
1130 }
1131
1132 pub fn scope(mut self, scope: impl Into<String>) -> Self {
1134 self.req.scope = scope.into();
1135 self
1136 }
1137
1138 pub fn state(mut self, state: impl Into<String>) -> Self {
1140 self.req.state = Some(state.into());
1141 self
1142 }
1143
1144 pub fn nonce(mut self, nonce: impl Into<String>) -> Self {
1146 self.req.nonce = Some(nonce.into());
1147 self
1148 }
1149
1150 pub fn max_age(mut self, seconds: u64) -> Self {
1152 self.req.max_age = Some(seconds);
1153 self
1154 }
1155
1156 pub fn login_hint(mut self, hint: impl Into<String>) -> Self {
1158 self.req.login_hint = Some(hint.into());
1159 self
1160 }
1161
1162 pub fn id_token_hint(mut self, hint: impl Into<String>) -> Self {
1164 self.req.id_token_hint = Some(hint.into());
1165 self
1166 }
1167
1168 pub fn acr_values(mut self, values: impl Into<String>) -> Self {
1170 self.req.acr_values = Some(values.into());
1171 self
1172 }
1173
1174 pub fn build(self) -> OidcAuthorizationRequest {
1176 self.req
1177 }
1178}
1179
1180#[derive(Debug, Clone)]
1182pub struct AuthorizationValidationResult {
1183 pub valid: bool,
1184 pub client_id: String,
1185 pub redirect_uri: String,
1186 pub scope: String,
1187 pub state: Option<String>,
1188 pub nonce: Option<String>,
1189 pub max_age: Option<u64>,
1190 pub response_type: String,
1191}
1192
1193#[derive(Debug, Clone, Serialize, Deserialize)]
1195pub struct IdTokenClaims {
1196 pub iss: String,
1198 pub sub: String,
1200 pub aud: Vec<String>,
1202 pub exp: u64,
1204 pub iat: u64,
1206 #[serde(skip_serializing_if = "Option::is_none")]
1208 pub auth_time: Option<u64>,
1209 #[serde(skip_serializing_if = "Option::is_none")]
1211 pub nonce: Option<String>,
1212 #[serde(flatten)]
1214 pub additional_claims: HashMap<String, Value>,
1215}
1216
1217#[derive(Debug, Clone, Serialize, Deserialize)]
1219pub struct UserInfo {
1220 pub sub: String,
1221 #[serde(skip_serializing_if = "Option::is_none")]
1222 pub name: Option<String>,
1223 #[serde(skip_serializing_if = "Option::is_none")]
1224 pub given_name: Option<String>,
1225 #[serde(skip_serializing_if = "Option::is_none")]
1226 pub family_name: Option<String>,
1227 #[serde(skip_serializing_if = "Option::is_none")]
1228 pub middle_name: Option<String>,
1229 #[serde(skip_serializing_if = "Option::is_none")]
1230 pub nickname: Option<String>,
1231 #[serde(skip_serializing_if = "Option::is_none")]
1232 pub preferred_username: Option<String>,
1233 #[serde(skip_serializing_if = "Option::is_none")]
1234 pub profile: Option<String>,
1235 #[serde(skip_serializing_if = "Option::is_none")]
1236 pub picture: Option<String>,
1237 #[serde(skip_serializing_if = "Option::is_none")]
1238 pub website: Option<String>,
1239 #[serde(skip_serializing_if = "Option::is_none")]
1240 pub email: Option<String>,
1241 #[serde(skip_serializing_if = "Option::is_none")]
1242 pub email_verified: Option<bool>,
1243 #[serde(skip_serializing_if = "Option::is_none")]
1244 pub gender: Option<String>,
1245 #[serde(skip_serializing_if = "Option::is_none")]
1246 pub birthdate: Option<String>,
1247 #[serde(skip_serializing_if = "Option::is_none")]
1248 pub zoneinfo: Option<String>,
1249 #[serde(skip_serializing_if = "Option::is_none")]
1250 pub locale: Option<String>,
1251 #[serde(skip_serializing_if = "Option::is_none")]
1252 pub phone_number: Option<String>,
1253 #[serde(skip_serializing_if = "Option::is_none")]
1254 pub phone_number_verified: Option<bool>,
1255 #[serde(skip_serializing_if = "Option::is_none")]
1256 pub address: Option<Address>,
1257 #[serde(skip_serializing_if = "Option::is_none")]
1258 pub updated_at: Option<u64>,
1259 #[serde(flatten)]
1260 pub additional_claims: HashMap<String, Value>,
1261}
1262
1263#[derive(Debug, Clone, Serialize, Deserialize)]
1265pub struct Address {
1266 #[serde(skip_serializing_if = "Option::is_none")]
1267 pub formatted: Option<String>,
1268 #[serde(skip_serializing_if = "Option::is_none")]
1269 pub street_address: Option<String>,
1270 #[serde(skip_serializing_if = "Option::is_none")]
1271 pub locality: Option<String>,
1272 #[serde(skip_serializing_if = "Option::is_none")]
1273 pub region: Option<String>,
1274 #[serde(skip_serializing_if = "Option::is_none")]
1275 pub postal_code: Option<String>,
1276 #[serde(skip_serializing_if = "Option::is_none")]
1277 pub country: Option<String>,
1278}
1279
1280#[derive(Debug, Clone, Serialize, Deserialize)]
1282pub struct OidcDiscoveryDocument {
1283 pub issuer: String,
1284 pub authorization_endpoint: String,
1285 pub token_endpoint: String,
1286 pub userinfo_endpoint: String,
1287 pub jwks_uri: String,
1288 #[serde(skip_serializing_if = "Option::is_none")]
1289 pub registration_endpoint: Option<String>,
1290 pub scopes_supported: Vec<String>,
1291 pub response_types_supported: Vec<String>,
1292 #[serde(skip_serializing_if = "Option::is_none")]
1293 pub response_modes_supported: Option<Vec<String>>,
1294 #[serde(skip_serializing_if = "Option::is_none")]
1295 pub grant_types_supported: Option<Vec<String>>,
1296 pub subject_types_supported: Vec<SubjectType>,
1297 pub id_token_signing_alg_values_supported: Vec<String>,
1298 #[serde(skip_serializing_if = "Option::is_none")]
1299 pub userinfo_signing_alg_values_supported: Option<Vec<String>>,
1300 #[serde(skip_serializing_if = "Option::is_none")]
1301 pub token_endpoint_auth_methods_supported: Option<Vec<String>>,
1302 #[serde(skip_serializing_if = "Option::is_none")]
1303 pub claims_supported: Option<Vec<String>>,
1304 #[serde(skip_serializing_if = "Option::is_none")]
1305 pub claims_parameter_supported: Option<bool>,
1306 #[serde(skip_serializing_if = "Option::is_none")]
1307 pub request_parameter_supported: Option<bool>,
1308 #[serde(skip_serializing_if = "Option::is_none")]
1309 pub request_uri_parameter_supported: Option<bool>,
1310 #[serde(skip_serializing_if = "Option::is_none")]
1311 pub code_challenge_methods_supported: Option<Vec<String>>,
1312}
1313
1314#[derive(Debug, Clone, Serialize, Deserialize)]
1316pub struct JwkSet {
1317 pub keys: Vec<Jwk>,
1318}
1319
1320#[derive(Debug, Clone, Serialize, Deserialize)]
1322pub struct Jwk {
1323 pub kty: String,
1324 #[serde(rename = "use", skip_serializing_if = "Option::is_none")]
1325 pub use_: Option<String>,
1326 #[serde(skip_serializing_if = "Option::is_none")]
1327 pub key_ops: Option<Vec<String>>,
1328 #[serde(skip_serializing_if = "Option::is_none")]
1329 pub alg: Option<String>,
1330 #[serde(skip_serializing_if = "Option::is_none")]
1331 pub kid: Option<String>,
1332 pub n: String,
1333 pub e: String,
1334 #[serde(flatten)]
1335 pub additional_params: HashMap<String, Value>,
1336}
1337
1338#[derive(Debug, Clone)]
1340pub struct LogoutResponse {
1341 pub post_logout_redirect_uri: Option<String>,
1342 pub state: Option<String>,
1343}
1344
1345fn algorithm_to_string(alg: &Algorithm) -> String {
1347 match alg {
1348 Algorithm::HS256 => "HS256".to_string(),
1349 Algorithm::HS384 => "HS384".to_string(),
1350 Algorithm::HS512 => "HS512".to_string(),
1351 Algorithm::ES256 => "ES256".to_string(),
1352 Algorithm::ES384 => "ES384".to_string(),
1353 Algorithm::RS256 => "RS256".to_string(),
1354 Algorithm::RS384 => "RS384".to_string(),
1355 Algorithm::RS512 => "RS512".to_string(),
1356 Algorithm::PS256 => "PS256".to_string(),
1357 Algorithm::PS384 => "PS384".to_string(),
1358 Algorithm::PS512 => "PS512".to_string(),
1359 Algorithm::EdDSA => "EdDSA".to_string(),
1360 }
1361}
1362
1363#[cfg(test)]
1364mod tests {
1365 use super::*;
1366 use crate::storage::MemoryStorage;
1367
1368 async fn create_test_oidc_provider() -> OidcProvider<MemoryStorage> {
1369 let config = OidcConfig::default();
1370 let token_manager = Arc::new(TokenManager::new_hmac(
1371 b"test_secret_key_32_bytes_long!!!!",
1372 "test_issuer",
1373 "test_audience",
1374 ));
1375 let storage = Arc::new(MemoryStorage::new());
1376
1377 let client_registry = Arc::new(
1379 crate::server::core::client_registry::ClientRegistry::new(
1380 storage.clone() as Arc<dyn crate::storage::AuthStorage>
1381 )
1382 .await
1383 .unwrap(),
1384 );
1385 let test_client = crate::client::ClientConfig {
1386 client_id: "test_client".to_string(),
1387 client_secret: Some("test_secret".to_string()),
1388 client_type: crate::client::ClientType::Confidential,
1389 redirect_uris: vec!["https://client.example.com/callback".to_string()].into(),
1390 authorized_scopes: vec![
1391 "openid".to_string(),
1392 "profile".to_string(),
1393 "email".to_string(),
1394 ]
1395 .into(),
1396 authorized_grant_types: vec!["authorization_code".to_string()].into(),
1397 authorized_response_types: vec!["code".to_string()].into(),
1398 client_name: Some("Test Client".to_string()),
1399 client_description: None,
1400 metadata: std::collections::HashMap::new(),
1401 };
1402 client_registry.register_client(test_client).await.unwrap();
1403
1404 let mut provider = OidcProvider::new(config, token_manager, storage)
1405 .await
1406 .unwrap();
1407 provider.set_client_registry(client_registry);
1408 provider
1409 }
1410
1411 #[tokio::test]
1412 async fn test_oidc_provider_creation() {
1413 let provider = create_test_oidc_provider().await;
1414 assert_eq!(provider.config.issuer, "https://auth.example.com");
1415 assert!(
1416 provider
1417 .config
1418 .scopes_supported
1419 .contains(&"openid".to_string())
1420 );
1421 }
1422
1423 #[tokio::test]
1424 async fn test_discovery_document() {
1425 let provider = create_test_oidc_provider().await;
1426 let discovery = provider.discovery_document().unwrap();
1427
1428 assert_eq!(discovery.issuer, "https://auth.example.com");
1429 assert_eq!(
1430 discovery.authorization_endpoint,
1431 "https://auth.example.com/oidc/authorize"
1432 );
1433 assert!(discovery.scopes_supported.contains(&"openid".to_string()));
1434 assert!(
1435 discovery
1436 .response_types_supported
1437 .contains(&"code".to_string())
1438 );
1439 }
1440
1441 #[tokio::test]
1442 async fn test_authorization_request_validation() {
1443 let provider = create_test_oidc_provider().await;
1444
1445 let valid_request = OidcAuthorizationRequest {
1446 response_type: "code".to_string(),
1447 client_id: "test_client".to_string(),
1448 redirect_uri: "https://client.example.com/callback".to_string(),
1449 scope: "openid profile email".to_string(),
1450 state: Some("abc123".to_string()),
1451 nonce: Some("xyz789".to_string()),
1452 max_age: None,
1453 ui_locales: None,
1454 claims_locales: None,
1455 id_token_hint: None,
1456 login_hint: None,
1457 acr_values: None,
1458 claims: None,
1459 request: None,
1460 request_uri: None,
1461 };
1462
1463 let result = provider
1464 .validate_authorization_request(&valid_request)
1465 .await
1466 .unwrap();
1467 assert!(result.valid);
1468 assert_eq!(result.client_id, "test_client");
1469 assert_eq!(result.scope, "openid profile email");
1470 }
1471
1472 #[tokio::test]
1473 async fn test_authorization_request_missing_openid_scope() {
1474 let provider = create_test_oidc_provider().await;
1475
1476 let invalid_request = OidcAuthorizationRequest {
1477 response_type: "code".to_string(),
1478 client_id: "test_client".to_string(),
1479 redirect_uri: "https://client.example.com/callback".to_string(),
1480 scope: "profile email".to_string(), state: Some("abc123".to_string()),
1482 nonce: Some("xyz789".to_string()),
1483 max_age: None,
1484 ui_locales: None,
1485 claims_locales: None,
1486 id_token_hint: None,
1487 login_hint: None,
1488 acr_values: None,
1489 claims: None,
1490 request: None,
1491 request_uri: None,
1492 };
1493
1494 let result = provider
1495 .validate_authorization_request(&invalid_request)
1496 .await;
1497 assert!(result.is_err());
1498 }
1499
1500 #[tokio::test]
1501 async fn test_id_token_creation() {
1502 let provider = create_test_oidc_provider().await;
1503
1504 let auth_time = SystemTime::now();
1505 let mut claims = HashMap::new();
1506 claims.insert("name".to_string(), Value::String("John Doe".to_string()));
1507 claims.insert(
1508 "email".to_string(),
1509 Value::String("john@example.com".to_string()),
1510 );
1511
1512 use crate::server::oidc::core::IdTokenRequest;
1513 let id_token = provider
1514 .create_id_token(
1515 IdTokenRequest::new("user123", "client456")
1516 .with_nonce("nonce789")
1517 .with_auth_time(auth_time)
1518 .with_claims(&claims),
1519 )
1520 .await
1521 .unwrap();
1522
1523 assert!(!id_token.is_empty());
1524 assert!(id_token.contains('.'));
1525 }
1526
1527 #[tokio::test]
1528 async fn test_jwks_generation() {
1529 let provider = create_test_oidc_provider().await;
1530 let jwks = provider.generate_jwks().unwrap();
1531
1532 assert!(jwks.keys.is_empty());
1533 }
1534
1535 #[tokio::test]
1536 async fn test_logout_handling() {
1537 let provider = create_test_oidc_provider().await;
1538
1539 let logout_response = provider
1541 .handle_logout(None, None, Some("state123"))
1542 .await
1543 .unwrap();
1544
1545 assert_eq!(logout_response.post_logout_redirect_uri, None);
1546 assert_eq!(logout_response.state, Some("state123".to_string()));
1547 }
1548
1549 #[test]
1550 fn test_subject_type_serialization() {
1551 let public = SubjectType::Public;
1552 let pairwise = SubjectType::Pairwise;
1553
1554 let public_json = serde_json::to_string(&public).unwrap();
1555 let pairwise_json = serde_json::to_string(&pairwise).unwrap();
1556
1557 assert_eq!(public_json, "\"public\"");
1558 assert_eq!(pairwise_json, "\"pairwise\"");
1559 }
1560
1561 #[test]
1562 fn test_algorithm_to_string_conversion() {
1563 assert_eq!(algorithm_to_string(&Algorithm::RS256), "RS256");
1564 assert_eq!(algorithm_to_string(&Algorithm::ES256), "ES256");
1565 assert_eq!(algorithm_to_string(&Algorithm::HS256), "HS256");
1566 assert_eq!(algorithm_to_string(&Algorithm::EdDSA), "EdDSA");
1567 }
1568
1569 #[test]
1570 fn test_oidc_config_default() {
1571 let config = OidcConfig::default();
1572 assert_eq!(config.issuer, "https://auth.example.com");
1573 assert!(config.scopes_supported.contains(&"openid".to_string()));
1574 assert!(config.claims_supported.contains(&"sub".to_string()));
1575 assert_eq!(config.subject_types_supported, vec![SubjectType::Public]);
1576 }
1577}