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(Debug, 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
43/// Token introspection response (RFC 7662)
44#[derive(Debug, Serialize)]
45pub struct IntrospectResponse {
46    /// Indicates if the token is currently active
47    pub active: bool,
48
49    /// The subject of the token
50    #[serde(skip_serializing_if = "Option::is_none")]
51    pub sub: Option<String>,
52
53    /// The client_id associated with the token
54    #[serde(skip_serializing_if = "Option::is_none")]
55    pub client_id: Option<String>,
56
57    /// The scopes associated with the token
58    #[serde(skip_serializing_if = "Option::is_none")]
59    pub scope: Option<String>,
60
61    /// Token expiration timestamp
62    #[serde(skip_serializing_if = "Option::is_none")]
63    pub exp: Option<i64>,
64
65    /// Token issued at timestamp
66    #[serde(skip_serializing_if = "Option::is_none")]
67    pub iat: Option<i64>,
68
69    /// Not before timestamp
70    #[serde(skip_serializing_if = "Option::is_none")]
71    pub nbf: Option<i64>,
72
73    /// Issuer of the token
74    #[serde(skip_serializing_if = "Option::is_none")]
75    pub iss: Option<String>,
76
77    /// Audience of the token
78    #[serde(skip_serializing_if = "Option::is_none")]
79    pub aud: Option<JsonValue>,
80
81    /// JWT ID
82    #[serde(skip_serializing_if = "Option::is_none")]
83    pub jti: Option<String>,
84
85    /// Token type (e.g., "Bearer")
86    #[serde(skip_serializing_if = "Option::is_none")]
87    pub token_type: Option<String>,
88
89    /// Username associated with the token
90    #[serde(skip_serializing_if = "Option::is_none")]
91    pub username: Option<String>,
92}
93
94/// Pushed Authorization Request parameters (RFC 9126)
95///
96/// Required fields are non-optional so Axum Form validation returns 422
97/// automatically when they are missing from the request body.
98#[derive(Debug, Deserialize)]
99pub struct PARRequest {
100    /// Required: OAuth 2.0 response type (e.g., "code")
101    pub response_type: String,
102
103    /// Required: The client identifier
104    pub client_id: String,
105
106    /// Required: Redirection URI for the authorization response
107    pub redirect_uri: String,
108
109    /// Optional: Requested scope(s)
110    pub scope: Option<String>,
111
112    /// Optional: Opaque state value for the client
113    pub state: Option<String>,
114
115    /// Optional: Nonce for OIDC requests
116    pub nonce: Option<String>,
117
118    /// Optional: PKCE code challenge
119    pub code_challenge: Option<String>,
120
121    /// Optional: PKCE code challenge method (e.g., "S256")
122    pub code_challenge_method: Option<String>,
123}
124
125/// Pushed Authorization Request response (RFC 9126)
126#[derive(Debug, Serialize)]
127pub struct PARResponse {
128    /// The request URI for the authorization request
129    pub request_uri: String,
130
131    /// Expiration time in seconds
132    pub expires_in: u64,
133}
134
135// ============================================================================
136// Endpoint Handlers
137// ============================================================================
138
139/// Verify OAuth2 client credentials against the registered client record in storage.
140///
141/// Returns `Ok(true)` if the credentials are valid, `Ok(false)` if the client_id
142/// is unknown or the secret does not match, and `Err(...)` on storage failures.
143/// The function uses constant-time comparison to prevent timing oracle attacks on
144/// the client_secret.
145async fn verify_client_credentials(
146    state: &State<ApiState>,
147    client_id: &str,
148    client_secret: &str,
149) -> Result<bool, (StatusCode, Json<JsonValue>)> {
150    let client_key = format!("oauth2_client:{}", client_id);
151    let client_data = match state.auth_framework.storage().get_kv(&client_key).await {
152        Ok(Some(bytes)) => match serde_json::from_slice::<serde_json::Value>(&bytes) {
153            Ok(v) => v,
154            Err(_) => {
155                error!(
156                    "Introspect: failed to deserialize client record for {}",
157                    client_id
158                );
159                return Err((
160                    StatusCode::INTERNAL_SERVER_ERROR,
161                    Json(json!({
162                        "error": "server_error",
163                        "error_description": "Internal server error"
164                    })),
165                ));
166            }
167        },
168        Ok(None) => {
169            // Unknown client — return false (don't reveal whether the client exists)
170            return Ok(false);
171        }
172        Err(e) => {
173            error!(
174                "Introspect: storage error looking up client {}: {}",
175                client_id, e
176            );
177            return Err((
178                StatusCode::INTERNAL_SERVER_ERROR,
179                Json(json!({
180                    "error": "server_error",
181                    "error_description": "Internal server error"
182                })),
183            ));
184        }
185    };
186
187    let stored_secret = client_data["client_secret"].as_str().unwrap_or("");
188    // Constant-time comparison prevents timing oracle on the secret
189    Ok(
190        crate::security::timing_protection::constant_time_string_compare(
191            client_secret,
192            stored_secret,
193        ),
194    )
195}
196
197/// Token introspection endpoint (RFC 7662)
198///
199/// Allows authorized clients to determine the active state and meta-information
200/// about a given token.
201///
202/// Authentication is required via either:
203/// - HTTP Basic Auth header (`Authorization: Basic <base64(client_id:client_secret)>`)
204/// - POST body parameters (`client_id` + `client_secret`)
205///
206/// Bearer token authentication is explicitly rejected per RFC 7662 §2.1.
207pub async fn introspect_token(
208    state: State<ApiState>,
209    headers: HeaderMap,
210    form: Form<IntrospectRequest>,
211) -> Result<Json<IntrospectResponse>, (StatusCode, Json<JsonValue>)> {
212    debug!("Processing token introspection request");
213
214    // --- Authentication enforcement (RFC 7662 §2.1) ---
215    let auth_header = headers.get(axum::http::header::AUTHORIZATION);
216
217    let authenticated = match auth_header {
218        Some(value) => {
219            let value_str = value.to_str().unwrap_or("");
220            if value_str.starts_with("Bearer ") {
221                // Bearer tokens are not a valid authentication method for introspection
222                debug!("Introspect rejected: Bearer auth is not allowed");
223                return Err((
224                    StatusCode::UNAUTHORIZED,
225                    Json(json!({
226                        "error": "invalid_client",
227                        "error_description": "Bearer token authentication is not supported for token introspection"
228                    })),
229                ));
230            } else if let Some(encoded) = value_str.strip_prefix("Basic ") {
231                // Decode Basic auth credentials and verify against registered client.
232                match general_purpose::STANDARD.decode(encoded) {
233                    Ok(decoded_bytes) => {
234                        let decoded = String::from_utf8_lossy(&decoded_bytes);
235                        let mut parts = decoded.splitn(2, ':');
236                        let basic_client_id = parts.next().unwrap_or("").to_string();
237                        let basic_client_secret = parts.next().unwrap_or("").to_string();
238                        verify_client_credentials(&state, &basic_client_id, &basic_client_secret)
239                            .await?
240                    }
241                    Err(_) => {
242                        debug!("Introspect rejected: invalid Basic auth encoding");
243                        return Err((
244                            StatusCode::UNAUTHORIZED,
245                            Json(json!({
246                                "error": "invalid_client",
247                                "error_description": "Invalid Basic authentication encoding"
248                            })),
249                        ));
250                    }
251                }
252            } else {
253                // Unrecognised auth scheme
254                debug!("Introspect rejected: unknown auth scheme");
255                return Err((
256                    StatusCode::UNAUTHORIZED,
257                    Json(json!({
258                        "error": "invalid_client",
259                        "error_description": "Unsupported authentication scheme"
260                    })),
261                ));
262            }
263        }
264        None => {
265            // No Authorization header — verify using POST body client_id + client_secret.
266            match (&form.client_id, &form.client_secret) {
267                (Some(id), Some(secret)) => verify_client_credentials(&state, id, secret).await?,
268                _ => {
269                    debug!("Introspect rejected: missing client credentials");
270                    return Err((
271                        StatusCode::UNAUTHORIZED,
272                        Json(json!({
273                            "error": "invalid_client",
274                            "error_description": "client_id and client_secret are required"
275                        })),
276                    ));
277                }
278            }
279        }
280    };
281
282    if !authenticated {
283        debug!("Introspect rejected: invalid client credentials");
284        return Err((
285            StatusCode::UNAUTHORIZED,
286            Json(json!({
287                "error": "invalid_client",
288                "error_description": "Client authentication failed"
289            })),
290        ));
291    }
292
293    // --- Token validation ---
294    let token_manager = state.auth_framework.token_manager();
295
296    match token_manager.validate_jwt_token(&form.token) {
297        Ok(claims) => {
298            // Cross-check the revocation list before reporting the token as active.
299            // Tokens revoked via POST /oauth/revoke or POST /auth/logout are stored
300            // under revoked_token:{jti}; return active=false without revealing why.
301            let revocation_key = format!("revoked_token:{}", claims.jti);
302            // A revocation list that cannot be read is treated as "revoked" (fail closed).
303            let storage = state.auth_framework.storage();
304            let mut revoked = !matches!(storage.get_kv(&revocation_key).await, Ok(None));
305            // A token whose account is deactivated or gone cannot be used: not active.
306            if !revoked
307                && crate::auth::ensure_account_active(storage.as_ref(), &claims.sub, false)
308                    .await
309                    .is_err()
310            {
311                revoked = true;
312            }
313            // An ID token, client assertion or any other token that declares a use other than
314            // refresh is not an access token: it is not reported as one.
315            if !revoked && claims.token_use().is_some() && !claims.is_refresh_token() {
316                revoked = true;
317            }
318            // A refresh token is active only while it is unspent and its chain is intact.
319            if !revoked && claims.is_refresh_token() {
320                revoked = !matches!(
321                    storage
322                        .get_kv(&format!("refresh_consumed:{}", claims.jti))
323                        .await,
324                    Ok(None)
325                ) || !matches!(
326                    storage
327                        .get_kv(&format!("revoked_family:{}", claims.refresh_family()))
328                        .await,
329                    Ok(None)
330                );
331            }
332            if revoked {
333                debug!(
334                    "Token introspection: token has been revoked (jti: {})",
335                    claims.jti
336                );
337                return Ok(Json(IntrospectResponse {
338                    active: false,
339                    sub: None,
340                    client_id: None,
341                    scope: None,
342                    exp: None,
343                    iat: None,
344                    nbf: None,
345                    iss: None,
346                    aud: None,
347                    jti: None,
348                    token_type: None,
349                    username: None,
350                }));
351            }
352
353            debug_assert!(!claims.sub.is_empty(), "Token subject should not be empty");
354            Ok(Json(IntrospectResponse {
355                active: true,
356                sub: Some(claims.sub.clone()),
357                client_id: claims.client_id.clone(),
358                scope: Some(claims.scope.clone()),
359                exp: Some(claims.exp),
360                iat: Some(claims.iat),
361                nbf: Some(claims.nbf),
362                iss: Some(claims.iss.clone()),
363                aud: Some(JsonValue::String(claims.aud.clone())),
364                jti: Some(claims.jti.clone()),
365                token_type: Some(if claims.is_refresh_token() {
366                    "refresh_token".to_string()
367                } else {
368                    "Bearer".to_string()
369                }),
370                username: Some(claims.sub),
371            }))
372        }
373        Err(_e) => {
374            debug!("Token introspection: token is inactive");
375            // Return inactive token (per RFC 7662, don't reveal why it's invalid)
376            Ok(Json(IntrospectResponse {
377                active: false,
378                sub: None,
379                client_id: None,
380                scope: None,
381                exp: None,
382                iat: None,
383                nbf: None,
384                iss: None,
385                aud: None,
386                jti: None,
387                token_type: None,
388                username: None,
389            }))
390        }
391    }
392}
393
394/// Pushed Authorization Request endpoint (RFC 9126)
395///
396/// Clients push authorization request parameters to the server and receive a
397/// `request_uri` they can use at the authorization endpoint. The URI is unique
398/// per request and expires after 90 seconds (RFC 9126 §2.2).
399///
400/// Required form fields: `response_type`, `client_id`, `redirect_uri`
401/// Missing required fields are automatically rejected with 422 by Axum.
402pub async fn pushed_authorization_request(
403    State(state): State<ApiState>,
404    Form(req): Form<PARRequest>,
405) -> (StatusCode, Json<PARResponse>) {
406    debug!("Processing PAR request for client_id={}", req.client_id);
407
408    // Validate redirect_uri is a well-formed URL before accepting it
409    if Url::parse(&req.redirect_uri).is_err() {
410        return (
411            StatusCode::BAD_REQUEST,
412            Json(PARResponse {
413                request_uri: String::new(),
414                expires_in: 0,
415            }),
416        );
417    }
418
419    // Generate a unique request URI per RFC 9126 §2.2
420    let request_id = Uuid::new_v4().to_string();
421    let request_uri = format!("urn:ietf:params:oauth:request_uri:{}", request_id);
422
423    // Persist the authorization request parameters so the /authorize endpoint
424    // can retrieve them when presented with this request_uri (RFC 9126 §4).
425    let par_data = json!({
426        "response_type": req.response_type,
427        "client_id": req.client_id,
428        "redirect_uri": req.redirect_uri,
429        "scope": req.scope,
430        "state": req.state,
431        "nonce": req.nonce,
432        "code_challenge": req.code_challenge,
433        "code_challenge_method": req.code_challenge_method,
434    });
435    let storage_key = format!("par_request:{}", request_id);
436    if let Err(e) = state
437        .auth_framework
438        .storage()
439        .store_kv(
440            &storage_key,
441            par_data.to_string().as_bytes(),
442            Some(std::time::Duration::from_secs(90)),
443        )
444        .await
445    {
446        error!("Failed to store PAR request: {}", e);
447        // The request_uri would be unresolvable; returning a 201 with a URI
448        // that will never resolve is worse than surfacing the error early.
449        return (
450            StatusCode::INTERNAL_SERVER_ERROR,
451            Json(PARResponse {
452                request_uri: String::new(),
453                expires_in: 0,
454            }),
455        );
456    }
457
458    (
459        StatusCode::CREATED,
460        Json(PARResponse {
461            request_uri,
462            expires_in: 90,
463        }),
464    )
465}
466
467/// Device Authorization endpoint (RFC 8628 §3.1)
468///
469/// Initiates a device-authorization flow for input-constrained devices.
470/// Returns a `device_code`, human-friendly `user_code`, `verification_uri`,
471/// `expires_in`, and a polling `interval`.
472pub async fn device_authorization(
473    State(state): State<ApiState>,
474    Form(form): Form<HashMap<String, String>>,
475) -> Result<Json<JsonValue>, (StatusCode, Json<JsonValue>)> {
476    // RFC 8628 §3.1 – client_id is required
477    if form.get("client_id").map(|s| s.is_empty()).unwrap_or(true) {
478        return Err((
479            StatusCode::BAD_REQUEST,
480            Json(json!({
481                "error": "invalid_request",
482                "error_description": "client_id is required"
483            })),
484        ));
485    }
486
487    // Generate a high-entropy device_code and a human-friendly user_code.
488    let device_code = format!("dc_{}", Uuid::new_v4().simple());
489    let user_code = generate_user_code();
490    let verification_uri = "/device";
491    let expires_in: u64 = 600; // RFC 8628 recommends ≥600 s
492
493    // Persist the device authorization request so the token endpoint can poll.
494    let device_data = json!({
495        "client_id": form.get("client_id").cloned().unwrap_or_default(),
496        "scope":     form.get("scope").cloned().unwrap_or_default(),
497        "user_code": user_code,
498        "authorized": false
499    });
500    state
501        .auth_framework
502        .storage()
503        .store_kv(
504            &format!("device:{}", device_code),
505            device_data.to_string().as_bytes(),
506            Some(std::time::Duration::from_secs(expires_in)),
507        )
508        .await
509        .map_err(|e| {
510            error!("Failed to store device authorization request: {}", e);
511            (
512                StatusCode::INTERNAL_SERVER_ERROR,
513                Json(json!({
514                    "error": "server_error",
515                    "error_description": "Failed to initiate device authorization flow"
516                })),
517            )
518        })?;
519
520    debug!(
521        "Device authorization initiated for client_id={}",
522        form.get("client_id")
523            .map(String::as_str)
524            .unwrap_or_default()
525    );
526
527    Ok(Json(json!({
528        "device_code":              device_code,
529        "user_code":               user_code,
530        "verification_uri":        verification_uri,
531        "verification_uri_complete": format!("{}?user_code={}", verification_uri, user_code),
532        "expires_in":              expires_in,
533        "interval":                5
534    })))
535}
536
537/// CIBA (Client Initiated Backchannel Authentication) endpoint (OpenID Connect CIBA Core §7.1)
538///
539/// Initiates a backchannel authentication request.  Exactly one of
540/// `login_hint`, `login_hint_token`, or `id_token_hint` must be present.
541/// Returns an `auth_req_id` that the client polls at the token endpoint.
542pub async fn ciba_backchannel_auth(
543    State(state): State<ApiState>,
544    Form(form): Form<HashMap<String, String>>,
545) -> Result<Json<JsonValue>, (StatusCode, Json<JsonValue>)> {
546    // CIBA Core §7.1 – exactly one user-identification hint is required.
547    let login_hint = form
548        .get("login_hint")
549        .or_else(|| form.get("login_hint_token"))
550        .or_else(|| form.get("id_token_hint"))
551        .cloned()
552        .ok_or_else(|| {
553            (
554                StatusCode::BAD_REQUEST,
555                Json(json!({
556                    "error": "invalid_request",
557                    "error_description":
558                        "One of login_hint, login_hint_token, or id_token_hint is required"
559                })),
560            )
561        })?;
562
563    let auth_req_id = Uuid::new_v4().to_string();
564    let expires_in: u64 = 120; // 2-minute window for the authenticating device
565
566    // Persist the CIBA request so the token-endpoint poll can resolve it.
567    let ciba_data = json!({
568        "login_hint":      login_hint,
569        "client_id":       form.get("client_id").cloned().unwrap_or_default(),
570        "scope":           form.get("scope").cloned().unwrap_or_default(),
571        "binding_message": form.get("binding_message").cloned(),
572        "status":          "pending"
573    });
574    state
575        .auth_framework
576        .storage()
577        .store_kv(
578            &format!("ciba:{}", auth_req_id),
579            ciba_data.to_string().as_bytes(),
580            Some(std::time::Duration::from_secs(expires_in)),
581        )
582        .await
583        .map_err(|e| {
584            error!("Failed to store CIBA request: {}", e);
585            (
586                StatusCode::INTERNAL_SERVER_ERROR,
587                Json(json!({
588                    "error": "server_error",
589                    "error_description": "Failed to initiate backchannel authentication"
590                })),
591            )
592        })?;
593
594    debug!("CIBA request created: auth_req_id={}", auth_req_id);
595
596    Ok(Json(json!({
597        "auth_req_id": auth_req_id,
598        "expires_in":  expires_in,
599        "interval":    5
600    })))
601}
602
603// ---------------------------------------------------------------------------
604// Helpers
605// ---------------------------------------------------------------------------
606
607/// Generate an 8-character, human-friendly user code (RFC 8628 §6.1 charset).
608/// Uses only unambiguous uppercase letters and digits (no O/0, I/1).
609fn generate_user_code() -> String {
610    use rand::RngExt;
611    const CHARS: &[u8] = b"ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
612    let mut rng = rand::rng();
613    (0..8)
614        .map(|_| CHARS[rng.random_range(0..CHARS.len())] as char)
615        .collect()
616}