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(Debug, Clone)]
89pub struct HeartManager {
90 config: HeartConfig,
92
93 sessions: Arc<RwLock<HashMap<String, HeartSession>>>,
95}
96
97#[derive(Debug, Clone)]
99pub struct HeartConfig {
100 pub organization_id: String,
102
103 pub fhir_endpoint: String,
105
106 pub required_scopes: Vec<String>,
108
109 pub enhanced_consent: bool,
111
112 pub authorized_providers: Vec<String>,
114
115 pub audit_config: HeartAuditConfig,
117}
118
119#[derive(Debug, Clone)]
121pub struct HeartAuditConfig {
122 pub enable_atna: bool,
124
125 pub syslog_endpoint: Option<String>,
127
128 pub audit_level: HeartAuditLevel,
130}
131
132#[derive(Debug, Clone, PartialEq)]
134pub enum HeartAuditLevel {
135 Basic,
137 Enhanced,
139 Full,
141}
142
143#[derive(Clone, Serialize, Deserialize)]
145pub struct HeartSession {
146 pub session_id: String,
148
149 pub patient_id: Option<String>,
151
152 pub provider_id: String,
154
155 pub authorized_resources: Vec<String>,
157
158 pub consent_status: ConsentStatus,
160
161 pub metadata: HashMap<String, Value>,
163}
164
165impl std::fmt::Debug for HeartSession {
166 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
167 let mut d = f.debug_struct("HeartSession");
168 d.field(
169 "session_id",
170 &crate::utils::redact::redacted(&self.session_id),
171 );
172 d.field("patient_id", &self.patient_id);
173 d.field("provider_id", &self.provider_id);
174 d.field("authorized_resources", &self.authorized_resources);
175 d.field("consent_status", &self.consent_status);
176 d.field("metadata", &self.metadata);
177 d.finish()
178 }
179}
180
181#[derive(Debug, Clone, Serialize, Deserialize)]
183pub enum ConsentStatus {
184 Granted,
186 Denied,
188 Pending,
190 Revoked,
192}
193
194#[derive(Debug, Clone)]
198pub struct SharedSignalsManager {
199 config: SharedSignalsConfig,
201
202 receivers: Arc<RwLock<HashMap<String, SignalReceiver>>>,
204
205 transmitters: Arc<RwLock<HashMap<String, SignalTransmitter>>>,
207}
208
209#[derive(Debug, Clone)]
211pub struct SharedSignalsConfig {
212 pub endpoint_url: String,
214
215 pub supported_events: Vec<String>,
217
218 pub max_event_age: i64,
220
221 pub verify_events: bool,
223}
224
225#[derive(Debug, Clone)]
227pub struct SignalReceiver {
228 pub receiver_id: String,
230
231 pub endpoint_url: String,
233
234 pub event_types: Vec<String>,
236
237 pub auth_method: SignalAuthMethod,
239}
240
241#[derive(Debug, Clone)]
243pub struct SignalTransmitter {
244 pub transmitter_id: String,
246
247 pub endpoints: Vec<String>,
249
250 pub event_buffer: Vec<SecurityEvent>,
252}
253
254impl SignalTransmitter {
255 pub async fn send_event(&self, event_jwt: &str, receiver_url: &str) -> Result<(), AuthError> {
257 use crate::server::core::common_config::EndpointConfig;
258 use crate::server::core::common_http::HttpClient;
259 use std::collections::HashMap;
260
261 let config = EndpointConfig::new(receiver_url);
263 let client = HttpClient::new(config)?;
264
265 let mut headers = HashMap::new();
267 headers.insert(
268 "Content-Type".to_string(),
269 "application/secevent+jwt".to_string(),
270 );
271 headers.insert("Accept".to_string(), "application/json".to_string());
272
273 let response = client
275 .request_with_headers(
276 reqwest::Method::POST,
277 "",
278 headers,
279 Some(&event_jwt.to_string()),
280 )
281 .await?;
282
283 if !response.status().is_success() {
284 let (status, body) =
285 crate::server::core::common_http::response::extract_error_details(response).await;
286 return Err(AuthError::internal(format!(
287 "Security event transmission failed with status {}: {}",
288 status, body
289 )));
290 }
291
292 tracing::info!(
293 "Successfully transmitted security event to: {}",
294 receiver_url
295 );
296 Ok(())
297 }
298}
299
300#[derive(Clone)]
302pub enum SignalAuthMethod {
303 Bearer(String),
305 MutualTls,
307 SignedJwt,
309}
310
311impl std::fmt::Debug for SignalAuthMethod {
312 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
313 match self {
314 Self::Bearer(token) => f
315 .debug_tuple("Bearer")
316 .field(&crate::utils::redact::redacted(token))
317 .finish(),
318 Self::MutualTls => f.write_str("MutualTls"),
319 Self::SignedJwt => f.write_str("SignedJwt"),
320 }
321 }
322}
323
324#[derive(Debug, Clone, Serialize, Deserialize)]
326pub struct SecurityEvent {
327 pub event_id: String,
329
330 pub event_type: String,
332
333 pub timestamp: DateTime<Utc>,
335
336 pub subject: String,
338
339 pub data: Value,
341
342 pub severity: EventSeverity,
344}
345
346#[derive(Debug, Clone, Serialize, Deserialize)]
348pub struct AccountDisableRequest {
349 pub user_id: String,
351 pub reason: String,
353 pub disable_timestamp: DateTime<Utc>,
355 pub initiated_by: String,
357}
358
359#[derive(Debug, Clone, Serialize, Deserialize)]
361pub enum EventSeverity {
362 Info,
364 Warning,
366 Critical,
368 Emergency,
370}
371
372#[derive(Debug, Clone)]
376pub struct EkycManager {
377 config: EkycConfig,
379
380 verification_sessions: Arc<RwLock<HashMap<String, EkycSession>>>,
382}
383
384#[derive(Debug, Clone)]
386pub struct EkycConfig {
387 pub verification_provider: String,
389
390 pub required_ial: IdentityAssuranceLevel,
392
393 pub verification_methods: Vec<VerificationMethod>,
395
396 pub document_verification: bool,
398
399 pub biometric_verification: bool,
401}
402
403#[derive(Debug, Clone, PartialEq, PartialOrd, Serialize, Deserialize)]
405pub enum IdentityAssuranceLevel {
406 IAL1,
408 IAL2,
410 IAL3,
412}
413
414#[derive(Debug, Clone, Serialize, Deserialize)]
416pub enum VerificationMethod {
417 Document,
419 Biometric,
421 Database,
423 KnowledgeBased,
425}
426
427#[derive(Clone, Serialize, Deserialize)]
429pub struct EkycSession {
430 pub session_id: String,
432
433 pub user_id: String,
435
436 pub verification_status: VerificationStatus,
438
439 pub achieved_ial: IdentityAssuranceLevel,
441
442 pub verification_results: HashMap<String, Value>,
444}
445
446impl std::fmt::Debug for EkycSession {
447 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
448 let mut d = f.debug_struct("EkycSession");
449 d.field(
450 "session_id",
451 &crate::utils::redact::redacted(&self.session_id),
452 );
453 d.field("user_id", &self.user_id);
454 d.field("verification_status", &self.verification_status);
455 d.field("achieved_ial", &self.achieved_ial);
456 d.field("verification_results", &self.verification_results);
457 d.finish()
458 }
459}
460
461#[derive(Debug, Clone, Serialize, Deserialize)]
463pub enum VerificationStatus {
464 Pending,
466 InProgress,
468 Success,
470 Failed,
472 Expired,
474}
475
476#[derive(Debug, Clone)]
480pub struct FastFedManager {
481 config: FastFedConfig,
483
484 federations: Arc<RwLock<HashMap<String, FederationRelationship>>>,
486}
487
488#[derive(Debug, Clone)]
490pub struct FastFedConfig {
491 pub metadata_endpoint: String,
493
494 pub supported_protocols: Vec<String>,
496
497 pub auto_provisioning: bool,
499
500 pub trusted_partners: Vec<String>,
502
503 pub trust_anchor: String,
505}
506
507#[derive(Debug, Clone, Serialize, Deserialize)]
509pub struct FederationRelationship {
510 pub relationship_id: String,
512
513 pub partner_org: String,
515
516 pub status: FederationStatus,
518
519 pub config: Value,
521
522 pub created_at: DateTime<Utc>,
524}
525
526#[derive(Debug, Clone, Serialize, Deserialize)]
528pub enum FederationStatus {
529 Pending,
531 Active,
533 Suspended,
535 Terminated,
537}
538
539impl OidcExtensionsManager {
540 pub fn new(
542 oidc_provider: Arc<OidcProvider<dyn crate::storage::AuthStorage>>,
543 config: OidcExtensionsConfig,
544 ) -> Self {
545 let heart_manager = Arc::new(HeartManager::new(HeartConfig::default()));
546 let shared_signals_manager =
547 Arc::new(SharedSignalsManager::new(SharedSignalsConfig::default()));
548 let ekyc_manager = Arc::new(EkycManager::new(EkycConfig::default()));
549 let fastfed_manager = Arc::new(FastFedManager::new(FastFedConfig::default()));
550
551 Self {
552 oidc_provider,
553 heart_manager,
554 shared_signals_manager,
555 ekyc_manager,
556 fastfed_manager,
557 config,
558 }
559 }
560
561 pub fn get_supported_extensions(&self) -> Vec<&str> {
563 let mut extensions = Vec::new();
564
565 if self.config.enable_heart {
566 extensions.push("HEART");
567 }
568 if self.config.enable_shared_signals {
569 extensions.push("Shared Signals Framework");
570 }
571 if self.config.enable_ekyc {
572 extensions.push("eKYC-IDA");
573 }
574 if self.config.enable_fastfed {
575 extensions.push("FastFed");
576 }
577 if self.config.enable_modrna {
578 extensions.push("MODRNA");
579 }
580 if self.config.enable_igov {
581 extensions.push("iGov");
582 }
583 if self.config.enable_authzen {
584 extensions.push("AuthZEN");
585 }
586
587 extensions
588 }
589
590 pub async fn handle_authorization_request(
592 &self,
593 extension: &str,
594 request: Value,
595 ) -> Result<Value> {
596 match extension {
597 "HEART" if self.config.enable_heart => {
598 self.heart_manager.handle_authorization(request).await
599 }
600 "SharedSignals" if self.config.enable_shared_signals => {
601 self.handle_shared_signals_request(request).await
602 }
603 "eKYC" if self.config.enable_ekyc => {
604 self.ekyc_manager.handle_verification_request(request).await
605 }
606 "FastFed" if self.config.enable_fastfed => {
607 self.fastfed_manager
608 .handle_federation_request(request)
609 .await
610 }
611 "OIDCProvider" => self.handle_oidc_provider_request(request).await,
612 _ => Err(AuthError::validation(format!(
613 "Unsupported extension: {}",
614 extension
615 ))),
616 }
617 }
618
619 async fn handle_shared_signals_request(&self, request: Value) -> Result<Value> {
621 let event_type = request["event_type"]
622 .as_str()
623 .ok_or_else(|| AuthError::auth_method("shared_signals", "Missing event_type"))?;
624
625 match event_type {
626 "send_event" => {
627 let security_event = SecurityEvent {
628 event_id: format!("evt-{}", uuid::Uuid::new_v4()),
629 event_type: request["security_event"]["event_type"]
630 .as_str()
631 .unwrap_or("unknown")
632 .to_string(),
633 subject: request["security_event"]["subject"]
634 .as_str()
635 .unwrap_or("")
636 .to_string(),
637 timestamp: chrono::Utc::now(),
638 data: request["security_event"]["data"].clone(),
639 severity: EventSeverity::Info,
640 };
641
642 self.shared_signals_manager
643 .send_event(security_event)
644 .await?;
645
646 Ok(serde_json::json!({
647 "status": "success",
648 "message": "Security event sent"
649 }))
650 }
651 "receive_event" => {
652 let security_event = SecurityEvent {
653 event_id: format!("evt-{}", uuid::Uuid::new_v4()),
654 event_type: request["event"]["event_type"]
655 .as_str()
656 .unwrap_or("unknown")
657 .to_string(),
658 subject: request["event"]["subject"]
659 .as_str()
660 .unwrap_or("")
661 .to_string(),
662 timestamp: chrono::Utc::now(),
663 data: request["event"]["data"].clone(),
664 severity: EventSeverity::Info,
665 };
666
667 self.shared_signals_manager
668 .receive_event(security_event)
669 .await?;
670
671 Ok(serde_json::json!({
672 "status": "success",
673 "message": "Security event processed"
674 }))
675 }
676 _ => Err(AuthError::validation(format!(
677 "Unsupported shared signals event type: {}",
678 event_type
679 ))),
680 }
681 }
682
683 async fn handle_oidc_provider_request(&self, request: Value) -> Result<Value> {
685 let request_type = request["request_type"]
686 .as_str()
687 .ok_or_else(|| AuthError::auth_method("oidc_provider", "Missing request_type"))?;
688
689 match request_type {
690 "discovery" => {
691 self.generate_oidc_discovery_document().await
693 }
694 "jwks" => {
695 self.generate_oidc_jwks().await
697 }
698 "userinfo" => {
699 self.handle_oidc_userinfo_request(request).await
701 }
702 _ => Err(AuthError::validation(format!(
703 "Unsupported OIDC provider request type: {}",
704 request_type
705 ))),
706 }
707 }
708
709 async fn generate_oidc_discovery_document(&self) -> Result<Value> {
711 let base_discovery = self.oidc_provider.as_ref().discovery_document()?;
713
714 let mut extensions_supported = Vec::new();
716 let mut scopes_supported = base_discovery.scopes_supported.clone();
717
718 if self.config.enable_heart {
720 extensions_supported.push("heart");
721 scopes_supported.push("heart".to_string());
722 }
723 if self.config.enable_shared_signals {
724 extensions_supported.push("shared_signals");
725 scopes_supported.push("shared_signals".to_string());
726 }
727 if self.config.enable_ekyc {
728 extensions_supported.push("ekyc");
729 scopes_supported.push("ekyc".to_string());
730 }
731 if self.config.enable_fastfed {
732 extensions_supported.push("fastfed");
733 scopes_supported.push("fastfed".to_string());
734 }
735
736 Ok(serde_json::json!({
737 "issuer": base_discovery.issuer,
738 "authorization_endpoint": base_discovery.authorization_endpoint,
739 "token_endpoint": base_discovery.token_endpoint,
740 "userinfo_endpoint": base_discovery.userinfo_endpoint,
741 "jwks_uri": base_discovery.jwks_uri,
742 "registration_endpoint": base_discovery.registration_endpoint,
743 "scopes_supported": scopes_supported,
744 "extensions_supported": extensions_supported,
745 "response_types_supported": base_discovery.response_types_supported,
746 "grant_types_supported": base_discovery.grant_types_supported.unwrap_or_else(|| vec![
747 "authorization_code".to_string(),
748 "implicit".to_string(),
749 "refresh_token".to_string()
750 ]),
751 "subject_types_supported": base_discovery.subject_types_supported,
752 "id_token_signing_alg_values_supported": base_discovery.id_token_signing_alg_values_supported,
753 "userinfo_signing_alg_values_supported": base_discovery.userinfo_signing_alg_values_supported.unwrap_or_default(),
754 "token_endpoint_auth_methods_supported": base_discovery.token_endpoint_auth_methods_supported.unwrap_or_default(),
755 "claims_supported": base_discovery.claims_supported.unwrap_or_default(),
756 "claims_parameter_supported": base_discovery.claims_parameter_supported.unwrap_or(false),
757 "request_parameter_supported": base_discovery.request_parameter_supported.unwrap_or(false),
758 "request_uri_parameter_supported": base_discovery.request_uri_parameter_supported.unwrap_or(false),
759 "code_challenge_methods_supported": base_discovery.code_challenge_methods_supported.unwrap_or_default()
760 }))
761 }
762
763 async fn generate_oidc_jwks(&self) -> Result<Value> {
765 let jwk_set = self.oidc_provider.as_ref().generate_jwks()?;
767 Ok(serde_json::to_value(jwk_set)?)
768 }
769
770 async fn handle_oidc_userinfo_request(&self, request: Value) -> Result<Value> {
772 let access_token = request["access_token"]
773 .as_str()
774 .ok_or_else(|| AuthError::auth_method("oidc_provider", "Missing access_token"))?;
775
776 let userinfo = self
778 .oidc_provider
779 .as_ref()
780 .get_userinfo(access_token)
781 .await?;
782
783 let mut userinfo_json = serde_json::json!({
785 "sub": userinfo.sub,
786 "name": userinfo.name,
787 "email": userinfo.email,
788 "email_verified": userinfo.email_verified,
789 "given_name": userinfo.given_name,
790 "family_name": userinfo.family_name,
791 "picture": userinfo.picture,
792 "locale": userinfo.locale,
793 "phone_number": userinfo.phone_number,
794 "phone_number_verified": userinfo.phone_number_verified,
795 "address": userinfo.address,
796 "updated_at": userinfo.updated_at
797 });
798
799 let mut extensions = serde_json::Map::new();
801 if self.config.enable_heart {
802 extensions.insert("heart_verified".to_string(), serde_json::Value::Bool(true));
803 }
804 if self.config.enable_ekyc {
805 extensions.insert("ekyc_verified".to_string(), serde_json::Value::Bool(true));
806 }
807 if self.config.enable_shared_signals {
808 extensions.insert(
809 "shared_signals_enabled".to_string(),
810 serde_json::Value::Bool(true),
811 );
812 }
813 if self.config.enable_fastfed {
814 extensions.insert("fastfed_enabled".to_string(), serde_json::Value::Bool(true));
815 }
816
817 if !extensions.is_empty() {
818 userinfo_json["extensions"] = serde_json::Value::Object(extensions);
819 }
820
821 Ok(userinfo_json)
822 }
823}
824
825impl HeartManager {
826 pub fn new(config: HeartConfig) -> Self {
828 Self {
829 config,
830 sessions: Arc::new(RwLock::new(HashMap::new())),
831 }
832 }
833
834 pub async fn handle_authorization(&self, request: Value) -> Result<Value> {
836 let provider_id = request["provider_id"]
839 .as_str()
840 .ok_or_else(|| AuthError::auth_method("heart", "Missing provider_id"))?;
841
842 let patient_id = request["patient_id"].as_str();
843 let empty_resources = vec![];
844 let requested_resources = request["resources"].as_array().unwrap_or(&empty_resources);
845
846 if !self
848 .config
849 .authorized_providers
850 .contains(&provider_id.to_string())
851 {
852 return Err(AuthError::auth_method(
853 "heart",
854 "Unauthorized healthcare provider",
855 ));
856 }
857
858 Ok(json!({
859 "status": "authorized",
860 "heart_compliant": true,
861 "organization_id": self.config.organization_id,
862 "provider_id": provider_id,
863 "patient_id": patient_id,
864 "authorized_resources": requested_resources
865 }))
866 }
867
868 pub async fn create_session(
870 &self,
871 provider_id: &str,
872 patient_id: Option<&str>,
873 authorized_resources: Vec<String>,
874 ) -> Result<String> {
875 let session_id = Uuid::new_v4().to_string();
876
877 let session = HeartSession {
878 session_id: session_id.clone(),
879 patient_id: patient_id.map(|s| s.to_string()),
880 provider_id: provider_id.to_string(),
881 authorized_resources,
882 consent_status: ConsentStatus::Pending,
883 metadata: HashMap::new(),
884 };
885
886 let mut sessions = self.sessions.write().await;
887 sessions.insert(session_id.clone(), session);
888
889 Ok(session_id)
890 }
891}
892
893impl SharedSignalsManager {
894 pub fn new(config: SharedSignalsConfig) -> Self {
896 Self {
897 config,
898 receivers: Arc::new(RwLock::new(HashMap::new())),
899 transmitters: Arc::new(RwLock::new(HashMap::new())),
900 }
901 }
902
903 pub async fn send_event(&self, event: SecurityEvent) -> Result<()> {
905 let event_jwt = self.create_event_jwt(&event).await?;
908
909 let transmitters = self.transmitters.read().await;
910 for (receiver_url, transmitter) in transmitters.iter() {
911 match transmitter.send_event(&event_jwt, receiver_url).await {
912 Ok(_) => tracing::info!("Security event sent to {}", receiver_url),
913 Err(e) => tracing::error!("Failed to send event to {}: {}", receiver_url, e),
914 }
915 }
916
917 tracing::info!("Security event transmitted: {:?}", event);
918 Ok(())
919 }
920
921 pub async fn receive_event(&self, event: SecurityEvent) -> Result<()> {
923 if !self.is_event_type_supported(&event.event_type) {
925 return Err(AuthError::auth_method(
926 "shared_signals",
927 format!("Unsupported event type: {}", event.event_type),
928 ));
929 }
930
931 if !self.is_event_valid_age(&event) {
933 return Err(AuthError::auth_method("shared_signals", "Event too old"));
934 }
935
936 if self.config.verify_events && !self.validate_event_signature(&event).await? {
938 return Err(AuthError::auth_method(
939 "shared_signals",
940 "Invalid event signature",
941 ));
942 }
943
944 match event.event_type.as_str() {
946 "session_revoked" => self.handle_session_revocation(&event).await?,
947 "account_disabled" => self.handle_account_disabled(&event).await?,
948 "credential_change" => self.handle_credential_change(&event).await?,
949 "fraud_detected" => self.handle_fraud_detection(&event).await?,
950 _ => tracing::warn!("Unknown security event type: {}", event.event_type),
951 }
952
953 tracing::info!("Processed security event: {:?}", event);
954 Ok(())
955 }
956
957 async fn create_event_jwt(&self, event: &SecurityEvent) -> Result<String> {
959 use serde_json;
961 let event_json = serde_json::to_string(event)
962 .map_err(|e| AuthError::internal(format!("Failed to serialize event: {}", e)))?;
963
964 Ok(format!(
966 "signed.jwt.{}",
967 BASE64_STANDARD.encode(&event_json)
968 ))
969 }
970
971 async fn validate_event_signature(&self, event: &SecurityEvent) -> Result<bool> {
972 if let Some(jwt_token) = event.data.get("jwt") {
977 use jsonwebtoken::{Algorithm, DecodingKey, Validation};
980
981 let decoding_key = if let Ok(key_material) =
983 std::env::var("SHARED_SIGNALS_VERIFICATION_KEY")
984 {
985 if key_material.starts_with("-----BEGIN PUBLIC KEY-----") {
987 match DecodingKey::from_rsa_pem(key_material.as_bytes()) {
989 Ok(key) => key,
990 Err(e) => {
991 tracing::error!("Failed to parse RSA public key: {}", e);
992 return Err(AuthError::InvalidRequest(
993 "Invalid RSA public key configuration".to_string(),
994 ));
995 }
996 }
997 } else if key_material.starts_with("-----BEGIN EC PUBLIC KEY-----") {
998 match DecodingKey::from_ec_pem(key_material.as_bytes()) {
1000 Ok(key) => key,
1001 Err(e) => {
1002 tracing::error!("Failed to parse ECDSA public key: {}", e);
1003 return Err(AuthError::InvalidRequest(
1004 "Invalid ECDSA public key configuration".to_string(),
1005 ));
1006 }
1007 }
1008 } else {
1009 DecodingKey::from_secret(key_material.as_bytes())
1011 }
1012 } else {
1013 tracing::error!(
1015 "🔐 SECURITY WARNING: Using development key for shared signals - configure SHARED_SIGNALS_VERIFICATION_KEY for production"
1016 );
1017 tracing::warn!(
1018 "Set SHARED_SIGNALS_VERIFICATION_KEY environment variable with your production key"
1019 );
1020 DecodingKey::from_secret(
1021 "shared_signals_development_key_not_for_production".as_ref(),
1022 )
1023 };
1024
1025 let algorithm = if std::env::var("SHARED_SIGNALS_VERIFICATION_KEY").is_ok() {
1027 if let Ok(alg_str) = std::env::var("SHARED_SIGNALS_ALGORITHM") {
1029 match alg_str.as_str() {
1030 "HS256" => Algorithm::HS256,
1031 "HS384" => Algorithm::HS384,
1032 "HS512" => Algorithm::HS512,
1033 "RS256" => Algorithm::RS256,
1034 "RS384" => Algorithm::RS384,
1035 "RS512" => Algorithm::RS512,
1036 "ES256" => Algorithm::ES256,
1037 "ES384" => Algorithm::ES384,
1038 _ => {
1039 tracing::warn!("Unknown algorithm {}, defaulting to HS256", alg_str);
1040 Algorithm::HS256
1041 }
1042 }
1043 } else {
1044 Algorithm::HS256
1045 }
1046 } else {
1047 Algorithm::HS256
1048 };
1049
1050 let mut validation = Validation::new(algorithm);
1051 validation.validate_exp = true;
1052 validation.validate_nbf = true;
1053 validation.validate_aud = false; if let Ok(expected_issuer) = std::env::var("SHARED_SIGNALS_ISSUER") {
1057 validation.set_issuer(&[expected_issuer]);
1058 tracing::debug!("Validating shared signals issuer");
1059 }
1060
1061 match jsonwebtoken::decode::<serde_json::Value>(
1062 jwt_token.as_str().unwrap_or(""),
1063 &decoding_key,
1064 &validation,
1065 ) {
1066 Ok(_) => {
1067 tracing::info!("Security event JWT signature validated successfully");
1068 Ok(true)
1069 }
1070 Err(e) => {
1071 tracing::warn!("Security event JWT signature validation failed: {}", e);
1072 Ok(false)
1073 }
1074 }
1075 } else {
1076 tracing::info!("Non-JWT security event - performing basic validation");
1078 Ok(!event.subject.is_empty() && !event.event_type.is_empty())
1079 }
1080 }
1081
1082 async fn handle_session_revocation(&self, event: &SecurityEvent) -> Result<()> {
1083 tracing::info!("Handling session revocation for event: {}", event.event_id);
1084
1085 if let Some(session_id) = event.data.get("session_id") {
1087 let session_id_str = session_id.as_str().unwrap_or("");
1088 tracing::info!("Revoking session: {}", session_id_str);
1089
1090 if let Err(e) = self.remove_session_from_store(session_id_str).await {
1093 tracing::error!("Failed to remove session from store: {}", e);
1094 }
1095
1096 if let Err(e) = self.add_session_to_revocation_list(session_id_str).await {
1098 tracing::error!("Failed to add session to revocation list: {}", e);
1099 }
1100
1101 if let Err(e) = self
1103 .notify_resource_servers_session_revoked(session_id_str)
1104 .await
1105 {
1106 tracing::error!("Failed to notify resource servers: {}", e);
1107 }
1108
1109 self.log_session_revocation_audit(session_id_str, &event.subject)
1111 .await;
1112
1113 self.execute_session_revocation(session_id_str).await;
1115
1116 tracing::info!(
1117 "Session revocation completed for session: {} - all associated tokens invalidated",
1118 session_id_str
1119 );
1120 } else {
1121 tracing::info!("Revoking all sessions for subject: {}", event.subject);
1123 self.revoke_all_user_sessions(&event.subject).await;
1124 }
1125
1126 Ok(())
1127 }
1128
1129 async fn handle_account_disabled(&self, event: &SecurityEvent) -> Result<()> {
1130 tracing::info!("Handling account disabled for event: {}", event.event_id);
1131
1132 let reason = event
1134 .data
1135 .get("reason")
1136 .and_then(|v| v.as_str())
1137 .unwrap_or("Security event");
1138
1139 let disable_timestamp = event
1140 .data
1141 .get("disable_timestamp")
1142 .and_then(|v| v.as_str())
1143 .unwrap_or("immediate");
1144
1145 tracing::warn!(
1146 "Account disabled for subject: {} - Reason: {} - Timestamp: {}",
1147 event.subject,
1148 reason,
1149 disable_timestamp
1150 );
1151
1152 let disable_request = AccountDisableRequest {
1161 user_id: event.subject.clone(),
1162 reason: reason.to_string(),
1163 disable_timestamp: Utc::now(),
1164 initiated_by: "security_event_handler".to_string(),
1165 };
1166
1167 self.execute_account_disable(&disable_request).await?;
1169
1170 tracing::info!("Account successfully disabled for user: {}", event.subject);
1171
1172 Ok(())
1173 }
1174
1175 async fn execute_account_disable(&self, request: &AccountDisableRequest) -> Result<()> {
1177 tracing::info!("Executing account disable for user: {}", request.user_id);
1178
1179 self.revoke_all_user_sessions(&request.user_id).await;
1183 tracing::info!(
1184 "Revoked all active sessions for disabled user: {}",
1185 request.user_id
1186 );
1187
1188 self.notify_resource_servers_account_disabled(&request.user_id)
1190 .await?;
1191
1192 self.log_account_disable_audit(request).await?;
1194
1195 self.trigger_security_monitoring_alert(
1197 "account_disabled",
1198 &request.user_id,
1199 &request.reason,
1200 )
1201 .await?;
1202
1203 tracing::info!(
1205 "Account disable executed - User: {}, Reason: {}, Timestamp: {}",
1206 request.user_id,
1207 request.reason,
1208 request.disable_timestamp.to_rfc3339()
1209 );
1210
1211 Ok(())
1212 }
1213
1214 async fn notify_resource_servers_account_disabled(&self, user_id: &str) -> Result<()> {
1216 let _notification = serde_json::json!({
1217 "type": "account_disabled",
1218 "user_id": user_id,
1219 "timestamp": chrono::Utc::now().to_rfc3339(),
1220 "issuer": &self.config.endpoint_url,
1221 "action_required": "invalidate_user_tokens"
1222 });
1223
1224 let transmitters = self.transmitters.read().await;
1228 if transmitters.is_empty() {
1229 tracing::debug!(
1230 "No registered signal transmitters — skipping account-disabled notification for user {}",
1231 user_id
1232 );
1233 } else {
1234 for (id, tx) in transmitters.iter() {
1235 for endpoint in &tx.endpoints {
1236 tracing::debug!(
1237 "Notifying transmitter {} endpoint {} about account disabled: {}",
1238 id,
1239 endpoint,
1240 user_id
1241 );
1242 }
1244 }
1245 }
1246
1247 tracing::info!("Sent account disabled notifications for user: {}", user_id);
1248 Ok(())
1249 }
1250
1251 async fn log_account_disable_audit(&self, request: &AccountDisableRequest) -> Result<()> {
1253 let audit_entry = serde_json::json!({
1254 "event_type": "account_disabled",
1255 "user_id": request.user_id,
1256 "reason": &request.reason,
1257 "timestamp": chrono::Utc::now().to_rfc3339(),
1258 "source": "oidc_extensions",
1259 "severity": "high"
1260 });
1261
1262 tracing::warn!(
1263 "SECURITY AUDIT: Account disabled - User: {}, Reason: {}, Event: {}",
1264 request.user_id,
1265 request.reason,
1266 audit_entry
1267 );
1268
1269 Ok(())
1271 }
1272
1273 async fn trigger_security_monitoring_alert(
1275 &self,
1276 alert_type: &str,
1277 user_id: &str,
1278 reason: &str,
1279 ) -> Result<()> {
1280 let alert = serde_json::json!({
1281 "alert_type": alert_type,
1282 "severity": "high",
1283 "user_id": user_id,
1284 "reason": reason,
1285 "timestamp": chrono::Utc::now().to_rfc3339(),
1286 "source": "shared_signals_manager"
1287 });
1288
1289 tracing::error!(
1290 "SECURITY ALERT: {} - User: {}, Reason: {}, Details: {}",
1291 alert_type.to_uppercase(),
1292 user_id,
1293 reason,
1294 alert
1295 );
1296
1297 Ok(())
1299 }
1300
1301 async fn execute_session_revocation(&self, session_id: &str) {
1303 tracing::info!("Executing session revocation for session: {}", session_id);
1304
1305 tracing::info!(
1309 "Session revocation workflow completed for session: {} - all associated tokens and grants invalidated",
1310 session_id
1311 );
1312 }
1313
1314 async fn remove_session_from_store(&self, session_id: &str) -> Result<()> {
1316 tracing::debug!("Removing session {} from active sessions store", session_id);
1317
1318 tracing::info!(
1322 "Session {} removed from active store (no-op: no backing store configured)",
1323 session_id
1324 );
1325 Ok(())
1326 }
1327
1328 async fn add_session_to_revocation_list(&self, session_id: &str) -> Result<()> {
1330 tracing::debug!("Adding session {} to revocation list", session_id);
1331
1332 let revocation_entry = serde_json::json!({
1335 "session_id": session_id,
1336 "revoked_at": chrono::Utc::now().to_rfc3339(),
1337 "reason": "security_event"
1338 });
1339
1340 tracing::info!(
1341 "Session {} added to revocation list: {}",
1342 session_id,
1343 revocation_entry
1344 );
1345 Ok(())
1346 }
1347
1348 async fn notify_resource_servers_session_revoked(&self, session_id: &str) -> Result<()> {
1350 tracing::debug!(
1351 "Notifying resource servers about session {} revocation",
1352 session_id
1353 );
1354
1355 let notification = serde_json::json!({
1358 "type": "session_revoked",
1359 "session_id": session_id,
1360 "timestamp": chrono::Utc::now().to_rfc3339(),
1361 "issuer": &self.config.endpoint_url
1362 });
1363
1364 let transmitters = self.transmitters.read().await;
1366 if transmitters.is_empty() {
1367 tracing::debug!(
1368 "No registered signal transmitters — skipping session-revocation notification for session {}",
1369 session_id
1370 );
1371 } else {
1372 for (id, tx) in transmitters.iter() {
1373 for endpoint in &tx.endpoints {
1374 tracing::info!(
1375 "Notifying transmitter {} endpoint {} of session revocation: {}",
1376 id,
1377 endpoint,
1378 notification
1379 );
1380 }
1382 }
1383 }
1384
1385 Ok(())
1386 }
1387
1388 async fn log_session_revocation_audit(&self, session_id: &str, subject: &str) {
1390 let audit_event = serde_json::json!({
1391 "event_type": "session_revoked",
1392 "session_id": session_id,
1393 "subject": subject,
1394 "timestamp": chrono::Utc::now().to_rfc3339(),
1395 "initiator": "security_event_handler",
1396 "reason": "security_event_triggered"
1397 });
1398
1399 tracing::info!(target: "audit", "Session revocation audit: {}", audit_event);
1400
1401 }
1403
1404 async fn revoke_all_user_sessions(&self, subject: &str) {
1406 tracing::info!("Revoking all sessions for subject: {}", subject);
1407
1408 let audit_event = serde_json::json!({
1414 "event_type": "all_sessions_revoked",
1415 "subject": subject,
1416 "timestamp": chrono::Utc::now().to_rfc3339(),
1417 "reason": "security_event_fallback"
1418 });
1419
1420 tracing::info!(target: "audit", "All sessions revoked for user: {}", audit_event);
1421 }
1422
1423 async fn handle_credential_change(&self, event: &SecurityEvent) -> Result<()> {
1424 tracing::info!("Handling credential change for event: {}", event.event_id);
1425
1426 let credential_type = event
1427 .data
1428 .get("credential_type")
1429 .and_then(|v| v.as_str())
1430 .unwrap_or("unknown");
1431
1432 let change_type = event
1433 .data
1434 .get("change_type")
1435 .and_then(|v| v.as_str())
1436 .unwrap_or("update");
1437
1438 tracing::info!(
1439 "Credential change detected - Subject: {}, Type: {}, Change: {}",
1440 event.subject,
1441 credential_type,
1442 change_type
1443 );
1444
1445 match change_type {
1446 "password_change" => {
1447 if let Some(session_to_keep) = event.data.get("session_id") {
1449 tracing::info!(
1450 "Revoking all sessions except: {}",
1451 session_to_keep.as_str().unwrap_or("")
1452 );
1453 }
1454 }
1456 "mfa_enabled" => {
1457 tracing::info!(
1459 "MFA enabled for user: {} - security posture improved",
1460 event.subject
1461 );
1462 }
1463 "mfa_disabled" => {
1464 tracing::warn!(
1466 "MFA disabled for user: {} - consider security review",
1467 event.subject
1468 );
1469 }
1470 "recovery_codes_reset" => {
1471 tracing::info!("Recovery codes reset for user: {}", event.subject);
1473 }
1474 _ => {
1475 tracing::info!("General credential change for user: {}", event.subject);
1476 }
1477 }
1478
1479 Ok(())
1480 }
1481
1482 async fn handle_fraud_detection(&self, event: &SecurityEvent) -> Result<()> {
1483 tracing::info!("Handling fraud detection for event: {}", event.event_id);
1484 Ok(())
1486 }
1487
1488 pub async fn register_receiver(
1490 &self,
1491 receiver_id: String,
1492 receiver: SignalReceiver,
1493 ) -> Result<()> {
1494 let mut receivers = self.receivers.write().await;
1495 receivers.insert(receiver_id.clone(), receiver);
1496 tracing::info!("Signal receiver registered: {}", receiver_id);
1497 Ok(())
1498 }
1499
1500 pub async fn unregister_receiver(&self, receiver_id: &str) -> Result<()> {
1502 let mut receivers = self.receivers.write().await;
1503 if receivers.remove(receiver_id).is_some() {
1504 tracing::info!("Signal receiver unregistered: {}", receiver_id);
1505 Ok(())
1506 } else {
1507 Err(AuthError::auth_method(
1508 "shared_signals",
1509 "Receiver not found",
1510 ))
1511 }
1512 }
1513
1514 pub fn get_config(&self) -> &SharedSignalsConfig {
1516 &self.config
1517 }
1518
1519 pub fn is_event_type_supported(&self, event_type: &str) -> bool {
1521 self.config
1522 .supported_events
1523 .contains(&event_type.to_string())
1524 }
1525
1526 pub fn is_event_valid_age(&self, event: &SecurityEvent) -> bool {
1528 let now = chrono::Utc::now();
1529 let event_age = now.signed_duration_since(event.timestamp).num_seconds();
1530 event_age <= self.config.max_event_age
1531 }
1532
1533 pub async fn list_receivers(&self) -> Vec<String> {
1535 let receivers = self.receivers.read().await;
1536 receivers.keys().cloned().collect()
1537 }
1538}
1539
1540impl EkycManager {
1541 pub fn new(config: EkycConfig) -> Self {
1543 Self {
1544 config,
1545 verification_sessions: Arc::new(RwLock::new(HashMap::new())),
1546 }
1547 }
1548
1549 pub async fn handle_verification_request(&self, request: Value) -> Result<Value> {
1551 let user_id = request["user_id"]
1553 .as_str()
1554 .ok_or_else(|| AuthError::auth_method("ekyc", "Missing user_id"))?;
1555
1556 let requested_ial = request["requested_ial"]
1557 .as_str()
1558 .and_then(|s| s.parse::<u8>().ok())
1559 .unwrap_or(1);
1560
1561 if requested_ial < self.config.required_ial.clone() as u8 {
1563 return Err(AuthError::auth_method(
1564 "ekyc",
1565 "Insufficient identity assurance level",
1566 ));
1567 }
1568
1569 let session_id = Uuid::new_v4().to_string();
1571 let ekyc_session = EkycSession {
1572 session_id: session_id.clone(),
1573 user_id: user_id.to_string(),
1574 verification_status: VerificationStatus::Pending,
1575 achieved_ial: IdentityAssuranceLevel::from_u8(requested_ial),
1576 verification_results: HashMap::new(),
1577 };
1578
1579 let mut sessions = self.verification_sessions.write().await;
1581 sessions.insert(session_id.clone(), ekyc_session);
1582
1583 Ok(json!({
1584 "status": "verification_initiated",
1585 "session_id": session_id,
1586 "required_ial": requested_ial,
1587 "required_methods": self.config.verification_methods,
1588 "verification_endpoint": format!("/ekyc/verify/{}", session_id)
1589 }))
1590 }
1591
1592 pub async fn start_verification(&self, user_id: &str) -> Result<String> {
1594 let session_id = Uuid::new_v4().to_string();
1595
1596 let session = EkycSession {
1597 session_id: session_id.clone(),
1598 user_id: user_id.to_string(),
1599 verification_status: VerificationStatus::Pending,
1600 achieved_ial: IdentityAssuranceLevel::IAL1,
1601 verification_results: HashMap::new(),
1602 };
1603
1604 let mut sessions = self.verification_sessions.write().await;
1605 sessions.insert(session_id.clone(), session);
1606
1607 Ok(session_id)
1608 }
1609}
1610
1611impl FastFedManager {
1612 pub fn new(config: FastFedConfig) -> Self {
1614 Self {
1615 config,
1616 federations: Arc::new(RwLock::new(HashMap::new())),
1617 }
1618 }
1619
1620 pub async fn handle_federation_request(&self, request: Value) -> Result<Value> {
1622 let partner_org = request["partner_organization"]
1624 .as_str()
1625 .ok_or_else(|| AuthError::auth_method("fastfed", "Missing partner_organization"))?;
1626
1627 let federation_metadata = request["federation_metadata"]
1628 .as_object()
1629 .ok_or_else(|| AuthError::auth_method("fastfed", "Missing federation_metadata"))?;
1630
1631 if !self
1633 .config
1634 .trusted_partners
1635 .contains(&partner_org.to_string())
1636 {
1637 return Err(AuthError::auth_method(
1638 "fastfed",
1639 "Untrusted federation partner",
1640 ));
1641 }
1642
1643 let required_capabilities = ["oidc", "saml2", "scim"];
1645 for capability in required_capabilities {
1646 if !federation_metadata.contains_key(capability) {
1647 return Err(AuthError::auth_method(
1648 "fastfed",
1649 format!("Missing required capability: {}", capability),
1650 ));
1651 }
1652 }
1653
1654 let federation_id = if self.config.auto_provisioning {
1656 Some(self.establish_federation(partner_org).await?)
1657 } else {
1658 None
1659 };
1660
1661 Ok(json!({
1662 "status": "federation_request_accepted",
1663 "federation_id": federation_id,
1664 "auto_provisioning": self.config.auto_provisioning,
1665 "supported_protocols": self.config.supported_protocols,
1666 "next_steps": if federation_id.is_some() {
1667 "Federation automatically established"
1668 } else {
1669 "Manual federation approval required"
1670 }
1671 }))
1672 }
1673
1674 pub async fn establish_federation(&self, partner_org: &str) -> Result<String> {
1676 let relationship_id = Uuid::new_v4().to_string();
1677
1678 let relationship = FederationRelationship {
1679 relationship_id: relationship_id.clone(),
1680 partner_org: partner_org.to_string(),
1681 status: FederationStatus::Pending,
1682 config: json!({}),
1683 created_at: Utc::now(),
1684 };
1685
1686 let mut federations = self.federations.write().await;
1687 federations.insert(relationship_id.clone(), relationship);
1688
1689 Ok(relationship_id)
1690 }
1691}
1692
1693impl Default for OidcExtensionsConfig {
1696 fn default() -> Self {
1697 Self {
1698 enable_heart: true,
1699 enable_shared_signals: true,
1700 enable_ekyc: true,
1701 enable_fastfed: true,
1702 enable_modrna: false, enable_igov: false, enable_authzen: false, }
1706 }
1707}
1708
1709impl Default for HeartConfig {
1710 fn default() -> Self {
1711 Self {
1712 organization_id: "example-healthcare-org".to_string(),
1713 fhir_endpoint: "https://example.com/fhir".to_string(),
1714 required_scopes: vec!["patient/*.read".to_string(), "user/*.read".to_string()],
1715 enhanced_consent: true,
1716 authorized_providers: Vec::new(), audit_config: HeartAuditConfig::default(),
1718 }
1719 }
1720}
1721
1722impl Default for HeartAuditConfig {
1723 fn default() -> Self {
1724 Self {
1725 enable_atna: true,
1726 syslog_endpoint: None,
1727 audit_level: HeartAuditLevel::Enhanced,
1728 }
1729 }
1730}
1731
1732impl Default for SharedSignalsConfig {
1733 fn default() -> Self {
1734 Self {
1735 endpoint_url: "https://example.com/signals".to_string(),
1736 supported_events: vec![
1737 "security_advisory".to_string(),
1738 "account_disabled".to_string(),
1739 "credential_change".to_string(),
1740 "session_revoked".to_string(),
1741 ],
1742 max_event_age: 3600, verify_events: true,
1744 }
1745 }
1746}
1747
1748#[derive(Clone)]
1750pub struct VerificationSession {
1751 pub session_id: String,
1752 pub user_id: String,
1753 pub requested_ial: IdentityAssuranceLevel,
1754 pub status: String,
1755 pub required_methods: Vec<VerificationMethod>,
1756 pub completed_verifications: Vec<VerificationMethod>,
1757 pub created_at: SystemTime,
1758}
1759
1760impl std::fmt::Debug for VerificationSession {
1761 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1762 let mut d = f.debug_struct("VerificationSession");
1763 d.field(
1764 "session_id",
1765 &crate::utils::redact::redacted(&self.session_id),
1766 );
1767 d.field("user_id", &self.user_id);
1768 d.field("requested_ial", &self.requested_ial);
1769 d.field("status", &self.status);
1770 d.field("required_methods", &self.required_methods);
1771 d.field("completed_verifications", &self.completed_verifications);
1772 d.field("created_at", &self.created_at);
1773 d.finish()
1774 }
1775}
1776
1777impl IdentityAssuranceLevel {
1778 pub fn from_u8(level: u8) -> Self {
1779 match level {
1780 1 => IdentityAssuranceLevel::IAL1,
1781 2 => IdentityAssuranceLevel::IAL2,
1782 3 => IdentityAssuranceLevel::IAL3,
1783 _ => IdentityAssuranceLevel::IAL1,
1784 }
1785 }
1786}
1787
1788pub struct EventTransmitter {
1790 pub endpoint: String,
1791 pub public_key: String,
1792}
1793
1794impl EventTransmitter {
1795 pub async fn send_event(&self, event_jwt: &str, receiver_url: &str) -> Result<()> {
1796 tracing::info!("Sending event JWT to {}: {}", receiver_url, event_jwt);
1797 Ok(())
1799 }
1800}
1801
1802impl Default for EkycConfig {
1803 fn default() -> Self {
1804 Self {
1805 verification_provider: "example-kyc-provider".to_string(),
1806 required_ial: IdentityAssuranceLevel::IAL2,
1807 verification_methods: vec![VerificationMethod::Document, VerificationMethod::Database],
1808 document_verification: true,
1809 biometric_verification: false,
1810 }
1811 }
1812}
1813
1814impl Default for FastFedConfig {
1815 fn default() -> Self {
1816 Self {
1817 metadata_endpoint: "https://example.com/.well-known/fastfed".to_string(),
1818 supported_protocols: vec!["OIDC".to_string(), "SAML2".to_string()],
1819 auto_provisioning: false, trusted_partners: Vec::new(), trust_anchor: "example-trust-anchor".to_string(),
1822 }
1823 }
1824}
1825
1826#[cfg(test)]
1827mod tests {
1828 use super::*;
1829
1830 #[tokio::test]
1831 async fn test_oidc_extensions_creation() {
1832 let config = OidcExtensionsConfig::default();
1833
1834 assert!(config.enable_heart);
1836 assert!(config.enable_shared_signals);
1837 assert!(config.enable_ekyc);
1838 assert!(config.enable_fastfed);
1839
1840 assert!(!config.enable_modrna);
1842 assert!(!config.enable_igov);
1843 assert!(!config.enable_authzen);
1844 }
1845
1846 #[tokio::test]
1847 async fn test_heart_session_creation() {
1848 let config = HeartConfig::default();
1849 let heart_manager = HeartManager::new(config);
1850
1851 let session_id = heart_manager
1852 .create_session(
1853 "provider123",
1854 Some("patient456"),
1855 vec!["patient/*.read".to_string()],
1856 )
1857 .await
1858 .unwrap();
1859
1860 assert!(!session_id.is_empty());
1861 }
1862
1863 #[tokio::test]
1864 async fn test_ekyc_verification() {
1865 let config = EkycConfig::default();
1866 let ekyc_manager = EkycManager::new(config);
1867
1868 let session_id = ekyc_manager.start_verification("user123").await.unwrap();
1869
1870 assert!(!session_id.is_empty());
1871 }
1872
1873 #[tokio::test]
1874 async fn test_fastfed_federation() {
1875 let config = FastFedConfig::default();
1876 let fastfed_manager = FastFedManager::new(config);
1877
1878 let relationship_id = fastfed_manager
1879 .establish_federation("partner-org")
1880 .await
1881 .unwrap();
1882
1883 assert!(!relationship_id.is_empty());
1884 }
1885}