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