1use crate::errors::{AuthError, Result};
20use serde::{Deserialize, Serialize};
21use std::collections::HashMap;
22use std::sync::Arc;
23use std::time::{Duration, SystemTime, UNIX_EPOCH};
24use tokio::sync::RwLock;
25
26#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
30#[serde(rename_all = "snake_case")]
31pub enum CibaMode {
32 Poll,
33 Ping,
34 Push,
35}
36
37#[derive(Debug, Clone, Serialize, Deserialize)]
39pub struct CibaConfig {
40 pub auth_endpoint: String,
42 pub token_endpoint: String,
44 pub modes_supported: Vec<CibaMode>,
46 #[serde(default = "default_interval")]
48 pub default_interval: u64,
49 #[serde(default = "default_expires_in")]
51 pub expires_in: u64,
52 #[serde(default)]
54 pub user_code_supported: bool,
55}
56
57fn default_interval() -> u64 {
58 5
59}
60fn default_expires_in() -> u64 {
61 300
62}
63
64#[derive(Clone, Serialize, Deserialize)]
68#[serde(rename_all = "snake_case")]
69pub enum LoginHint {
70 LoginHintToken(String),
72 IdTokenHint(String),
74 LoginHint(String),
76}
77
78impl std::fmt::Debug for LoginHint {
79 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
80 use crate::utils::redact::redacted;
81 match self {
82 Self::LoginHintToken(v) => f.debug_tuple("LoginHintToken").field(&redacted(v)).finish(),
83 Self::IdTokenHint(v) => f.debug_tuple("IdTokenHint").field(&redacted(v)).finish(),
84 Self::LoginHint(v) => f.debug_tuple("LoginHint").field(v).finish(),
86 }
87 }
88}
89
90#[derive(Clone, Serialize, Deserialize)]
92pub struct CibaAuthRequest {
93 pub scope: String,
95 pub hint: LoginHint,
97 #[serde(skip_serializing_if = "Option::is_none")]
99 pub binding_message: Option<String>,
100 #[serde(skip_serializing_if = "Option::is_none")]
102 pub user_code: Option<String>,
103 #[serde(skip_serializing_if = "Option::is_none")]
105 pub requested_expiry: Option<u64>,
106 #[serde(skip_serializing_if = "Option::is_none")]
108 pub acr_values: Option<String>,
109 #[serde(skip_serializing_if = "Option::is_none")]
111 pub client_notification_token: Option<String>,
112}
113
114impl std::fmt::Debug for CibaAuthRequest {
115 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
116 let mut d = f.debug_struct("CibaAuthRequest");
117 d.field("scope", &self.scope);
118 d.field("hint", &self.hint);
119 d.field("binding_message", &self.binding_message);
120 d.field(
121 "user_code",
122 &crate::utils::redact::redacted(&self.user_code),
123 );
124 d.field("requested_expiry", &self.requested_expiry);
125 d.field("acr_values", &self.acr_values);
126 d.field(
127 "client_notification_token",
128 &crate::utils::redact::redacted(&self.client_notification_token),
129 );
130 d.finish()
131 }
132}
133
134#[derive(Clone, Serialize, Deserialize)]
136pub struct CibaAuthResponse {
137 pub auth_req_id: String,
139 pub expires_in: u64,
141 #[serde(skip_serializing_if = "Option::is_none")]
143 pub interval: Option<u64>,
144}
145
146impl std::fmt::Debug for CibaAuthResponse {
147 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
148 let mut d = f.debug_struct("CibaAuthResponse");
149 d.field(
150 "auth_req_id",
151 &crate::utils::redact::redacted(&self.auth_req_id),
152 );
153 d.field("expires_in", &self.expires_in);
154 d.field("interval", &self.interval);
155 d.finish()
156 }
157}
158
159#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
163#[serde(rename_all = "snake_case")]
164pub enum CibaRequestStatus {
165 Pending,
166 Approved,
167 Denied,
168 Expired,
169}
170
171#[derive(Clone, Serialize, Deserialize)]
173pub struct CibaTokenResponse {
174 pub access_token: String,
175 pub token_type: String,
176 #[serde(skip_serializing_if = "Option::is_none")]
177 pub refresh_token: Option<String>,
178 pub expires_in: u64,
179 #[serde(skip_serializing_if = "Option::is_none")]
180 pub id_token: Option<String>,
181}
182
183impl std::fmt::Debug for CibaTokenResponse {
184 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
185 let mut d = f.debug_struct("CibaTokenResponse");
186 d.field(
187 "access_token",
188 &crate::utils::redact::redacted(&self.access_token),
189 );
190 d.field("token_type", &self.token_type);
191 d.field(
192 "refresh_token",
193 &crate::utils::redact::redacted(&self.refresh_token),
194 );
195 d.field("expires_in", &self.expires_in);
196 d.field("id_token", &crate::utils::redact::redacted(&self.id_token));
197 d.finish()
198 }
199}
200
201#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
203#[serde(rename_all = "snake_case")]
204pub enum CibaError {
205 AuthorizationPending,
206 SlowDown,
207 ExpiredToken,
208 AccessDenied,
209 InvalidRequest,
210 UnauthorizedClient,
211 InvalidScope,
212 InvalidBindingMessage,
213}
214
215#[derive(Debug, Clone)]
218struct PendingAuth {
219 request: CibaAuthRequest,
220 status: CibaRequestStatus,
221 expires_at: u64,
222 last_polled: Option<u64>,
223 mode: CibaMode,
224 subject: Option<String>,
225 token_response: Option<CibaTokenResponse>,
226}
227
228pub struct CibaProvider {
232 config: CibaConfig,
233 pending: Arc<RwLock<HashMap<String, PendingAuth>>>,
235 token_generator: Arc<CibaTokenGenerator>,
237}
238
239type CibaTokenGenerator = dyn Fn(&str, &str, &str) -> CibaTokenResponse + Send + Sync;
242
243impl CibaProvider {
244 pub fn new(
246 config: CibaConfig,
247 token_generator: impl Fn(&str, &str, &str) -> CibaTokenResponse + Send + Sync + 'static,
248 ) -> Self {
249 Self {
250 config,
251 pending: Arc::new(RwLock::new(HashMap::new())),
252 token_generator: Arc::new(token_generator),
253 }
254 }
255
256 fn now_secs() -> u64 {
257 SystemTime::now()
258 .duration_since(UNIX_EPOCH)
259 .unwrap_or(Duration::ZERO)
260 .as_secs()
261 }
262
263 fn generate_auth_req_id() -> String {
264 uuid::Uuid::new_v4().to_string()
265 }
266
267 pub async fn authenticate(
271 &self,
272 request: CibaAuthRequest,
273 mode: CibaMode,
274 ) -> Result<CibaAuthResponse> {
275 if !self.config.modes_supported.contains(&mode) {
277 return Err(AuthError::validation(format!(
278 "CIBA mode {:?} not supported",
279 mode
280 )));
281 }
282
283 if let Some(ref msg) = request.binding_message
285 && (msg.is_empty() || msg.len() > 256)
286 {
287 return Err(AuthError::validation(
288 "Binding message must be 1-256 characters",
289 ));
290 }
291
292 if matches!(mode, CibaMode::Ping | CibaMode::Push)
294 && request.client_notification_token.is_none()
295 {
296 return Err(AuthError::validation(
297 "client_notification_token required for ping/push mode",
298 ));
299 }
300
301 if request.scope.is_empty() {
303 return Err(AuthError::validation("scope is required"));
304 }
305
306 let now = Self::now_secs();
307 let expires_in = request
308 .requested_expiry
309 .unwrap_or(self.config.expires_in)
310 .min(self.config.expires_in);
311
312 let auth_req_id = Self::generate_auth_req_id();
313
314 let pending = PendingAuth {
315 request,
316 status: CibaRequestStatus::Pending,
317 expires_at: now + expires_in,
318 last_polled: None,
319 mode,
320 subject: None,
321 token_response: None,
322 };
323
324 self.pending
325 .write()
326 .await
327 .insert(auth_req_id.clone(), pending);
328
329 Ok(CibaAuthResponse {
330 auth_req_id,
331 expires_in,
332 interval: if matches!(mode, CibaMode::Poll | CibaMode::Ping) {
333 Some(self.config.default_interval)
334 } else {
335 None
336 },
337 })
338 }
339
340 pub async fn approve(&self, auth_req_id: &str, subject: &str) -> Result<()> {
344 let mut pending = self.pending.write().await;
345 let entry = pending
346 .get_mut(auth_req_id)
347 .ok_or_else(|| AuthError::validation("Unknown auth_req_id"))?;
348
349 if entry.status != CibaRequestStatus::Pending {
350 return Err(AuthError::validation(format!(
351 "Request already {:?}",
352 entry.status
353 )));
354 }
355
356 let now = Self::now_secs();
357 if now > entry.expires_at {
358 entry.status = CibaRequestStatus::Expired;
359 return Err(AuthError::validation("Request has expired"));
360 }
361
362 let token_response = (self.token_generator)(auth_req_id, subject, &entry.request.scope);
364
365 entry.status = CibaRequestStatus::Approved;
366 entry.subject = Some(subject.to_string());
367 entry.token_response = Some(token_response);
368 Ok(())
369 }
370
371 pub async fn deny(&self, auth_req_id: &str) -> Result<()> {
373 let mut pending = self.pending.write().await;
374 let entry = pending
375 .get_mut(auth_req_id)
376 .ok_or_else(|| AuthError::validation("Unknown auth_req_id"))?;
377
378 if entry.status != CibaRequestStatus::Pending {
379 return Err(AuthError::validation(format!(
380 "Request already {:?}",
381 entry.status
382 )));
383 }
384
385 entry.status = CibaRequestStatus::Denied;
386 Ok(())
387 }
388
389 pub async fn poll_token(
396 &self,
397 auth_req_id: &str,
398 ) -> std::result::Result<CibaTokenResponse, CibaError> {
399 let mut pending = self.pending.write().await;
400 let entry = pending
401 .get_mut(auth_req_id)
402 .ok_or(CibaError::InvalidRequest)?;
403
404 let now = Self::now_secs();
405
406 if now > entry.expires_at {
408 entry.status = CibaRequestStatus::Expired;
409 return Err(CibaError::ExpiredToken);
410 }
411
412 if let Some(last) = entry.last_polled
414 && now - last < self.config.default_interval
415 {
416 return Err(CibaError::SlowDown);
417 }
418 entry.last_polled = Some(now);
419
420 match entry.status {
421 CibaRequestStatus::Pending => Err(CibaError::AuthorizationPending),
422 CibaRequestStatus::Denied => Err(CibaError::AccessDenied),
423 CibaRequestStatus::Expired => Err(CibaError::ExpiredToken),
424 CibaRequestStatus::Approved => entry
425 .token_response
426 .clone()
427 .ok_or(CibaError::InvalidRequest),
428 }
429 }
430
431 pub async fn get_notification(
433 &self,
434 auth_req_id: &str,
435 ) -> Result<(CibaMode, Option<String>, Option<CibaTokenResponse>)> {
436 let pending = self.pending.read().await;
437 let entry = pending
438 .get(auth_req_id)
439 .ok_or_else(|| AuthError::validation("Unknown auth_req_id"))?;
440
441 let client_notification_token = entry.request.client_notification_token.clone();
442 let token_response = entry.token_response.clone();
443 Ok((entry.mode, client_notification_token, token_response))
444 }
445
446 pub async fn cleanup_expired(&self) {
448 let now = Self::now_secs();
449 self.pending
450 .write()
451 .await
452 .retain(|_, entry| now <= entry.expires_at);
453 }
454
455 pub async fn get_status(&self, auth_req_id: &str) -> Option<CibaRequestStatus> {
457 let pending = self.pending.read().await;
458 pending.get(auth_req_id).map(|e| e.status.clone())
459 }
460
461 pub async fn pending_count(&self) -> usize {
463 self.pending.read().await.len()
464 }
465}
466
467#[cfg(test)]
468mod tests {
469 use super::*;
470
471 fn test_config() -> CibaConfig {
472 CibaConfig {
473 auth_endpoint: "https://op.example.com/ciba".to_string(),
474 token_endpoint: "https://op.example.com/token".to_string(),
475 modes_supported: vec![CibaMode::Poll, CibaMode::Ping, CibaMode::Push],
476 default_interval: 1,
477 expires_in: 120,
478 user_code_supported: false,
479 }
480 }
481
482 fn test_token_gen() -> impl Fn(&str, &str, &str) -> CibaTokenResponse {
483 |_req_id, subject, scope| CibaTokenResponse {
484 access_token: format!("at_{subject}_{scope}"),
485 token_type: "Bearer".to_string(),
486 refresh_token: Some(format!("rt_{subject}")),
487 expires_in: 3600,
488 id_token: Some(format!("idt_{subject}")),
489 }
490 }
491
492 fn poll_request() -> CibaAuthRequest {
493 CibaAuthRequest {
494 scope: "openid email".to_string(),
495 hint: LoginHint::LoginHint("alice@example.com".to_string()),
496 binding_message: Some("Confirm login on terminal 42".to_string()),
497 user_code: None,
498 requested_expiry: None,
499 acr_values: None,
500 client_notification_token: None,
501 }
502 }
503
504 #[test]
507 fn test_ciba_mode_serde() {
508 let json = serde_json::to_string(&CibaMode::Poll).unwrap();
509 assert_eq!(json, "\"poll\"");
510 let parsed: CibaMode = serde_json::from_str(&json).unwrap();
511 assert_eq!(parsed, CibaMode::Poll);
512 }
513
514 #[test]
515 fn test_config_serde() {
516 let config = test_config();
517 let json = serde_json::to_string(&config).unwrap();
518 let parsed: CibaConfig = serde_json::from_str(&json).unwrap();
519 assert_eq!(parsed.auth_endpoint, config.auth_endpoint);
520 assert_eq!(parsed.modes_supported.len(), 3);
521 }
522
523 #[tokio::test]
526 async fn test_auth_request_poll_mode() {
527 let provider = CibaProvider::new(test_config(), test_token_gen());
528 let resp = provider
529 .authenticate(poll_request(), CibaMode::Poll)
530 .await
531 .unwrap();
532 assert!(!resp.auth_req_id.is_empty());
533 assert!(resp.expires_in > 0);
534 assert!(resp.interval.is_some());
535 }
536
537 #[tokio::test]
538 async fn test_auth_request_push_mode_requires_notification_token() {
539 let provider = CibaProvider::new(test_config(), test_token_gen());
540 let result = provider.authenticate(poll_request(), CibaMode::Push).await;
541 assert!(result.is_err());
542 }
543
544 #[tokio::test]
545 async fn test_auth_request_push_mode_with_token() {
546 let provider = CibaProvider::new(test_config(), test_token_gen());
547 let mut req = poll_request();
548 req.client_notification_token = Some("cnt_abc123".to_string());
549 let resp = provider.authenticate(req, CibaMode::Push).await.unwrap();
550 assert!(!resp.auth_req_id.is_empty());
551 assert!(resp.interval.is_none()); }
553
554 #[tokio::test]
555 async fn test_auth_request_empty_scope_rejected() {
556 let provider = CibaProvider::new(test_config(), test_token_gen());
557 let mut req = poll_request();
558 req.scope = String::new();
559 assert!(provider.authenticate(req, CibaMode::Poll).await.is_err());
560 }
561
562 #[tokio::test]
563 async fn test_auth_request_invalid_binding_message() {
564 let provider = CibaProvider::new(test_config(), test_token_gen());
565 let mut req = poll_request();
566 req.binding_message = Some(String::new());
567 assert!(provider.authenticate(req, CibaMode::Poll).await.is_err());
568 }
569
570 #[tokio::test]
571 async fn test_unsupported_mode_rejected() {
572 let config = CibaConfig {
573 modes_supported: vec![CibaMode::Poll],
574 ..test_config()
575 };
576 let provider = CibaProvider::new(config, test_token_gen());
577 let mut req = poll_request();
578 req.client_notification_token = Some("token".to_string());
579 assert!(provider.authenticate(req, CibaMode::Push).await.is_err());
580 }
581
582 #[tokio::test]
585 async fn test_approve_and_poll() {
586 let config = CibaConfig {
588 default_interval: 0,
589 ..test_config()
590 };
591 let provider = CibaProvider::new(config, test_token_gen());
592 let resp = provider
593 .authenticate(poll_request(), CibaMode::Poll)
594 .await
595 .unwrap();
596
597 assert_eq!(
599 provider.get_status(&resp.auth_req_id).await.unwrap(),
600 CibaRequestStatus::Pending
601 );
602
603 let poll_result = provider.poll_token(&resp.auth_req_id).await;
605 assert_eq!(poll_result.unwrap_err(), CibaError::AuthorizationPending);
606
607 provider
609 .approve(&resp.auth_req_id, "user:alice")
610 .await
611 .unwrap();
612 assert_eq!(
613 provider.get_status(&resp.auth_req_id).await.unwrap(),
614 CibaRequestStatus::Approved
615 );
616
617 let token = provider.poll_token(&resp.auth_req_id).await.unwrap();
619 assert!(token.access_token.contains("alice"));
620 assert_eq!(token.token_type, "Bearer");
621 assert!(token.id_token.is_some());
622 }
623
624 #[tokio::test]
625 async fn test_deny_and_poll() {
626 let provider = CibaProvider::new(test_config(), test_token_gen());
627 let resp = provider
628 .authenticate(poll_request(), CibaMode::Poll)
629 .await
630 .unwrap();
631
632 provider.deny(&resp.auth_req_id).await.unwrap();
633
634 let poll_result = provider.poll_token(&resp.auth_req_id).await;
635 assert_eq!(poll_result.unwrap_err(), CibaError::AccessDenied);
636 }
637
638 #[tokio::test]
639 async fn test_double_approve_rejected() {
640 let provider = CibaProvider::new(test_config(), test_token_gen());
641 let resp = provider
642 .authenticate(poll_request(), CibaMode::Poll)
643 .await
644 .unwrap();
645 provider
646 .approve(&resp.auth_req_id, "user:alice")
647 .await
648 .unwrap();
649 assert!(
650 provider
651 .approve(&resp.auth_req_id, "user:bob")
652 .await
653 .is_err()
654 );
655 }
656
657 #[tokio::test]
658 async fn test_approve_unknown_id() {
659 let provider = CibaProvider::new(test_config(), test_token_gen());
660 assert!(provider.approve("nonexistent", "user:alice").await.is_err());
661 }
662
663 #[tokio::test]
666 async fn test_cleanup_expired() {
667 let mut config = test_config();
668 config.expires_in = 1; let provider = CibaProvider::new(config, test_token_gen());
670 let resp = provider
671 .authenticate(poll_request(), CibaMode::Poll)
672 .await
673 .unwrap();
674 assert_eq!(provider.pending_count().await, 1);
675
676 {
679 let mut pending = provider.pending.write().await;
680 let entry = pending.get_mut(&resp.auth_req_id).unwrap();
681 entry.expires_at = 0; }
683
684 provider.cleanup_expired().await;
685 assert_eq!(provider.pending_count().await, 0);
686 }
687
688 #[tokio::test]
691 async fn test_get_notification_push() {
692 let provider = CibaProvider::new(test_config(), test_token_gen());
693 let mut req = poll_request();
694 req.client_notification_token = Some("cnt_xyz".to_string());
695 let resp = provider.authenticate(req, CibaMode::Push).await.unwrap();
696
697 provider
698 .approve(&resp.auth_req_id, "user:alice")
699 .await
700 .unwrap();
701
702 let (mode, cnt, token) = provider.get_notification(&resp.auth_req_id).await.unwrap();
703 assert_eq!(mode, CibaMode::Push);
704 assert_eq!(cnt.unwrap(), "cnt_xyz");
705 assert!(token.is_some());
706 }
707
708 #[test]
711 fn test_login_hint_serde() {
712 let hint = LoginHint::IdTokenHint("eyJ...".to_string());
713 let json = serde_json::to_string(&hint).unwrap();
714 let parsed: LoginHint = serde_json::from_str(&json).unwrap();
715 match parsed {
716 LoginHint::IdTokenHint(v) => assert_eq!(v, "eyJ..."),
717 _ => panic!("Wrong hint variant"),
718 }
719 }
720
721 #[test]
724 fn test_ciba_error_serde() {
725 let err = CibaError::SlowDown;
726 let json = serde_json::to_string(&err).unwrap();
727 assert_eq!(json, "\"slow_down\"");
728 }
729}