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_typed_jwt_token(
565 subject,
566 vec!["openid".to_string()],
567 Some(Duration::from_secs(3600)),
568 "id_token",
569 )
570 .map_err(|e| AuthError::auth_method("oidc", format!("JWT creation failed: {}", e)))?;
571
572 Ok(token)
573 }
574
575 pub async fn validate_authorization_request(
577 &self,
578 request: &OidcAuthorizationRequest,
579 ) -> Result<AuthorizationValidationResult> {
580 if !request.scope.split_whitespace().any(|s| s == "openid") {
582 return Err(AuthError::auth_method(
583 "oidc",
584 "Missing required 'openid' scope",
585 ));
586 }
587
588 match &request.state {
590 None => {
591 return Err(AuthError::auth_method(
592 "oidc",
593 "Missing required 'state' parameter",
594 ));
595 }
596 Some(s) if s.is_empty() => {
597 return Err(AuthError::auth_method(
598 "oidc",
599 "The 'state' parameter must not be empty",
600 ));
601 }
602 _ => {}
603 }
604
605 if !self
607 .config
608 .response_types_supported
609 .contains(&request.response_type)
610 {
611 return Err(AuthError::auth_method(
612 "oidc",
613 format!("Unsupported response_type: {}", request.response_type),
614 ));
615 }
616
617 {
620 let rt = &request.response_type;
621 if rt.split_whitespace().any(|part| part == "token")
622 && !rt.split_whitespace().any(|part| part == "code")
623 {
624 return Err(AuthError::auth_method(
625 "oidc",
626 "Implicit grant (response_type containing 'token' without 'code') is not permitted",
627 ));
628 }
629 }
630
631 if request.client_id.is_empty() {
633 return Err(AuthError::auth_method("oidc", "Missing client_id"));
634 }
635
636 if let Some(client_registry) = &self.client_registry {
638 if client_registry
639 .get_client(&request.client_id)
640 .await?
641 .is_none()
642 {
643 return Err(AuthError::auth_method("oidc", "Invalid client_id"));
644 }
645
646 if !client_registry
648 .validate_redirect_uri(&request.client_id, &request.redirect_uri)
649 .await?
650 {
651 return Err(AuthError::auth_method(
652 "oidc",
653 "Invalid redirect_uri for client",
654 ));
655 }
656
657 for scope in request.scope.split_whitespace() {
659 if !client_registry
660 .validate_scope(&request.client_id, scope)
661 .await?
662 {
663 return Err(AuthError::auth_method(
664 "oidc",
665 format!("Client is not authorized for scope '{}'", scope),
666 ));
667 }
668 }
669 } else {
670 return Err(AuthError::auth_method(
674 "oidc",
675 "Client registry is required for authorization requests",
676 ));
677 }
678
679 for scope in request.scope.split_whitespace() {
681 if !self.config.scopes_supported.contains(&scope.to_string()) {
682 return Err(AuthError::auth_method(
683 "oidc",
684 format!("Unsupported scope '{}'", scope),
685 ));
686 }
687 }
688
689 Ok(AuthorizationValidationResult {
690 valid: true,
691 client_id: request.client_id.clone(),
692 redirect_uri: request.redirect_uri.clone(),
693 scope: request.scope.clone(),
694 state: request.state.clone(),
695 nonce: request.nonce.clone(),
696 max_age: request.max_age,
697 response_type: request.response_type.clone(),
698 })
699 }
700
701 pub async fn get_userinfo(&self, access_token: &str) -> Result<UserInfo> {
703 let token_claims = self
705 .token_manager
706 .validate_jwt_token(access_token)
707 .map_err(|e| AuthError::auth_method("oidc", format!("Invalid access token: {}", e)))?;
708 if token_claims.token_use().is_some() {
709 return Err(AuthError::auth_method(
710 "oidc",
711 "Invalid access token: only an access token can be used here",
712 ));
713 }
714 match self
716 .storage
717 .get_kv(&format!("revoked_token:{}", token_claims.jti))
718 .await
719 {
720 Ok(None) => {}
721 Ok(Some(_)) => {
722 return Err(AuthError::auth_method(
723 "oidc",
724 "Invalid access token: it has been revoked",
725 ));
726 }
727 Err(e) => {
728 tracing::error!("Could not check token revocation list: {}", e);
729 return Err(AuthError::auth_method(
730 "oidc",
731 "Unable to verify access token status",
732 ));
733 }
734 }
735
736 match self
739 .storage
740 .get_kv(&format!("user:{}", token_claims.sub))
741 .await
742 {
743 Ok(Some(bytes)) => {
744 let record: serde_json::Value = serde_json::from_slice(&bytes)
745 .map_err(|_| AuthError::auth_method("oidc", "Unable to verify the account"))?;
746 if record["active"].as_bool() == Some(false) {
747 return Err(AuthError::auth_method(
748 "oidc",
749 "The account has been deactivated",
750 ));
751 }
752 }
753 Ok(None) => {
754 return Err(AuthError::auth_method("oidc", "Unknown account"));
755 }
756 Err(e) => {
757 tracing::error!("Could not read the account record: {}", e);
758 return Err(AuthError::auth_method(
759 "oidc",
760 "Unable to verify the account",
761 ));
762 }
763 }
764
765 let subject = &token_claims.sub;
767
768 let user_key = format!("user:{}", subject);
770 if let Some(user_data) = self.storage.get_kv(&user_key).await? {
771 let user_str = std::str::from_utf8(&user_data).unwrap_or("{}");
772 let user_profile: HashMap<String, Value> =
773 serde_json::from_str(user_str).unwrap_or_default();
774
775 Ok(UserInfo {
776 sub: subject.clone(),
777 name: user_profile
778 .get("name")
779 .and_then(|v| v.as_str())
780 .map(|s| s.to_string()),
781 given_name: user_profile
782 .get("given_name")
783 .and_then(|v| v.as_str())
784 .map(|s| s.to_string()),
785 family_name: user_profile
786 .get("family_name")
787 .and_then(|v| v.as_str())
788 .map(|s| s.to_string()),
789 middle_name: user_profile
790 .get("middle_name")
791 .and_then(|v| v.as_str())
792 .map(|s| s.to_string()),
793 nickname: user_profile
794 .get("nickname")
795 .and_then(|v| v.as_str())
796 .map(|s| s.to_string()),
797 preferred_username: user_profile
798 .get("preferred_username")
799 .and_then(|v| v.as_str())
800 .map(|s| s.to_string()),
801 profile: user_profile
802 .get("profile")
803 .and_then(|v| v.as_str())
804 .map(|s| s.to_string()),
805 picture: user_profile
806 .get("picture")
807 .and_then(|v| v.as_str())
808 .map(|s| s.to_string()),
809 website: user_profile
810 .get("website")
811 .and_then(|v| v.as_str())
812 .map(|s| s.to_string()),
813 email: user_profile
814 .get("email")
815 .and_then(|v| v.as_str())
816 .map(|s| s.to_string()),
817 email_verified: user_profile.get("email_verified").and_then(|v| v.as_bool()),
818 gender: user_profile
819 .get("gender")
820 .and_then(|v| v.as_str())
821 .map(|s| s.to_string()),
822 birthdate: user_profile
823 .get("birthdate")
824 .and_then(|v| v.as_str())
825 .map(|s| s.to_string()),
826 zoneinfo: user_profile
827 .get("zoneinfo")
828 .and_then(|v| v.as_str())
829 .map(|s| s.to_string()),
830 locale: user_profile
831 .get("locale")
832 .and_then(|v| v.as_str())
833 .map(|s| s.to_string()),
834 phone_number: user_profile
835 .get("phone_number")
836 .and_then(|v| v.as_str())
837 .map(|s| s.to_string()),
838 phone_number_verified: user_profile
839 .get("phone_number_verified")
840 .and_then(|v| v.as_bool()),
841 address: user_profile
842 .get("address")
843 .and_then(|addr| addr.as_object())
844 .map(|addr_obj| Address {
845 formatted: addr_obj
846 .get("formatted")
847 .and_then(|v| v.as_str())
848 .map(|s| s.to_string()),
849 street_address: addr_obj
850 .get("street_address")
851 .and_then(|v| v.as_str())
852 .map(|s| s.to_string()),
853 locality: addr_obj
854 .get("locality")
855 .and_then(|v| v.as_str())
856 .map(|s| s.to_string()),
857 region: addr_obj
858 .get("region")
859 .and_then(|v| v.as_str())
860 .map(|s| s.to_string()),
861 postal_code: addr_obj
862 .get("postal_code")
863 .and_then(|v| v.as_str())
864 .map(|s| s.to_string()),
865 country: addr_obj
866 .get("country")
867 .and_then(|v| v.as_str())
868 .map(|s| s.to_string()),
869 }),
870 updated_at: user_profile.get("updated_at").and_then(|v| v.as_u64()),
871 additional_claims: user_profile
872 .into_iter()
873 .filter(|(k, _)| {
874 ![
875 "sub",
876 "name",
877 "given_name",
878 "family_name",
879 "middle_name",
880 "nickname",
881 "preferred_username",
882 "profile",
883 "picture",
884 "website",
885 "email",
886 "email_verified",
887 "gender",
888 "birthdate",
889 "zoneinfo",
890 "locale",
891 "phone_number",
892 "phone_number_verified",
893 "address",
894 "updated_at",
895 ]
896 .contains(&k.as_str())
897 })
898 .collect(),
899 })
900 } else {
901 Ok(UserInfo {
903 sub: subject.clone(),
904 name: None,
905 given_name: None,
906 family_name: None,
907 middle_name: None,
908 nickname: None,
909 preferred_username: Some(subject.clone()),
910 profile: None,
911 picture: None,
912 website: None,
913 email: None,
914 email_verified: None,
915 gender: None,
916 birthdate: None,
917 zoneinfo: None,
918 locale: None,
919 phone_number: None,
920 phone_number_verified: None,
921 address: None,
922 updated_at: None,
923 additional_claims: HashMap::new(),
924 })
925 }
926 }
927
928 pub async fn handle_logout(
930 &self,
931 id_token_hint: Option<&str>,
932 post_logout_redirect_uri: Option<&str>,
933 state: Option<&str>,
934 ) -> Result<LogoutResponse> {
935 if let Some(id_token) = id_token_hint {
937 let claims = self
938 .token_manager
939 .validate_jwt_token(id_token)
940 .map_err(|e| AuthError::auth_method("oidc", format!("Invalid ID token: {}", e)))?;
941
942 let user_sessions = self
944 .storage
945 .list_user_sessions(&claims.sub)
946 .await
947 .map_err(|e| AuthError::internal(format!("Failed to list user sessions: {}", e)))?;
948
949 for session in user_sessions {
950 self.storage
951 .delete_session(&session.session_id)
952 .await
953 .map_err(|e| AuthError::internal(format!("Failed to delete session: {}", e)))?;
954 }
955 }
956
957 if let Some(post_logout_uri) = post_logout_redirect_uri {
959 if let Some(id_token) = id_token_hint {
961 let claims = self
962 .token_manager
963 .validate_jwt_token(id_token)
964 .map_err(|e| {
965 AuthError::auth_method("oidc", format!("Invalid ID token: {}", e))
966 })?;
967
968 if let Some(aud) = claims.aud.split_whitespace().next() {
969 if !self
971 .is_post_logout_uri_registered(aud, post_logout_uri)
972 .await?
973 {
974 return Err(AuthError::validation(
975 "post_logout_redirect_uri not registered for client",
976 ));
977 }
978 }
979 } else {
980 return Err(AuthError::validation(
983 "id_token_hint required for post_logout_redirect_uri validation",
984 ));
985 }
986 }
987
988 Ok(LogoutResponse {
989 post_logout_redirect_uri: post_logout_redirect_uri.map(|uri| uri.to_string()),
990 state: state.map(|s| s.to_string()),
991 })
992 }
993
994 async fn is_post_logout_uri_registered(&self, client_id: &str, uri: &str) -> Result<bool> {
996 if !uri.starts_with("https://")
1000 && !uri.starts_with("http://localhost")
1001 && !uri.starts_with("http://127.0.0.1")
1002 {
1003 tracing::warn!(
1004 "Rejected post-logout redirect URI with invalid scheme: {}",
1005 uri
1006 );
1007 return Ok(false);
1008 }
1009
1010 match self.get_client_registered_post_logout_uris(client_id).await {
1012 Ok(registered_uris) => {
1013 let is_registered = registered_uris.contains(&uri.to_string());
1014 if !is_registered {
1015 tracing::warn!(
1016 "Rejected unregistered post-logout redirect URI for client {}: {}",
1017 client_id,
1018 uri
1019 );
1020 }
1021 Ok(is_registered)
1022 }
1023 Err(_) => {
1024 tracing::error!(
1028 "Rejected redirect URI — client lookup failed for {}: {}",
1029 client_id,
1030 uri
1031 );
1032 Ok(false)
1033 }
1034 }
1035 }
1036
1037 async fn get_client_registered_post_logout_uris(&self, client_id: &str) -> Result<Vec<String>> {
1039 if let Some(client_registry) = &self.client_registry
1041 && let Some(client) = client_registry.get_client(client_id).await?
1042 {
1043 if let Some(uris) = client.metadata.get("post_logout_redirect_uris")
1045 && let Some(arr) = uris.as_array()
1046 {
1047 return Ok(arr
1048 .iter()
1049 .filter_map(|v| v.as_str().map(|s| s.to_string()))
1050 .collect());
1051 }
1052 }
1053 Ok(Vec::new())
1056 }
1057
1058 pub fn generate_jwks(&self) -> Result<JwkSet> {
1060 let keys = self
1061 .token_manager
1062 .export_public_jwks()?
1063 .into_iter()
1064 .map(|key| Jwk {
1065 kty: "RSA".to_string(),
1066 use_: Some("sig".to_string()),
1067 key_ops: Some(vec!["verify".to_string()]),
1068 alg: Some(algorithm_to_string(&key.algorithm)),
1069 kid: Some(key.kid),
1070 n: key.n,
1071 e: key.e,
1072 additional_params: HashMap::new(),
1073 })
1074 .collect();
1075
1076 Ok(JwkSet { keys })
1077 }
1078}
1079
1080#[derive(Debug, Clone, Serialize, Deserialize)]
1082pub struct OidcAuthorizationRequest {
1083 pub response_type: String,
1084 pub client_id: String,
1085 pub redirect_uri: String,
1086 pub scope: String,
1087 pub state: Option<String>,
1088 pub nonce: Option<String>,
1089 pub max_age: Option<u64>,
1090 pub ui_locales: Option<String>,
1091 pub claims_locales: Option<String>,
1092 pub id_token_hint: Option<String>,
1093 pub login_hint: Option<String>,
1094 pub acr_values: Option<String>,
1095 pub claims: Option<String>,
1096 pub request: Option<String>,
1097 pub request_uri: Option<String>,
1098}
1099
1100impl OidcAuthorizationRequest {
1101 pub fn builder(
1105 client_id: impl Into<String>,
1106 redirect_uri: impl Into<String>,
1107 ) -> OidcAuthorizationRequestBuilder {
1108 OidcAuthorizationRequestBuilder::new(client_id, redirect_uri)
1109 }
1110}
1111
1112pub struct OidcAuthorizationRequestBuilder {
1129 req: OidcAuthorizationRequest,
1130}
1131
1132impl OidcAuthorizationRequestBuilder {
1133 fn new(client_id: impl Into<String>, redirect_uri: impl Into<String>) -> Self {
1134 Self {
1135 req: OidcAuthorizationRequest {
1136 response_type: "code".to_string(),
1137 client_id: client_id.into(),
1138 redirect_uri: redirect_uri.into(),
1139 scope: "openid".to_string(),
1140 state: None,
1141 nonce: None,
1142 max_age: None,
1143 ui_locales: None,
1144 claims_locales: None,
1145 id_token_hint: None,
1146 login_hint: None,
1147 acr_values: None,
1148 claims: None,
1149 request: None,
1150 request_uri: None,
1151 },
1152 }
1153 }
1154
1155 pub fn response_type(mut self, rt: impl Into<String>) -> Self {
1157 self.req.response_type = rt.into();
1158 self
1159 }
1160
1161 pub fn scope(mut self, scope: impl Into<String>) -> Self {
1163 self.req.scope = scope.into();
1164 self
1165 }
1166
1167 pub fn state(mut self, state: impl Into<String>) -> Self {
1169 self.req.state = Some(state.into());
1170 self
1171 }
1172
1173 pub fn nonce(mut self, nonce: impl Into<String>) -> Self {
1175 self.req.nonce = Some(nonce.into());
1176 self
1177 }
1178
1179 pub fn max_age(mut self, seconds: u64) -> Self {
1181 self.req.max_age = Some(seconds);
1182 self
1183 }
1184
1185 pub fn login_hint(mut self, hint: impl Into<String>) -> Self {
1187 self.req.login_hint = Some(hint.into());
1188 self
1189 }
1190
1191 pub fn id_token_hint(mut self, hint: impl Into<String>) -> Self {
1193 self.req.id_token_hint = Some(hint.into());
1194 self
1195 }
1196
1197 pub fn acr_values(mut self, values: impl Into<String>) -> Self {
1199 self.req.acr_values = Some(values.into());
1200 self
1201 }
1202
1203 pub fn build(self) -> OidcAuthorizationRequest {
1205 self.req
1206 }
1207}
1208
1209#[derive(Debug, Clone)]
1211pub struct AuthorizationValidationResult {
1212 pub valid: bool,
1213 pub client_id: String,
1214 pub redirect_uri: String,
1215 pub scope: String,
1216 pub state: Option<String>,
1217 pub nonce: Option<String>,
1218 pub max_age: Option<u64>,
1219 pub response_type: String,
1220}
1221
1222#[derive(Debug, Clone, Serialize, Deserialize)]
1224pub struct IdTokenClaims {
1225 pub iss: String,
1227 pub sub: String,
1229 pub aud: Vec<String>,
1231 pub exp: u64,
1233 pub iat: u64,
1235 #[serde(skip_serializing_if = "Option::is_none")]
1237 pub auth_time: Option<u64>,
1238 #[serde(skip_serializing_if = "Option::is_none")]
1240 pub nonce: Option<String>,
1241 #[serde(flatten)]
1243 pub additional_claims: HashMap<String, Value>,
1244}
1245
1246#[derive(Debug, Clone, Serialize, Deserialize)]
1248pub struct UserInfo {
1249 pub sub: String,
1250 #[serde(skip_serializing_if = "Option::is_none")]
1251 pub name: Option<String>,
1252 #[serde(skip_serializing_if = "Option::is_none")]
1253 pub given_name: Option<String>,
1254 #[serde(skip_serializing_if = "Option::is_none")]
1255 pub family_name: Option<String>,
1256 #[serde(skip_serializing_if = "Option::is_none")]
1257 pub middle_name: Option<String>,
1258 #[serde(skip_serializing_if = "Option::is_none")]
1259 pub nickname: Option<String>,
1260 #[serde(skip_serializing_if = "Option::is_none")]
1261 pub preferred_username: Option<String>,
1262 #[serde(skip_serializing_if = "Option::is_none")]
1263 pub profile: Option<String>,
1264 #[serde(skip_serializing_if = "Option::is_none")]
1265 pub picture: Option<String>,
1266 #[serde(skip_serializing_if = "Option::is_none")]
1267 pub website: Option<String>,
1268 #[serde(skip_serializing_if = "Option::is_none")]
1269 pub email: Option<String>,
1270 #[serde(skip_serializing_if = "Option::is_none")]
1271 pub email_verified: Option<bool>,
1272 #[serde(skip_serializing_if = "Option::is_none")]
1273 pub gender: Option<String>,
1274 #[serde(skip_serializing_if = "Option::is_none")]
1275 pub birthdate: Option<String>,
1276 #[serde(skip_serializing_if = "Option::is_none")]
1277 pub zoneinfo: Option<String>,
1278 #[serde(skip_serializing_if = "Option::is_none")]
1279 pub locale: Option<String>,
1280 #[serde(skip_serializing_if = "Option::is_none")]
1281 pub phone_number: Option<String>,
1282 #[serde(skip_serializing_if = "Option::is_none")]
1283 pub phone_number_verified: Option<bool>,
1284 #[serde(skip_serializing_if = "Option::is_none")]
1285 pub address: Option<Address>,
1286 #[serde(skip_serializing_if = "Option::is_none")]
1287 pub updated_at: Option<u64>,
1288 #[serde(flatten)]
1289 pub additional_claims: HashMap<String, Value>,
1290}
1291
1292#[derive(Debug, Clone, Serialize, Deserialize)]
1294pub struct Address {
1295 #[serde(skip_serializing_if = "Option::is_none")]
1296 pub formatted: Option<String>,
1297 #[serde(skip_serializing_if = "Option::is_none")]
1298 pub street_address: Option<String>,
1299 #[serde(skip_serializing_if = "Option::is_none")]
1300 pub locality: Option<String>,
1301 #[serde(skip_serializing_if = "Option::is_none")]
1302 pub region: Option<String>,
1303 #[serde(skip_serializing_if = "Option::is_none")]
1304 pub postal_code: Option<String>,
1305 #[serde(skip_serializing_if = "Option::is_none")]
1306 pub country: Option<String>,
1307}
1308
1309#[derive(Debug, Clone, Serialize, Deserialize)]
1311pub struct OidcDiscoveryDocument {
1312 pub issuer: String,
1313 pub authorization_endpoint: String,
1314 pub token_endpoint: String,
1315 pub userinfo_endpoint: String,
1316 pub jwks_uri: String,
1317 #[serde(skip_serializing_if = "Option::is_none")]
1318 pub registration_endpoint: Option<String>,
1319 pub scopes_supported: Vec<String>,
1320 pub response_types_supported: Vec<String>,
1321 #[serde(skip_serializing_if = "Option::is_none")]
1322 pub response_modes_supported: Option<Vec<String>>,
1323 #[serde(skip_serializing_if = "Option::is_none")]
1324 pub grant_types_supported: Option<Vec<String>>,
1325 pub subject_types_supported: Vec<SubjectType>,
1326 pub id_token_signing_alg_values_supported: Vec<String>,
1327 #[serde(skip_serializing_if = "Option::is_none")]
1328 pub userinfo_signing_alg_values_supported: Option<Vec<String>>,
1329 #[serde(skip_serializing_if = "Option::is_none")]
1330 pub token_endpoint_auth_methods_supported: Option<Vec<String>>,
1331 #[serde(skip_serializing_if = "Option::is_none")]
1332 pub claims_supported: Option<Vec<String>>,
1333 #[serde(skip_serializing_if = "Option::is_none")]
1334 pub claims_parameter_supported: Option<bool>,
1335 #[serde(skip_serializing_if = "Option::is_none")]
1336 pub request_parameter_supported: Option<bool>,
1337 #[serde(skip_serializing_if = "Option::is_none")]
1338 pub request_uri_parameter_supported: Option<bool>,
1339 #[serde(skip_serializing_if = "Option::is_none")]
1340 pub code_challenge_methods_supported: Option<Vec<String>>,
1341}
1342
1343#[derive(Debug, Clone, Serialize, Deserialize)]
1345pub struct JwkSet {
1346 pub keys: Vec<Jwk>,
1347}
1348
1349#[derive(Debug, Clone, Serialize, Deserialize)]
1351pub struct Jwk {
1352 pub kty: String,
1353 #[serde(rename = "use", skip_serializing_if = "Option::is_none")]
1354 pub use_: Option<String>,
1355 #[serde(skip_serializing_if = "Option::is_none")]
1356 pub key_ops: Option<Vec<String>>,
1357 #[serde(skip_serializing_if = "Option::is_none")]
1358 pub alg: Option<String>,
1359 #[serde(skip_serializing_if = "Option::is_none")]
1360 pub kid: Option<String>,
1361 pub n: String,
1362 pub e: String,
1363 #[serde(flatten)]
1364 pub additional_params: HashMap<String, Value>,
1365}
1366
1367#[derive(Debug, Clone)]
1369pub struct LogoutResponse {
1370 pub post_logout_redirect_uri: Option<String>,
1371 pub state: Option<String>,
1372}
1373
1374fn algorithm_to_string(alg: &Algorithm) -> String {
1376 match alg {
1377 Algorithm::HS256 => "HS256".to_string(),
1378 Algorithm::HS384 => "HS384".to_string(),
1379 Algorithm::HS512 => "HS512".to_string(),
1380 Algorithm::ES256 => "ES256".to_string(),
1381 Algorithm::ES384 => "ES384".to_string(),
1382 Algorithm::RS256 => "RS256".to_string(),
1383 Algorithm::RS384 => "RS384".to_string(),
1384 Algorithm::RS512 => "RS512".to_string(),
1385 Algorithm::PS256 => "PS256".to_string(),
1386 Algorithm::PS384 => "PS384".to_string(),
1387 Algorithm::PS512 => "PS512".to_string(),
1388 Algorithm::EdDSA => "EdDSA".to_string(),
1389 other => format!("{other:?}"),
1391 }
1392}
1393
1394#[cfg(test)]
1395mod tests {
1396 use super::*;
1397 use crate::storage::MemoryStorage;
1398
1399 #[test]
1401 fn algorithm_names_are_the_jose_names() {
1402 for (alg, want) in [
1403 (Algorithm::HS256, "HS256"),
1404 (Algorithm::HS384, "HS384"),
1405 (Algorithm::HS512, "HS512"),
1406 (Algorithm::ES256, "ES256"),
1407 (Algorithm::ES384, "ES384"),
1408 (Algorithm::RS256, "RS256"),
1409 (Algorithm::RS384, "RS384"),
1410 (Algorithm::RS512, "RS512"),
1411 (Algorithm::PS256, "PS256"),
1412 (Algorithm::PS384, "PS384"),
1413 (Algorithm::PS512, "PS512"),
1414 (Algorithm::EdDSA, "EdDSA"),
1415 ] {
1416 assert_eq!(algorithm_to_string(&alg), want);
1417 }
1418 }
1419
1420 #[tokio::test]
1421 async fn userinfo_refuses_a_deactivated_or_unknown_account() {
1422 let provider = create_test_oidc_provider().await;
1423 let tm = provider.token_manager.clone();
1424 let token_for = |sub: &str| {
1425 tm.create_jwt_token(
1426 sub,
1427 vec!["openid".into()],
1428 Some(std::time::Duration::from_secs(600)),
1429 )
1430 .unwrap()
1431 };
1432 provider
1433 .storage
1434 .store_kv(
1435 "user:gone",
1436 serde_json::json!({"id": "gone", "active": false})
1437 .to_string()
1438 .as_bytes(),
1439 None,
1440 )
1441 .await
1442 .unwrap();
1443 let err = provider
1444 .get_userinfo(&token_for("gone"))
1445 .await
1446 .unwrap_err()
1447 .to_string();
1448 assert!(err.to_lowercase().contains("deactivated"), "{err}");
1449 let err = provider
1450 .get_userinfo(&token_for("never-registered"))
1451 .await
1452 .unwrap_err()
1453 .to_string();
1454 assert!(err.to_lowercase().contains("unknown account"), "{err}");
1455 }
1456
1457 #[tokio::test]
1458 async fn userinfo_refuses_revoked_and_refresh_tokens() {
1459 let provider = create_test_oidc_provider().await;
1460 let tm = provider.token_manager.clone();
1461 let access = tm
1462 .create_jwt_token(
1463 "user_x",
1464 vec!["openid".into()],
1465 Some(std::time::Duration::from_secs(600)),
1466 )
1467 .unwrap();
1468 let refresh = tm
1469 .create_refresh_jwt_token("user_x", Some(std::time::Duration::from_secs(600)))
1470 .unwrap();
1471 assert!(
1472 provider.get_userinfo(&refresh).await.is_err(),
1473 "refresh JWT"
1474 );
1475
1476 let jti = tm.validate_jwt_token(&access).unwrap().jti;
1477 provider
1478 .storage
1479 .store_kv(&format!("revoked_token:{jti}"), b"revoked", None)
1480 .await
1481 .unwrap();
1482 let err = provider
1483 .get_userinfo(&access)
1484 .await
1485 .unwrap_err()
1486 .to_string();
1487 assert!(err.contains("revoked"), "{err}");
1488 }
1489
1490 async fn create_test_oidc_provider() -> OidcProvider<MemoryStorage> {
1491 let config = OidcConfig::default();
1492 let token_manager = Arc::new(TokenManager::new_hmac(
1493 b"test_secret_key_32_bytes_long!!!!",
1494 "test_issuer",
1495 "test_audience",
1496 ));
1497 let storage = Arc::new(MemoryStorage::new());
1498
1499 let client_registry = Arc::new(
1501 crate::server::core::client_registry::ClientRegistry::new(
1502 storage.clone() as Arc<dyn crate::storage::AuthStorage>
1503 )
1504 .await
1505 .unwrap(),
1506 );
1507 let test_client = crate::client::ClientConfig {
1508 client_id: "test_client".to_string(),
1509 client_secret: Some("test_secret".to_string()),
1510 client_type: crate::client::ClientType::Confidential,
1511 redirect_uris: vec!["https://client.example.com/callback".to_string()].into(),
1512 authorized_scopes: vec![
1513 "openid".to_string(),
1514 "profile".to_string(),
1515 "email".to_string(),
1516 ]
1517 .into(),
1518 authorized_grant_types: vec!["authorization_code".to_string()].into(),
1519 authorized_response_types: vec!["code".to_string()].into(),
1520 client_name: Some("Test Client".to_string()),
1521 client_description: None,
1522 metadata: std::collections::HashMap::new(),
1523 };
1524 client_registry.register_client(test_client).await.unwrap();
1525
1526 let mut provider = OidcProvider::new(config, token_manager, storage)
1527 .await
1528 .unwrap();
1529 provider.set_client_registry(client_registry);
1530 provider
1531 }
1532
1533 #[tokio::test]
1534 async fn test_oidc_provider_creation() {
1535 let provider = create_test_oidc_provider().await;
1536 assert_eq!(provider.config.issuer, "https://auth.example.com");
1537 assert!(
1538 provider
1539 .config
1540 .scopes_supported
1541 .contains(&"openid".to_string())
1542 );
1543 }
1544
1545 #[tokio::test]
1546 async fn test_discovery_document() {
1547 let provider = create_test_oidc_provider().await;
1548 let discovery = provider.discovery_document().unwrap();
1549
1550 assert_eq!(discovery.issuer, "https://auth.example.com");
1551 assert_eq!(
1552 discovery.authorization_endpoint,
1553 "https://auth.example.com/oidc/authorize"
1554 );
1555 assert!(discovery.scopes_supported.contains(&"openid".to_string()));
1556 assert!(
1557 discovery
1558 .response_types_supported
1559 .contains(&"code".to_string())
1560 );
1561 }
1562
1563 #[tokio::test]
1564 async fn test_authorization_request_validation() {
1565 let provider = create_test_oidc_provider().await;
1566
1567 let valid_request = OidcAuthorizationRequest {
1568 response_type: "code".to_string(),
1569 client_id: "test_client".to_string(),
1570 redirect_uri: "https://client.example.com/callback".to_string(),
1571 scope: "openid profile email".to_string(),
1572 state: Some("abc123".to_string()),
1573 nonce: Some("xyz789".to_string()),
1574 max_age: None,
1575 ui_locales: None,
1576 claims_locales: None,
1577 id_token_hint: None,
1578 login_hint: None,
1579 acr_values: None,
1580 claims: None,
1581 request: None,
1582 request_uri: None,
1583 };
1584
1585 let result = provider
1586 .validate_authorization_request(&valid_request)
1587 .await
1588 .unwrap();
1589 assert!(result.valid);
1590 assert_eq!(result.client_id, "test_client");
1591 assert_eq!(result.scope, "openid profile email");
1592 }
1593
1594 #[tokio::test]
1595 async fn test_authorization_request_missing_openid_scope() {
1596 let provider = create_test_oidc_provider().await;
1597
1598 let invalid_request = OidcAuthorizationRequest {
1599 response_type: "code".to_string(),
1600 client_id: "test_client".to_string(),
1601 redirect_uri: "https://client.example.com/callback".to_string(),
1602 scope: "profile email".to_string(), state: Some("abc123".to_string()),
1604 nonce: Some("xyz789".to_string()),
1605 max_age: None,
1606 ui_locales: None,
1607 claims_locales: None,
1608 id_token_hint: None,
1609 login_hint: None,
1610 acr_values: None,
1611 claims: None,
1612 request: None,
1613 request_uri: None,
1614 };
1615
1616 let result = provider
1617 .validate_authorization_request(&invalid_request)
1618 .await;
1619 assert!(result.is_err());
1620 }
1621
1622 #[tokio::test]
1623 async fn test_id_token_creation() {
1624 let provider = create_test_oidc_provider().await;
1625
1626 let auth_time = SystemTime::now();
1627 let mut claims = HashMap::new();
1628 claims.insert("name".to_string(), Value::String("John Doe".to_string()));
1629 claims.insert(
1630 "email".to_string(),
1631 Value::String("john@example.com".to_string()),
1632 );
1633
1634 use crate::server::oidc::core::IdTokenRequest;
1635 let id_token = provider
1636 .create_id_token(
1637 IdTokenRequest::new("user123", "client456")
1638 .with_nonce("nonce789")
1639 .with_auth_time(auth_time)
1640 .with_claims(&claims),
1641 )
1642 .await
1643 .unwrap();
1644
1645 assert!(!id_token.is_empty());
1646 assert!(id_token.contains('.'));
1647 }
1648
1649 #[tokio::test]
1650 async fn an_id_token_is_not_an_access_token() {
1651 use crate::server::oidc::core::IdTokenRequest;
1652 let provider = create_test_oidc_provider().await;
1653 let id_token = provider
1654 .create_id_token(IdTokenRequest::new("user123", "client456"))
1655 .await
1656 .unwrap();
1657 assert!(provider.token_manager.validate_jwt_token(&id_token).is_ok());
1659 let storage = MemoryStorage::new();
1661 assert!(
1662 crate::auth::validate_access_jwt_with(
1663 &provider.token_manager,
1664 &storage,
1665 &id_token,
1666 false,
1667 false
1668 )
1669 .await
1670 .is_err(),
1671 "an ID token must not be accepted as an access token"
1672 );
1673 let access = provider
1675 .token_manager
1676 .create_jwt_token("user123", vec!["openid".into()], None)
1677 .unwrap();
1678 assert!(
1679 crate::auth::validate_access_jwt_with(
1680 &provider.token_manager,
1681 &storage,
1682 &access,
1683 false,
1684 false
1685 )
1686 .await
1687 .is_ok()
1688 );
1689 }
1690
1691 #[tokio::test]
1692 async fn test_jwks_generation() {
1693 let provider = create_test_oidc_provider().await;
1694 let jwks = provider.generate_jwks().unwrap();
1695
1696 assert!(jwks.keys.is_empty());
1697 }
1698
1699 #[tokio::test]
1700 async fn test_logout_handling() {
1701 let provider = create_test_oidc_provider().await;
1702
1703 let logout_response = provider
1705 .handle_logout(None, None, Some("state123"))
1706 .await
1707 .unwrap();
1708
1709 assert_eq!(logout_response.post_logout_redirect_uri, None);
1710 assert_eq!(logout_response.state, Some("state123".to_string()));
1711 }
1712
1713 #[test]
1714 fn test_subject_type_serialization() {
1715 let public = SubjectType::Public;
1716 let pairwise = SubjectType::Pairwise;
1717
1718 let public_json = serde_json::to_string(&public).unwrap();
1719 let pairwise_json = serde_json::to_string(&pairwise).unwrap();
1720
1721 assert_eq!(public_json, "\"public\"");
1722 assert_eq!(pairwise_json, "\"pairwise\"");
1723 }
1724
1725 #[test]
1726 fn test_algorithm_to_string_conversion() {
1727 assert_eq!(algorithm_to_string(&Algorithm::RS256), "RS256");
1728 assert_eq!(algorithm_to_string(&Algorithm::ES256), "ES256");
1729 assert_eq!(algorithm_to_string(&Algorithm::HS256), "HS256");
1730 assert_eq!(algorithm_to_string(&Algorithm::EdDSA), "EdDSA");
1731 }
1732
1733 #[test]
1734 fn test_oidc_config_default() {
1735 let config = OidcConfig::default();
1736 assert_eq!(config.issuer, "https://auth.example.com");
1737 assert!(config.scopes_supported.contains(&"openid".to_string()));
1738 assert!(config.claims_supported.contains(&"sub".to_string()));
1739 assert_eq!(config.subject_types_supported, vec![SubjectType::Public]);
1740 }
1741}