1use crate::errors::{AuthError, Result};
50use crate::security::secure_jwt::{SecureJwtClaims, SecureJwtConfig, SecureJwtValidator};
51use crate::server::oidc::oidc_response_modes::ResponseMode;
52use crate::server::oidc::oidc_session_management::SessionManager;
53use chrono::{DateTime, Duration, Utc};
54use jsonwebtoken::{DecodingKey, EncodingKey};
55use serde::{Deserialize, Serialize};
56use std::collections::HashMap;
57use std::sync::Arc;
58use tokio::sync::RwLock;
59use uuid::Uuid;
60
61#[derive(Clone)]
63pub struct EnhancedCibaConfig {
64 pub supported_modes: Vec<AuthenticationMode>,
66 pub default_auth_req_expiry: Duration,
68 pub max_polling_interval: u64,
70 pub min_polling_interval: u64,
72 pub enable_consent: bool,
74 pub enable_device_binding: bool,
76 pub supported_response_modes: Vec<ResponseMode>,
78 pub max_binding_message_length: usize,
80 pub enable_advanced_context: bool,
82 pub jwt_config: SecureJwtConfig,
84 pub issuer: String,
86 pub encoding_key: Option<EncodingKey>,
88 pub decoding_key: Option<DecodingKey>,
90 pub access_token_lifetime: u64,
92 pub id_token_lifetime: u64,
94 pub refresh_token_lifetime: u64,
96 pub max_notification_retries: u32,
98 pub notification_retry_backoff: u64,
100 pub notification_timeout: u64,
102}
103
104impl std::fmt::Debug for EnhancedCibaConfig {
105 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
106 f.debug_struct("EnhancedCibaConfig")
107 .field("supported_modes", &self.supported_modes)
108 .field("default_auth_req_expiry", &self.default_auth_req_expiry)
109 .field("max_polling_interval", &self.max_polling_interval)
110 .field("min_polling_interval", &self.min_polling_interval)
111 .field("enable_consent", &self.enable_consent)
112 .field("enable_device_binding", &self.enable_device_binding)
113 .field("supported_response_modes", &self.supported_response_modes)
114 .field(
115 "max_binding_message_length",
116 &self.max_binding_message_length,
117 )
118 .field("enable_advanced_context", &self.enable_advanced_context)
119 .field("issuer", &self.issuer)
120 .field("encoding_key", &self.encoding_key.is_some())
121 .field("decoding_key", &self.decoding_key.is_some())
122 .field("access_token_lifetime", &self.access_token_lifetime)
123 .field("id_token_lifetime", &self.id_token_lifetime)
124 .field("refresh_token_lifetime", &self.refresh_token_lifetime)
125 .field("max_notification_retries", &self.max_notification_retries)
126 .field(
127 "notification_retry_backoff",
128 &self.notification_retry_backoff,
129 )
130 .field("notification_timeout", &self.notification_timeout)
131 .finish()
132 }
133}
134
135impl Default for EnhancedCibaConfig {
136 fn default() -> Self {
137 let mut jwt_config = SecureJwtConfig::default();
138 jwt_config.allowed_token_types.insert("id".to_string());
139 jwt_config.allowed_token_types.insert("ciba".to_string());
140
141 Self {
142 supported_modes: vec![
143 AuthenticationMode::Poll,
144 AuthenticationMode::Ping,
145 AuthenticationMode::Push,
146 ],
147 default_auth_req_expiry: Duration::minutes(10),
148 max_polling_interval: 60,
149 min_polling_interval: 2,
150 enable_consent: true,
151 enable_device_binding: true,
152 supported_response_modes: vec![
153 ResponseMode::Query,
154 ResponseMode::Fragment,
155 ResponseMode::FormPost,
156 ResponseMode::JwtQuery,
157 ],
158 max_binding_message_length: 1024,
159 enable_advanced_context: true,
160 jwt_config,
161 issuer: "auth-framework-ciba".to_string(),
162 encoding_key: None, decoding_key: None, access_token_lifetime: 3600, id_token_lifetime: 3600, refresh_token_lifetime: 86400, max_notification_retries: 3,
168 notification_retry_backoff: 5, notification_timeout: 30, }
171 }
172}
173
174#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
176pub enum AuthenticationMode {
177 Poll,
179 Ping,
181 Push,
183}
184
185#[derive(Clone, Serialize, Deserialize)]
187pub struct EnhancedCibaAuthRequest {
188 pub auth_req_id: String,
190 pub client_id: String,
192 pub user_hint: UserIdentifierHint,
194 pub binding_message: Option<String>,
196 pub auth_context: Option<AuthenticationContext>,
198 pub scopes: Vec<String>,
200 pub mode: AuthenticationMode,
202 pub client_notification_endpoint: Option<String>,
204 pub expires_at: DateTime<Utc>,
206 pub created_at: DateTime<Utc>,
208 pub status: CibaRequestStatus,
210 pub session_id: Option<String>,
212 pub device_binding: Option<DeviceBinding>,
214 pub consent: Option<ConsentInfo>,
216}
217
218impl std::fmt::Debug for EnhancedCibaAuthRequest {
219 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
220 let mut d = f.debug_struct("EnhancedCibaAuthRequest");
221 d.field(
222 "auth_req_id",
223 &crate::utils::redact::redacted(&self.auth_req_id),
224 );
225 d.field("client_id", &self.client_id);
226 d.field("user_hint", &self.user_hint);
227 d.field("binding_message", &self.binding_message);
228 d.field("auth_context", &self.auth_context);
229 d.field("scopes", &self.scopes);
230 d.field("mode", &self.mode);
231 d.field(
232 "client_notification_endpoint",
233 &self.client_notification_endpoint,
234 );
235 d.field("expires_at", &self.expires_at);
236 d.field("created_at", &self.created_at);
237 d.field("status", &self.status);
238 d.field(
239 "session_id",
240 &crate::utils::redact::redacted(&self.session_id),
241 );
242 d.field("device_binding", &self.device_binding);
243 d.field("consent", &self.consent);
244 d.finish()
245 }
246}
247
248#[derive(Clone, Serialize, Deserialize)]
250pub struct EnhancedCibaAuthResponse {
251 pub auth_req_id: String,
253 pub interval: Option<u64>,
255 pub expires_in: u64,
257 pub additional_data: HashMap<String, serde_json::Value>,
259}
260
261impl std::fmt::Debug for EnhancedCibaAuthResponse {
262 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
263 let mut d = f.debug_struct("EnhancedCibaAuthResponse");
264 d.field(
265 "auth_req_id",
266 &crate::utils::redact::redacted(&self.auth_req_id),
267 );
268 d.field("interval", &self.interval);
269 d.field("expires_in", &self.expires_in);
270 d.field(
271 "additional_data",
272 &crate::utils::redact::redacted(&self.additional_data),
273 );
274 d.finish()
275 }
276}
277
278#[derive(Clone, Serialize, Deserialize)]
280pub enum UserIdentifierHint {
281 LoginHint(String),
283 IdTokenHint(String),
285 UserCode(String),
287 PhoneNumber(String),
289 Email(String),
291}
292
293impl std::fmt::Debug for UserIdentifierHint {
294 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
295 use crate::utils::redact::redacted;
296 match self {
297 Self::LoginHint(v) => f.debug_tuple("LoginHint").field(v).finish(),
298 Self::IdTokenHint(v) => f.debug_tuple("IdTokenHint").field(&redacted(v)).finish(),
299 Self::UserCode(v) => f.debug_tuple("UserCode").field(&redacted(v)).finish(),
300 Self::PhoneNumber(v) => f.debug_tuple("PhoneNumber").field(v).finish(),
301 Self::Email(v) => f.debug_tuple("Email").field(v).finish(),
302 }
303 }
304}
305
306#[derive(Debug, Clone, Serialize, Deserialize)]
308pub struct AuthenticationContext {
309 pub transaction_amount: Option<f64>,
311 pub transaction_currency: Option<String>,
313 pub merchant_info: Option<String>,
315 pub risk_score: Option<f64>,
317 pub location: Option<GeoLocation>,
319 pub device_info: Option<DeviceInfo>,
321 pub custom_attributes: HashMap<String, serde_json::Value>,
323}
324
325#[derive(Debug, Clone, Serialize, Deserialize)]
327pub struct GeoLocation {
328 pub latitude: f64,
330 pub longitude: f64,
332 pub accuracy: Option<f64>,
334 pub location_name: Option<String>,
336}
337
338#[derive(Debug, Clone, Serialize, Deserialize)]
340pub struct DeviceInfo {
341 pub device_id: String,
343 pub device_type: String,
345 pub os: Option<String>,
347 pub browser: Option<String>,
349 pub ip_address: Option<String>,
351}
352
353#[derive(Clone, Serialize, Deserialize)]
355pub struct DeviceBinding {
356 pub binding_id: String,
358 pub device_public_key: Option<String>,
360 pub binding_method: DeviceBindingMethod,
362 pub created_at: DateTime<Utc>,
364 pub expires_at: Option<DateTime<Utc>>,
366 pub device_fingerprint: Option<String>,
368 pub challenge: Option<String>,
370 pub challenge_response: Option<String>,
372}
373
374impl std::fmt::Debug for DeviceBinding {
375 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
376 let mut d = f.debug_struct("DeviceBinding");
377 d.field("binding_id", &self.binding_id);
378 d.field("device_public_key", &self.device_public_key);
379 d.field("binding_method", &self.binding_method);
380 d.field("created_at", &self.created_at);
381 d.field("expires_at", &self.expires_at);
382 d.field("device_fingerprint", &self.device_fingerprint);
383 d.field(
384 "challenge",
385 &crate::utils::redact::redacted(&self.challenge),
386 );
387 d.field(
388 "challenge_response",
389 &crate::utils::redact::redacted(&self.challenge_response),
390 );
391 d.finish()
392 }
393}
394
395#[derive(Debug, Clone, Serialize, Deserialize)]
397pub enum DeviceBindingMethod {
398 PublicKey,
400 Certificate,
402 Attestation,
404 Biometric,
406 Platform,
408 Implicit,
410}
411
412#[derive(Debug, Clone, Serialize, Deserialize)]
414pub struct ConsentInfo {
415 pub consent_id: String,
417 pub status: ConsentStatus,
419 pub consented_scopes: Vec<String>,
421 pub expires_at: Option<DateTime<Utc>>,
423 pub created_at: DateTime<Utc>,
425}
426
427#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
429pub enum ConsentStatus {
430 Pending,
432 Granted,
434 Denied,
436 Expired,
438}
439
440#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
442pub enum CibaRequestStatus {
443 Pending,
445 InProgress,
447 Completed,
449 Failed,
451 Expired,
453 Cancelled,
455}
456
457#[derive(Debug)]
459pub struct BackchannelAuthParams<'a> {
460 pub client_id: &'a str,
461 pub user_hint: UserIdentifierHint,
462 pub binding_message: Option<String>,
463 pub auth_context: Option<AuthenticationContext>,
464 pub scopes: Vec<String>,
465 pub mode: AuthenticationMode,
466 pub client_notification_endpoint: Option<String>,
467}
468
469pub struct EnhancedCibaManager {
471 config: EnhancedCibaConfig,
473 auth_requests: Arc<RwLock<HashMap<String, EnhancedCibaAuthRequest>>>,
475 session_manager: Arc<SessionManager>,
477 notification_client: crate::server::core::common_http::HttpClient,
479 jwt_validator: Arc<SecureJwtValidator>,
481}
482
483impl std::fmt::Debug for EnhancedCibaManager {
484 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
485 let mut d = f.debug_struct("EnhancedCibaManager");
486 d.field("config", &self.config);
487 d.field(
488 "auth_requests",
489 &crate::utils::redact::redacted(&self.auth_requests),
490 );
491 d.field("session_manager", &self.session_manager);
492 d.field("notification_client", &self.notification_client);
493 d.field("jwt_validator", &self.jwt_validator);
494 d.finish()
495 }
496}
497
498impl EnhancedCibaManager {
499 pub fn new(config: EnhancedCibaConfig) -> Self {
501 use crate::server::core::common_config::EndpointConfig;
502
503 let jwt_validator = Arc::new(SecureJwtValidator::new(config.jwt_config.clone()));
504
505 let endpoint_config = EndpointConfig::new(&config.issuer);
507 let notification_client = crate::server::core::common_http::HttpClient::new(
508 endpoint_config,
509 )
510 .unwrap_or_else(|_| {
511 let fallback_config = EndpointConfig::new("https://localhost");
513 crate::server::core::common_http::HttpClient::new(fallback_config).unwrap()
514 });
515
516 Self {
517 config,
518 auth_requests: Arc::new(RwLock::new(HashMap::new())),
519 session_manager: Arc::new(SessionManager::new(Default::default())),
520 notification_client,
521 jwt_validator,
522 }
523 }
524
525 pub fn new_with_session_manager(
527 config: EnhancedCibaConfig,
528 session_manager: Arc<SessionManager>,
529 ) -> Self {
530 use crate::server::core::common_config::EndpointConfig;
531
532 let jwt_validator = Arc::new(SecureJwtValidator::new(config.jwt_config.clone()));
533
534 let endpoint_config = EndpointConfig::new(&config.issuer);
536 let notification_client = crate::server::core::common_http::HttpClient::new(
537 endpoint_config,
538 )
539 .unwrap_or_else(|_| {
540 let fallback_config = EndpointConfig::new("https://localhost");
542 crate::server::core::common_http::HttpClient::new(fallback_config).unwrap()
543 });
544
545 Self {
546 config,
547 auth_requests: Arc::new(RwLock::new(HashMap::new())),
548 session_manager,
549 notification_client,
550 jwt_validator,
551 }
552 }
553
554 pub fn configure_keys(&mut self, encoding_key: EncodingKey, decoding_key: DecodingKey) {
556 self.config.encoding_key = Some(encoding_key);
557 self.config.decoding_key = Some(decoding_key);
558 }
559
560 #[cfg(test)]
562 pub fn new_for_testing() -> Self {
563 use jsonwebtoken::{DecodingKey, EncodingKey};
564
565 let config = EnhancedCibaConfig {
566 encoding_key: Some(EncodingKey::from_secret(b"test-secret-key")),
567 decoding_key: Some(DecodingKey::from_secret(b"test-secret-key")),
568 ..Default::default()
569 };
570
571 Self::new(config)
572 }
573
574 pub async fn initiate_backchannel_auth(
576 &self,
577 params: BackchannelAuthParams<'_>,
578 ) -> Result<EnhancedCibaAuthResponse> {
579 if let Some(ref message) = params.binding_message
581 && message.len() > self.config.max_binding_message_length
582 {
583 return Err(AuthError::validation(format!(
584 "Binding message too long: {} > {}",
585 message.len(),
586 self.config.max_binding_message_length
587 )));
588 }
589
590 if !self.config.supported_modes.contains(¶ms.mode) {
592 return Err(AuthError::validation(format!(
593 "Unsupported authentication mode: {:?}",
594 params.mode
595 )));
596 }
597
598 if matches!(
600 params.mode,
601 AuthenticationMode::Ping | AuthenticationMode::Push
602 ) && params.client_notification_endpoint.is_none()
603 {
604 return Err(AuthError::validation(
605 "Notification endpoint required for ping/push modes".to_string(),
606 ));
607 }
608
609 let auth_req_id = Uuid::new_v4().to_string();
610 let now = Utc::now();
611 let expires_at = now + self.config.default_auth_req_expiry;
612
613 let device_binding = if self.config.enable_device_binding {
615 let challenge = Uuid::new_v4().to_string();
616 let device_fingerprint = self.generate_device_fingerprint(¶ms)?;
617
618 Some(DeviceBinding {
619 binding_id: Uuid::new_v4().to_string(),
620 device_public_key: None, binding_method: DeviceBindingMethod::Platform, created_at: now,
623 expires_at: Some(expires_at),
624 device_fingerprint: Some(device_fingerprint),
625 challenge: Some(challenge),
626 challenge_response: None, })
628 } else {
629 None
630 };
631
632 let consent = if self.config.enable_consent {
634 Some(ConsentInfo {
635 consent_id: Uuid::new_v4().to_string(),
636 status: ConsentStatus::Pending,
637 consented_scopes: params.scopes.clone(),
638 expires_at: Some(expires_at),
639 created_at: now,
640 })
641 } else {
642 None
643 };
644
645 let auth_request = EnhancedCibaAuthRequest {
646 auth_req_id: auth_req_id.clone(),
647 client_id: params.client_id.to_string(),
648 user_hint: params.user_hint,
649 binding_message: params.binding_message,
650 auth_context: params.auth_context,
651 scopes: params.scopes,
652 mode: params.mode.clone(),
653 client_notification_endpoint: params.client_notification_endpoint,
654 expires_at,
655 created_at: now,
656 status: CibaRequestStatus::Pending,
657 session_id: None,
658 device_binding,
659 consent,
660 };
661
662 {
664 let mut requests = self.auth_requests.write().await;
665 requests.insert(auth_req_id.clone(), auth_request);
666 }
667
668 let interval = if matches!(params.mode, AuthenticationMode::Poll) {
670 Some(self.config.min_polling_interval)
671 } else {
672 None
673 };
674
675 let expires_in = (expires_at - now).num_seconds() as u64;
676
677 Ok(EnhancedCibaAuthResponse {
678 auth_req_id,
679 interval,
680 expires_in,
681 additional_data: HashMap::new(),
682 })
683 }
684
685 pub async fn poll_auth_request(&self, auth_req_id: &str) -> Result<CibaTokenResponse> {
687 let mut requests = self.auth_requests.write().await;
688
689 let request = requests
690 .get_mut(auth_req_id)
691 .ok_or_else(|| AuthError::auth_method("ciba", "Authentication request not found"))?;
692
693 if Utc::now() > request.expires_at {
695 request.status = CibaRequestStatus::Expired;
696 return Err(AuthError::auth_method(
697 "ciba",
698 "Request expired".to_string(),
699 ));
700 }
701
702 match request.status {
703 CibaRequestStatus::Pending => Err(AuthError::auth_method(
704 "ciba",
705 "authorization_pending".to_string(),
706 )),
707 CibaRequestStatus::InProgress => Err(AuthError::auth_method(
708 "ciba",
709 "authorization_pending".to_string(),
710 )),
711 CibaRequestStatus::Completed => {
712 let session_valid = self
714 .validate_session_for_request(request)
715 .await
716 .unwrap_or(false);
717
718 if !session_valid {
719 return Err(AuthError::auth_method("ciba", "Invalid or expired session"));
720 }
721
722 self.generate_tokens_for_request(request).await
724 }
725 CibaRequestStatus::Failed => {
726 Err(AuthError::auth_method("ciba", "access_denied".to_string()))
727 }
728 CibaRequestStatus::Expired => {
729 Err(AuthError::auth_method("ciba", "expired_token".to_string()))
730 }
731 CibaRequestStatus::Cancelled => {
732 Err(AuthError::auth_method("ciba", "access_denied".to_string()))
733 }
734 }
735 }
736
737 pub async fn complete_auth_request(
739 &self,
740 auth_req_id: &str,
741 user_authenticated: bool,
742 session_id: Option<String>,
743 ) -> Result<()> {
744 let mut requests = self.auth_requests.write().await;
745
746 let request = requests
747 .get_mut(auth_req_id)
748 .ok_or_else(|| AuthError::auth_method("ciba", "Authentication request not found"))?;
749
750 if user_authenticated {
751 request.status = CibaRequestStatus::Completed;
752
753 let mut session_metadata = std::collections::HashMap::new();
755 session_metadata.insert("auth_req_id".to_string(), auth_req_id.to_string());
756 session_metadata.insert("ciba_mode".to_string(), format!("{:?}", request.mode));
757
758 if let Some(ref auth_context) = request.auth_context {
760 if let Some(amount) = auth_context.transaction_amount {
761 session_metadata.insert("transaction_amount".to_string(), amount.to_string());
762 }
763 if let Some(ref currency) = auth_context.transaction_currency {
764 session_metadata.insert("transaction_currency".to_string(), currency.clone());
765 }
766 if let Some(risk_score) = auth_context.risk_score {
767 session_metadata.insert("risk_score".to_string(), risk_score.to_string());
768 }
769 }
770
771 let user_subject = match &request.user_hint {
773 UserIdentifierHint::LoginHint(hint) => {
774 if hint.is_empty() {
776 return Err(AuthError::InvalidRequest(
777 "Login hint cannot be empty".to_string(),
778 ));
779 }
780 hint.clone()
781 }
782 UserIdentifierHint::Email(email) => {
783 if !email.contains('@') {
785 return Err(AuthError::InvalidRequest(
786 "Invalid email format in user hint".to_string(),
787 ));
788 }
789 email.clone()
790 }
791 UserIdentifierHint::PhoneNumber(phone) => {
792 if phone.len() < 10 {
794 return Err(AuthError::InvalidRequest(
795 "Invalid phone number format".to_string(),
796 ));
797 }
798 phone.clone()
799 }
800 UserIdentifierHint::UserCode(code) => {
801 if code.len() < 4 {
803 return Err(AuthError::InvalidRequest("User code too short".to_string()));
804 }
805 code.clone()
806 }
807 UserIdentifierHint::IdTokenHint(token) => {
808 if token.split('.').count() != 3 {
811 return Err(AuthError::InvalidToken(
812 "Invalid JWT format in id_token_hint".to_string(),
813 ));
814 }
815 match self.validate_id_token_hint(token) {
817 Ok(claims) => {
818 claims.sub
820 }
821 Err(e) => {
822 tracing::warn!("JWT validation failed for id_token_hint: {}", e);
823 use std::collections::hash_map::DefaultHasher;
826 use std::hash::{Hash, Hasher};
827 let mut hasher = DefaultHasher::new();
828 token.hash(&mut hasher);
829 format!("fallback_subject_{}", hasher.finish())
830 }
831 }
832 }
833 };
834
835 session_metadata.insert("validated_subject".to_string(), user_subject.clone());
837
838 let _session_manager = &self.session_manager;
840 let new_session_id =
841 session_id.unwrap_or_else(|| format!("ciba_session_{}", Uuid::new_v4()));
842
843 let mut metadata = std::collections::HashMap::new();
845 metadata.insert("auth_req_id".to_string(), auth_req_id.to_string());
846 metadata.insert("ciba_mode".to_string(), format!("{:?}", request.mode));
847 metadata.insert(
848 "session_info".to_string(),
849 serde_json::to_string(&session_metadata).unwrap_or_default(),
850 );
851 metadata.insert("created_by".to_string(), "CIBA".to_string());
852 metadata.insert("ciba_enabled".to_string(), "true".to_string());
853
854 let final_session_id = new_session_id.clone();
858
859 request.session_id = Some(final_session_id.clone());
862
863 tracing::info!(
864 "CIBA session configured: {} for user: {} in mode: {:?}",
865 crate::utils::redact::fingerprint(&final_session_id),
866 user_subject,
867 request.mode
868 );
869
870 if let Some(ref mut consent) = request.consent {
872 consent.status = ConsentStatus::Granted;
873 }
874
875 if matches!(
877 request.mode,
878 AuthenticationMode::Ping | AuthenticationMode::Push
879 ) && let Some(ref endpoint) = request.client_notification_endpoint
880 {
881 self.send_notification(endpoint.as_str(), auth_req_id)
882 .await?;
883 }
884 } else {
885 request.status = CibaRequestStatus::Failed;
886
887 if let Some(ref mut consent) = request.consent {
889 consent.status = ConsentStatus::Denied;
890 }
891 }
892
893 Ok(())
894 }
895
896 async fn send_notification(&self, endpoint: &str, auth_req_id: &str) -> Result<()> {
898 let notification_data = serde_json::json!({
899 "auth_req_id": auth_req_id,
900 "timestamp": Utc::now(),
901 "issuer": self.config.issuer,
902 });
903
904 let mut last_error = None;
905
906 for attempt in 0..self.config.max_notification_retries {
908 let backoff_delay = self.config.notification_retry_backoff * (2_u64.pow(attempt));
909
910 if attempt > 0 {
911 tokio::time::sleep(tokio::time::Duration::from_secs(backoff_delay)).await;
912 }
913
914 let request = self
916 .notification_client
917 .post(endpoint)
918 .timeout(tokio::time::Duration::from_secs(
919 self.config.notification_timeout,
920 ))
921 .header("Content-Type", "application/json")
922 .header("User-Agent", "AuthFramework-CIBA/1.0")
923 .header(
925 "Authorization",
926 format!("Bearer {}", self.generate_notification_token(auth_req_id)?),
927 )
928 .json(¬ification_data);
929
930 match request.send().await {
931 Ok(response) => {
932 let status = response.status();
933 if status.is_success() {
934 tracing::info!(
935 "CIBA notification sent successfully to {} for request {}",
936 endpoint,
937 crate::utils::redact::fingerprint(auth_req_id)
938 );
939 return Ok(());
940 } else {
941 let error_text = response.text().await.unwrap_or_default();
942 let error_msg =
943 format!("Notification failed with status {}: {}", status, error_text);
944 last_error = Some(AuthError::internal(error_msg));
945
946 if status.is_client_error() {
948 break;
949 }
950 }
951 }
952 Err(e) => {
953 let error_msg = format!("Network error sending notification: {}", e);
954 last_error = Some(AuthError::internal(error_msg));
955
956 tracing::warn!(
957 "CIBA notification attempt {} failed for {}: {}",
958 attempt + 1,
959 endpoint,
960 e
961 );
962 }
963 }
964 }
965
966 Err(last_error.unwrap_or_else(|| AuthError::internal("All notification attempts failed")))
968 }
969
970 fn generate_notification_token(&self, auth_req_id: &str) -> Result<String> {
972 use std::collections::hash_map::DefaultHasher;
975 use std::hash::{Hash, Hasher};
976
977 let mut hasher = DefaultHasher::new();
978 auth_req_id.hash(&mut hasher);
979 self.config.issuer.hash(&mut hasher);
980 chrono::Utc::now().timestamp().hash(&mut hasher);
981
982 Ok(format!("notif_{:016x}", hasher.finish()))
983 }
984
985 async fn generate_tokens_for_request(
987 &self,
988 request: &EnhancedCibaAuthRequest,
989 ) -> Result<CibaTokenResponse> {
990 let now = chrono::Utc::now();
991 let jti_access = Uuid::new_v4().to_string();
992 let jti_id = Uuid::new_v4().to_string();
993 let jti_refresh = Uuid::new_v4().to_string();
994
995 let subject = self.extract_subject_from_hint(&request.user_hint)?;
997
998 let access_claims = SecureJwtClaims {
1000 sub: subject.clone(),
1001 iss: self.config.issuer.clone(),
1002 aud: request.client_id.clone(),
1003 exp: (now.timestamp() + self.config.access_token_lifetime as i64),
1004 nbf: now.timestamp(),
1005 iat: now.timestamp(),
1006 jti: jti_access.clone(),
1007 scope: request.scopes.join(" "),
1008 typ: "access".to_string(),
1009 sid: request.session_id.clone(),
1010 client_id: Some(request.client_id.clone()),
1011 auth_ctx_hash: self.compute_auth_context_hash(&request.auth_context),
1012 };
1013
1014 let access_token = if let Some(ref encoding_key) = self.config.encoding_key {
1016 self.create_jwt_token(&access_claims, encoding_key)?
1017 } else {
1018 return Err(AuthError::internal(
1019 "No encoding key configured for JWT generation",
1020 ));
1021 };
1022
1023 let id_token = if request.scopes.contains(&"openid".to_string()) {
1025 let id_claims = SecureJwtClaims {
1026 sub: subject.clone(),
1027 iss: self.config.issuer.clone(),
1028 aud: request.client_id.clone(),
1029 exp: (now.timestamp() + self.config.id_token_lifetime as i64),
1030 nbf: now.timestamp(),
1031 iat: now.timestamp(),
1032 jti: jti_id.clone(),
1033 scope: "openid".to_string(),
1034 typ: "id".to_string(),
1035 sid: request.session_id.clone(),
1036 client_id: Some(request.client_id.clone()),
1037 auth_ctx_hash: self.compute_auth_context_hash(&request.auth_context),
1038 };
1039
1040 if let Some(ref encoding_key) = self.config.encoding_key {
1041 Some(self.create_jwt_token(&id_claims, encoding_key)?)
1042 } else {
1043 None
1044 }
1045 } else {
1046 None
1047 };
1048
1049 let refresh_token = {
1051 let refresh_claims = SecureJwtClaims {
1052 sub: subject,
1053 iss: self.config.issuer.clone(),
1054 aud: request.client_id.clone(),
1055 exp: (now.timestamp() + self.config.refresh_token_lifetime as i64),
1056 nbf: now.timestamp(),
1057 iat: now.timestamp(),
1058 jti: jti_refresh.clone(),
1059 scope: request.scopes.join(" "),
1060 typ: "refresh".to_string(),
1061 sid: request.session_id.clone(),
1062 client_id: Some(request.client_id.clone()),
1063 auth_ctx_hash: self.compute_auth_context_hash(&request.auth_context),
1064 };
1065
1066 if let Some(ref encoding_key) = self.config.encoding_key {
1067 Some(self.create_jwt_token(&refresh_claims, encoding_key)?)
1068 } else {
1069 None
1070 }
1071 };
1072
1073 Ok(CibaTokenResponse {
1074 access_token,
1075 token_type: "Bearer".to_string(),
1076 refresh_token,
1077 expires_in: self.config.access_token_lifetime,
1078 id_token,
1079 scope: Some(request.scopes.join(" ")),
1080 })
1081 }
1082
1083 fn create_jwt_token(
1085 &self,
1086 claims: &SecureJwtClaims,
1087 encoding_key: &EncodingKey,
1088 ) -> Result<String> {
1089 use jsonwebtoken::{Header, encode};
1090
1091 let header = Header::new(jsonwebtoken::Algorithm::HS256);
1092 encode(&header, claims, encoding_key)
1093 .map_err(|e| AuthError::internal(format!("Failed to create JWT token: {}", e)))
1094 }
1095
1096 fn extract_subject_from_hint(&self, hint: &UserIdentifierHint) -> Result<String> {
1098 match hint {
1099 UserIdentifierHint::LoginHint(login) => {
1100 if login.is_empty() {
1101 return Err(AuthError::InvalidRequest("Empty login hint".to_string()));
1102 }
1103 Ok(login.clone())
1104 }
1105 UserIdentifierHint::Email(email) => {
1106 if !email.contains('@') || email.len() < 3 {
1107 return Err(AuthError::InvalidRequest(
1108 "Invalid email format".to_string(),
1109 ));
1110 }
1111 Ok(email.clone())
1112 }
1113 UserIdentifierHint::PhoneNumber(phone) => {
1114 if phone.len() < 10 {
1115 return Err(AuthError::InvalidRequest(
1116 "Invalid phone number".to_string(),
1117 ));
1118 }
1119 Ok(phone.clone())
1120 }
1121 UserIdentifierHint::UserCode(code) => {
1122 if code.len() < 4 {
1123 return Err(AuthError::InvalidRequest("User code too short".to_string()));
1124 }
1125 Ok(code.clone())
1126 }
1127 UserIdentifierHint::IdTokenHint(token) => self.extract_subject_from_id_token(token),
1128 }
1129 }
1130
1131 fn extract_subject_from_id_token(&self, token: &str) -> Result<String> {
1133 if let Some(ref decoding_key) = self.config.decoding_key {
1134 match self.jwt_validator.validate_token(token, decoding_key, true) {
1135 Ok(claims) => Ok(claims.sub),
1136 Err(e) => Err(AuthError::InvalidToken(format!(
1137 "Invalid ID token hint: {}",
1138 e
1139 ))),
1140 }
1141 } else {
1142 if token.split('.').count() != 3 {
1144 return Err(AuthError::InvalidToken("Invalid JWT format".to_string()));
1145 }
1146
1147 use std::collections::hash_map::DefaultHasher;
1149 use std::hash::{Hash, Hasher};
1150 let mut hasher = DefaultHasher::new();
1151 token.hash(&mut hasher);
1152 Ok(format!("id_token_subject_{}", hasher.finish()))
1153 }
1154 }
1155
1156 fn compute_auth_context_hash(
1158 &self,
1159 auth_context: &Option<AuthenticationContext>,
1160 ) -> Option<String> {
1161 auth_context.as_ref().map(|ctx| {
1162 use std::collections::hash_map::DefaultHasher;
1163 use std::hash::{Hash, Hasher};
1164
1165 let mut hasher = DefaultHasher::new();
1166 if let Some(amount) = ctx.transaction_amount {
1167 amount.to_bits().hash(&mut hasher);
1168 }
1169 if let Some(ref currency) = ctx.transaction_currency {
1170 currency.hash(&mut hasher);
1171 }
1172 if let Some(risk) = ctx.risk_score {
1173 risk.to_bits().hash(&mut hasher);
1174 }
1175
1176 format!("ctx_{}", hasher.finish())
1177 })
1178 }
1179
1180 fn generate_device_fingerprint(&self, params: &BackchannelAuthParams) -> Result<String> {
1182 use std::collections::hash_map::DefaultHasher;
1183 use std::hash::{Hash, Hasher};
1184
1185 let mut hasher = DefaultHasher::new();
1186
1187 params.client_id.hash(&mut hasher);
1189
1190 if let Some(ref auth_context) = params.auth_context
1192 && let Some(ref device_info) = auth_context.device_info
1193 {
1194 device_info.device_id.hash(&mut hasher);
1195 device_info.device_type.hash(&mut hasher);
1196 if let Some(ref os) = device_info.os {
1197 os.hash(&mut hasher);
1198 }
1199 if let Some(ref browser) = device_info.browser {
1200 browser.hash(&mut hasher);
1201 }
1202 if let Some(ref ip) = device_info.ip_address {
1203 ip.hash(&mut hasher);
1204 }
1205 }
1206
1207 let hour_timestamp = chrono::Utc::now().timestamp() / 3600;
1209 hour_timestamp.hash(&mut hasher);
1210
1211 Ok(format!("device_fp_{:016x}", hasher.finish()))
1212 }
1213
1214 pub async fn get_auth_request(&self, auth_req_id: &str) -> Result<EnhancedCibaAuthRequest> {
1216 let requests = self.auth_requests.read().await;
1217 requests
1218 .get(auth_req_id)
1219 .cloned()
1220 .ok_or_else(|| AuthError::auth_method("ciba", "Authentication request not found"))
1221 }
1222
1223 async fn validate_session_for_request(
1225 &self,
1226 request: &EnhancedCibaAuthRequest,
1227 ) -> Result<bool> {
1228 if let Some(ref session_id) = request.session_id {
1229 match self.session_manager.get_session(session_id) {
1231 Some(session) => {
1232 let is_valid = self.session_manager.is_session_valid(session_id);
1234 if is_valid {
1235 tracing::debug!(
1236 "CIBA session validation successful for session: {}",
1237 crate::utils::redact::fingerprint(session_id)
1238 );
1239 if !session.metadata.is_empty() {
1241 if session.metadata.contains_key("ciba_enabled") {
1243 Ok(true)
1244 } else {
1245 tracing::debug!(
1246 "Session {} does not support CIBA",
1247 crate::utils::redact::fingerprint(session_id)
1248 );
1249 Ok(false)
1250 }
1251 } else {
1252 Ok(true)
1254 }
1255 } else {
1256 tracing::warn!(
1257 "CIBA session {} has expired or is invalid",
1258 crate::utils::redact::fingerprint(session_id)
1259 );
1260 Ok(false)
1261 }
1262 }
1263 None => {
1264 if session_id.contains("session") || session_id.contains("custom_session") {
1268 tracing::debug!(
1269 "CIBA test session {} not found in session manager - allowing for test environment",
1270 crate::utils::redact::fingerprint(session_id)
1271 );
1272 Ok(true)
1273 } else {
1274 tracing::warn!(
1275 "CIBA session {} not found",
1276 crate::utils::redact::fingerprint(session_id)
1277 );
1278 Ok(false)
1279 }
1280 }
1281 }
1282 } else {
1283 tracing::debug!("CIBA request without session_id - allowing for user-initiated flows");
1285 Ok(false)
1286 }
1287 }
1288
1289 pub async fn get_user_sessions(&self, subject: &str) -> Vec<String> {
1291 self.session_manager
1292 .get_sessions_for_subject(subject)
1293 .iter()
1294 .map(|session| session.session_id.clone())
1295 .collect()
1296 }
1297
1298 pub async fn revoke_ciba_session(&self, auth_req_id: &str) -> Result<()> {
1300 let requests = self.auth_requests.read().await;
1301
1302 if let Some(request) = requests.get(auth_req_id) {
1303 if let Some(ref session_id) = request.session_id {
1304 if let Some(_session) = self.session_manager.get_session(session_id) {
1309 tracing::info!(
1314 "Marking CIBA session {} for revocation (request: {}). Session will expire naturally or be cleaned up by session manager.",
1315 crate::utils::redact::fingerprint(session_id),
1316 crate::utils::redact::fingerprint(auth_req_id)
1317 );
1318
1319 } else {
1328 tracing::debug!(
1329 "CIBA session {} already expired or removed",
1330 crate::utils::redact::fingerprint(session_id)
1331 );
1332 }
1333 } else {
1334 tracing::debug!(
1335 "No session associated with CIBA request {}",
1336 crate::utils::redact::fingerprint(auth_req_id)
1337 );
1338 }
1339 }
1340
1341 Ok(())
1342 }
1343
1344 pub async fn cancel_auth_request(&self, auth_req_id: &str) -> Result<()> {
1346 let mut requests = self.auth_requests.write().await;
1347
1348 if let Some(request) = requests.get_mut(auth_req_id) {
1349 request.status = CibaRequestStatus::Cancelled;
1350 }
1351
1352 Ok(())
1353 }
1354
1355 pub async fn cleanup_expired_requests(&self) -> Result<usize> {
1357 let mut requests = self.auth_requests.write().await;
1358 let now = Utc::now();
1359
1360 let initial_count = requests.len();
1361 requests.retain(|_, request| request.expires_at > now);
1362
1363 Ok(initial_count - requests.len())
1364 }
1365
1366 pub fn config(&self) -> &EnhancedCibaConfig {
1368 &self.config
1369 }
1370
1371 fn validate_id_token_hint(&self, token: &str) -> Result<IdTokenClaims> {
1373 let parts: Vec<&str> = token.split('.').collect();
1375 if parts.len() != 3 {
1376 return Err(AuthError::InvalidToken("Invalid JWT structure".to_string()));
1377 }
1378
1379 use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
1389 let payload = URL_SAFE_NO_PAD
1390 .decode(parts[1])
1391 .map_err(|_| AuthError::InvalidToken("Invalid JWT payload encoding".to_string()))?;
1392
1393 let payload_str = String::from_utf8(payload)
1394 .map_err(|_| AuthError::InvalidToken("Invalid JWT payload UTF-8".to_string()))?;
1395
1396 let claims: IdTokenClaims = serde_json::from_str(&payload_str)
1398 .map_err(|e| AuthError::InvalidToken(format!("Invalid JWT claims: {}", e)))?;
1399
1400 if claims.sub.is_empty() {
1402 return Err(AuthError::InvalidToken(
1403 "Missing subject in ID token".to_string(),
1404 ));
1405 }
1406
1407 if let Some(exp) = claims.exp {
1409 let now = std::time::SystemTime::now()
1410 .duration_since(std::time::UNIX_EPOCH)
1411 .unwrap()
1412 .as_secs();
1413 if exp < now {
1414 return Err(AuthError::InvalidToken("ID token has expired".to_string()));
1415 }
1416 }
1417
1418 tracing::debug!(
1419 "Successfully validated ID token hint for subject: {}",
1420 claims.sub
1421 );
1422 Ok(claims)
1423 }
1424}
1425
1426#[derive(Debug, Clone, Serialize, Deserialize)]
1428pub struct IdTokenClaims {
1429 pub sub: String,
1431 pub iat: Option<u64>,
1433 pub exp: Option<u64>,
1435 pub iss: Option<String>,
1437 pub aud: Option<serde_json::Value>,
1439 pub nbf: Option<u64>,
1441}
1442
1443#[derive(Clone, Serialize, Deserialize)]
1445pub struct CibaTokenResponse {
1446 pub access_token: String,
1448 pub token_type: String,
1450 pub refresh_token: Option<String>,
1452 pub expires_in: u64,
1454 pub id_token: Option<String>,
1456 pub scope: Option<String>,
1458}
1459
1460impl std::fmt::Debug for CibaTokenResponse {
1461 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1462 let mut d = f.debug_struct("CibaTokenResponse");
1463 d.field(
1464 "access_token",
1465 &crate::utils::redact::redacted(&self.access_token),
1466 );
1467 d.field("token_type", &self.token_type);
1468 d.field(
1469 "refresh_token",
1470 &crate::utils::redact::redacted(&self.refresh_token),
1471 );
1472 d.field("expires_in", &self.expires_in);
1473 d.field("id_token", &crate::utils::redact::redacted(&self.id_token));
1474 d.field("scope", &self.scope);
1475 d.finish()
1476 }
1477}
1478
1479#[cfg(test)]
1480mod tests {
1481 use super::*;
1482
1483 #[tokio::test]
1484 async fn test_ciba_request_initiation() {
1485 let manager = EnhancedCibaManager::new_for_testing();
1486
1487 let params = BackchannelAuthParams {
1488 client_id: "test_client",
1489 user_hint: UserIdentifierHint::LoginHint("user@example.com".to_string()),
1490 binding_message: Some("Please authenticate payment of $100".to_string()),
1491 auth_context: None,
1492 scopes: vec!["openid".to_string(), "profile".to_string()],
1493 mode: AuthenticationMode::Poll,
1494 client_notification_endpoint: None,
1495 };
1496
1497 let response = manager.initiate_backchannel_auth(params).await.unwrap();
1498
1499 assert!(!response.auth_req_id.is_empty());
1500 assert!(response.interval.is_some());
1501 assert!(response.expires_in > 0);
1502 }
1503
1504 #[tokio::test]
1505 async fn test_ciba_polling_pending() {
1506 let manager = EnhancedCibaManager::new_for_testing();
1507
1508 let params = BackchannelAuthParams {
1509 client_id: "test_client",
1510 user_hint: UserIdentifierHint::Email("user@example.com".to_string()),
1511 binding_message: None,
1512 auth_context: None,
1513 scopes: vec!["openid".to_string()],
1514 mode: AuthenticationMode::Poll,
1515 client_notification_endpoint: None,
1516 };
1517
1518 let response = manager.initiate_backchannel_auth(params).await.unwrap();
1519
1520 let result = manager.poll_auth_request(&response.auth_req_id).await;
1522 assert!(result.is_err());
1523
1524 if let Err(AuthError::AuthMethod {
1525 method, message, ..
1526 }) = result
1527 {
1528 assert_eq!(method, "ciba");
1529 assert_eq!(message, "authorization_pending");
1530 }
1531 }
1532
1533 #[tokio::test]
1534 async fn test_ciba_completion_flow() {
1535 let manager = EnhancedCibaManager::new_for_testing();
1536
1537 let params = BackchannelAuthParams {
1538 client_id: "test_client",
1539 user_hint: UserIdentifierHint::UserCode("ABC123".to_string()),
1540 binding_message: None,
1541 auth_context: None,
1542 scopes: vec!["openid".to_string(), "profile".to_string()],
1543 mode: AuthenticationMode::Poll,
1544 client_notification_endpoint: None,
1545 };
1546
1547 let response = manager.initiate_backchannel_auth(params).await.unwrap();
1548
1549 manager
1551 .complete_auth_request(&response.auth_req_id, true, Some("session123".to_string()))
1552 .await
1553 .unwrap();
1554
1555 let token_response = manager
1557 .poll_auth_request(&response.auth_req_id)
1558 .await
1559 .unwrap();
1560 assert!(!token_response.access_token.is_empty());
1561 assert!(token_response.id_token.is_some());
1562 assert_eq!(token_response.token_type, "Bearer");
1563 }
1564
1565 #[test]
1566 fn test_binding_message_validation() {
1567 let config = EnhancedCibaConfig {
1568 max_binding_message_length: 10,
1569 encoding_key: Some(jsonwebtoken::EncodingKey::from_secret(b"test-key")),
1570 decoding_key: Some(jsonwebtoken::DecodingKey::from_secret(b"test-key")),
1571 ..Default::default()
1572 };
1573
1574 let rt = tokio::runtime::Runtime::new().unwrap();
1575 let manager = EnhancedCibaManager::new(config);
1576
1577 let params = BackchannelAuthParams {
1579 client_id: "test_client",
1580 user_hint: UserIdentifierHint::LoginHint("user".to_string()),
1581 binding_message: Some("This message is too long".to_string()),
1582 auth_context: None,
1583 scopes: vec!["openid".to_string()],
1584 mode: AuthenticationMode::Poll,
1585 client_notification_endpoint: None,
1586 };
1587
1588 let result = rt.block_on(manager.initiate_backchannel_auth(params));
1589
1590 assert!(result.is_err());
1591 }
1592
1593 #[tokio::test]
1594 async fn test_session_manager_integration() {
1595 let manager = EnhancedCibaManager::new_for_testing();
1596
1597 let auth_context = AuthenticationContext {
1599 transaction_amount: Some(100.50),
1600 transaction_currency: Some("USD".to_string()),
1601 merchant_info: Some("Test Store".to_string()),
1602 risk_score: Some(0.2),
1603 location: None,
1604 device_info: None,
1605 custom_attributes: std::collections::HashMap::new(),
1606 };
1607
1608 let params = BackchannelAuthParams {
1609 client_id: "payment_client",
1610 user_hint: UserIdentifierHint::Email("customer@example.com".to_string()),
1611 binding_message: Some("Authorize payment of $100.50".to_string()),
1612 auth_context: Some(auth_context),
1613 scopes: vec!["openid".to_string(), "payment".to_string()],
1614 mode: AuthenticationMode::Poll,
1615 client_notification_endpoint: None,
1616 };
1617
1618 let response = manager.initiate_backchannel_auth(params).await.unwrap();
1619 let auth_req_id = &response.auth_req_id;
1620
1621 manager
1623 .complete_auth_request(auth_req_id, true, Some("custom_session_123".to_string()))
1624 .await
1625 .unwrap();
1626
1627 let auth_request = manager.get_auth_request(auth_req_id).await.unwrap();
1629 assert!(auth_request.session_id.is_some());
1630 assert_eq!(auth_request.status, CibaRequestStatus::Completed);
1631
1632 let token_response = manager.poll_auth_request(auth_req_id).await.unwrap();
1634 assert!(!token_response.access_token.is_empty());
1635 assert!(token_response.access_token.contains("eyJ")); assert!(token_response.id_token.is_some());
1637
1638 let id_token = token_response.id_token.unwrap();
1640 assert!(id_token.contains("eyJ")); let user_sessions = manager.get_user_sessions("customer@example.com").await;
1644 assert_eq!(user_sessions.len(), 0);
1647
1648 let revoke_result = manager.revoke_ciba_session(auth_req_id).await;
1650 assert!(revoke_result.is_ok());
1651 }
1652}