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    let stored_secret = client_data["client_secret"].as_str().unwrap_or("");
214    // Constant-time comparison prevents timing oracle on the secret
215    Ok(
216        crate::security::timing_protection::constant_time_string_compare(
217            client_secret,
218            stored_secret,
219        ),
220    )
221}
222
223/// Token introspection endpoint (RFC 7662)
224///
225/// Allows authorized clients to determine the active state and meta-information
226/// about a given token.
227///
228/// Authentication is required via either:
229/// - HTTP Basic Auth header (`Authorization: Basic <base64(client_id:client_secret)>`)
230/// - POST body parameters (`client_id` + `client_secret`)
231///
232/// Bearer token authentication is explicitly rejected per RFC 7662 §2.1.
233pub async fn introspect_token(
234    state: State<ApiState>,
235    headers: HeaderMap,
236    form: Form<IntrospectRequest>,
237) -> Result<Json<IntrospectResponse>, (StatusCode, Json<JsonValue>)> {
238    debug!("Processing token introspection request");
239
240    // --- Authentication enforcement (RFC 7662 §2.1) ---
241    let auth_header = headers.get(axum::http::header::AUTHORIZATION);
242
243    let authenticated = match auth_header {
244        Some(value) => {
245            let value_str = value.to_str().unwrap_or("");
246            if value_str.starts_with("Bearer ") {
247                // Bearer tokens are not a valid authentication method for introspection
248                debug!("Introspect rejected: Bearer auth is not allowed");
249                return Err((
250                    StatusCode::UNAUTHORIZED,
251                    Json(json!({
252                        "error": "invalid_client",
253                        "error_description": "Bearer token authentication is not supported for token introspection"
254                    })),
255                ));
256            } else if let Some(encoded) = value_str.strip_prefix("Basic ") {
257                // Decode Basic auth credentials and verify against registered client.
258                match general_purpose::STANDARD.decode(encoded) {
259                    Ok(decoded_bytes) => {
260                        let decoded = String::from_utf8_lossy(&decoded_bytes);
261                        let mut parts = decoded.splitn(2, ':');
262                        let basic_client_id = parts.next().unwrap_or("").to_string();
263                        let basic_client_secret = parts.next().unwrap_or("").to_string();
264                        verify_client_credentials(&state, &basic_client_id, &basic_client_secret)
265                            .await?
266                    }
267                    Err(_) => {
268                        debug!("Introspect rejected: invalid Basic auth encoding");
269                        return Err((
270                            StatusCode::UNAUTHORIZED,
271                            Json(json!({
272                                "error": "invalid_client",
273                                "error_description": "Invalid Basic authentication encoding"
274                            })),
275                        ));
276                    }
277                }
278            } else {
279                // Unrecognised auth scheme
280                debug!("Introspect rejected: unknown auth scheme");
281                return Err((
282                    StatusCode::UNAUTHORIZED,
283                    Json(json!({
284                        "error": "invalid_client",
285                        "error_description": "Unsupported authentication scheme"
286                    })),
287                ));
288            }
289        }
290        None => {
291            // No Authorization header — verify using POST body client_id + client_secret.
292            match (&form.client_id, &form.client_secret) {
293                (Some(id), Some(secret)) => verify_client_credentials(&state, id, secret).await?,
294                _ => {
295                    debug!("Introspect rejected: missing client credentials");
296                    return Err((
297                        StatusCode::UNAUTHORIZED,
298                        Json(json!({
299                            "error": "invalid_client",
300                            "error_description": "client_id and client_secret are required"
301                        })),
302                    ));
303                }
304            }
305        }
306    };
307
308    if !authenticated {
309        debug!("Introspect rejected: invalid client credentials");
310        return Err((
311            StatusCode::UNAUTHORIZED,
312            Json(json!({
313                "error": "invalid_client",
314                "error_description": "Client authentication failed"
315            })),
316        ));
317    }
318
319    // --- Token validation ---
320    let token_manager = state.auth_framework.token_manager();
321
322    match token_manager.validate_jwt_token(&form.token) {
323        Ok(claims) => {
324            // Cross-check the revocation list before reporting the token as active.
325            // Tokens revoked via POST /oauth/revoke or POST /auth/logout are stored
326            // under revoked_token:{jti}; return active=false without revealing why.
327            let revocation_key = format!("revoked_token:{}", claims.jti);
328            // A revocation list that cannot be read is treated as "revoked" (fail closed).
329            let storage = state.auth_framework.storage();
330            let mut revoked = !matches!(storage.get_kv(&revocation_key).await, Ok(None));
331            // A token whose account is deactivated or gone cannot be used: not active.
332            if !revoked
333                && crate::auth::ensure_account_active(storage.as_ref(), &claims.sub, false)
334                    .await
335                    .is_err()
336            {
337                revoked = true;
338            }
339            // An ID token, client assertion or any other token that declares a use other than
340            // refresh is not an access token: it is not reported as one.
341            if !revoked && claims.token_use().is_some() && !claims.is_refresh_token() {
342                revoked = true;
343            }
344            // A refresh token is active only while it is unspent and its chain is intact.
345            if !revoked && claims.is_refresh_token() {
346                revoked = !matches!(
347                    storage
348                        .get_kv(&format!("refresh_consumed:{}", claims.jti))
349                        .await,
350                    Ok(None)
351                ) || !matches!(
352                    storage
353                        .get_kv(&format!("revoked_family:{}", claims.refresh_family()))
354                        .await,
355                    Ok(None)
356                );
357            }
358            if revoked {
359                debug!(
360                    "Token introspection: token has been revoked (jti: {})",
361                    claims.jti
362                );
363                return Ok(Json(IntrospectResponse {
364                    active: false,
365                    sub: None,
366                    client_id: None,
367                    scope: None,
368                    exp: None,
369                    iat: None,
370                    nbf: None,
371                    iss: None,
372                    aud: None,
373                    jti: None,
374                    token_type: None,
375                    username: None,
376                }));
377            }
378
379            debug_assert!(!claims.sub.is_empty(), "Token subject should not be empty");
380            Ok(Json(IntrospectResponse {
381                active: true,
382                sub: Some(claims.sub.clone()),
383                client_id: claims.client_id.clone(),
384                scope: Some(claims.scope.clone()),
385                exp: Some(claims.exp),
386                iat: Some(claims.iat),
387                nbf: Some(claims.nbf),
388                iss: Some(claims.iss.clone()),
389                aud: Some(JsonValue::String(claims.aud.clone())),
390                jti: Some(claims.jti.clone()),
391                token_type: Some(if claims.is_refresh_token() {
392                    "refresh_token".to_string()
393                } else {
394                    "Bearer".to_string()
395                }),
396                username: Some(claims.sub),
397            }))
398        }
399        Err(_e) => {
400            debug!("Token introspection: token is inactive");
401            // Return inactive token (per RFC 7662, don't reveal why it's invalid)
402            Ok(Json(IntrospectResponse {
403                active: false,
404                sub: None,
405                client_id: None,
406                scope: None,
407                exp: None,
408                iat: None,
409                nbf: None,
410                iss: None,
411                aud: None,
412                jti: None,
413                token_type: None,
414                username: None,
415            }))
416        }
417    }
418}
419
420/// Pushed Authorization Request endpoint (RFC 9126)
421///
422/// Clients push authorization request parameters to the server and receive a
423/// `request_uri` they can use at the authorization endpoint. The URI is unique
424/// per request and expires after 90 seconds (RFC 9126 §2.2).
425///
426/// Required form fields: `response_type`, `client_id`, `redirect_uri`
427/// Missing required fields are automatically rejected with 422 by Axum.
428pub async fn pushed_authorization_request(
429    State(state): State<ApiState>,
430    Form(req): Form<PARRequest>,
431) -> (StatusCode, Json<PARResponse>) {
432    debug!("Processing PAR request for client_id={}", req.client_id);
433
434    // Validate redirect_uri is a well-formed URL before accepting it
435    if Url::parse(&req.redirect_uri).is_err() {
436        return (
437            StatusCode::BAD_REQUEST,
438            Json(PARResponse {
439                request_uri: String::new(),
440                expires_in: 0,
441            }),
442        );
443    }
444
445    // Generate a unique request URI per RFC 9126 §2.2
446    let request_id = Uuid::new_v4().to_string();
447    let request_uri = format!("urn:ietf:params:oauth:request_uri:{}", request_id);
448
449    // Persist the authorization request parameters so the /authorize endpoint
450    // can retrieve them when presented with this request_uri (RFC 9126 §4).
451    let par_data = json!({
452        "response_type": req.response_type,
453        "client_id": req.client_id,
454        "redirect_uri": req.redirect_uri,
455        "scope": req.scope,
456        "state": req.state,
457        "nonce": req.nonce,
458        "code_challenge": req.code_challenge,
459        "code_challenge_method": req.code_challenge_method,
460    });
461    let storage_key = format!("par_request:{}", request_id);
462    if let Err(e) = state
463        .auth_framework
464        .storage()
465        .store_kv(
466            &storage_key,
467            par_data.to_string().as_bytes(),
468            Some(std::time::Duration::from_secs(90)),
469        )
470        .await
471    {
472        error!("Failed to store PAR request: {}", e);
473        // The request_uri would be unresolvable; returning a 201 with a URI
474        // that will never resolve is worse than surfacing the error early.
475        return (
476            StatusCode::INTERNAL_SERVER_ERROR,
477            Json(PARResponse {
478                request_uri: String::new(),
479                expires_in: 0,
480            }),
481        );
482    }
483
484    (
485        StatusCode::CREATED,
486        Json(PARResponse {
487            request_uri,
488            expires_in: 90,
489        }),
490    )
491}
492
493/// Device Authorization endpoint (RFC 8628 §3.1)
494///
495/// Initiates a device-authorization flow for input-constrained devices.
496/// Returns a `device_code`, human-friendly `user_code`, `verification_uri`,
497/// `expires_in`, and a polling `interval`.
498pub async fn device_authorization(
499    State(state): State<ApiState>,
500    Form(form): Form<HashMap<String, String>>,
501) -> Result<Json<JsonValue>, (StatusCode, Json<JsonValue>)> {
502    // RFC 8628 §3.1 – client_id is required
503    if form.get("client_id").map(|s| s.is_empty()).unwrap_or(true) {
504        return Err((
505            StatusCode::BAD_REQUEST,
506            Json(json!({
507                "error": "invalid_request",
508                "error_description": "client_id is required"
509            })),
510        ));
511    }
512
513    // Generate a high-entropy device_code and a human-friendly user_code.
514    let device_code = format!("dc_{}", Uuid::new_v4().simple());
515    let user_code = generate_user_code();
516    let verification_uri = "/device";
517    let expires_in: u64 = 600; // RFC 8628 recommends ≥600 s
518
519    // Persist the device authorization request so the token endpoint can poll.
520    let device_data = json!({
521        "client_id": form.get("client_id").cloned().unwrap_or_default(),
522        "scope":     form.get("scope").cloned().unwrap_or_default(),
523        "user_code": user_code,
524        "authorized": false
525    });
526    state
527        .auth_framework
528        .storage()
529        .store_kv(
530            &format!("device:{}", device_code),
531            device_data.to_string().as_bytes(),
532            Some(std::time::Duration::from_secs(expires_in)),
533        )
534        .await
535        .map_err(|e| {
536            error!("Failed to store device authorization request: {}", e);
537            (
538                StatusCode::INTERNAL_SERVER_ERROR,
539                Json(json!({
540                    "error": "server_error",
541                    "error_description": "Failed to initiate device authorization flow"
542                })),
543            )
544        })?;
545
546    debug!(
547        "Device authorization initiated for client_id={}",
548        form.get("client_id")
549            .map(String::as_str)
550            .unwrap_or_default()
551    );
552
553    Ok(Json(json!({
554        "device_code":              device_code,
555        "user_code":               user_code,
556        "verification_uri":        verification_uri,
557        "verification_uri_complete": format!("{}?user_code={}", verification_uri, user_code),
558        "expires_in":              expires_in,
559        "interval":                5
560    })))
561}
562
563/// CIBA (Client Initiated Backchannel Authentication) endpoint (OpenID Connect CIBA Core §7.1)
564///
565/// Initiates a backchannel authentication request.  Exactly one of
566/// `login_hint`, `login_hint_token`, or `id_token_hint` must be present.
567/// Returns an `auth_req_id` that the client polls at the token endpoint.
568pub async fn ciba_backchannel_auth(
569    State(state): State<ApiState>,
570    Form(form): Form<HashMap<String, String>>,
571) -> Result<Json<JsonValue>, (StatusCode, Json<JsonValue>)> {
572    // CIBA Core §7.1 – exactly one user-identification hint is required.
573    let login_hint = form
574        .get("login_hint")
575        .or_else(|| form.get("login_hint_token"))
576        .or_else(|| form.get("id_token_hint"))
577        .cloned()
578        .ok_or_else(|| {
579            (
580                StatusCode::BAD_REQUEST,
581                Json(json!({
582                    "error": "invalid_request",
583                    "error_description":
584                        "One of login_hint, login_hint_token, or id_token_hint is required"
585                })),
586            )
587        })?;
588
589    let auth_req_id = Uuid::new_v4().to_string();
590    let expires_in: u64 = 120; // 2-minute window for the authenticating device
591
592    // Persist the CIBA request so the token-endpoint poll can resolve it.
593    let ciba_data = json!({
594        "login_hint":      login_hint,
595        "client_id":       form.get("client_id").cloned().unwrap_or_default(),
596        "scope":           form.get("scope").cloned().unwrap_or_default(),
597        "binding_message": form.get("binding_message").cloned(),
598        "status":          "pending"
599    });
600    state
601        .auth_framework
602        .storage()
603        .store_kv(
604            &format!("ciba:{}", auth_req_id),
605            ciba_data.to_string().as_bytes(),
606            Some(std::time::Duration::from_secs(expires_in)),
607        )
608        .await
609        .map_err(|e| {
610            error!("Failed to store CIBA request: {}", e);
611            (
612                StatusCode::INTERNAL_SERVER_ERROR,
613                Json(json!({
614                    "error": "server_error",
615                    "error_description": "Failed to initiate backchannel authentication"
616                })),
617            )
618        })?;
619
620    debug!(
621        "CIBA request created: auth_req_id={}",
622        crate::utils::redact::fingerprint(&auth_req_id)
623    );
624
625    Ok(Json(json!({
626        "auth_req_id": auth_req_id,
627        "expires_in":  expires_in,
628        "interval":    5
629    })))
630}
631
632// ---------------------------------------------------------------------------
633// Helpers
634// ---------------------------------------------------------------------------
635
636/// Generate an 8-character, human-friendly user code (RFC 8628 §6.1 charset).
637/// Uses only unambiguous uppercase letters and digits (no O/0, I/1).
638fn generate_user_code() -> String {
639    use rand::RngExt;
640    const CHARS: &[u8] = b"ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
641    let mut rng = rand::rng();
642    (0..8)
643        .map(|_| CHARS[rng.random_range(0..CHARS.len())] as char)
644        .collect()
645}