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            // Cross-check the revocation list before reporting the token as active.
409            // Tokens revoked via POST /oauth/revoke or POST /auth/logout are stored
410            // under revoked_token:{jti}; return active=false without revealing why.
411            let revocation_key = format!("revoked_token:{}", claims.jti);
412            // A revocation list that cannot be read is treated as "revoked" (fail closed).
413            let storage = state.auth_framework.storage();
414            let mut revoked = !matches!(storage.get_kv(&revocation_key).await, Ok(None));
415            // A token whose account is deactivated or gone cannot be used: not active.
416            if !revoked
417                && crate::auth::ensure_account_active(storage.as_ref(), &claims.sub, false)
418                    .await
419                    .is_err()
420            {
421                revoked = true;
422            }
423            // An ID token, client assertion or any other token that declares a use other than
424            // refresh is not an access token: it is not reported as one.
425            if !revoked && claims.token_use().is_some() && !claims.is_refresh_token() {
426                revoked = true;
427            }
428            // A refresh token is active only while it is unspent and its chain is intact.
429            if !revoked && claims.is_refresh_token() {
430                revoked = !matches!(
431                    storage
432                        .get_kv(&format!("refresh_consumed:{}", claims.jti))
433                        .await,
434                    Ok(None)
435                ) || !matches!(
436                    storage
437                        .get_kv(&format!("revoked_family:{}", claims.refresh_family()))
438                        .await,
439                    Ok(None)
440                );
441            }
442            if revoked {
443                audit_introspection(
444                    &state,
445                    &audit_client,
446                    true,
447                    "inactive_revoked_or_unusable",
448                    Some(&claims.sub),
449                    Some(&claims.jti),
450                )
451                .await;
452                debug!(
453                    "Token introspection: token has been revoked (jti: {})",
454                    claims.jti
455                );
456                return Ok(Json(IntrospectResponse {
457                    active: false,
458                    sub: None,
459                    client_id: None,
460                    scope: None,
461                    exp: None,
462                    iat: None,
463                    nbf: None,
464                    iss: None,
465                    aud: None,
466                    jti: None,
467                    token_type: None,
468                    username: None,
469                }));
470            }
471
472            debug_assert!(!claims.sub.is_empty(), "Token subject should not be empty");
473            audit_introspection(
474                &state,
475                &audit_client,
476                true,
477                "active",
478                Some(&claims.sub),
479                Some(&claims.jti),
480            )
481            .await;
482            Ok(Json(IntrospectResponse {
483                active: true,
484                sub: Some(claims.sub.clone()),
485                client_id: claims.client_id.clone(),
486                scope: Some(claims.scope.clone()),
487                exp: Some(claims.exp),
488                iat: Some(claims.iat),
489                nbf: Some(claims.nbf),
490                iss: Some(claims.iss.clone()),
491                aud: Some(JsonValue::String(claims.aud.clone())),
492                jti: Some(claims.jti.clone()),
493                token_type: Some(if claims.is_refresh_token() {
494                    "refresh_token".to_string()
495                } else {
496                    "Bearer".to_string()
497                }),
498                username: Some(claims.sub),
499            }))
500        }
501        Err(_e) => {
502            audit_introspection(&state, &audit_client, true, "inactive_invalid", None, None).await;
503            debug!("Token introspection: token is inactive");
504            // Return inactive token (per RFC 7662, don't reveal why it's invalid)
505            Ok(Json(IntrospectResponse {
506                active: false,
507                sub: None,
508                client_id: None,
509                scope: None,
510                exp: None,
511                iat: None,
512                nbf: None,
513                iss: None,
514                aud: None,
515                jti: None,
516                token_type: None,
517                username: None,
518            }))
519        }
520    }
521}
522
523/// Pushed Authorization Request endpoint (RFC 9126)
524///
525/// Clients push authorization request parameters to the server and receive a
526/// `request_uri` they can use at the authorization endpoint. The URI is unique
527/// per request and expires after 90 seconds (RFC 9126 §2.2).
528///
529/// Required form fields: `response_type`, `client_id`, `redirect_uri`
530/// Missing required fields are automatically rejected with 422 by Axum.
531pub async fn pushed_authorization_request(
532    State(state): State<ApiState>,
533    Form(req): Form<PARRequest>,
534) -> (StatusCode, Json<PARResponse>) {
535    debug!("Processing PAR request for client_id={}", req.client_id);
536
537    // Validate redirect_uri is a well-formed URL before accepting it
538    if Url::parse(&req.redirect_uri).is_err() {
539        return (
540            StatusCode::BAD_REQUEST,
541            Json(PARResponse {
542                request_uri: String::new(),
543                expires_in: 0,
544            }),
545        );
546    }
547
548    // Generate a unique request URI per RFC 9126 §2.2
549    let request_id = Uuid::new_v4().to_string();
550    let request_uri = format!("urn:ietf:params:oauth:request_uri:{}", request_id);
551
552    // Persist the authorization request parameters so the /authorize endpoint
553    // can retrieve them when presented with this request_uri (RFC 9126 §4).
554    let par_data = json!({
555        "response_type": req.response_type,
556        "client_id": req.client_id,
557        "redirect_uri": req.redirect_uri,
558        "scope": req.scope,
559        "state": req.state,
560        "nonce": req.nonce,
561        "code_challenge": req.code_challenge,
562        "code_challenge_method": req.code_challenge_method,
563    });
564    let storage_key = format!("par_request:{}", request_id);
565    if let Err(e) = state
566        .auth_framework
567        .storage()
568        .store_kv(
569            &storage_key,
570            par_data.to_string().as_bytes(),
571            Some(std::time::Duration::from_secs(90)),
572        )
573        .await
574    {
575        error!("Failed to store PAR request: {}", e);
576        // The request_uri would be unresolvable; returning a 201 with a URI
577        // that will never resolve is worse than surfacing the error early.
578        return (
579            StatusCode::INTERNAL_SERVER_ERROR,
580            Json(PARResponse {
581                request_uri: String::new(),
582                expires_in: 0,
583            }),
584        );
585    }
586
587    (
588        StatusCode::CREATED,
589        Json(PARResponse {
590            request_uri,
591            expires_in: 90,
592        }),
593    )
594}
595
596/// Device Authorization endpoint (RFC 8628 §3.1)
597///
598/// Initiates a device-authorization flow for input-constrained devices.
599/// Returns a `device_code`, human-friendly `user_code`, `verification_uri`,
600/// `expires_in`, and a polling `interval`.
601pub async fn device_authorization(
602    State(state): State<ApiState>,
603    Form(form): Form<HashMap<String, String>>,
604) -> Result<Json<JsonValue>, (StatusCode, Json<JsonValue>)> {
605    // RFC 8628 §3.1 – client_id is required
606    if form.get("client_id").map(|s| s.is_empty()).unwrap_or(true) {
607        return Err((
608            StatusCode::BAD_REQUEST,
609            Json(json!({
610                "error": "invalid_request",
611                "error_description": "client_id is required"
612            })),
613        ));
614    }
615
616    // Generate a high-entropy device_code and a human-friendly user_code.
617    let device_code = format!("dc_{}", Uuid::new_v4().simple());
618    let user_code = generate_user_code();
619    let verification_uri = "/device";
620    let expires_in: u64 = 600; // RFC 8628 recommends ≥600 s
621
622    // Persist the device authorization request so the token endpoint can poll.
623    let device_data = json!({
624        "client_id": form.get("client_id").cloned().unwrap_or_default(),
625        "scope":     form.get("scope").cloned().unwrap_or_default(),
626        "user_code": user_code,
627        "authorized": false
628    });
629    state
630        .auth_framework
631        .storage()
632        .store_kv(
633            &format!("device:{}", device_code),
634            device_data.to_string().as_bytes(),
635            Some(std::time::Duration::from_secs(expires_in)),
636        )
637        .await
638        .map_err(|e| {
639            error!("Failed to store device authorization request: {}", e);
640            (
641                StatusCode::INTERNAL_SERVER_ERROR,
642                Json(json!({
643                    "error": "server_error",
644                    "error_description": "Failed to initiate device authorization flow"
645                })),
646            )
647        })?;
648
649    debug!(
650        "Device authorization initiated for client_id={}",
651        form.get("client_id")
652            .map(String::as_str)
653            .unwrap_or_default()
654    );
655
656    Ok(Json(json!({
657        "device_code":              device_code,
658        "user_code":               user_code,
659        "verification_uri":        verification_uri,
660        "verification_uri_complete": format!("{}?user_code={}", verification_uri, user_code),
661        "expires_in":              expires_in,
662        "interval":                5
663    })))
664}
665
666/// CIBA (Client Initiated Backchannel Authentication) endpoint (OpenID Connect CIBA Core §7.1)
667///
668/// Initiates a backchannel authentication request.  Exactly one of
669/// `login_hint`, `login_hint_token`, or `id_token_hint` must be present.
670/// Returns an `auth_req_id` that the client polls at the token endpoint.
671pub async fn ciba_backchannel_auth(
672    State(state): State<ApiState>,
673    Form(form): Form<HashMap<String, String>>,
674) -> Result<Json<JsonValue>, (StatusCode, Json<JsonValue>)> {
675    // CIBA Core §7.1 – exactly one user-identification hint is required.
676    let login_hint = form
677        .get("login_hint")
678        .or_else(|| form.get("login_hint_token"))
679        .or_else(|| form.get("id_token_hint"))
680        .cloned()
681        .ok_or_else(|| {
682            (
683                StatusCode::BAD_REQUEST,
684                Json(json!({
685                    "error": "invalid_request",
686                    "error_description":
687                        "One of login_hint, login_hint_token, or id_token_hint is required"
688                })),
689            )
690        })?;
691
692    let auth_req_id = Uuid::new_v4().to_string();
693    let expires_in: u64 = 120; // 2-minute window for the authenticating device
694
695    // Persist the CIBA request so the token-endpoint poll can resolve it.
696    let ciba_data = json!({
697        "login_hint":      login_hint,
698        "client_id":       form.get("client_id").cloned().unwrap_or_default(),
699        "scope":           form.get("scope").cloned().unwrap_or_default(),
700        "binding_message": form.get("binding_message").cloned(),
701        "status":          "pending"
702    });
703    state
704        .auth_framework
705        .storage()
706        .store_kv(
707            &format!("ciba:{}", auth_req_id),
708            ciba_data.to_string().as_bytes(),
709            Some(std::time::Duration::from_secs(expires_in)),
710        )
711        .await
712        .map_err(|e| {
713            error!("Failed to store CIBA request: {}", e);
714            (
715                StatusCode::INTERNAL_SERVER_ERROR,
716                Json(json!({
717                    "error": "server_error",
718                    "error_description": "Failed to initiate backchannel authentication"
719                })),
720            )
721        })?;
722
723    debug!(
724        "CIBA request created: auth_req_id={}",
725        crate::utils::redact::fingerprint(&auth_req_id)
726    );
727
728    Ok(Json(json!({
729        "auth_req_id": auth_req_id,
730        "expires_in":  expires_in,
731        "interval":    5
732    })))
733}
734
735// ---------------------------------------------------------------------------
736// Helpers
737// ---------------------------------------------------------------------------
738
739/// Generate an 8-character, human-friendly user code (RFC 8628 §6.1 charset).
740/// Uses only unambiguous uppercase letters and digits (no O/0, I/1).
741fn generate_user_code() -> String {
742    use rand::RngExt;
743    const CHARS: &[u8] = b"ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
744    let mut rng = rand::rng();
745    (0..8)
746        .map(|_| CHARS[rng.random_range(0..CHARS.len())] as char)
747        .collect()
748}