Skip to main content

auth_framework/api/
oauth_advanced.rs

1//! OAuth 2.0 Advanced Features API Endpoints
2//!
3//! This module implements OAuth 2.0 advanced features:
4//! - RFC 7662: Token Introspection
5//! - RFC 9126: Pushed Authorization Requests  
6//! - RFC 8628: Device Authorization Grant
7//! - OpenID Connect CIBA (Client Initiated Backchannel Authentication)
8
9use crate::api::ApiState;
10use axum::{
11    Form,
12    extract::State,
13    http::{HeaderMap, StatusCode},
14    response::Json,
15};
16use base64::{Engine as _, engine::general_purpose};
17use serde::{Deserialize, Serialize};
18use serde_json::{Value as JsonValue, json};
19use std::collections::HashMap;
20use tracing::{debug, error};
21use url::Url;
22use uuid::Uuid;
23
24/// Token introspection request (RFC 7662)
25#[derive(Deserialize)]
26pub struct IntrospectRequest {
27    /// The token to introspect
28    pub token: String,
29
30    /// Optional hint about the token type
31    #[serde(skip_serializing_if = "Option::is_none")]
32    pub token_type_hint: Option<String>,
33
34    /// Client ID (if using POST body authentication)
35    #[serde(skip_serializing_if = "Option::is_none")]
36    pub client_id: Option<String>,
37
38    /// Client secret (if using POST body authentication)
39    #[serde(skip_serializing_if = "Option::is_none")]
40    pub client_secret: Option<String>,
41}
42
43impl std::fmt::Debug for IntrospectRequest {
44    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
45        let mut d = f.debug_struct("IntrospectRequest");
46        d.field("token", &crate::utils::redact::redacted(&self.token));
47        d.field("token_type_hint", &self.token_type_hint);
48        d.field("client_id", &self.client_id);
49        d.field(
50            "client_secret",
51            &crate::utils::redact::redacted(&self.client_secret),
52        );
53        d.finish()
54    }
55}
56
57/// Token introspection response (RFC 7662)
58#[derive(Debug, Serialize)]
59pub struct IntrospectResponse {
60    /// Indicates if the token is currently active
61    pub active: bool,
62
63    /// The subject of the token
64    #[serde(skip_serializing_if = "Option::is_none")]
65    pub sub: Option<String>,
66
67    /// The client_id associated with the token
68    #[serde(skip_serializing_if = "Option::is_none")]
69    pub client_id: Option<String>,
70
71    /// The scopes associated with the token
72    #[serde(skip_serializing_if = "Option::is_none")]
73    pub scope: Option<String>,
74
75    /// Token expiration timestamp
76    #[serde(skip_serializing_if = "Option::is_none")]
77    pub exp: Option<i64>,
78
79    /// Token issued at timestamp
80    #[serde(skip_serializing_if = "Option::is_none")]
81    pub iat: Option<i64>,
82
83    /// Not before timestamp
84    #[serde(skip_serializing_if = "Option::is_none")]
85    pub nbf: Option<i64>,
86
87    /// Issuer of the token
88    #[serde(skip_serializing_if = "Option::is_none")]
89    pub iss: Option<String>,
90
91    /// Audience of the token
92    #[serde(skip_serializing_if = "Option::is_none")]
93    pub aud: Option<JsonValue>,
94
95    /// JWT ID
96    #[serde(skip_serializing_if = "Option::is_none")]
97    pub jti: Option<String>,
98
99    /// Token type (e.g., "Bearer")
100    #[serde(skip_serializing_if = "Option::is_none")]
101    pub token_type: Option<String>,
102
103    /// Username associated with the token
104    #[serde(skip_serializing_if = "Option::is_none")]
105    pub username: Option<String>,
106}
107
108/// Pushed Authorization Request parameters (RFC 9126)
109///
110/// Required fields are non-optional so Axum Form validation returns 422
111/// automatically when they are missing from the request body.
112#[derive(Debug, Deserialize)]
113pub struct PARRequest {
114    /// Required: OAuth 2.0 response type (e.g., "code")
115    pub response_type: String,
116
117    /// Required: The client identifier
118    pub client_id: String,
119
120    /// Required: Redirection URI for the authorization response
121    pub redirect_uri: String,
122
123    /// Optional: Requested scope(s)
124    pub scope: Option<String>,
125
126    /// Optional: Opaque state value for the client
127    pub state: Option<String>,
128
129    /// Optional: Nonce for OIDC requests
130    pub nonce: Option<String>,
131
132    /// Optional: PKCE code challenge
133    pub code_challenge: Option<String>,
134
135    /// Optional: PKCE code challenge method (e.g., "S256")
136    pub code_challenge_method: Option<String>,
137}
138
139/// Pushed Authorization Request response (RFC 9126)
140#[derive(Serialize)]
141pub struct PARResponse {
142    /// The request URI for the authorization request
143    pub request_uri: String,
144
145    /// Expiration time in seconds
146    pub expires_in: u64,
147}
148
149impl std::fmt::Debug for PARResponse {
150    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
151        let mut d = f.debug_struct("PARResponse");
152        d.field(
153            "request_uri",
154            &crate::utils::redact::redacted(&self.request_uri),
155        );
156        d.field("expires_in", &self.expires_in);
157        d.finish()
158    }
159}
160
161// ============================================================================
162// Endpoint Handlers
163// ============================================================================
164
165/// Verify OAuth2 client credentials against the registered client record in storage.
166///
167/// Returns `Ok(true)` if the credentials are valid, `Ok(false)` if the client_id
168/// is unknown or the secret does not match, and `Err(...)` on storage failures.
169/// The function uses constant-time comparison to prevent timing oracle attacks on
170/// the client_secret.
171async fn verify_client_credentials(
172    state: &State<ApiState>,
173    client_id: &str,
174    client_secret: &str,
175) -> Result<bool, (StatusCode, Json<JsonValue>)> {
176    let client_key = format!("oauth2_client:{}", client_id);
177    let client_data = match state.auth_framework.storage().get_kv(&client_key).await {
178        Ok(Some(bytes)) => match serde_json::from_slice::<serde_json::Value>(&bytes) {
179            Ok(v) => v,
180            Err(_) => {
181                error!(
182                    "Introspect: failed to deserialize client record for {}",
183                    client_id
184                );
185                return Err((
186                    StatusCode::INTERNAL_SERVER_ERROR,
187                    Json(json!({
188                        "error": "server_error",
189                        "error_description": "Internal server error"
190                    })),
191                ));
192            }
193        },
194        Ok(None) => {
195            // Unknown client — return false (don't reveal whether the client exists)
196            return Ok(false);
197        }
198        Err(e) => {
199            error!(
200                "Introspect: storage error looking up client {}: {}",
201                client_id, e
202            );
203            return Err((
204                StatusCode::INTERNAL_SERVER_ERROR,
205                Json(json!({
206                    "error": "server_error",
207                    "error_description": "Internal server error"
208                })),
209            ));
210        }
211    };
212
213    if super::client_secret::is_confidential(&client_data) {
214        // A hashed secret is verified against its hash; a legacy plain one is compared in
215        // constant time and then replaced by its hash.
216        let authenticated = super::client_secret::authenticate(
217            state.auth_framework.storage().as_ref(),
218            client_id,
219            &client_data,
220            client_secret,
221        )
222        .await;
223        // An authenticated client is limited by its own identity, whatever address it uses
224        // (#92); a failed attempt is not counted against the client it names.
225        if authenticated
226            && let Err(limited) = super::client_rate_limit::check(state, client_id).await
227        {
228            return Err(match limited {
229                super::client_rate_limit::ClientLimited::Exceeded { retry_after_secs } => (
230                    StatusCode::TOO_MANY_REQUESTS,
231                    Json(json!({
232                        "error": "rate_limit_exceeded",
233                        "error_description": "This client is making too many requests",
234                        "retry_after": retry_after_secs
235                    })),
236                ),
237                super::client_rate_limit::ClientLimited::Unavailable => (
238                    StatusCode::SERVICE_UNAVAILABLE,
239                    Json(json!({
240                        "error": "temporarily_unavailable",
241                        "error_description": "Rate limiting is temporarily unavailable"
242                    })),
243                ),
244            });
245        }
246        return Ok(authenticated);
247    }
248    // A client registered without a secret (a public client) has nothing to authenticate with,
249    // so it cannot call the introspection endpoint (RFC 7662 section 2.1); an empty presented
250    // secret is not a credential.
251    Ok(false)
252}
253
254/// Record an introspection request in the audit trail: who asked, what came of it, and (for a
255/// token that could be read) its subject and `jti`. Never the token or any secret.
256async fn audit_introspection(
257    state: &State<ApiState>,
258    client_id: &str,
259    success: bool,
260    result: &str,
261    subject: Option<&str>,
262    jti: Option<&str>,
263) {
264    use crate::audit::{AuditEvent, AuditEventType, EventOutcome, RiskLevel};
265    let mut event = AuditEvent::builder(
266        AuditEventType::TokenIntrospected,
267        format!("OAuth2 token introspection: {result}"),
268    )
269    .outcome(if success {
270        EventOutcome::Success
271    } else {
272        EventOutcome::Failure
273    })
274    .risk_level(if success {
275        RiskLevel::Low
276    } else {
277        RiskLevel::Medium
278    })
279    .with_actor("oauth_client", client_id)
280    .detail("endpoint", "/oauth/introspect")
281    .detail("result", result);
282    if let Some(subject) = subject {
283        event = event.user_id(subject);
284    }
285    if let Some(jti) = jti {
286        event = event.detail("jti", jti);
287    }
288    state.auth_framework.record_audit_event(event.build()).await;
289}
290
291/// Token introspection endpoint (RFC 7662)
292///
293/// Allows authorized clients to determine the active state and meta-information
294/// about a given token.
295///
296/// Authentication is required via either:
297/// - HTTP Basic Auth header (`Authorization: Basic <base64(client_id:client_secret)>`)
298/// - POST body parameters (`client_id` + `client_secret`)
299///
300/// Bearer token authentication is explicitly rejected per RFC 7662 §2.1.
301pub async fn introspect_token(
302    state: State<ApiState>,
303    headers: HeaderMap,
304    form: Form<IntrospectRequest>,
305) -> Result<Json<IntrospectResponse>, (StatusCode, Json<JsonValue>)> {
306    debug!("Processing token introspection request");
307
308    // --- Authentication enforcement (RFC 7662 §2.1) ---
309    let auth_header = headers.get(axum::http::header::AUTHORIZATION);
310
311    // Who the caller said it was, for the audit trail (never a secret).
312    let presented_client_id: Option<String>;
313    let authenticated = match auth_header {
314        Some(value) => {
315            let value_str = value.to_str().unwrap_or("");
316            if value_str.starts_with("Bearer ") {
317                // Bearer tokens are not a valid authentication method for introspection
318                debug!("Introspect rejected: Bearer auth is not allowed");
319                return Err((
320                    StatusCode::UNAUTHORIZED,
321                    Json(json!({
322                        "error": "invalid_client",
323                        "error_description": "Bearer token authentication is not supported for token introspection"
324                    })),
325                ));
326            } else if let Some(encoded) = value_str.strip_prefix("Basic ") {
327                // Decode Basic auth credentials and verify against registered client.
328                match general_purpose::STANDARD.decode(encoded) {
329                    Ok(decoded_bytes) => {
330                        let decoded = String::from_utf8_lossy(&decoded_bytes);
331                        let mut parts = decoded.splitn(2, ':');
332                        let basic_client_id = parts.next().unwrap_or("").to_string();
333                        let basic_client_secret = parts.next().unwrap_or("").to_string();
334                        presented_client_id = Some(basic_client_id.clone());
335                        verify_client_credentials(&state, &basic_client_id, &basic_client_secret)
336                            .await?
337                    }
338                    Err(_) => {
339                        debug!("Introspect rejected: invalid Basic auth encoding");
340                        return Err((
341                            StatusCode::UNAUTHORIZED,
342                            Json(json!({
343                                "error": "invalid_client",
344                                "error_description": "Invalid Basic authentication encoding"
345                            })),
346                        ));
347                    }
348                }
349            } else {
350                // Unrecognised auth scheme
351                debug!("Introspect rejected: unknown auth scheme");
352                return Err((
353                    StatusCode::UNAUTHORIZED,
354                    Json(json!({
355                        "error": "invalid_client",
356                        "error_description": "Unsupported authentication scheme"
357                    })),
358                ));
359            }
360        }
361        None => {
362            // No Authorization header — verify using POST body client_id + client_secret.
363            match (&form.client_id, &form.client_secret) {
364                (Some(id), Some(secret)) => {
365                    presented_client_id = Some(id.clone());
366                    verify_client_credentials(&state, id, secret).await?
367                }
368                _ => {
369                    debug!("Introspect rejected: missing client credentials");
370                    return Err((
371                        StatusCode::UNAUTHORIZED,
372                        Json(json!({
373                            "error": "invalid_client",
374                            "error_description": "client_id and client_secret are required"
375                        })),
376                    ));
377                }
378            }
379        }
380    };
381
382    let audit_client = presented_client_id.unwrap_or_default();
383    if !authenticated {
384        audit_introspection(
385            &state,
386            &audit_client,
387            false,
388            "client_authentication_failed",
389            None,
390            None,
391        )
392        .await;
393        debug!("Introspect rejected: invalid client credentials");
394        return Err((
395            StatusCode::UNAUTHORIZED,
396            Json(json!({
397                "error": "invalid_client",
398                "error_description": "Client authentication failed"
399            })),
400        ));
401    }
402
403    // --- Token validation ---
404    let token_manager = state.auth_framework.token_manager();
405
406    match token_manager.validate_jwt_token(&form.token) {
407        Ok(claims) => {
408            // A token issued to a client is reported only to that client (RFC 7662 section 4):
409            // another authenticated client learns nothing about it, not even that it is valid.
410            // A token with no client (a first-party token) is not restricted: the framework has
411            // no resource-server role yet to restrict it to.
412            if claims
413                .client_id
414                .as_deref()
415                .is_some_and(|owner| owner != audit_client)
416            {
417                audit_introspection(
418                    &state,
419                    &audit_client,
420                    true,
421                    "inactive_not_issued_to_caller",
422                    None,
423                    None,
424                )
425                .await;
426                debug!("Token introspection: token was issued to another client");
427                return Ok(Json(IntrospectResponse {
428                    active: false,
429                    sub: None,
430                    client_id: None,
431                    scope: None,
432                    exp: None,
433                    iat: None,
434                    nbf: None,
435                    iss: None,
436                    aud: None,
437                    jti: None,
438                    token_type: None,
439                    username: None,
440                }));
441            }
442            // Cross-check the revocation list before reporting the token as active.
443            // Tokens revoked via POST /oauth/revoke or POST /auth/logout are stored
444            // under revoked_token:{jti}; return active=false without revealing why.
445            let revocation_key = format!("revoked_token:{}", claims.jti);
446            // A revocation list that cannot be read is treated as "revoked" (fail closed).
447            let storage = state.auth_framework.storage();
448            let mut revoked = !matches!(storage.get_kv(&revocation_key).await, Ok(None));
449            // A token whose account is deactivated or gone cannot be used: not active.
450            if !revoked
451                && crate::auth::ensure_account_active(storage.as_ref(), &claims.sub, false)
452                    .await
453                    .is_err()
454            {
455                revoked = true;
456            }
457            // An ID token, client assertion or any other token that declares a use other than
458            // refresh is not an access token: it is not reported as one.
459            if !revoked && claims.token_use().is_some() && !claims.is_refresh_token() {
460                revoked = true;
461            }
462            // A refresh token is active only while it is unspent and its chain is intact.
463            if !revoked && claims.is_refresh_token() {
464                revoked = !matches!(
465                    storage
466                        .get_kv(&format!("refresh_consumed:{}", claims.jti))
467                        .await,
468                    Ok(None)
469                ) || !matches!(
470                    storage
471                        .get_kv(&format!("revoked_family:{}", claims.refresh_family()))
472                        .await,
473                    Ok(None)
474                );
475            }
476            if revoked {
477                audit_introspection(
478                    &state,
479                    &audit_client,
480                    true,
481                    "inactive_revoked_or_unusable",
482                    Some(&claims.sub),
483                    Some(&claims.jti),
484                )
485                .await;
486                debug!(
487                    "Token introspection: token has been revoked (jti: {})",
488                    claims.jti
489                );
490                return Ok(Json(IntrospectResponse {
491                    active: false,
492                    sub: None,
493                    client_id: None,
494                    scope: None,
495                    exp: None,
496                    iat: None,
497                    nbf: None,
498                    iss: None,
499                    aud: None,
500                    jti: None,
501                    token_type: None,
502                    username: None,
503                }));
504            }
505
506            debug_assert!(!claims.sub.is_empty(), "Token subject should not be empty");
507            audit_introspection(
508                &state,
509                &audit_client,
510                true,
511                "active",
512                Some(&claims.sub),
513                Some(&claims.jti),
514            )
515            .await;
516            Ok(Json(IntrospectResponse {
517                active: true,
518                sub: Some(claims.sub.clone()),
519                client_id: claims.client_id.clone(),
520                scope: Some(claims.scope.clone()),
521                exp: Some(claims.exp),
522                iat: Some(claims.iat),
523                nbf: Some(claims.nbf),
524                iss: Some(claims.iss.clone()),
525                aud: Some(JsonValue::String(claims.aud.clone())),
526                jti: Some(claims.jti.clone()),
527                token_type: Some(if claims.is_refresh_token() {
528                    "refresh_token".to_string()
529                } else {
530                    "Bearer".to_string()
531                }),
532                username: Some(claims.sub),
533            }))
534        }
535        Err(_e) => {
536            audit_introspection(&state, &audit_client, true, "inactive_invalid", None, None).await;
537            debug!("Token introspection: token is inactive");
538            // Return inactive token (per RFC 7662, don't reveal why it's invalid)
539            Ok(Json(IntrospectResponse {
540                active: false,
541                sub: None,
542                client_id: None,
543                scope: None,
544                exp: None,
545                iat: None,
546                nbf: None,
547                iss: None,
548                aud: None,
549                jti: None,
550                token_type: None,
551                username: None,
552            }))
553        }
554    }
555}
556
557/// Pushed Authorization Request endpoint (RFC 9126)
558///
559/// Clients push authorization request parameters to the server and receive a
560/// `request_uri` they can use at the authorization endpoint. The URI is unique
561/// per request and expires after 90 seconds (RFC 9126 §2.2).
562///
563/// Required form fields: `response_type`, `client_id`, `redirect_uri`
564/// Missing required fields are automatically rejected with 422 by Axum.
565pub async fn pushed_authorization_request(
566    State(state): State<ApiState>,
567    Form(req): Form<PARRequest>,
568) -> (StatusCode, Json<PARResponse>) {
569    debug!("Processing PAR request for client_id={}", req.client_id);
570
571    // Validate redirect_uri is a well-formed URL before accepting it
572    if Url::parse(&req.redirect_uri).is_err() {
573        return (
574            StatusCode::BAD_REQUEST,
575            Json(PARResponse {
576                request_uri: String::new(),
577                expires_in: 0,
578            }),
579        );
580    }
581
582    // Generate a unique request URI per RFC 9126 §2.2
583    let request_id = Uuid::new_v4().to_string();
584    let request_uri = format!("urn:ietf:params:oauth:request_uri:{}", request_id);
585
586    // Persist the authorization request parameters so the /authorize endpoint
587    // can retrieve them when presented with this request_uri (RFC 9126 §4).
588    let par_data = json!({
589        "response_type": req.response_type,
590        "client_id": req.client_id,
591        "redirect_uri": req.redirect_uri,
592        "scope": req.scope,
593        "state": req.state,
594        "nonce": req.nonce,
595        "code_challenge": req.code_challenge,
596        "code_challenge_method": req.code_challenge_method,
597    });
598    let storage_key = format!("par_request:{}", request_id);
599    if let Err(e) = state
600        .auth_framework
601        .storage()
602        .store_kv(
603            &storage_key,
604            par_data.to_string().as_bytes(),
605            Some(std::time::Duration::from_secs(90)),
606        )
607        .await
608    {
609        error!("Failed to store PAR request: {}", e);
610        // The request_uri would be unresolvable; returning a 201 with a URI
611        // that will never resolve is worse than surfacing the error early.
612        return (
613            StatusCode::INTERNAL_SERVER_ERROR,
614            Json(PARResponse {
615                request_uri: String::new(),
616                expires_in: 0,
617            }),
618        );
619    }
620
621    (
622        StatusCode::CREATED,
623        Json(PARResponse {
624            request_uri,
625            expires_in: 90,
626        }),
627    )
628}
629
630/// Device Authorization endpoint (RFC 8628 §3.1)
631///
632/// Initiates a device-authorization flow for input-constrained devices.
633/// Returns a `device_code`, human-friendly `user_code`, `verification_uri`,
634/// `expires_in`, and a polling `interval`.
635pub async fn device_authorization(
636    State(state): State<ApiState>,
637    Form(form): Form<HashMap<String, String>>,
638) -> Result<Json<JsonValue>, (StatusCode, Json<JsonValue>)> {
639    // RFC 8628 §3.1 – client_id is required
640    if form.get("client_id").map(|s| s.is_empty()).unwrap_or(true) {
641        return Err((
642            StatusCode::BAD_REQUEST,
643            Json(json!({
644                "error": "invalid_request",
645                "error_description": "client_id is required"
646            })),
647        ));
648    }
649
650    // Generate a high-entropy device_code and a human-friendly user_code.
651    let device_code = format!("dc_{}", Uuid::new_v4().simple());
652    let user_code = generate_user_code();
653    let verification_uri = "/device";
654    let expires_in: u64 = 600; // RFC 8628 recommends ≥600 s
655
656    // Persist the device authorization request so the token endpoint can poll.
657    let device_data = json!({
658        "client_id": form.get("client_id").cloned().unwrap_or_default(),
659        "scope":     form.get("scope").cloned().unwrap_or_default(),
660        "user_code": user_code,
661        "authorized": false
662    });
663    state
664        .auth_framework
665        .storage()
666        .store_kv(
667            &format!("device:{}", device_code),
668            device_data.to_string().as_bytes(),
669            Some(std::time::Duration::from_secs(expires_in)),
670        )
671        .await
672        .map_err(|e| {
673            error!("Failed to store device authorization request: {}", e);
674            (
675                StatusCode::INTERNAL_SERVER_ERROR,
676                Json(json!({
677                    "error": "server_error",
678                    "error_description": "Failed to initiate device authorization flow"
679                })),
680            )
681        })?;
682
683    debug!(
684        "Device authorization initiated for client_id={}",
685        form.get("client_id")
686            .map(String::as_str)
687            .unwrap_or_default()
688    );
689
690    Ok(Json(json!({
691        "device_code":              device_code,
692        "user_code":               user_code,
693        "verification_uri":        verification_uri,
694        "verification_uri_complete": format!("{}?user_code={}", verification_uri, user_code),
695        "expires_in":              expires_in,
696        "interval":                5
697    })))
698}
699
700/// CIBA (Client Initiated Backchannel Authentication) endpoint (OpenID Connect CIBA Core §7.1)
701///
702/// Initiates a backchannel authentication request.  Exactly one of
703/// `login_hint`, `login_hint_token`, or `id_token_hint` must be present.
704/// Returns an `auth_req_id` that the client polls at the token endpoint.
705pub async fn ciba_backchannel_auth(
706    State(state): State<ApiState>,
707    Form(form): Form<HashMap<String, String>>,
708) -> Result<Json<JsonValue>, (StatusCode, Json<JsonValue>)> {
709    // CIBA Core §7.1 – exactly one user-identification hint is required.
710    let login_hint = form
711        .get("login_hint")
712        .or_else(|| form.get("login_hint_token"))
713        .or_else(|| form.get("id_token_hint"))
714        .cloned()
715        .ok_or_else(|| {
716            (
717                StatusCode::BAD_REQUEST,
718                Json(json!({
719                    "error": "invalid_request",
720                    "error_description":
721                        "One of login_hint, login_hint_token, or id_token_hint is required"
722                })),
723            )
724        })?;
725
726    let auth_req_id = Uuid::new_v4().to_string();
727    let expires_in: u64 = 120; // 2-minute window for the authenticating device
728
729    // Persist the CIBA request so the token-endpoint poll can resolve it.
730    let ciba_data = json!({
731        "login_hint":      login_hint,
732        "client_id":       form.get("client_id").cloned().unwrap_or_default(),
733        "scope":           form.get("scope").cloned().unwrap_or_default(),
734        "binding_message": form.get("binding_message").cloned(),
735        "status":          "pending"
736    });
737    state
738        .auth_framework
739        .storage()
740        .store_kv(
741            &format!("ciba:{}", auth_req_id),
742            ciba_data.to_string().as_bytes(),
743            Some(std::time::Duration::from_secs(expires_in)),
744        )
745        .await
746        .map_err(|e| {
747            error!("Failed to store CIBA request: {}", e);
748            (
749                StatusCode::INTERNAL_SERVER_ERROR,
750                Json(json!({
751                    "error": "server_error",
752                    "error_description": "Failed to initiate backchannel authentication"
753                })),
754            )
755        })?;
756
757    debug!(
758        "CIBA request created: auth_req_id={}",
759        crate::utils::redact::fingerprint(&auth_req_id)
760    );
761
762    Ok(Json(json!({
763        "auth_req_id": auth_req_id,
764        "expires_in":  expires_in,
765        "interval":    5
766    })))
767}
768
769// ---------------------------------------------------------------------------
770// Helpers
771// ---------------------------------------------------------------------------
772
773/// Generate an 8-character, human-friendly user code (RFC 8628 §6.1 charset).
774/// Uses only unambiguous uppercase letters and digits (no O/0, I/1).
775fn generate_user_code() -> String {
776    use rand::RngExt;
777    const CHARS: &[u8] = b"ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
778    let mut rng = rand::rng();
779    (0..8)
780        .map(|_| CHARS[rng.random_range(0..CHARS.len())] as char)
781        .collect()
782}