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(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 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
1055pub 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 pub fn response_type(mut self, rt: impl Into<String>) -> Self {
1100 self.req.response_type = rt.into();
1101 self
1102 }
1103
1104 pub fn scope(mut self, scope: impl Into<String>) -> Self {
1106 self.req.scope = scope.into();
1107 self
1108 }
1109
1110 pub fn state(mut self, state: impl Into<String>) -> Self {
1112 self.req.state = Some(state.into());
1113 self
1114 }
1115
1116 pub fn nonce(mut self, nonce: impl Into<String>) -> Self {
1118 self.req.nonce = Some(nonce.into());
1119 self
1120 }
1121
1122 pub fn max_age(mut self, seconds: u64) -> Self {
1124 self.req.max_age = Some(seconds);
1125 self
1126 }
1127
1128 pub fn login_hint(mut self, hint: impl Into<String>) -> Self {
1130 self.req.login_hint = Some(hint.into());
1131 self
1132 }
1133
1134 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 pub fn acr_values(mut self, values: impl Into<String>) -> Self {
1142 self.req.acr_values = Some(values.into());
1143 self
1144 }
1145
1146 pub fn build(self) -> OidcAuthorizationRequest {
1148 self.req
1149 }
1150}
1151
1152#[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#[derive(Debug, Clone, Serialize, Deserialize)]
1167pub struct IdTokenClaims {
1168 pub iss: String,
1170 pub sub: String,
1172 pub aud: Vec<String>,
1174 pub exp: u64,
1176 pub iat: u64,
1178 #[serde(skip_serializing_if = "Option::is_none")]
1180 pub auth_time: Option<u64>,
1181 #[serde(skip_serializing_if = "Option::is_none")]
1183 pub nonce: Option<String>,
1184 #[serde(flatten)]
1186 pub additional_claims: HashMap<String, Value>,
1187}
1188
1189#[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#[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#[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#[derive(Debug, Clone, Serialize, Deserialize)]
1288pub struct JwkSet {
1289 pub keys: Vec<Jwk>,
1290}
1291
1292#[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#[derive(Debug, Clone)]
1312pub struct LogoutResponse {
1313 pub post_logout_redirect_uri: Option<String>,
1314 pub state: Option<String>,
1315}
1316
1317fn 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 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(), 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 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}