Skip to main content

auth_framework/protocols/
ciba.rs

1//! OpenID Connect Client-Initiated Backchannel Authentication (CIBA).
2//!
3//! Implements the CIBA flow where a *consumption device* (e.g. a POS terminal
4//! or call-center application) authenticates the user on a separate
5//! *authentication device* (e.g. the user's phone) without a browser redirect.
6//!
7//! # Modes
8//!
9//! - **Poll** — the client repeatedly polls the token endpoint.
10//! - **Ping** — the OP sends a notification to the client's callback URI, then the client
11//!   fetches the token.
12//! - **Push** — the OP pushes the token directly to the client's callback URI.
13//!
14//! # References
15//!
16//! - [OpenID Connect CIBA Core 1.0](https://openid.net/specs/openid-client-initiated-backchannel-authentication-core-1_0.html)
17//! - [RFC 9449 — DPoP](https://www.rfc-editor.org/rfc/rfc9449) (optional token binding)
18
19use 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// ── Configuration ───────────────────────────────────────────────────
27
28/// CIBA token delivery mode.
29#[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/// Configuration for a CIBA provider.
38#[derive(Debug, Clone, Serialize, Deserialize)]
39pub struct CibaConfig {
40    /// Backchannel authentication endpoint URL.
41    pub auth_endpoint: String,
42    /// Token endpoint URL.
43    pub token_endpoint: String,
44    /// Supported delivery modes.
45    pub modes_supported: Vec<CibaMode>,
46    /// Default polling interval in seconds.
47    #[serde(default = "default_interval")]
48    pub default_interval: u64,
49    /// Maximum auth request lifetime in seconds.
50    #[serde(default = "default_expires_in")]
51    pub expires_in: u64,
52    /// Optional user code support.
53    #[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// ── Authentication Request ──────────────────────────────────────────
65
66/// Hint identifying the end-user to authenticate.
67#[derive(Clone, Serialize, Deserialize)]
68#[serde(rename_all = "snake_case")]
69pub enum LoginHint {
70    /// Subject identifier.
71    LoginHintToken(String),
72    /// An id_token_hint.
73    IdTokenHint(String),
74    /// Login hint (e.g. email or phone).
75    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            // An e-mail address or phone number the client supplied, not a credential.
85            Self::LoginHint(v) => f.debug_tuple("LoginHint").field(v).finish(),
86        }
87    }
88}
89
90/// A backchannel authentication request sent by the consumption device.
91#[derive(Clone, Serialize, Deserialize)]
92pub struct CibaAuthRequest {
93    /// The scopes requested.
94    pub scope: String,
95    /// Hint identifying the user.
96    pub hint: LoginHint,
97    /// Human-readable binding message shown on the authentication device.
98    #[serde(skip_serializing_if = "Option::is_none")]
99    pub binding_message: Option<String>,
100    /// User code entered on the consumption device (for user-code mode).
101    #[serde(skip_serializing_if = "Option::is_none")]
102    pub user_code: Option<String>,
103    /// Requested expiry (seconds).
104    #[serde(skip_serializing_if = "Option::is_none")]
105    pub requested_expiry: Option<u64>,
106    /// ACR values.
107    #[serde(skip_serializing_if = "Option::is_none")]
108    pub acr_values: Option<String>,
109    /// Client notification token (required for ping/push modes).
110    #[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/// Successful response to a backchannel authentication request.
135#[derive(Clone, Serialize, Deserialize)]
136pub struct CibaAuthResponse {
137    /// Unique identifier for the authentication request.
138    pub auth_req_id: String,
139    /// Expires-in (seconds).
140    pub expires_in: u64,
141    /// Minimum polling interval (seconds) — included for poll / ping modes.
142    #[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// ── Token Request / Response ────────────────────────────────────────
160
161/// Pending request state.
162#[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/// Token response after successful authentication.
172#[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/// Error response per CIBA spec.
202#[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// ── Internal state ──────────────────────────────────────────────────
216
217#[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
228// ── CIBA Provider ───────────────────────────────────────────────────
229
230/// In-memory CIBA provider implementing Auth Request → Token lifecycle.
231pub struct CibaProvider {
232    config: CibaConfig,
233    /// `auth_req_id → PendingAuth`
234    pending: Arc<RwLock<HashMap<String, PendingAuth>>>,
235    /// Token generator function (auth_req_id, subject, scope) → CibaTokenResponse.
236    token_generator: Arc<CibaTokenGenerator>,
237}
238
239/// Signature of the callback that mints a [`CibaTokenResponse`] for
240/// `(auth_req_id, subject, scope)`.
241type CibaTokenGenerator = dyn Fn(&str, &str, &str) -> CibaTokenResponse + Send + Sync;
242
243impl CibaProvider {
244    /// Create a provider with the given config and token generator.
245    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    // ── Phase 1: Authentication Request ─────────────────────────
268
269    /// Process a backchannel authentication request.
270    pub async fn authenticate(
271        &self,
272        request: CibaAuthRequest,
273        mode: CibaMode,
274    ) -> Result<CibaAuthResponse> {
275        // Validate mode is supported
276        if !self.config.modes_supported.contains(&mode) {
277            return Err(AuthError::validation(format!(
278                "CIBA mode {:?} not supported",
279                mode
280            )));
281        }
282
283        // Validate binding message length
284        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        // Ping/push requires client_notification_token
293        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        // Validate scope is non-empty
302        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    // ── Phase 2: User consent (called by authentication device) ─
341
342    /// Approve an authentication request (called when user consents).
343    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        // Generate tokens
363        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    /// Deny an authentication request.
372    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    // ── Phase 3: Token retrieval (poll mode) ────────────────────
390
391    /// Poll for the token (used in poll mode).
392    ///
393    /// Returns `Ok(CibaTokenResponse)` on success,
394    /// `Err` with appropriate CIBA error on pending/denied/expired/slow-down.
395    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        // Check expiry
407        if now > entry.expires_at {
408            entry.status = CibaRequestStatus::Expired;
409            return Err(CibaError::ExpiredToken);
410        }
411
412        // Slow-down check
413        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    /// Get the notification payload for ping/push modes.
432    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    /// Clean up expired requests.
447    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    /// Get the status of an auth request.
456    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    /// Get the total number of pending requests.
462    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    // ── Config serialization ────────────────────────────────────
505
506    #[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    // ── Authentication request ──────────────────────────────────
524
525    #[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()); // Push mode has no polling interval
552    }
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    // ── Approve / Deny ──────────────────────────────────────────
583
584    #[tokio::test]
585    async fn test_approve_and_poll() {
586        // Use interval=0 so rapid successive polls don't trigger SlowDown
587        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        // Initially pending
598        assert_eq!(
599            provider.get_status(&resp.auth_req_id).await.unwrap(),
600            CibaRequestStatus::Pending
601        );
602
603        // Polling before approval → authorization_pending
604        let poll_result = provider.poll_token(&resp.auth_req_id).await;
605        assert_eq!(poll_result.unwrap_err(), CibaError::AuthorizationPending);
606
607        // Approve
608        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        // Poll should now succeed (after interval)
618        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    // ── Expiry ──────────────────────────────────────────────────
664
665    #[tokio::test]
666    async fn test_cleanup_expired() {
667        let mut config = test_config();
668        config.expires_in = 1; // 1 second
669        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        // The request expires_in=1s, but we can't sleep. Instead, manually
677        // set the entry to expired by over-riding expires_at.
678        {
679            let mut pending = provider.pending.write().await;
680            let entry = pending.get_mut(&resp.auth_req_id).unwrap();
681            entry.expires_at = 0; // Force expired
682        }
683
684        provider.cleanup_expired().await;
685        assert_eq!(provider.pending_count().await, 0);
686    }
687
688    // ── Notification info ───────────────────────────────────────
689
690    #[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    // ── Login hint variants ─────────────────────────────────────
709
710    #[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    // ── CibaError equality ──────────────────────────────────────
722
723    #[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}