1use crate::errors::{AuthError, Result};
27use crate::server::oidc::OidcProvider;
28use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64_STANDARD};
29use chrono::{DateTime, Utc};
30use serde::{Deserialize, Serialize};
31use serde_json::{Value, json};
32use std::collections::HashMap;
33use std::sync::Arc;
34use std::time::SystemTime;
35use tokio::sync::RwLock;
36use uuid::Uuid;
37
38#[derive(Debug, Clone)]
40pub struct OidcExtensionsManager {
41 oidc_provider: Arc<OidcProvider<dyn crate::storage::AuthStorage>>,
43
44 heart_manager: Arc<HeartManager>,
46
47 shared_signals_manager: Arc<SharedSignalsManager>,
49
50 ekyc_manager: Arc<EkycManager>,
52
53 fastfed_manager: Arc<FastFedManager>,
55
56 config: OidcExtensionsConfig,
58}
59
60#[derive(Debug, Clone)]
62pub struct OidcExtensionsConfig {
63 pub enable_heart: bool,
65
66 pub enable_shared_signals: bool,
68
69 pub enable_ekyc: bool,
71
72 pub enable_fastfed: bool,
74
75 pub enable_modrna: bool,
77
78 pub enable_igov: bool,
80
81 pub enable_authzen: bool,
83}
84
85#[derive(Clone)]
89pub struct HeartManager {
90 config: HeartConfig,
92
93 sessions: Arc<RwLock<HashMap<String, HeartSession>>>,
95}
96
97impl std::fmt::Debug for HeartManager {
98 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
99 let mut d = f.debug_struct("HeartManager");
100 d.field("config", &self.config);
101 d.field("sessions", &crate::utils::redact::redacted(&self.sessions));
102 d.finish()
103 }
104}
105
106#[derive(Debug, Clone)]
108pub struct HeartConfig {
109 pub organization_id: String,
111
112 pub fhir_endpoint: String,
114
115 pub required_scopes: Vec<String>,
117
118 pub enhanced_consent: bool,
120
121 pub authorized_providers: Vec<String>,
123
124 pub audit_config: HeartAuditConfig,
126}
127
128#[derive(Debug, Clone)]
130pub struct HeartAuditConfig {
131 pub enable_atna: bool,
133
134 pub syslog_endpoint: Option<String>,
136
137 pub audit_level: HeartAuditLevel,
139}
140
141#[derive(Debug, Clone, PartialEq)]
143pub enum HeartAuditLevel {
144 Basic,
146 Enhanced,
148 Full,
150}
151
152#[derive(Clone, Serialize, Deserialize)]
154pub struct HeartSession {
155 pub session_id: String,
157
158 pub patient_id: Option<String>,
160
161 pub provider_id: String,
163
164 pub authorized_resources: Vec<String>,
166
167 pub consent_status: ConsentStatus,
169
170 pub metadata: HashMap<String, Value>,
172}
173
174impl std::fmt::Debug for HeartSession {
175 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
176 let mut d = f.debug_struct("HeartSession");
177 d.field(
178 "session_id",
179 &crate::utils::redact::redacted(&self.session_id),
180 );
181 d.field("patient_id", &self.patient_id);
182 d.field("provider_id", &self.provider_id);
183 d.field("authorized_resources", &self.authorized_resources);
184 d.field("consent_status", &self.consent_status);
185 d.field("metadata", &self.metadata);
186 d.finish()
187 }
188}
189
190#[derive(Debug, Clone, Serialize, Deserialize)]
192pub enum ConsentStatus {
193 Granted,
195 Denied,
197 Pending,
199 Revoked,
201}
202
203#[derive(Debug, Clone)]
207pub struct SharedSignalsManager {
208 config: SharedSignalsConfig,
210
211 receivers: Arc<RwLock<HashMap<String, SignalReceiver>>>,
213
214 transmitters: Arc<RwLock<HashMap<String, SignalTransmitter>>>,
216}
217
218#[derive(Debug, Clone)]
220pub struct SharedSignalsConfig {
221 pub endpoint_url: String,
223
224 pub supported_events: Vec<String>,
226
227 pub max_event_age: i64,
229
230 pub verify_events: bool,
232}
233
234#[derive(Debug, Clone)]
236pub struct SignalReceiver {
237 pub receiver_id: String,
239
240 pub endpoint_url: String,
242
243 pub event_types: Vec<String>,
245
246 pub auth_method: SignalAuthMethod,
248}
249
250#[derive(Debug, Clone)]
252pub struct SignalTransmitter {
253 pub transmitter_id: String,
255
256 pub endpoints: Vec<String>,
258
259 pub event_buffer: Vec<SecurityEvent>,
261}
262
263impl SignalTransmitter {
264 pub async fn send_event(&self, event_jwt: &str, receiver_url: &str) -> Result<(), AuthError> {
266 use crate::server::core::common_config::EndpointConfig;
267 use crate::server::core::common_http::HttpClient;
268 use std::collections::HashMap;
269
270 let config = EndpointConfig::new(receiver_url);
272 let client = HttpClient::new(config)?;
273
274 let mut headers = HashMap::new();
276 headers.insert(
277 "Content-Type".to_string(),
278 "application/secevent+jwt".to_string(),
279 );
280 headers.insert("Accept".to_string(), "application/json".to_string());
281
282 let response = client
284 .request_with_headers(
285 reqwest::Method::POST,
286 "",
287 headers,
288 Some(&event_jwt.to_string()),
289 )
290 .await?;
291
292 if !response.status().is_success() {
293 let (status, body) =
294 crate::server::core::common_http::response::extract_error_details(response).await;
295 return Err(AuthError::internal(format!(
296 "Security event transmission failed with status {}: {}",
297 status, body
298 )));
299 }
300
301 tracing::info!(
302 "Successfully transmitted security event to: {}",
303 receiver_url
304 );
305 Ok(())
306 }
307}
308
309#[derive(Clone)]
311pub enum SignalAuthMethod {
312 Bearer(String),
314 MutualTls,
316 SignedJwt,
318}
319
320impl std::fmt::Debug for SignalAuthMethod {
321 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
322 match self {
323 Self::Bearer(token) => f
324 .debug_tuple("Bearer")
325 .field(&crate::utils::redact::redacted(token))
326 .finish(),
327 Self::MutualTls => f.write_str("MutualTls"),
328 Self::SignedJwt => f.write_str("SignedJwt"),
329 }
330 }
331}
332
333#[derive(Clone, Serialize, Deserialize)]
335pub struct SecurityEvent {
336 pub event_id: String,
338
339 pub event_type: String,
341
342 pub timestamp: DateTime<Utc>,
344
345 pub subject: String,
347
348 pub data: Value,
350
351 pub severity: EventSeverity,
353}
354
355impl std::fmt::Debug for SecurityEvent {
356 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
357 let mut d = f.debug_struct("SecurityEvent");
358 d.field("event_id", &self.event_id);
359 d.field("event_type", &self.event_type);
360 d.field("timestamp", &self.timestamp);
361 d.field("subject", &self.subject);
362 d.field("data", &crate::utils::redact::redacted(&self.data));
363 d.field("severity", &self.severity);
364 d.finish()
365 }
366}
367
368#[derive(Debug, Clone, Serialize, Deserialize)]
370pub struct AccountDisableRequest {
371 pub user_id: String,
373 pub reason: String,
375 pub disable_timestamp: DateTime<Utc>,
377 pub initiated_by: String,
379}
380
381#[derive(Debug, Clone, Serialize, Deserialize)]
383pub enum EventSeverity {
384 Info,
386 Warning,
388 Critical,
390 Emergency,
392}
393
394#[derive(Clone)]
398pub struct EkycManager {
399 config: EkycConfig,
401
402 verification_sessions: Arc<RwLock<HashMap<String, EkycSession>>>,
404}
405
406impl std::fmt::Debug for EkycManager {
407 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
408 let mut d = f.debug_struct("EkycManager");
409 d.field("config", &self.config);
410 d.field(
411 "verification_sessions",
412 &crate::utils::redact::redacted(&self.verification_sessions),
413 );
414 d.finish()
415 }
416}
417
418#[derive(Debug, Clone)]
420pub struct EkycConfig {
421 pub verification_provider: String,
423
424 pub required_ial: IdentityAssuranceLevel,
426
427 pub verification_methods: Vec<VerificationMethod>,
429
430 pub document_verification: bool,
432
433 pub biometric_verification: bool,
435}
436
437#[derive(Debug, Clone, PartialEq, PartialOrd, Serialize, Deserialize)]
439pub enum IdentityAssuranceLevel {
440 IAL1,
442 IAL2,
444 IAL3,
446}
447
448#[derive(Debug, Clone, Serialize, Deserialize)]
450pub enum VerificationMethod {
451 Document,
453 Biometric,
455 Database,
457 KnowledgeBased,
459}
460
461#[derive(Clone, Serialize, Deserialize)]
463pub struct EkycSession {
464 pub session_id: String,
466
467 pub user_id: String,
469
470 pub verification_status: VerificationStatus,
472
473 pub achieved_ial: IdentityAssuranceLevel,
475
476 pub verification_results: HashMap<String, Value>,
478}
479
480impl std::fmt::Debug for EkycSession {
481 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
482 let mut d = f.debug_struct("EkycSession");
483 d.field(
484 "session_id",
485 &crate::utils::redact::redacted(&self.session_id),
486 );
487 d.field("user_id", &self.user_id);
488 d.field("verification_status", &self.verification_status);
489 d.field("achieved_ial", &self.achieved_ial);
490 d.field(
491 "verification_results",
492 &crate::utils::redact::redacted(&self.verification_results),
493 );
494 d.finish()
495 }
496}
497
498#[derive(Debug, Clone, Serialize, Deserialize)]
500pub enum VerificationStatus {
501 Pending,
503 InProgress,
505 Success,
507 Failed,
509 Expired,
511}
512
513#[derive(Debug, Clone)]
517pub struct FastFedManager {
518 config: FastFedConfig,
520
521 federations: Arc<RwLock<HashMap<String, FederationRelationship>>>,
523}
524
525#[derive(Debug, Clone)]
527pub struct FastFedConfig {
528 pub metadata_endpoint: String,
530
531 pub supported_protocols: Vec<String>,
533
534 pub auto_provisioning: bool,
536
537 pub trusted_partners: Vec<String>,
539
540 pub trust_anchor: String,
542}
543
544#[derive(Clone, Serialize, Deserialize)]
546pub struct FederationRelationship {
547 pub relationship_id: String,
549
550 pub partner_org: String,
552
553 pub status: FederationStatus,
555
556 pub config: Value,
558
559 pub created_at: DateTime<Utc>,
561}
562
563impl std::fmt::Debug for FederationRelationship {
564 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
565 let mut d = f.debug_struct("FederationRelationship");
566 d.field("relationship_id", &self.relationship_id);
567 d.field("partner_org", &self.partner_org);
568 d.field("status", &self.status);
569 d.field("config", &crate::utils::redact::redacted(&self.config));
570 d.field("created_at", &self.created_at);
571 d.finish()
572 }
573}
574
575#[derive(Debug, Clone, Serialize, Deserialize)]
577pub enum FederationStatus {
578 Pending,
580 Active,
582 Suspended,
584 Terminated,
586}
587
588impl OidcExtensionsManager {
589 pub fn new(
591 oidc_provider: Arc<OidcProvider<dyn crate::storage::AuthStorage>>,
592 config: OidcExtensionsConfig,
593 ) -> Self {
594 let heart_manager = Arc::new(HeartManager::new(HeartConfig::default()));
595 let shared_signals_manager =
596 Arc::new(SharedSignalsManager::new(SharedSignalsConfig::default()));
597 let ekyc_manager = Arc::new(EkycManager::new(EkycConfig::default()));
598 let fastfed_manager = Arc::new(FastFedManager::new(FastFedConfig::default()));
599
600 Self {
601 oidc_provider,
602 heart_manager,
603 shared_signals_manager,
604 ekyc_manager,
605 fastfed_manager,
606 config,
607 }
608 }
609
610 pub fn get_supported_extensions(&self) -> Vec<&str> {
612 let mut extensions = Vec::new();
613
614 if self.config.enable_heart {
615 extensions.push("HEART");
616 }
617 if self.config.enable_shared_signals {
618 extensions.push("Shared Signals Framework");
619 }
620 if self.config.enable_ekyc {
621 extensions.push("eKYC-IDA");
622 }
623 if self.config.enable_fastfed {
624 extensions.push("FastFed");
625 }
626 if self.config.enable_modrna {
627 extensions.push("MODRNA");
628 }
629 if self.config.enable_igov {
630 extensions.push("iGov");
631 }
632 if self.config.enable_authzen {
633 extensions.push("AuthZEN");
634 }
635
636 extensions
637 }
638
639 pub async fn handle_authorization_request(
641 &self,
642 extension: &str,
643 request: Value,
644 ) -> Result<Value> {
645 match extension {
646 "HEART" if self.config.enable_heart => {
647 self.heart_manager.handle_authorization(request).await
648 }
649 "SharedSignals" if self.config.enable_shared_signals => {
650 self.handle_shared_signals_request(request).await
651 }
652 "eKYC" if self.config.enable_ekyc => {
653 self.ekyc_manager.handle_verification_request(request).await
654 }
655 "FastFed" if self.config.enable_fastfed => {
656 self.fastfed_manager
657 .handle_federation_request(request)
658 .await
659 }
660 "OIDCProvider" => self.handle_oidc_provider_request(request).await,
661 _ => Err(AuthError::validation(format!(
662 "Unsupported extension: {}",
663 extension
664 ))),
665 }
666 }
667
668 async fn handle_shared_signals_request(&self, request: Value) -> Result<Value> {
670 let event_type = request["event_type"]
671 .as_str()
672 .ok_or_else(|| AuthError::auth_method("shared_signals", "Missing event_type"))?;
673
674 match event_type {
675 "send_event" => {
676 let security_event = SecurityEvent {
677 event_id: format!("evt-{}", uuid::Uuid::new_v4()),
678 event_type: request["security_event"]["event_type"]
679 .as_str()
680 .unwrap_or("unknown")
681 .to_string(),
682 subject: request["security_event"]["subject"]
683 .as_str()
684 .unwrap_or("")
685 .to_string(),
686 timestamp: chrono::Utc::now(),
687 data: request["security_event"]["data"].clone(),
688 severity: EventSeverity::Info,
689 };
690
691 self.shared_signals_manager
692 .send_event(security_event)
693 .await?;
694
695 Ok(serde_json::json!({
696 "status": "success",
697 "message": "Security event sent"
698 }))
699 }
700 "receive_event" => {
701 let security_event = SecurityEvent {
702 event_id: format!("evt-{}", uuid::Uuid::new_v4()),
703 event_type: request["event"]["event_type"]
704 .as_str()
705 .unwrap_or("unknown")
706 .to_string(),
707 subject: request["event"]["subject"]
708 .as_str()
709 .unwrap_or("")
710 .to_string(),
711 timestamp: chrono::Utc::now(),
712 data: request["event"]["data"].clone(),
713 severity: EventSeverity::Info,
714 };
715
716 self.shared_signals_manager
717 .receive_event(security_event)
718 .await?;
719
720 Ok(serde_json::json!({
721 "status": "success",
722 "message": "Security event processed"
723 }))
724 }
725 _ => Err(AuthError::validation(format!(
726 "Unsupported shared signals event type: {}",
727 event_type
728 ))),
729 }
730 }
731
732 async fn handle_oidc_provider_request(&self, request: Value) -> Result<Value> {
734 let request_type = request["request_type"]
735 .as_str()
736 .ok_or_else(|| AuthError::auth_method("oidc_provider", "Missing request_type"))?;
737
738 match request_type {
739 "discovery" => {
740 self.generate_oidc_discovery_document().await
742 }
743 "jwks" => {
744 self.generate_oidc_jwks().await
746 }
747 "userinfo" => {
748 self.handle_oidc_userinfo_request(request).await
750 }
751 _ => Err(AuthError::validation(format!(
752 "Unsupported OIDC provider request type: {}",
753 request_type
754 ))),
755 }
756 }
757
758 async fn generate_oidc_discovery_document(&self) -> Result<Value> {
760 let base_discovery = self.oidc_provider.as_ref().discovery_document()?;
762
763 let mut extensions_supported = Vec::new();
765 let mut scopes_supported = base_discovery.scopes_supported.clone();
766
767 if self.config.enable_heart {
769 extensions_supported.push("heart");
770 scopes_supported.push("heart".to_string());
771 }
772 if self.config.enable_shared_signals {
773 extensions_supported.push("shared_signals");
774 scopes_supported.push("shared_signals".to_string());
775 }
776 if self.config.enable_ekyc {
777 extensions_supported.push("ekyc");
778 scopes_supported.push("ekyc".to_string());
779 }
780 if self.config.enable_fastfed {
781 extensions_supported.push("fastfed");
782 scopes_supported.push("fastfed".to_string());
783 }
784
785 Ok(serde_json::json!({
786 "issuer": base_discovery.issuer,
787 "authorization_endpoint": base_discovery.authorization_endpoint,
788 "token_endpoint": base_discovery.token_endpoint,
789 "userinfo_endpoint": base_discovery.userinfo_endpoint,
790 "jwks_uri": base_discovery.jwks_uri,
791 "registration_endpoint": base_discovery.registration_endpoint,
792 "scopes_supported": scopes_supported,
793 "extensions_supported": extensions_supported,
794 "response_types_supported": base_discovery.response_types_supported,
795 "grant_types_supported": base_discovery.grant_types_supported.unwrap_or_else(|| vec![
796 "authorization_code".to_string(),
797 "implicit".to_string(),
798 "refresh_token".to_string()
799 ]),
800 "subject_types_supported": base_discovery.subject_types_supported,
801 "id_token_signing_alg_values_supported": base_discovery.id_token_signing_alg_values_supported,
802 "userinfo_signing_alg_values_supported": base_discovery.userinfo_signing_alg_values_supported.unwrap_or_default(),
803 "token_endpoint_auth_methods_supported": base_discovery.token_endpoint_auth_methods_supported.unwrap_or_default(),
804 "claims_supported": base_discovery.claims_supported.unwrap_or_default(),
805 "claims_parameter_supported": base_discovery.claims_parameter_supported.unwrap_or(false),
806 "request_parameter_supported": base_discovery.request_parameter_supported.unwrap_or(false),
807 "request_uri_parameter_supported": base_discovery.request_uri_parameter_supported.unwrap_or(false),
808 "code_challenge_methods_supported": base_discovery.code_challenge_methods_supported.unwrap_or_default()
809 }))
810 }
811
812 async fn generate_oidc_jwks(&self) -> Result<Value> {
814 let jwk_set = self.oidc_provider.as_ref().generate_jwks()?;
816 Ok(serde_json::to_value(jwk_set)?)
817 }
818
819 async fn handle_oidc_userinfo_request(&self, request: Value) -> Result<Value> {
821 let access_token = request["access_token"]
822 .as_str()
823 .ok_or_else(|| AuthError::auth_method("oidc_provider", "Missing access_token"))?;
824
825 let userinfo = self
827 .oidc_provider
828 .as_ref()
829 .get_userinfo(access_token)
830 .await?;
831
832 let mut userinfo_json = serde_json::json!({
834 "sub": userinfo.sub,
835 "name": userinfo.name,
836 "email": userinfo.email,
837 "email_verified": userinfo.email_verified,
838 "given_name": userinfo.given_name,
839 "family_name": userinfo.family_name,
840 "picture": userinfo.picture,
841 "locale": userinfo.locale,
842 "phone_number": userinfo.phone_number,
843 "phone_number_verified": userinfo.phone_number_verified,
844 "address": userinfo.address,
845 "updated_at": userinfo.updated_at
846 });
847
848 let mut extensions = serde_json::Map::new();
850 if self.config.enable_heart {
851 extensions.insert("heart_verified".to_string(), serde_json::Value::Bool(true));
852 }
853 if self.config.enable_ekyc {
854 extensions.insert("ekyc_verified".to_string(), serde_json::Value::Bool(true));
855 }
856 if self.config.enable_shared_signals {
857 extensions.insert(
858 "shared_signals_enabled".to_string(),
859 serde_json::Value::Bool(true),
860 );
861 }
862 if self.config.enable_fastfed {
863 extensions.insert("fastfed_enabled".to_string(), serde_json::Value::Bool(true));
864 }
865
866 if !extensions.is_empty() {
867 userinfo_json["extensions"] = serde_json::Value::Object(extensions);
868 }
869
870 Ok(userinfo_json)
871 }
872}
873
874impl HeartManager {
875 pub fn new(config: HeartConfig) -> Self {
877 Self {
878 config,
879 sessions: Arc::new(RwLock::new(HashMap::new())),
880 }
881 }
882
883 pub async fn handle_authorization(&self, request: Value) -> Result<Value> {
885 let provider_id = request["provider_id"]
888 .as_str()
889 .ok_or_else(|| AuthError::auth_method("heart", "Missing provider_id"))?;
890
891 let patient_id = request["patient_id"].as_str();
892 let empty_resources = vec![];
893 let requested_resources = request["resources"].as_array().unwrap_or(&empty_resources);
894
895 if !self
897 .config
898 .authorized_providers
899 .contains(&provider_id.to_string())
900 {
901 return Err(AuthError::auth_method(
902 "heart",
903 "Unauthorized healthcare provider",
904 ));
905 }
906
907 Ok(json!({
908 "status": "authorized",
909 "heart_compliant": true,
910 "organization_id": self.config.organization_id,
911 "provider_id": provider_id,
912 "patient_id": patient_id,
913 "authorized_resources": requested_resources
914 }))
915 }
916
917 pub async fn create_session(
919 &self,
920 provider_id: &str,
921 patient_id: Option<&str>,
922 authorized_resources: Vec<String>,
923 ) -> Result<String> {
924 let session_id = Uuid::new_v4().to_string();
925
926 let session = HeartSession {
927 session_id: session_id.clone(),
928 patient_id: patient_id.map(|s| s.to_string()),
929 provider_id: provider_id.to_string(),
930 authorized_resources,
931 consent_status: ConsentStatus::Pending,
932 metadata: HashMap::new(),
933 };
934
935 let mut sessions = self.sessions.write().await;
936 sessions.insert(session_id.clone(), session);
937
938 Ok(session_id)
939 }
940}
941
942impl SharedSignalsManager {
943 pub fn new(config: SharedSignalsConfig) -> Self {
945 Self {
946 config,
947 receivers: Arc::new(RwLock::new(HashMap::new())),
948 transmitters: Arc::new(RwLock::new(HashMap::new())),
949 }
950 }
951
952 pub async fn send_event(&self, event: SecurityEvent) -> Result<()> {
954 let event_jwt = self.create_event_jwt(&event).await?;
957
958 let transmitters = self.transmitters.read().await;
959 for (receiver_url, transmitter) in transmitters.iter() {
960 match transmitter.send_event(&event_jwt, receiver_url).await {
961 Ok(_) => tracing::info!("Security event sent to {}", receiver_url),
962 Err(e) => tracing::error!("Failed to send event to {}: {}", receiver_url, e),
963 }
964 }
965
966 tracing::info!("Security event transmitted: {:?}", event);
967 Ok(())
968 }
969
970 pub async fn receive_event(&self, event: SecurityEvent) -> Result<()> {
972 if !self.is_event_type_supported(&event.event_type) {
974 return Err(AuthError::auth_method(
975 "shared_signals",
976 format!("Unsupported event type: {}", event.event_type),
977 ));
978 }
979
980 if !self.is_event_valid_age(&event) {
982 return Err(AuthError::auth_method("shared_signals", "Event too old"));
983 }
984
985 if self.config.verify_events && !self.validate_event_signature(&event).await? {
987 return Err(AuthError::auth_method(
988 "shared_signals",
989 "Invalid event signature",
990 ));
991 }
992
993 match event.event_type.as_str() {
995 "session_revoked" => self.handle_session_revocation(&event).await?,
996 "account_disabled" => self.handle_account_disabled(&event).await?,
997 "credential_change" => self.handle_credential_change(&event).await?,
998 "fraud_detected" => self.handle_fraud_detection(&event).await?,
999 _ => tracing::warn!("Unknown security event type: {}", event.event_type),
1000 }
1001
1002 tracing::info!("Processed security event: {:?}", event);
1003 Ok(())
1004 }
1005
1006 async fn create_event_jwt(&self, event: &SecurityEvent) -> Result<String> {
1008 use serde_json;
1010 let event_json = serde_json::to_string(event)
1011 .map_err(|e| AuthError::internal(format!("Failed to serialize event: {}", e)))?;
1012
1013 Ok(format!(
1015 "signed.jwt.{}",
1016 BASE64_STANDARD.encode(&event_json)
1017 ))
1018 }
1019
1020 async fn validate_event_signature(&self, event: &SecurityEvent) -> Result<bool> {
1021 if let Some(jwt_token) = event.data.get("jwt") {
1026 use jsonwebtoken::{Algorithm, DecodingKey, Validation};
1029
1030 let decoding_key = if let Ok(key_material) =
1032 std::env::var("SHARED_SIGNALS_VERIFICATION_KEY")
1033 {
1034 if key_material.starts_with("-----BEGIN PUBLIC KEY-----") {
1036 match DecodingKey::from_rsa_pem(key_material.as_bytes()) {
1038 Ok(key) => key,
1039 Err(e) => {
1040 tracing::error!("Failed to parse RSA public key: {}", e);
1041 return Err(AuthError::InvalidRequest(
1042 "Invalid RSA public key configuration".to_string(),
1043 ));
1044 }
1045 }
1046 } else if key_material.starts_with("-----BEGIN EC PUBLIC KEY-----") {
1047 match DecodingKey::from_ec_pem(key_material.as_bytes()) {
1049 Ok(key) => key,
1050 Err(e) => {
1051 tracing::error!("Failed to parse ECDSA public key: {}", e);
1052 return Err(AuthError::InvalidRequest(
1053 "Invalid ECDSA public key configuration".to_string(),
1054 ));
1055 }
1056 }
1057 } else {
1058 DecodingKey::from_secret(key_material.as_bytes())
1060 }
1061 } else {
1062 tracing::error!(
1064 "🔐 SECURITY WARNING: Using development key for shared signals - configure SHARED_SIGNALS_VERIFICATION_KEY for production"
1065 );
1066 tracing::warn!(
1067 "Set SHARED_SIGNALS_VERIFICATION_KEY environment variable with your production key"
1068 );
1069 DecodingKey::from_secret(
1070 "shared_signals_development_key_not_for_production".as_ref(),
1071 )
1072 };
1073
1074 let algorithm = if std::env::var("SHARED_SIGNALS_VERIFICATION_KEY").is_ok() {
1076 if let Ok(alg_str) = std::env::var("SHARED_SIGNALS_ALGORITHM") {
1078 match alg_str.as_str() {
1079 "HS256" => Algorithm::HS256,
1080 "HS384" => Algorithm::HS384,
1081 "HS512" => Algorithm::HS512,
1082 "RS256" => Algorithm::RS256,
1083 "RS384" => Algorithm::RS384,
1084 "RS512" => Algorithm::RS512,
1085 "ES256" => Algorithm::ES256,
1086 "ES384" => Algorithm::ES384,
1087 _ => {
1088 tracing::warn!("Unknown algorithm {}, defaulting to HS256", alg_str);
1089 Algorithm::HS256
1090 }
1091 }
1092 } else {
1093 Algorithm::HS256
1094 }
1095 } else {
1096 Algorithm::HS256
1097 };
1098
1099 let mut validation = Validation::new(algorithm);
1100 validation.validate_exp = true;
1101 validation.validate_nbf = true;
1102 validation.validate_aud = false; if let Ok(expected_issuer) = std::env::var("SHARED_SIGNALS_ISSUER") {
1106 validation.set_issuer(&[expected_issuer]);
1107 tracing::debug!("Validating shared signals issuer");
1108 }
1109
1110 match jsonwebtoken::decode::<serde_json::Value>(
1111 jwt_token.as_str().unwrap_or(""),
1112 &decoding_key,
1113 &validation,
1114 ) {
1115 Ok(_) => {
1116 tracing::info!("Security event JWT signature validated successfully");
1117 Ok(true)
1118 }
1119 Err(e) => {
1120 tracing::warn!("Security event JWT signature validation failed: {}", e);
1121 Ok(false)
1122 }
1123 }
1124 } else {
1125 tracing::info!("Non-JWT security event - performing basic validation");
1127 Ok(!event.subject.is_empty() && !event.event_type.is_empty())
1128 }
1129 }
1130
1131 async fn handle_session_revocation(&self, event: &SecurityEvent) -> Result<()> {
1132 tracing::info!("Handling session revocation for event: {}", event.event_id);
1133
1134 if let Some(session_id) = event.data.get("session_id") {
1136 let session_id_str = session_id.as_str().unwrap_or("");
1137 tracing::info!("Revoking session: {}", session_id_str);
1138
1139 if let Err(e) = self.remove_session_from_store(session_id_str).await {
1142 tracing::error!("Failed to remove session from store: {}", e);
1143 }
1144
1145 if let Err(e) = self.add_session_to_revocation_list(session_id_str).await {
1147 tracing::error!("Failed to add session to revocation list: {}", e);
1148 }
1149
1150 if let Err(e) = self
1152 .notify_resource_servers_session_revoked(session_id_str)
1153 .await
1154 {
1155 tracing::error!("Failed to notify resource servers: {}", e);
1156 }
1157
1158 self.log_session_revocation_audit(session_id_str, &event.subject)
1160 .await;
1161
1162 self.execute_session_revocation(session_id_str).await;
1164
1165 tracing::info!(
1166 "Session revocation completed for session: {} - all associated tokens invalidated",
1167 session_id_str
1168 );
1169 } else {
1170 tracing::info!("Revoking all sessions for subject: {}", event.subject);
1172 self.revoke_all_user_sessions(&event.subject).await;
1173 }
1174
1175 Ok(())
1176 }
1177
1178 async fn handle_account_disabled(&self, event: &SecurityEvent) -> Result<()> {
1179 tracing::info!("Handling account disabled for event: {}", event.event_id);
1180
1181 let reason = event
1183 .data
1184 .get("reason")
1185 .and_then(|v| v.as_str())
1186 .unwrap_or("Security event");
1187
1188 let disable_timestamp = event
1189 .data
1190 .get("disable_timestamp")
1191 .and_then(|v| v.as_str())
1192 .unwrap_or("immediate");
1193
1194 tracing::warn!(
1195 "Account disabled for subject: {} - Reason: {} - Timestamp: {}",
1196 event.subject,
1197 reason,
1198 disable_timestamp
1199 );
1200
1201 let disable_request = AccountDisableRequest {
1210 user_id: event.subject.clone(),
1211 reason: reason.to_string(),
1212 disable_timestamp: Utc::now(),
1213 initiated_by: "security_event_handler".to_string(),
1214 };
1215
1216 self.execute_account_disable(&disable_request).await?;
1218
1219 tracing::info!("Account successfully disabled for user: {}", event.subject);
1220
1221 Ok(())
1222 }
1223
1224 async fn execute_account_disable(&self, request: &AccountDisableRequest) -> Result<()> {
1226 tracing::info!("Executing account disable for user: {}", request.user_id);
1227
1228 self.revoke_all_user_sessions(&request.user_id).await;
1232 tracing::info!(
1233 "Revoked all active sessions for disabled user: {}",
1234 request.user_id
1235 );
1236
1237 self.notify_resource_servers_account_disabled(&request.user_id)
1239 .await?;
1240
1241 self.log_account_disable_audit(request).await?;
1243
1244 self.trigger_security_monitoring_alert(
1246 "account_disabled",
1247 &request.user_id,
1248 &request.reason,
1249 )
1250 .await?;
1251
1252 tracing::info!(
1254 "Account disable executed - User: {}, Reason: {}, Timestamp: {}",
1255 request.user_id,
1256 request.reason,
1257 request.disable_timestamp.to_rfc3339()
1258 );
1259
1260 Ok(())
1261 }
1262
1263 async fn notify_resource_servers_account_disabled(&self, user_id: &str) -> Result<()> {
1265 let _notification = serde_json::json!({
1266 "type": "account_disabled",
1267 "user_id": user_id,
1268 "timestamp": chrono::Utc::now().to_rfc3339(),
1269 "issuer": &self.config.endpoint_url,
1270 "action_required": "invalidate_user_tokens"
1271 });
1272
1273 let transmitters = self.transmitters.read().await;
1277 if transmitters.is_empty() {
1278 tracing::debug!(
1279 "No registered signal transmitters — skipping account-disabled notification for user {}",
1280 user_id
1281 );
1282 } else {
1283 for (id, tx) in transmitters.iter() {
1284 for endpoint in &tx.endpoints {
1285 tracing::debug!(
1286 "Notifying transmitter {} endpoint {} about account disabled: {}",
1287 id,
1288 endpoint,
1289 user_id
1290 );
1291 }
1293 }
1294 }
1295
1296 tracing::info!("Sent account disabled notifications for user: {}", user_id);
1297 Ok(())
1298 }
1299
1300 async fn log_account_disable_audit(&self, request: &AccountDisableRequest) -> Result<()> {
1302 let audit_entry = serde_json::json!({
1303 "event_type": "account_disabled",
1304 "user_id": request.user_id,
1305 "reason": &request.reason,
1306 "timestamp": chrono::Utc::now().to_rfc3339(),
1307 "source": "oidc_extensions",
1308 "severity": "high"
1309 });
1310
1311 tracing::warn!(
1312 "SECURITY AUDIT: Account disabled - User: {}, Reason: {}, Event: {}",
1313 request.user_id,
1314 request.reason,
1315 audit_entry
1316 );
1317
1318 Ok(())
1320 }
1321
1322 async fn trigger_security_monitoring_alert(
1324 &self,
1325 alert_type: &str,
1326 user_id: &str,
1327 reason: &str,
1328 ) -> Result<()> {
1329 let alert = serde_json::json!({
1330 "alert_type": alert_type,
1331 "severity": "high",
1332 "user_id": user_id,
1333 "reason": reason,
1334 "timestamp": chrono::Utc::now().to_rfc3339(),
1335 "source": "shared_signals_manager"
1336 });
1337
1338 tracing::error!(
1339 "SECURITY ALERT: {} - User: {}, Reason: {}, Details: {}",
1340 alert_type.to_uppercase(),
1341 user_id,
1342 reason,
1343 alert
1344 );
1345
1346 Ok(())
1348 }
1349
1350 async fn execute_session_revocation(&self, session_id: &str) {
1352 tracing::info!("Executing session revocation for session: {}", session_id);
1353
1354 tracing::info!(
1358 "Session revocation workflow completed for session: {} - all associated tokens and grants invalidated",
1359 session_id
1360 );
1361 }
1362
1363 async fn remove_session_from_store(&self, session_id: &str) -> Result<()> {
1365 tracing::debug!("Removing session {} from active sessions store", session_id);
1366
1367 tracing::info!(
1371 "Session {} removed from active store (no-op: no backing store configured)",
1372 session_id
1373 );
1374 Ok(())
1375 }
1376
1377 async fn add_session_to_revocation_list(&self, session_id: &str) -> Result<()> {
1379 tracing::debug!("Adding session {} to revocation list", session_id);
1380
1381 let revocation_entry = serde_json::json!({
1384 "session_id": session_id,
1385 "revoked_at": chrono::Utc::now().to_rfc3339(),
1386 "reason": "security_event"
1387 });
1388
1389 tracing::info!(
1390 "Session {} added to revocation list: {}",
1391 session_id,
1392 revocation_entry
1393 );
1394 Ok(())
1395 }
1396
1397 async fn notify_resource_servers_session_revoked(&self, session_id: &str) -> Result<()> {
1399 tracing::debug!(
1400 "Notifying resource servers about session {} revocation",
1401 session_id
1402 );
1403
1404 let notification = serde_json::json!({
1407 "type": "session_revoked",
1408 "session_id": session_id,
1409 "timestamp": chrono::Utc::now().to_rfc3339(),
1410 "issuer": &self.config.endpoint_url
1411 });
1412
1413 let transmitters = self.transmitters.read().await;
1415 if transmitters.is_empty() {
1416 tracing::debug!(
1417 "No registered signal transmitters — skipping session-revocation notification for session {}",
1418 session_id
1419 );
1420 } else {
1421 for (id, tx) in transmitters.iter() {
1422 for endpoint in &tx.endpoints {
1423 tracing::info!(
1424 "Notifying transmitter {} endpoint {} of session revocation: {}",
1425 id,
1426 endpoint,
1427 notification
1428 );
1429 }
1431 }
1432 }
1433
1434 Ok(())
1435 }
1436
1437 async fn log_session_revocation_audit(&self, session_id: &str, subject: &str) {
1439 let audit_event = serde_json::json!({
1440 "event_type": "session_revoked",
1441 "session_id": session_id,
1442 "subject": subject,
1443 "timestamp": chrono::Utc::now().to_rfc3339(),
1444 "initiator": "security_event_handler",
1445 "reason": "security_event_triggered"
1446 });
1447
1448 tracing::info!(target: "audit", "Session revocation audit: {}", audit_event);
1449
1450 }
1452
1453 async fn revoke_all_user_sessions(&self, subject: &str) {
1455 tracing::info!("Revoking all sessions for subject: {}", subject);
1456
1457 let audit_event = serde_json::json!({
1463 "event_type": "all_sessions_revoked",
1464 "subject": subject,
1465 "timestamp": chrono::Utc::now().to_rfc3339(),
1466 "reason": "security_event_fallback"
1467 });
1468
1469 tracing::info!(target: "audit", "All sessions revoked for user: {}", audit_event);
1470 }
1471
1472 async fn handle_credential_change(&self, event: &SecurityEvent) -> Result<()> {
1473 tracing::info!("Handling credential change for event: {}", event.event_id);
1474
1475 let credential_type = event
1476 .data
1477 .get("credential_type")
1478 .and_then(|v| v.as_str())
1479 .unwrap_or("unknown");
1480
1481 let change_type = event
1482 .data
1483 .get("change_type")
1484 .and_then(|v| v.as_str())
1485 .unwrap_or("update");
1486
1487 tracing::info!(
1488 "Credential change detected - Subject: {}, Type: {}, Change: {}",
1489 event.subject,
1490 credential_type,
1491 change_type
1492 );
1493
1494 match change_type {
1495 "password_change" => {
1496 if let Some(session_to_keep) = event.data.get("session_id") {
1498 tracing::info!(
1499 "Revoking all sessions except: {}",
1500 session_to_keep.as_str().unwrap_or("")
1501 );
1502 }
1503 }
1505 "mfa_enabled" => {
1506 tracing::info!(
1508 "MFA enabled for user: {} - security posture improved",
1509 event.subject
1510 );
1511 }
1512 "mfa_disabled" => {
1513 tracing::warn!(
1515 "MFA disabled for user: {} - consider security review",
1516 event.subject
1517 );
1518 }
1519 "recovery_codes_reset" => {
1520 tracing::info!("Recovery codes reset for user: {}", event.subject);
1522 }
1523 _ => {
1524 tracing::info!("General credential change for user: {}", event.subject);
1525 }
1526 }
1527
1528 Ok(())
1529 }
1530
1531 async fn handle_fraud_detection(&self, event: &SecurityEvent) -> Result<()> {
1532 tracing::info!("Handling fraud detection for event: {}", event.event_id);
1533 Ok(())
1535 }
1536
1537 pub async fn register_receiver(
1539 &self,
1540 receiver_id: String,
1541 receiver: SignalReceiver,
1542 ) -> Result<()> {
1543 let mut receivers = self.receivers.write().await;
1544 receivers.insert(receiver_id.clone(), receiver);
1545 tracing::info!("Signal receiver registered: {}", receiver_id);
1546 Ok(())
1547 }
1548
1549 pub async fn unregister_receiver(&self, receiver_id: &str) -> Result<()> {
1551 let mut receivers = self.receivers.write().await;
1552 if receivers.remove(receiver_id).is_some() {
1553 tracing::info!("Signal receiver unregistered: {}", receiver_id);
1554 Ok(())
1555 } else {
1556 Err(AuthError::auth_method(
1557 "shared_signals",
1558 "Receiver not found",
1559 ))
1560 }
1561 }
1562
1563 pub fn get_config(&self) -> &SharedSignalsConfig {
1565 &self.config
1566 }
1567
1568 pub fn is_event_type_supported(&self, event_type: &str) -> bool {
1570 self.config
1571 .supported_events
1572 .contains(&event_type.to_string())
1573 }
1574
1575 pub fn is_event_valid_age(&self, event: &SecurityEvent) -> bool {
1577 let now = chrono::Utc::now();
1578 let event_age = now.signed_duration_since(event.timestamp).num_seconds();
1579 event_age <= self.config.max_event_age
1580 }
1581
1582 pub async fn list_receivers(&self) -> Vec<String> {
1584 let receivers = self.receivers.read().await;
1585 receivers.keys().cloned().collect()
1586 }
1587}
1588
1589impl EkycManager {
1590 pub fn new(config: EkycConfig) -> Self {
1592 Self {
1593 config,
1594 verification_sessions: Arc::new(RwLock::new(HashMap::new())),
1595 }
1596 }
1597
1598 pub async fn handle_verification_request(&self, request: Value) -> Result<Value> {
1600 let user_id = request["user_id"]
1602 .as_str()
1603 .ok_or_else(|| AuthError::auth_method("ekyc", "Missing user_id"))?;
1604
1605 let requested_ial = request["requested_ial"]
1606 .as_str()
1607 .and_then(|s| s.parse::<u8>().ok())
1608 .unwrap_or(1);
1609
1610 if requested_ial < self.config.required_ial.clone() as u8 {
1612 return Err(AuthError::auth_method(
1613 "ekyc",
1614 "Insufficient identity assurance level",
1615 ));
1616 }
1617
1618 let session_id = Uuid::new_v4().to_string();
1620 let ekyc_session = EkycSession {
1621 session_id: session_id.clone(),
1622 user_id: user_id.to_string(),
1623 verification_status: VerificationStatus::Pending,
1624 achieved_ial: IdentityAssuranceLevel::from_u8(requested_ial),
1625 verification_results: HashMap::new(),
1626 };
1627
1628 let mut sessions = self.verification_sessions.write().await;
1630 sessions.insert(session_id.clone(), ekyc_session);
1631
1632 Ok(json!({
1633 "status": "verification_initiated",
1634 "session_id": session_id,
1635 "required_ial": requested_ial,
1636 "required_methods": self.config.verification_methods,
1637 "verification_endpoint": format!("/ekyc/verify/{}", session_id)
1638 }))
1639 }
1640
1641 pub async fn start_verification(&self, user_id: &str) -> Result<String> {
1643 let session_id = Uuid::new_v4().to_string();
1644
1645 let session = EkycSession {
1646 session_id: session_id.clone(),
1647 user_id: user_id.to_string(),
1648 verification_status: VerificationStatus::Pending,
1649 achieved_ial: IdentityAssuranceLevel::IAL1,
1650 verification_results: HashMap::new(),
1651 };
1652
1653 let mut sessions = self.verification_sessions.write().await;
1654 sessions.insert(session_id.clone(), session);
1655
1656 Ok(session_id)
1657 }
1658}
1659
1660impl FastFedManager {
1661 pub fn new(config: FastFedConfig) -> Self {
1663 Self {
1664 config,
1665 federations: Arc::new(RwLock::new(HashMap::new())),
1666 }
1667 }
1668
1669 pub async fn handle_federation_request(&self, request: Value) -> Result<Value> {
1671 let partner_org = request["partner_organization"]
1673 .as_str()
1674 .ok_or_else(|| AuthError::auth_method("fastfed", "Missing partner_organization"))?;
1675
1676 let federation_metadata = request["federation_metadata"]
1677 .as_object()
1678 .ok_or_else(|| AuthError::auth_method("fastfed", "Missing federation_metadata"))?;
1679
1680 if !self
1682 .config
1683 .trusted_partners
1684 .contains(&partner_org.to_string())
1685 {
1686 return Err(AuthError::auth_method(
1687 "fastfed",
1688 "Untrusted federation partner",
1689 ));
1690 }
1691
1692 let required_capabilities = ["oidc", "saml2", "scim"];
1694 for capability in required_capabilities {
1695 if !federation_metadata.contains_key(capability) {
1696 return Err(AuthError::auth_method(
1697 "fastfed",
1698 format!("Missing required capability: {}", capability),
1699 ));
1700 }
1701 }
1702
1703 let federation_id = if self.config.auto_provisioning {
1705 Some(self.establish_federation(partner_org).await?)
1706 } else {
1707 None
1708 };
1709
1710 Ok(json!({
1711 "status": "federation_request_accepted",
1712 "federation_id": federation_id,
1713 "auto_provisioning": self.config.auto_provisioning,
1714 "supported_protocols": self.config.supported_protocols,
1715 "next_steps": if federation_id.is_some() {
1716 "Federation automatically established"
1717 } else {
1718 "Manual federation approval required"
1719 }
1720 }))
1721 }
1722
1723 pub async fn establish_federation(&self, partner_org: &str) -> Result<String> {
1725 let relationship_id = Uuid::new_v4().to_string();
1726
1727 let relationship = FederationRelationship {
1728 relationship_id: relationship_id.clone(),
1729 partner_org: partner_org.to_string(),
1730 status: FederationStatus::Pending,
1731 config: json!({}),
1732 created_at: Utc::now(),
1733 };
1734
1735 let mut federations = self.federations.write().await;
1736 federations.insert(relationship_id.clone(), relationship);
1737
1738 Ok(relationship_id)
1739 }
1740}
1741
1742impl Default for OidcExtensionsConfig {
1745 fn default() -> Self {
1746 Self {
1747 enable_heart: true,
1748 enable_shared_signals: true,
1749 enable_ekyc: true,
1750 enable_fastfed: true,
1751 enable_modrna: false, enable_igov: false, enable_authzen: false, }
1755 }
1756}
1757
1758impl Default for HeartConfig {
1759 fn default() -> Self {
1760 Self {
1761 organization_id: "example-healthcare-org".to_string(),
1762 fhir_endpoint: "https://example.com/fhir".to_string(),
1763 required_scopes: vec!["patient/*.read".to_string(), "user/*.read".to_string()],
1764 enhanced_consent: true,
1765 authorized_providers: Vec::new(), audit_config: HeartAuditConfig::default(),
1767 }
1768 }
1769}
1770
1771impl Default for HeartAuditConfig {
1772 fn default() -> Self {
1773 Self {
1774 enable_atna: true,
1775 syslog_endpoint: None,
1776 audit_level: HeartAuditLevel::Enhanced,
1777 }
1778 }
1779}
1780
1781impl Default for SharedSignalsConfig {
1782 fn default() -> Self {
1783 Self {
1784 endpoint_url: "https://example.com/signals".to_string(),
1785 supported_events: vec![
1786 "security_advisory".to_string(),
1787 "account_disabled".to_string(),
1788 "credential_change".to_string(),
1789 "session_revoked".to_string(),
1790 ],
1791 max_event_age: 3600, verify_events: true,
1793 }
1794 }
1795}
1796
1797#[derive(Clone)]
1799pub struct VerificationSession {
1800 pub session_id: String,
1801 pub user_id: String,
1802 pub requested_ial: IdentityAssuranceLevel,
1803 pub status: String,
1804 pub required_methods: Vec<VerificationMethod>,
1805 pub completed_verifications: Vec<VerificationMethod>,
1806 pub created_at: SystemTime,
1807}
1808
1809impl std::fmt::Debug for VerificationSession {
1810 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1811 let mut d = f.debug_struct("VerificationSession");
1812 d.field(
1813 "session_id",
1814 &crate::utils::redact::redacted(&self.session_id),
1815 );
1816 d.field("user_id", &self.user_id);
1817 d.field("requested_ial", &self.requested_ial);
1818 d.field("status", &self.status);
1819 d.field("required_methods", &self.required_methods);
1820 d.field("completed_verifications", &self.completed_verifications);
1821 d.field("created_at", &self.created_at);
1822 d.finish()
1823 }
1824}
1825
1826impl IdentityAssuranceLevel {
1827 pub fn from_u8(level: u8) -> Self {
1828 match level {
1829 1 => IdentityAssuranceLevel::IAL1,
1830 2 => IdentityAssuranceLevel::IAL2,
1831 3 => IdentityAssuranceLevel::IAL3,
1832 _ => IdentityAssuranceLevel::IAL1,
1833 }
1834 }
1835}
1836
1837pub struct EventTransmitter {
1839 pub endpoint: String,
1840 pub public_key: String,
1841}
1842
1843impl EventTransmitter {
1844 pub async fn send_event(&self, event_jwt: &str, receiver_url: &str) -> Result<()> {
1845 tracing::info!("Sending event JWT to {}: {}", receiver_url, event_jwt);
1846 Ok(())
1848 }
1849}
1850
1851impl Default for EkycConfig {
1852 fn default() -> Self {
1853 Self {
1854 verification_provider: "example-kyc-provider".to_string(),
1855 required_ial: IdentityAssuranceLevel::IAL2,
1856 verification_methods: vec![VerificationMethod::Document, VerificationMethod::Database],
1857 document_verification: true,
1858 biometric_verification: false,
1859 }
1860 }
1861}
1862
1863impl Default for FastFedConfig {
1864 fn default() -> Self {
1865 Self {
1866 metadata_endpoint: "https://example.com/.well-known/fastfed".to_string(),
1867 supported_protocols: vec!["OIDC".to_string(), "SAML2".to_string()],
1868 auto_provisioning: false, trusted_partners: Vec::new(), trust_anchor: "example-trust-anchor".to_string(),
1871 }
1872 }
1873}
1874
1875#[cfg(test)]
1876mod tests {
1877 use super::*;
1878
1879 #[tokio::test]
1880 async fn test_oidc_extensions_creation() {
1881 let config = OidcExtensionsConfig::default();
1882
1883 assert!(config.enable_heart);
1885 assert!(config.enable_shared_signals);
1886 assert!(config.enable_ekyc);
1887 assert!(config.enable_fastfed);
1888
1889 assert!(!config.enable_modrna);
1891 assert!(!config.enable_igov);
1892 assert!(!config.enable_authzen);
1893 }
1894
1895 #[tokio::test]
1896 async fn test_heart_session_creation() {
1897 let config = HeartConfig::default();
1898 let heart_manager = HeartManager::new(config);
1899
1900 let session_id = heart_manager
1901 .create_session(
1902 "provider123",
1903 Some("patient456"),
1904 vec!["patient/*.read".to_string()],
1905 )
1906 .await
1907 .unwrap();
1908
1909 assert!(!session_id.is_empty());
1910 }
1911
1912 #[tokio::test]
1913 async fn test_ekyc_verification() {
1914 let config = EkycConfig::default();
1915 let ekyc_manager = EkycManager::new(config);
1916
1917 let session_id = ekyc_manager.start_verification("user123").await.unwrap();
1918
1919 assert!(!session_id.is_empty());
1920 }
1921
1922 #[tokio::test]
1923 async fn test_fastfed_federation() {
1924 let config = FastFedConfig::default();
1925 let fastfed_manager = FastFedManager::new(config);
1926
1927 let relationship_id = fastfed_manager
1928 .establish_federation("partner-org")
1929 .await
1930 .unwrap();
1931
1932 assert!(!relationship_id.is_empty());
1933 }
1934}