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