Skip to main content

auth_framework/api/
oauth2.rs

1//! OAuth 2.0 API Endpoints
2//!
3//! Handles OAuth 2.0 authorization code flow (RFC 6749), token exchange,
4//! token revocation (RFC 7009), and client metadata retrieval.
5
6use crate::api::{ApiResponse, ApiState, extract_bearer_token, validate_api_token};
7use crate::oauth2_server::AuthorizationRequest;
8// Re-export canonical types for consumers that imported them from api::oauth2
9pub use crate::oauth2_server::{
10    AuthorizationRequest as AuthorizeRequest, TokenRequest, TokenResponse,
11};
12use axum::{
13    Json,
14    extract::{Path, Query, State},
15    http::{HeaderMap, StatusCode},
16    response::{IntoResponse, Redirect},
17};
18use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
19use serde::{Deserialize, Serialize};
20use sha2::{Digest, Sha256};
21use url::Url;
22use uuid::Uuid;
23
24/// Compare two redirect URIs using parsed URL normalization (RFC 6749 §3.1.2.3).
25///
26/// Normalization handles scheme/host case, default-port elision, and path
27/// normalization so that trivial textual differences don't cause mismatches.
28fn redirect_uri_matches(candidate: &str, registered: &str) -> bool {
29    match (Url::parse(candidate), Url::parse(registered)) {
30        (Ok(a), Ok(b)) => {
31            // RFC 6749 §3.1.2: redirect URIs MUST NOT contain a fragment component.
32            if a.fragment().is_some() || b.fragment().is_some() {
33                return false;
34            }
35
36            a.scheme() == b.scheme()
37                && a.host_str() == b.host_str()
38                && a.port_or_known_default() == b.port_or_known_default()
39                && a.path() == b.path()
40                && a.query() == b.query()
41        }
42        // If either side isn't a valid URL, fall back to exact string match
43        // so we don't silently accept garbage.
44        _ => candidate == registered,
45    }
46}
47
48/// OAuth error response per [RFC 6749 §5.2](https://datatracker.ietf.org/doc/html/rfc6749#section-5.2).
49///
50/// Use the constructor + chaining helpers to avoid specifying all four fields
51/// every time:
52///
53/// # Example
54/// ```rust
55/// use auth_framework::api::oauth2::OAuthError;
56///
57/// let err = OAuthError::new("invalid_request")
58///     .description("missing redirect_uri")
59///     .state("abc");
60/// assert_eq!(err.error, "invalid_request");
61/// assert_eq!(err.error_description.as_deref(), Some("missing redirect_uri"));
62/// ```
63#[derive(Debug, Serialize)]
64pub struct OAuthError {
65    pub error: String,
66    #[serde(skip_serializing_if = "Option::is_none")]
67    pub error_description: Option<String>,
68    #[serde(skip_serializing_if = "Option::is_none")]
69    pub error_uri: Option<String>,
70    #[serde(skip_serializing_if = "Option::is_none")]
71    pub state: Option<String>,
72}
73
74impl OAuthError {
75    /// Create a new error with the given error code (e.g. `"invalid_request"`).
76    pub fn new(error: impl Into<String>) -> Self {
77        Self {
78            error: error.into(),
79            error_description: None,
80            error_uri: None,
81            state: None,
82        }
83    }
84
85    /// Set the human-readable error description.
86    pub fn description(mut self, desc: impl Into<String>) -> Self {
87        self.error_description = Some(desc.into());
88        self
89    }
90
91    /// Set the `state` parameter (echoed back from the authorization request).
92    pub fn state(mut self, state: impl Into<String>) -> Self {
93        self.state = Some(state.into());
94        self
95    }
96
97    /// Set the `state` parameter from an `Option`.
98    pub fn maybe_state(mut self, state: Option<String>) -> Self {
99        self.state = state;
100        self
101    }
102
103    /// Set the error URI pointing to a page with more information.
104    pub fn error_uri(mut self, uri: impl Into<String>) -> Self {
105        self.error_uri = Some(uri.into());
106        self
107    }
108}
109
110/// Registered OAuth 2.0 client metadata.
111///
112/// Stored in KV at `oauth2_client:{client_id}` and returned by
113/// [`get_client_info`].
114///
115/// # Example
116/// ```rust
117/// use auth_framework::api::oauth2::ClientInfo;
118///
119/// let info = ClientInfo {
120///     client_id: "abc".into(),
121///     name: "My App".into(),
122///     description: "A demo app".into(),
123///     redirect_uris: vec!["https://example.com/cb".into()],
124///     scopes: vec!["openid".into()],
125/// };
126/// assert_eq!(info.client_id, "abc");
127/// ```
128#[derive(Debug, Serialize, Deserialize)]
129pub struct ClientInfo {
130    pub client_id: String,
131    pub name: String,
132    pub description: String,
133    pub redirect_uris: Vec<String>,
134    pub scopes: Vec<String>,
135}
136
137/// OAuth 2.0 token revocation request per [RFC 7009](https://datatracker.ietf.org/doc/html/rfc7009).
138///
139/// # Example
140/// ```rust
141/// use auth_framework::api::oauth2::RevokeRequest;
142///
143/// let req: RevokeRequest = serde_json::from_str(r#"{"token":"abc"}"#).unwrap();
144/// assert_eq!(req.token, "abc");
145/// assert!(req.token_type_hint.is_none());
146/// ```
147#[derive(Deserialize)]
148pub struct RevokeRequest {
149    pub token: String,
150    #[serde(default)]
151    pub token_type_hint: Option<String>, // "access_token" or "refresh_token"
152    /// The client making the request, when it does not use HTTP Basic (RFC 7009 section 2.1).
153    #[serde(default)]
154    pub client_id: Option<String>,
155    /// The client's secret, when it does not use HTTP Basic.
156    #[serde(default)]
157    pub client_secret: Option<String>,
158}
159
160impl std::fmt::Debug for RevokeRequest {
161    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
162        let mut d = f.debug_struct("RevokeRequest");
163        d.field("token", &crate::utils::redact::redacted(&self.token));
164        d.field("token_type_hint", &self.token_type_hint);
165        d.field("client_id", &self.client_id);
166        d.field(
167            "client_secret",
168            &crate::utils::redact::redacted(&self.client_secret),
169        );
170        d.finish()
171    }
172}
173
174/// OpenID Connect UserInfo response.
175///
176/// Contains claims about the authenticated user, filtered by the scopes
177/// granted to the access token.
178///
179/// # Example
180/// ```rust
181/// use auth_framework::api::oauth2::UserInfoResponse;
182///
183/// let info = UserInfoResponse {
184///     sub: "user-1".into(),
185///     name: Some("Alice".into()),
186///     email: None,
187///     picture: None,
188///     updated_at: None,
189/// };
190/// assert_eq!(info.sub, "user-1");
191/// ```
192#[derive(Debug, Serialize)]
193pub struct UserInfoResponse {
194    pub sub: String,
195    #[serde(skip_serializing_if = "Option::is_none")]
196    pub name: Option<String>,
197    #[serde(skip_serializing_if = "Option::is_none")]
198    pub email: Option<String>,
199    #[serde(skip_serializing_if = "Option::is_none")]
200    pub picture: Option<String>,
201    #[serde(skip_serializing_if = "Option::is_none")]
202    pub updated_at: Option<i64>,
203}
204
205/// GET /oauth/authorize
206/// OAuth 2.0 authorization endpoint — validates the client and redirect_uri, generates
207/// an authorization code, and redirects the user-agent back to the client (RFC 6749 §4.1.2).
208///
209/// SECURITY: The caller must supply their access token as `Authorization: Bearer <token>`.
210/// The authenticated user's identity is recorded in the authorization code so it can be
211/// used when the client exchanges the code for tokens.  Issuing codes without a verified
212/// user identity would allow any party that knows a valid client_id to obtain tokens.
213pub async fn authorize(
214    State(state): State<ApiState>,
215    headers: HeaderMap,
216    Query(params): Query<AuthorizationRequest>,
217) -> impl IntoResponse {
218    if params.response_type != "code" {
219        let error = OAuthError::new("unsupported_response_type")
220            .description("Only 'code' response type is supported")
221            .maybe_state(params.state);
222        return (StatusCode::BAD_REQUEST, Json(error)).into_response();
223    }
224
225    if params.client_id.is_empty() {
226        let error = OAuthError::new("invalid_request")
227            .description("client_id is required")
228            .maybe_state(params.state);
229        return (StatusCode::BAD_REQUEST, Json(error)).into_response();
230    }
231
232    if params.redirect_uri.is_empty() {
233        let error = OAuthError::new("invalid_request")
234            .description("redirect_uri is required")
235            .maybe_state(params.state);
236        return (StatusCode::BAD_REQUEST, Json(error)).into_response();
237    }
238
239    // SECURITY: Require the resource owner to be authenticated before issuing codes.
240    // The user must supply their Bearer access token.  Without this check, any caller
241    // that knows a registered client_id could obtain a code and exchange it for tokens.
242    let user_id = {
243        let token_str = match extract_bearer_token(&headers) {
244            Some(t) => t,
245            None => {
246                let error = OAuthError::new("unauthorized_client")
247                    .description(
248                        "User authentication required: supply your access token as \
249                         'Authorization: Bearer <token>'",
250                    )
251                    .maybe_state(params.state);
252                return (StatusCode::UNAUTHORIZED, Json(error)).into_response();
253            }
254        };
255        match validate_api_token(&state.auth_framework, &token_str).await {
256            Ok(auth_token) => auth_token.user_id,
257            Err(_) => {
258                let error = OAuthError::new("unauthorized_client")
259                    .description("Invalid or expired user access token")
260                    .maybe_state(params.state);
261                return (StatusCode::UNAUTHORIZED, Json(error)).into_response();
262            }
263        }
264    };
265
266    // SECURITY: Validate client_id and verify the redirect_uri is pre-registered.
267    // Redirecting to an unregistered URI would let an attacker steal the authorization code.
268    let client_key = format!("oauth2_client:{}", params.client_id);
269    let granted_scope = match state.auth_framework.storage().get_kv(&client_key).await {
270        Ok(Some(data)) => {
271            let client_data: serde_json::Value = serde_json::from_slice(&data).unwrap_or_default();
272            let registered_uris: Vec<String> = client_data["redirect_uris"]
273                .as_array()
274                .map(|arr| {
275                    arr.iter()
276                        .filter_map(|v| v.as_str().map(String::from))
277                        .collect()
278                })
279                .unwrap_or_default();
280
281            if !registered_uris
282                .iter()
283                .any(|r| redirect_uri_matches(&params.redirect_uri, r))
284            {
285                tracing::warn!(
286                    client_id = %params.client_id,
287                    redirect_uri = %params.redirect_uri,
288                    "OAuth authorize: redirect_uri not registered for client"
289                );
290                let error = OAuthError::new("invalid_request")
291                    .description("redirect_uri is not registered for this client")
292                    .maybe_state(params.state);
293                return (StatusCode::BAD_REQUEST, Json(error)).into_response();
294            }
295
296            // S8: Public clients (no client secret) MUST provide a PKCE code_challenge.
297            let is_public_client = !super::client_secret::is_confidential(&client_data);
298            if is_public_client && params.code_challenge.is_none() {
299                let error = OAuthError::new("invalid_request")
300                    .description("Public clients must use PKCE: code_challenge is required")
301                    .maybe_state(params.state);
302                return (StatusCode::BAD_REQUEST, Json(error)).into_response();
303            }
304
305            // A client can be granted only the scopes it is registered for.
306            match effective_scope(&client_data, params.scope.as_deref()) {
307                Ok(scope) => scope,
308                Err(description) => {
309                    let error = OAuthError::new("invalid_scope")
310                        .description(description)
311                        .maybe_state(params.state);
312                    return (StatusCode::BAD_REQUEST, Json(error)).into_response();
313                }
314            }
315        }
316        Ok(None) => {
317            tracing::warn!(client_id = %params.client_id, "OAuth authorize: unknown client_id");
318            let error = OAuthError::new("invalid_client")
319                .description("Unknown client_id")
320                .maybe_state(params.state);
321            return (StatusCode::BAD_REQUEST, Json(error)).into_response();
322        }
323        Err(e) => {
324            tracing::error!(
325                client_id = %params.client_id,
326                error = %e,
327                "OAuth authorize: storage error looking up client"
328            );
329            let error = OAuthError::new("server_error")
330                .description("Authorization server error")
331                .maybe_state(params.state);
332            return (StatusCode::INTERNAL_SERVER_ERROR, Json(error)).into_response();
333        }
334    };
335
336    let auth_code = format!("ac_{}", uuid::Uuid::new_v4().to_string().replace("-", ""));
337
338    // RFC 8707: Validate resource indicators if present.
339    if let Some(ref resources) = params.resource
340        && let Err(e) =
341            crate::server::oauth::resource_indicators::validate_resource_indicators(resources)
342    {
343        let error = OAuthError::new("invalid_target")
344            .description(e.to_string())
345            .maybe_state(params.state);
346        return (StatusCode::BAD_REQUEST, Json(error)).into_response();
347    }
348
349    let code_data = serde_json::json!({
350        "client_id": params.client_id,
351        "redirect_uri": params.redirect_uri,
352        "scope": granted_scope,
353        "state": params.state.clone(),
354        "code_challenge": params.code_challenge,
355        "code_challenge_method": params.code_challenge_method,
356        "user_id": user_id,
357        "resource": params.resource,
358        "created_at": chrono::Utc::now().to_rfc3339(),
359        "expires_at": (chrono::Utc::now() + chrono::Duration::minutes(10)).to_rfc3339(),
360        "used": false,
361    });
362
363    let storage_key = format!("oauth2_code:{}", auth_code);
364    let code_data_str = match serde_json::to_string(&code_data) {
365        Ok(s) => s,
366        Err(e) => {
367            tracing::error!("Failed to serialize OAuth authorization code data: {:?}", e);
368            let error =
369                OAuthError::new("server_error").description("Authorization server internal error");
370            return (StatusCode::INTERNAL_SERVER_ERROR, Json(error)).into_response();
371        }
372    };
373
374    if let Err(e) = state
375        .auth_framework
376        .storage()
377        .store_kv(
378            &storage_key,
379            code_data_str.as_bytes(),
380            Some(std::time::Duration::from_secs(600)),
381        )
382        .await
383    {
384        tracing::error!("Failed to store OAuth authorization code: {:?}", e);
385        let error = OAuthError::new("server_error")
386            .description("Authorization server error")
387            .maybe_state(params.state);
388        return (StatusCode::INTERNAL_SERVER_ERROR, Json(error)).into_response();
389    }
390
391    // SECURITY: URL-encode the state value to prevent parameter injection.
392    // A raw state like "&extra=injected" would append unintended query parameters.
393    let encoded_state: Option<String> = params.state.as_deref().map(|st| {
394        st.bytes()
395            .flat_map(|b| {
396                if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~') {
397                    vec![b as char]
398                } else {
399                    format!("%{:02X}", b).chars().collect()
400                }
401            })
402            .collect()
403    });
404
405    let mut redirect_url = params.redirect_uri;
406    redirect_url.push_str(&format!("?code={}", auth_code));
407    if let Some(ref st) = encoded_state {
408        redirect_url.push_str(&format!("&state={}", st));
409    }
410
411    tracing::info!(
412        client_id = %params.client_id,
413        user_id = %user_id,
414        "OAuth authorization code issued"
415    );
416    Redirect::to(&redirect_url).into_response()
417}
418
419/// POST /oauth/token — exchange an authorization code or refresh token for
420/// an access token (RFC 6749 §4.1.3, §6).
421///
422/// Supported grant types:
423/// - `authorization_code` — requires `code`, `client_id`, and optionally `code_verifier`
424/// - `refresh_token` — requires `refresh_token`
425///
426/// # Example
427/// ```rust,ignore
428/// // POST /oauth/token {"grant_type":"authorization_code","code":"ac_...","client_id":"..."}
429/// let response = token(State(api_state), Json(token_request)).await;
430/// assert!(response.success);
431/// ```
432pub async fn token(
433    State(state): State<ApiState>,
434    Json(req): Json<TokenRequest>,
435) -> ApiResponse<TokenResponse> {
436    match req.grant_type.as_str() {
437        "authorization_code" => handle_authorization_code_grant(state, req).await,
438        "refresh_token" => handle_refresh_token_grant(state, req).await,
439        _ => ApiResponse::error_typed(
440            "unsupported_grant_type",
441            "Supported grant types: authorization_code, refresh_token",
442        ),
443    }
444}
445
446async fn handle_authorization_code_grant(
447    state: ApiState,
448    req: TokenRequest,
449) -> ApiResponse<TokenResponse> {
450    let code = match req.code {
451        Some(c) => c,
452        None => {
453            return ApiResponse::validation_error_typed(
454                "code is required for authorization_code grant",
455            );
456        }
457    };
458
459    let client_id = match req.client_id {
460        Some(c) => c,
461        None => return ApiResponse::validation_error_typed("client_id is required"),
462    };
463
464    // Authenticate the client BEFORE the code is looked at, so a failed
465    // authentication neither reveals anything about the code nor consumes it.
466    let client_kind =
467        match authenticate_token_client(&state, &client_id, req.client_secret.as_deref()).await {
468            Ok(kind) => kind,
469            Err(refusal) => return *refusal,
470        };
471
472    let consumed_key = format!("oauth2_code_consumed:{}", code);
473    let storage_key = format!("oauth2_code:{}", code);
474    let code_data = match state.auth_framework.storage().get_kv(&storage_key).await {
475        Ok(Some(data)) => match serde_json::from_slice::<serde_json::Value>(&data) {
476            Ok(json) => json,
477            Err(e) => {
478                tracing::error!("Failed to parse stored authorization code data: {:?}", e);
479                return ApiResponse::error_typed("invalid_grant", "Invalid authorization code");
480            }
481        },
482        Ok(None) => {
483            return ApiResponse::error_typed(
484                "invalid_grant",
485                "Authorization code not found or expired",
486            );
487        }
488        Err(e) => {
489            tracing::error!("Failed to retrieve authorization code: {:?}", e);
490            return ApiResponse::error_typed(
491                "server_error",
492                "Failed to validate authorization code",
493            );
494        }
495    };
496
497    // Claim the code: of any number of simultaneous redemptions exactly one proceeds (atomic
498    // set-if-absent). The marker is only written for a code that exists, so presenting
499    // made-up codes stores nothing.
500    match state
501        .auth_framework
502        .storage()
503        .store_kv_if_absent(
504            &consumed_key,
505            b"1",
506            Some(std::time::Duration::from_secs(600)),
507        )
508        .await
509    {
510        Ok(true) => {}
511        Ok(false) => {
512            return ApiResponse::error_typed("invalid_grant", "Authorization code already used");
513        }
514        Err(e) => {
515            tracing::error!("Failed to claim authorization code: {:?}", e);
516            return ApiResponse::error_typed(
517                "server_error",
518                "Failed to process authorization code",
519            );
520        }
521    }
522
523    // A code issued to a different client is refused and left intact (with its
524    // consumed marker released), so presenting someone else's code cannot burn it.
525    if code_data["client_id"].as_str() != Some(&client_id) {
526        if let Err(e) = state
527            .auth_framework
528            .storage()
529            .delete_kv(&consumed_key)
530            .await
531        {
532            tracing::warn!("Failed to release code consumed marker: {:?}", e);
533        }
534        return ApiResponse::error_typed("invalid_grant", "client_id mismatch");
535    }
536
537    // Immediately delete the code to prevent reuse (single-use enforcement).
538    if let Err(e) = state.auth_framework.storage().delete_kv(&storage_key).await {
539        tracing::error!("Failed to delete authorization code from storage: {:?}", e);
540        return ApiResponse::error_typed("server_error", "Failed to process authorization code");
541    }
542
543    // Validate redirect_uri if provided
544    if let Some(redirect_uri) = &req.redirect_uri {
545        let stored_uri = code_data["redirect_uri"].as_str().unwrap_or_default();
546        if !redirect_uri_matches(redirect_uri, stored_uri) {
547            return ApiResponse::error_typed("invalid_grant", "redirect_uri mismatch");
548        }
549    }
550
551    // Check if PKCE was used in authorization - if so, code_verifier is required
552    let stored_challenge = code_data["code_challenge"].as_str();
553    let challenge_method = code_data["code_challenge_method"]
554        .as_str()
555        .unwrap_or("plain");
556
557    if let Some(stored) = stored_challenge {
558        // PKCE was used in authorization, so code_verifier is required
559        let code_verifier = match &req.code_verifier {
560            Some(verifier) => verifier,
561            None => {
562                return ApiResponse::error_typed(
563                    "invalid_request",
564                    "code_verifier is required when PKCE challenge was provided",
565                );
566            }
567        };
568
569        let computed_challenge = match challenge_method {
570            "S256" => {
571                let mut hasher = Sha256::new();
572                hasher.update(code_verifier.as_bytes());
573                URL_SAFE_NO_PAD.encode(hasher.finalize())
574            }
575            "plain" => code_verifier.clone(),
576            _ => {
577                return ApiResponse::error_typed(
578                    "invalid_request",
579                    "Unsupported code_challenge_method",
580                );
581            }
582        };
583
584        if computed_challenge != stored {
585            return ApiResponse::error_typed("invalid_grant", "PKCE verification failed");
586        }
587    } else if req.code_verifier.is_some() {
588        // code_verifier provided but no challenge was used - this is suspicious
589        return ApiResponse::error_typed(
590            "invalid_request",
591            "code_verifier provided but no PKCE challenge was used in authorization",
592        );
593    } else if client_kind == ClientKind::Public {
594        // S8: Public clients (registered without a secret) MUST use PKCE.
595        // Whether a client is public comes from its registration, not from whether
596        // the request happens to carry a secret.
597        return ApiResponse::error_typed(
598            "invalid_request",
599            "Public clients must use PKCE: provide code_challenge in authorization and code_verifier in token request",
600        );
601    }
602
603    // Code was already atomically deleted above (delete-first approach).
604    // No need to mark as used — the code is permanently consumed.
605
606    // RFC 8707: Validate resource indicators on the token request.
607    let authz_resources: Vec<String> = code_data["resource"]
608        .as_array()
609        .map(|arr| {
610            arr.iter()
611                .filter_map(|v| v.as_str().map(String::from))
612                .collect()
613        })
614        .unwrap_or_default();
615
616    if let Some(ref token_resources) = req.resource {
617        if let Err(e) =
618            crate::server::oauth::resource_indicators::validate_resource_indicators(token_resources)
619        {
620            return ApiResponse::error_typed("invalid_target", e.to_string());
621        }
622        if let Err(e) = crate::server::oauth::resource_indicators::validate_token_resource_subset(
623            token_resources,
624            &authz_resources,
625        ) {
626            return ApiResponse::error_typed("invalid_target", e.to_string());
627        }
628    }
629
630    // Create access and refresh tokens
631    //
632    // The granted scope never exceeds what the client is registered for, whatever the
633    // code carries (e.g. a code issued before scopes were enforced).
634    let client_record = match load_client_record(&state, &client_id).await {
635        Ok(Some(record)) => record,
636        Ok(None) => return ApiResponse::error_typed("invalid_client", "Unknown client"),
637        Err(refused) => return *refused,
638    };
639    let allowed = allowed_scopes(&client_record);
640    let scopes: Vec<String> = code_data["scope"]
641        .as_str()
642        .unwrap_or("openid profile email")
643        .split_whitespace()
644        .filter(|s| allowed.iter().any(|a| a == s))
645        .map(|s| s.to_string())
646        .collect();
647    if scopes.is_empty() {
648        return ApiResponse::error_typed(
649            "invalid_scope",
650            "No granted scope is allowed for this client",
651        );
652    }
653    let scope = scopes.join(" ");
654
655    // Use the user_id that was recorded in the authorization code when the resource owner
656    // authenticated via the /oauth/authorize endpoint.  This ensures tokens are bound to the
657    // actual user rather than a fabricated identifier derived from the client_id.
658    let user_id = match code_data["user_id"].as_str() {
659        Some(uid) if !uid.is_empty() => uid.to_string(),
660        _ => {
661            tracing::error!("Authorization code missing user_id field");
662            return ApiResponse::error_typed("server_error", "Malformed authorization code");
663        }
664    };
665
666    // The token is delegated access for this client, not the user's own session.
667    let token = match state
668        .auth_framework
669        .token_manager()
670        .create_client_auth_token(&user_id, &client_id, scopes.clone(), "oauth2", None)
671    {
672        Ok(token) => token,
673        Err(e) => {
674            tracing::error!("Failed to create access token: {:?}", e);
675            return ApiResponse::error_typed("server_error", "Failed to create access token");
676        }
677    };
678
679    // Persist a storage-backed refresh token so the refresh grant can validate and rotate it.
680    let refresh_token_value = uuid::Uuid::new_v4().to_string().replace("-", "");
681    let refresh_data = serde_json::json!({
682        "user_id": user_id,
683        "client_id": client_id,
684        "scopes": scope,
685    });
686    let refresh_key = format!("oauth2_refresh_token:{}", refresh_token_value);
687    if let Err(e) = state
688        .auth_framework
689        .storage()
690        .store_kv(
691            &refresh_key,
692            serde_json::to_string(&refresh_data)
693                .unwrap_or_default()
694                .as_bytes(),
695            Some(REFRESH_TOKEN_TTL),
696        )
697        .await
698    {
699        tracing::warn!("Failed to store refresh token: {:?}", e);
700    }
701
702    let expires_in = (token.expires_at - token.issued_at).num_seconds().max(0) as u64;
703    let response = TokenResponse {
704        access_token: token.access_token,
705        token_type: "Bearer".to_string(),
706        expires_in,
707        refresh_token: Some(refresh_token_value),
708        scope: Some(scope.to_string()),
709        id_token: None,
710    };
711
712    tracing::info!("OAuth2 tokens issued for client: {}", client_id);
713    ApiResponse::success(response)
714}
715
716/// A boxed error response (keeps the `Err` variant of the client-check helpers small).
717fn refusal(code: &str, message: &str) -> Box<ApiResponse<TokenResponse>> {
718    Box::new(ApiResponse::error_typed(code, message))
719}
720
721/// Load a registered client's record from `oauth2_client:{client_id}`.
722async fn load_client_record(
723    state: &ApiState,
724    client_id: &str,
725) -> std::result::Result<Option<serde_json::Value>, Box<ApiResponse<TokenResponse>>> {
726    let key = format!("oauth2_client:{client_id}");
727    match state.auth_framework.storage().get_kv(&key).await {
728        Ok(Some(data)) => serde_json::from_slice(&data).map(Some).map_err(|e| {
729            tracing::error!("Unreadable client record for {client_id}: {e}");
730            refusal("server_error", "Failed to validate client")
731        }),
732        Ok(None) => Ok(None),
733        Err(e) => {
734            tracing::error!("Failed to load client {client_id}: {e:?}");
735            Err(refusal("server_error", "Failed to validate client"))
736        }
737    }
738}
739
740/// How a client identified itself at the token endpoint.
741#[derive(Clone, Copy, PartialEq, Eq)]
742enum ClientKind {
743    /// Registered without a secret: identified by `client_id` alone (PKCE is mandatory).
744    Public,
745    /// Registered with a secret and authenticated with it.
746    Confidential,
747}
748
749/// Authenticate the client of an authorization-code exchange (RFC 6749 section 3.2.1).
750///
751/// The client must be registered (`oauth2_client:{id}`). A client whose record holds a
752/// secret (hashed, or a legacy plain one) is confidential and MUST present exactly that secret;
753/// a missing or wrong secret is `invalid_client`. Whether a client is public is decided by its
754/// registration, never by what the request carries.
755async fn authenticate_token_client(
756    state: &ApiState,
757    client_id: &str,
758    presented_secret: Option<&str>,
759) -> std::result::Result<ClientKind, Box<ApiResponse<TokenResponse>>> {
760    let Some(record) = load_client_record(state, client_id).await? else {
761        return Err(refusal("invalid_client", "Unknown client"));
762    };
763    match super::client_secret::is_confidential(&record) {
764        false => Ok(ClientKind::Public),
765        true => {
766            let authenticated = match presented_secret {
767                Some(presented) => {
768                    super::client_secret::authenticate(
769                        state.auth_framework.storage().as_ref(),
770                        client_id,
771                        &record,
772                        presented,
773                    )
774                    .await
775                }
776                None => false,
777            };
778            if authenticated {
779                Ok(ClientKind::Confidential)
780            } else {
781                Err(refusal("invalid_client", "Client authentication failed"))
782            }
783        }
784    }
785}
786
787/// Scopes granted to clients that were registered without any scope information.
788const DEFAULT_CLIENT_SCOPES: [&str; 3] = ["openid", "profile", "email"];
789
790/// The scopes a client may be granted: those it was registered for (the `scope` string
791/// and/or the `scopes` list). A record that names neither key predates scope registration
792/// and gets the OpenID defaults; a record that names a key but yields no scope (empty, or
793/// of an unexpected type) is granted nothing.
794fn allowed_scopes(record: &serde_json::Value) -> Vec<String> {
795    if record.get("scope").is_none_or(|v| v.is_null())
796        && record.get("scopes").is_none_or(|v| v.is_null())
797    {
798        return DEFAULT_CLIENT_SCOPES
799            .iter()
800            .map(|s| s.to_string())
801            .collect();
802    }
803    let mut allowed: Vec<String> = Vec::new();
804    if let Some(s) = record["scope"].as_str() {
805        allowed.extend(s.split_whitespace().map(String::from));
806    }
807    if let Some(list) = record["scopes"].as_array() {
808        for item in list.iter().filter_map(|v| v.as_str()) {
809            allowed.extend(item.split_whitespace().map(String::from));
810        }
811    }
812    allowed.sort();
813    allowed.dedup();
814    allowed
815}
816
817/// The scope to grant for a request: the requested scopes if every one is allowed
818/// (RFC 6749 section 3.3), otherwise `Err(invalid_scope description)`. With no scope
819/// requested, the client gets everything it is registered for.
820fn effective_scope(
821    record: &serde_json::Value,
822    requested: Option<&str>,
823) -> std::result::Result<String, String> {
824    let allowed = allowed_scopes(record);
825    let requested: Vec<&str> = requested
826        .map(|s| s.split_whitespace().collect())
827        .unwrap_or_default();
828    if requested.is_empty() {
829        return if allowed.is_empty() {
830            Err("this client is not registered for any scope".to_string())
831        } else {
832            Ok(allowed.join(" "))
833        };
834    }
835    if let Some(bad) = requested.iter().find(|s| !allowed.iter().any(|a| a == **s)) {
836        let shown: String = bad.chars().take(64).collect();
837        return Err(format!("scope '{shown}' is not allowed for this client"));
838    }
839    let mut granted: Vec<&str> = Vec::with_capacity(requested.len());
840    for s in requested {
841        if !granted.contains(&s) {
842            granted.push(s);
843        }
844    }
845    Ok(granted.join(" "))
846}
847
848/// Lifetime of a stored refresh token, and of the marker that records it was redeemed.
849const REFRESH_TOKEN_TTL: std::time::Duration = std::time::Duration::from_secs(30 * 24 * 3600);
850
851/// RFC 6749 §6 / §10.4: a refresh token issued to `stored_client` is
852/// redeemable only by that client.
853///
854/// * A **confidential** client (its record holds a secret) must authenticate,
855///   and the client that authenticated must be `stored_client`:
856///   missing/invalid credentials are `invalid_client`, a different (validly
857///   authenticated) client is `invalid_grant`.
858/// * A **public** client must present a `client_id` equal to `stored_client`:
859///   missing or different is `invalid_grant`.
860///
861/// There is no "check it only if it is present" path, and a token whose
862/// client is no longer registered fails closed.
863async fn authorize_refresh_client(
864    state: &ApiState,
865    stored_client: &str,
866    presented_id: Option<&str>,
867    presented_secret: Option<&str>,
868) -> std::result::Result<(), Box<ApiResponse<TokenResponse>>> {
869    let not_issued_to_you = || {
870        refusal(
871            "invalid_grant",
872            "Refresh token was not issued to this client",
873        )
874    };
875
876    let Some(stored_record) = load_client_record(state, stored_client).await? else {
877        return Err(refusal(
878            "invalid_grant",
879            "Refresh token was issued to a client that is no longer registered",
880        ));
881    };
882
883    if !super::client_secret::is_confidential(&stored_record) {
884        // Public client: it identifies itself, nothing more.
885        return match presented_id {
886            Some(id) if id == stored_client => Ok(()),
887            _ => Err(not_issued_to_you()),
888        };
889    }
890
891    // Confidential client: authenticate whoever is asking against THEIR record.
892    let (Some(presented_id), Some(presented_secret)) = (presented_id, presented_secret) else {
893        return Err(refusal(
894            "invalid_client",
895            "Client authentication is required",
896        ));
897    };
898    let presented_record = if presented_id == stored_client {
899        Some(stored_record)
900    } else {
901        load_client_record(state, presented_id).await?
902    };
903    let authenticated = match presented_record.as_ref() {
904        Some(record) => {
905            super::client_secret::authenticate(
906                state.auth_framework.storage().as_ref(),
907                presented_id,
908                record,
909                presented_secret,
910            )
911            .await
912        }
913        None => false,
914    };
915    if !authenticated {
916        return Err(refusal("invalid_client", "Client authentication failed"));
917    }
918    if presented_id != stored_client {
919        return Err(not_issued_to_you());
920    }
921    Ok(())
922}
923
924async fn handle_refresh_token_grant(
925    state: ApiState,
926    req: TokenRequest,
927) -> ApiResponse<TokenResponse> {
928    let refresh_token_str = match req.refresh_token {
929        Some(t) => t,
930        None => return ApiResponse::validation_error_typed("refresh_token is required"),
931    };
932
933    // A revoked refresh token must not mint new access tokens, regardless of
934    // whether its own storage entry has been deleted yet (see `revoke`). Fail
935    // closed on a storage error here -- matching the equivalent check in
936    // `api/auth.rs`'s refresh handler -- rather than treating "couldn't check"
937    // as "not revoked".
938    let revoked_key = format!("oauth2_revoked_token:{}", refresh_token_str);
939    match state.auth_framework.storage().get_kv(&revoked_key).await {
940        Ok(Some(_)) => {
941            return ApiResponse::error_typed("invalid_grant", "Refresh token has been revoked");
942        }
943        Ok(None) => {} // Not revoked -- proceed
944        Err(e) => {
945            tracing::error!("Refresh token revocation check failed: {:?}", e);
946            return ApiResponse::error_typed("server_error", "Failed to validate refresh token");
947        }
948    }
949
950    let consumed_key = format!("oauth2_refresh_consumed:{}", refresh_token_str);
951
952    // Validate the refresh token against persistent storage.
953    let refresh_key = format!("oauth2_refresh_token:{}", refresh_token_str);
954    let stored = match state.auth_framework.storage().get_kv(&refresh_key).await {
955        Ok(Some(data)) => match serde_json::from_slice::<serde_json::Value>(&data) {
956            Ok(v) => v,
957            Err(_) => return ApiResponse::error_typed("invalid_grant", "Invalid refresh token"),
958        },
959        Ok(None) => {
960            return ApiResponse::error_typed("invalid_grant", "Refresh token not found or expired");
961        }
962        Err(e) => {
963            tracing::error!("Failed to retrieve refresh token: {:?}", e);
964            return ApiResponse::error_typed("server_error", "Failed to validate refresh token");
965        }
966    };
967
968    // Claim the token: of any number of simultaneous redemptions exactly one proceeds (atomic
969    // set-if-absent). The marker is only written for a token that exists. It must outlive the
970    // token: if the old record's delete fails during rotation (below), this marker is the only
971    // thing that stops the rotated-out token being redeemed again.
972    match state
973        .auth_framework
974        .storage()
975        .store_kv_if_absent(&consumed_key, b"1", Some(REFRESH_TOKEN_TTL))
976        .await
977    {
978        Ok(true) => {}
979        Ok(false) => {
980            return ApiResponse::error_typed("invalid_grant", "Refresh token already consumed");
981        }
982        Err(e) => {
983            tracing::error!("Failed to claim refresh token: {:?}", e);
984            return ApiResponse::error_typed("server_error", "Failed to validate refresh token");
985        }
986    }
987
988    let user_id = match stored["user_id"].as_str() {
989        Some(u) => u.to_string(),
990        None => {
991            let _ = state
992                .auth_framework
993                .storage()
994                .delete_kv(&consumed_key)
995                .await;
996            return ApiResponse::error_typed("invalid_grant", "Malformed refresh token data");
997        }
998    };
999    let client_id = match &stored["client_id"] {
1000        serde_json::Value::Null => None,
1001        serde_json::Value::String(s) => Some(s.clone()),
1002        // A client_id of some other type cannot be checked: fail closed
1003        // instead of silently skipping the binding.
1004        _ => {
1005            let _ = state
1006                .auth_framework
1007                .storage()
1008                .delete_kv(&consumed_key)
1009                .await;
1010            return ApiResponse::error_typed("invalid_grant", "Malformed refresh token data");
1011        }
1012    };
1013
1014    // A token issued to a client is redeemable only by that client. A refused
1015    // attempt releases the consumed marker set above, so merely seeing a
1016    // refresh token (and presenting it wrongly) cannot burn it.
1017    if let Some(stored_client) = client_id.as_deref()
1018        && let Err(refusal) = authorize_refresh_client(
1019            &state,
1020            stored_client,
1021            req.client_id.as_deref(),
1022            req.client_secret.as_deref(),
1023        )
1024        .await
1025    {
1026        if let Err(e) = state
1027            .auth_framework
1028            .storage()
1029            .delete_kv(&consumed_key)
1030            .await
1031        {
1032            tracing::warn!("Failed to release refresh consumed marker: {:?}", e);
1033        }
1034        return *refusal;
1035    }
1036
1037    let mut scopes: Vec<String> = stored["scopes"]
1038        .as_str()
1039        .unwrap_or("openid profile email")
1040        .split_whitespace()
1041        .map(|s| s.to_string())
1042        .collect();
1043    // A refreshed token never exceeds what the client is registered for NOW, whatever the
1044    // stored record carries (older records, or a registration narrowed since).
1045    if let Some(client) = stored["client_id"].as_str() {
1046        let record = match load_client_record(&state, client).await {
1047            Ok(Some(record)) => record,
1048            Ok(None) => return ApiResponse::error_typed("invalid_client", "Unknown client"),
1049            Err(refused) => return *refused,
1050        };
1051        let allowed = allowed_scopes(&record);
1052        scopes.retain(|s| allowed.iter().any(|a| a == s));
1053        if scopes.is_empty() {
1054            return ApiResponse::error_typed(
1055                "invalid_scope",
1056                "No granted scope is allowed for this client",
1057            );
1058        }
1059    }
1060    let scope = scopes.join(" ");
1061
1062    let issued = match &client_id {
1063        Some(client) => state
1064            .auth_framework
1065            .token_manager()
1066            .create_client_auth_token(&user_id, client, scopes, "oauth2", None),
1067        None => state
1068            .auth_framework
1069            .token_manager()
1070            .create_auth_token(&user_id, scopes, "oauth2", None),
1071    };
1072    let token = match issued {
1073        Ok(t) => t,
1074        Err(e) => {
1075            tracing::error!("Failed to create access token on refresh: {:?}", e);
1076            // Nothing was issued and the old record is untouched: release the claim so the
1077            // client can retry instead of losing the session for the marker's 30 days.
1078            let _ = state
1079                .auth_framework
1080                .storage()
1081                .delete_kv(&consumed_key)
1082                .await;
1083            return ApiResponse::error_typed("server_error", "Failed to issue access token");
1084        }
1085    };
1086
1087    // Issue a new refresh token (rotation).
1088    // Store the new token BEFORE deleting the old one to avoid data loss on failure.
1089    let new_refresh_token = uuid::Uuid::new_v4().to_string().replace("-", "");
1090    let new_refresh_data = serde_json::json!({
1091        "user_id": user_id,
1092        "client_id": client_id,
1093        "scopes": scope,
1094    });
1095    let new_refresh_key = format!("oauth2_refresh_token:{}", new_refresh_token);
1096    if let Err(e) = state
1097        .auth_framework
1098        .storage()
1099        .store_kv(
1100            &new_refresh_key,
1101            serde_json::to_string(&new_refresh_data)
1102                .unwrap_or_default()
1103                .as_bytes(),
1104            Some(REFRESH_TOKEN_TTL),
1105        )
1106        .await
1107    {
1108        tracing::error!("Failed to store new refresh token: {:?}", e);
1109        let _ = state
1110            .auth_framework
1111            .storage()
1112            .delete_kv(&consumed_key)
1113            .await;
1114        return ApiResponse::error_typed("server_error", "Failed to issue refresh token");
1115    }
1116
1117    // Now that the new token is safely stored, delete the old one (single-use enforcement).
1118    if let Err(e) = state.auth_framework.storage().delete_kv(&refresh_key).await {
1119        tracing::warn!(
1120            "Failed to delete old refresh token during rotation: {:?}",
1121            e
1122        );
1123    }
1124
1125    let expires_in = (token.expires_at - token.issued_at).num_seconds().max(0) as u64;
1126    let response = TokenResponse {
1127        access_token: token.access_token,
1128        token_type: "Bearer".to_string(),
1129        expires_in,
1130        refresh_token: Some(new_refresh_token),
1131        scope: Some(scope),
1132        id_token: None,
1133    };
1134
1135    tracing::info!("OAuth2 token refreshed for user: {}", user_id);
1136    ApiResponse::success(response)
1137}
1138
1139/// Whether the caller of `/oauth/revoke` is the client `owner`, who the token was issued to:
1140/// it names itself with HTTP Basic or the `client_id` / `client_secret` body fields, and a
1141/// client that has a secret must present it.
1142async fn revocation_caller_is(
1143    state: &ApiState,
1144    headers: &HeaderMap,
1145    req: &RevokeRequest,
1146    owner: &str,
1147) -> bool {
1148    use base64::engine::general_purpose::STANDARD;
1149    let basic = headers
1150        .get(axum::http::header::AUTHORIZATION)
1151        .and_then(|value| value.to_str().ok())
1152        .and_then(|value| value.strip_prefix("Basic "))
1153        .and_then(|encoded| STANDARD.decode(encoded).ok())
1154        .and_then(|decoded| String::from_utf8(decoded).ok())
1155        .map(|decoded| match decoded.split_once(':') {
1156            Some((id, secret)) => (id.to_string(), Some(secret.to_string())),
1157            None => (decoded, None),
1158        });
1159    let (presented_id, presented_secret) = match basic {
1160        Some(pair) => pair,
1161        None => match &req.client_id {
1162            Some(id) => (id.clone(), req.client_secret.clone()),
1163            None => return false,
1164        },
1165    };
1166    if presented_id != owner {
1167        return false;
1168    }
1169    let key = format!("oauth2_client:{owner}");
1170    let record: serde_json::Value = match state.auth_framework.storage().get_kv(&key).await {
1171        Ok(Some(data)) => match serde_json::from_slice(&data) {
1172            Ok(record) => record,
1173            Err(_) => return false,
1174        },
1175        _ => return false,
1176    };
1177    if !super::client_secret::is_confidential(&record) {
1178        return true;
1179    }
1180    match presented_secret {
1181        Some(secret) => {
1182            super::client_secret::authenticate(
1183                state.auth_framework.storage().as_ref(),
1184                owner,
1185                &record,
1186                &secret,
1187            )
1188            .await
1189        }
1190        None => false,
1191    }
1192}
1193
1194/// POST /api/v1/oauth/revoke — revoke an access or refresh token.
1195///
1196/// Stores a revocation marker in KV (`oauth2_revoked_token:{token}`,
1197/// TTL'd to the refresh token's own 30-day lifetime -- not just the 7
1198/// days access-token revocation needs -- since this one marker has to
1199/// outlive whichever token type was actually revoked) and, for JWT
1200/// tokens, also stores a JTI-based marker (`revoked_token:{jti}`) so
1201/// that all authenticated endpoints reject the token immediately. If
1202/// the token is a refresh token, also deletes its `oauth2_refresh_token:`
1203/// storage entry outright -- `handle_refresh_token_grant` also checks
1204/// the revocation marker directly (failing closed on a storage error
1205/// there), so revocation is effective for the marker's full TTL even if
1206/// the delete itself fails.
1207///
1208/// Only a token this server issued is acted on; anything else is a no-op that answers like
1209/// success (RFC 7009 section 2.2) and stores nothing. A refresh token issued to an OAuth client
1210/// is revoked only by that client (RFC 7009 section 2.1): a confidential client authenticates
1211/// with HTTP Basic or `client_id` / `client_secret` in the body, a public one names itself with
1212/// `client_id`; otherwise `invalid_client`. A JWT, which carries no client on this line, is
1213/// revoked by whoever holds it.
1214///
1215/// # Example
1216/// ```rust,ignore
1217/// let resp = revoke(State(state), HeaderMap::new(), Json(RevokeRequest {
1218///     token: "access_token_value".into(),
1219///     token_type_hint: Some("access_token".into()),
1220///     client_id: None,
1221///     client_secret: None,
1222/// })).await;
1223/// assert!(resp.success);
1224/// ```
1225pub async fn revoke(
1226    State(state): State<ApiState>,
1227    headers: HeaderMap,
1228    Json(req): Json<RevokeRequest>,
1229) -> ApiResponse<serde_json::Value> {
1230    // The token becomes part of a storage key: bound its size.
1231    if req.token.is_empty() || req.token.len() > 8192 {
1232        return ApiResponse::error_typed("invalid_request", "Invalid token");
1233    }
1234
1235    // Only a token this server issued is revoked. Anything else (a guess, junk, an expired
1236    // or foreign JWT) is a no-op that answers like success (RFC 7009 section 2.2): the request
1237    // must not make the server store a marker for an arbitrary string.
1238    let issued_jwt = state
1239        .auth_framework
1240        .token_manager()
1241        .validate_jwt_token(&req.token)
1242        .ok();
1243    let refresh_record: Option<serde_json::Value> = match state
1244        .auth_framework
1245        .storage()
1246        .get_kv(&format!("oauth2_refresh_token:{}", req.token))
1247        .await
1248    {
1249        Ok(Some(data)) => serde_json::from_slice(&data).ok(),
1250        Ok(None) => None,
1251        Err(e) => {
1252            tracing::error!("Failed to look up the token to revoke: {:?}", e);
1253            return ApiResponse::error_typed("server_error", "Failed to revoke token");
1254        }
1255    };
1256    if issued_jwt.is_none() && refresh_record.is_none() {
1257        return ApiResponse::success(serde_json::json!({
1258            "message": "Token revoked successfully"
1259        }));
1260    }
1261
1262    // A token issued to an OAuth client is revoked only by that client (RFC 7009 section 2.1):
1263    // a confidential client authenticates, a public one identifies itself.
1264    // On this line only refresh tokens are issued to a client, but a JWT that carries a client
1265    // is bound to it too, so the check does not depend on that staying true.
1266    let owner_client = issued_jwt
1267        .as_ref()
1268        .and_then(|claims| claims.client_id.clone())
1269        .or_else(|| {
1270            refresh_record
1271                .as_ref()
1272                .and_then(|record| record["client_id"].as_str().map(String::from))
1273        });
1274    if let Some(owner) = owner_client
1275        && !revocation_caller_is(&state, &headers, &req, &owner).await
1276    {
1277        return ApiResponse::error_typed("invalid_client", "Client authentication failed");
1278    }
1279    // Store the revoked token in a blacklist for immediate invalidation.
1280    // Key by the raw token value so the userinfo endpoint can check it too.
1281    let revoked_token_key = format!("oauth2_revoked_token:{}", req.token);
1282    let revoked_data = serde_json::json!({
1283        "token": req.token,
1284        "revoked_at": chrono::Utc::now().to_rfc3339(),
1285        "token_type_hint": req.token_type_hint
1286    });
1287
1288    if let Err(e) = state
1289        .auth_framework
1290        .storage()
1291        .store_kv(
1292            &revoked_token_key,
1293            serde_json::to_string(&revoked_data)
1294                .unwrap_or_default()
1295                .as_bytes(),
1296            // 30 days: must outlive the longest-lived token type this
1297            // endpoint can revoke (the refresh token's own 30-day TTL),
1298            // not just the 7 days an access token's JWT markers need --
1299            // otherwise a revoked refresh token whose delete somehow
1300            // failed would become usable again once this marker expired.
1301            Some(std::time::Duration::from_secs(86400 * 30)),
1302        )
1303        .await
1304    {
1305        tracing::error!("Failed to store revoked token: {:?}", e);
1306        return ApiResponse::error_typed("server_error", "Failed to revoke token");
1307    }
1308
1309    // If this is a refresh token, delete its storage entry outright so it
1310    // can no longer be used to mint new access tokens. A no-op (and not an
1311    // error) if `req.token` isn't a refresh token at all -- the key simply
1312    // won't exist.
1313    let refresh_key = format!("oauth2_refresh_token:{}", req.token);
1314    if let Err(e) = state.auth_framework.storage().delete_kv(&refresh_key).await {
1315        tracing::warn!("Failed to delete refresh token on revoke: {:?}", e);
1316    }
1317
1318    // If the token is a JWT, also store revoked_token:{jti} so the authentication
1319    // middleware (validate_api_token in api/mod.rs) blocks it on all protected
1320    // endpoints. Without this step, the revocation would only be visible to the
1321    // userinfo endpoint, leaving all other authenticated routes unprotected.
1322    if let Ok(claims) = state
1323        .auth_framework
1324        .token_manager()
1325        .validate_jwt_token(&req.token)
1326    {
1327        let now = chrono::Utc::now().timestamp();
1328        let remaining_secs = (claims.exp - now + 60).max(60) as u64;
1329        let jti_key = format!("revoked_token:{}", claims.jti);
1330        if let Err(e) = state
1331            .auth_framework
1332            .storage()
1333            .store_kv(
1334                &jti_key,
1335                b"1",
1336                Some(std::time::Duration::from_secs(remaining_secs)),
1337            )
1338            .await
1339        {
1340            tracing::warn!("Failed to store JWT JTI revocation entry: {:?}", e);
1341        } else {
1342            tracing::info!("JWT token revoked via jti: {}", claims.jti);
1343        }
1344    }
1345
1346    tracing::info!(
1347        "OAuth2 token revoked: {}",
1348        &req.token[..10.min(req.token.len())]
1349    );
1350
1351    ApiResponse::success(serde_json::json!({
1352        "message": "Token revoked successfully"
1353    }))
1354}
1355
1356/// GET /api/v1/oauth/userinfo — return claims about the authenticated user.
1357///
1358/// The caller must supply a valid Bearer access token. If the token has been
1359/// revoked, an `invalid_token` error is returned. Email is included only
1360/// when the `email` scope is present in the token.
1361///
1362/// # Example
1363/// ```rust,ignore
1364/// // GET /api/v1/oauth/userinfo  Authorization: Bearer <token>
1365/// let resp = userinfo(State(state), headers).await;
1366/// assert_eq!(resp.data.unwrap().sub, "user-1");
1367/// ```
1368pub async fn userinfo(
1369    State(state): State<ApiState>,
1370    headers: HeaderMap,
1371) -> ApiResponse<UserInfoResponse> {
1372    // Extract and validate access token
1373    let token = match extract_bearer_token(&headers) {
1374        Some(t) => t,
1375        None => {
1376            return ApiResponse::error_typed("invalid_token", "Authorization header required");
1377        }
1378    };
1379
1380    // Check if token is revoked first
1381    let revoked_token_key = format!("oauth2_revoked_token:{}", token);
1382    if let Ok(Some(_)) = state
1383        .auth_framework
1384        .storage()
1385        .get_kv(&revoked_token_key)
1386        .await
1387    {
1388        return ApiResponse::error_typed("invalid_token", "Token has been revoked");
1389    }
1390
1391    // Validate the access token
1392    let claims = match state
1393        .auth_framework
1394        .token_manager()
1395        .validate_jwt_token(&token)
1396    {
1397        Ok(c) => c,
1398        Err(_) => {
1399            return ApiResponse::error_typed("invalid_token", "Access token is invalid");
1400        }
1401    };
1402
1403    // Get user profile
1404    let user_profile = match state.auth_framework.get_user_profile(&claims.sub).await {
1405        Ok(profile) => profile,
1406        Err(e) => {
1407            tracing::error!("Failed to get user profile: {:?}", e);
1408            return ApiResponse::error_typed("server_error", "Failed to retrieve user information");
1409        }
1410    };
1411
1412    let userinfo = UserInfoResponse {
1413        sub: claims.sub.clone(),
1414        name: user_profile.username.clone(),
1415        // Only include email if the token's scopes include "email"
1416        email: if claims.scope.split_whitespace().any(|s| s == "email") {
1417            user_profile.email.clone()
1418        } else {
1419            None
1420        },
1421        picture: user_profile.picture.clone(),
1422        updated_at: Some(chrono::Utc::now().timestamp()),
1423    };
1424
1425    tracing::info!("OAuth2 UserInfo requested for user: {}", claims.sub);
1426    ApiResponse::success(userinfo)
1427}
1428
1429/// GET /oauth/clients/{client_id} — return the stored metadata for a
1430/// registered OAuth 2.0 client.
1431///
1432/// # Example
1433/// ```rust,ignore
1434/// let resp = get_client_info(State(state), Path("my-client-id".into())).await;
1435/// ```
1436pub async fn get_client_info(
1437    State(state): State<ApiState>,
1438    Path(client_id): Path<String>,
1439) -> impl IntoResponse {
1440    let client_key = format!("oauth2_client:{}", client_id);
1441    match state.auth_framework.storage().get_kv(&client_key).await {
1442        Ok(Some(data)) => match serde_json::from_slice::<ClientInfo>(&data) {
1443            Ok(client) => (
1444                StatusCode::OK,
1445                Json(serde_json::json!({ "success": true, "data": client })),
1446            )
1447                .into_response(),
1448            Err(e) => {
1449                tracing::error!(client_id = %client_id, error = %e, "Failed to deserialize client record");
1450                (
1451                    StatusCode::INTERNAL_SERVER_ERROR,
1452                    Json(serde_json::json!({
1453                        "success": false,
1454                        "error": "server_error",
1455                        "message": "Failed to read client record"
1456                    })),
1457                )
1458                    .into_response()
1459            }
1460        },
1461        Ok(None) => (
1462            StatusCode::NOT_FOUND,
1463            Json(serde_json::json!({
1464                "success": false,
1465                "error": "invalid_client",
1466                "message": "Unknown client_id"
1467            })),
1468        )
1469            .into_response(),
1470        Err(e) => {
1471            tracing::error!(client_id = %client_id, error = %e, "Storage error looking up client");
1472            (
1473                StatusCode::INTERNAL_SERVER_ERROR,
1474                Json(serde_json::json!({
1475                    "success": false,
1476                    "error": "server_error",
1477                    "message": "Authorization server error"
1478                })),
1479            )
1480                .into_response()
1481        }
1482    }
1483}
1484
1485// ---------------------------------------------------------------------------
1486// OpenID Connect Discovery (RFC 8414 / OpenID Connect Discovery 1.0)
1487// ---------------------------------------------------------------------------
1488
1489/// OpenID Connect Discovery endpoint (RFC 8414 / OpenID Connect Discovery 1.0).
1490///
1491/// Returns server authorization metadata so clients can auto-configure
1492/// (issuer, endpoints, supported grants, signing algorithms, etc.).
1493///
1494/// # Example
1495/// ```rust,ignore
1496/// // GET /.well-known/openid-configuration
1497/// let (status, Json(config)) = openid_configuration(State(state)).await;
1498/// assert_eq!(status, StatusCode::OK);
1499/// ```
1500pub async fn openid_configuration(State(state): State<ApiState>) -> impl IntoResponse {
1501    let issuer = {
1502        let configured = state.auth_framework.config().issuer.clone();
1503        if configured.is_empty() {
1504            "https://auth.example.com".to_string()
1505        } else {
1506            configured
1507        }
1508    };
1509
1510    let config = serde_json::json!({
1511        "issuer": issuer,
1512        "authorization_endpoint": format!("{}/api/v1/oauth/authorize", issuer),
1513        "token_endpoint": format!("{}/api/v1/oauth/token", issuer),
1514        "userinfo_endpoint": format!("{}/api/v1/oauth/userinfo", issuer),
1515        "revocation_endpoint": format!("{}/api/v1/oauth/revoke", issuer),
1516        "introspection_endpoint": format!("{}/api/v1/oauth/introspect", issuer),
1517        "jwks_uri": format!("{}/api/v1/.well-known/jwks.json", issuer),
1518        "end_session_endpoint": format!("{}/api/v1/oauth/end_session", issuer),
1519        "pushed_authorization_request_endpoint": format!("{}/api/v1/oauth/par", issuer),
1520        "registration_endpoint": format!("{}/api/v1/oauth/register", issuer),
1521        "response_types_supported": ["code"],
1522        "grant_types_supported": [
1523            "authorization_code",
1524            "refresh_token"
1525        ],
1526        "subject_types_supported": ["public"],
1527        "id_token_signing_alg_values_supported": ["HS256"],
1528        "token_endpoint_auth_methods_supported": [
1529            "client_secret_basic",
1530            "client_secret_post"
1531        ],
1532        "code_challenge_methods_supported": ["S256"],
1533        "scopes_supported": ["openid", "profile", "email"]
1534    });
1535
1536    (StatusCode::OK, Json(config))
1537}
1538
1539// ---------------------------------------------------------------------------
1540// JWKS endpoint (RFC 7517)
1541// ---------------------------------------------------------------------------
1542
1543/// JSON Web Key Set (JWKS) endpoint ([RFC 7517](https://datatracker.ietf.org/doc/html/rfc7517)).
1544///
1545/// Returns the public keys used to verify tokens. Currently returns an
1546/// empty key set because HS256 (symmetric) signing is used; clients
1547/// should use the introspection endpoint for token validation.
1548///
1549/// # Example
1550/// ```rust,ignore
1551/// // GET /.well-known/jwks.json
1552/// let (status, Json(jwks)) = jwks(State(state)).await;
1553/// assert!(jwks["keys"].as_array().unwrap().is_empty());
1554/// ```
1555pub async fn jwks(State(_state): State<ApiState>) -> impl IntoResponse {
1556    (StatusCode::OK, Json(serde_json::json!({ "keys": [] })))
1557}
1558
1559// ---------------------------------------------------------------------------
1560// OIDC RP-Initiated Logout (OpenID Connect RP-Initiated Logout 1.0)
1561// ---------------------------------------------------------------------------
1562
1563/// Request parameters for OpenID Connect RP-Initiated Logout.
1564///
1565/// # Example
1566/// ```rust
1567/// use auth_framework::api::oauth2::EndSessionRequest;
1568///
1569/// let req: EndSessionRequest = serde_json::from_str(
1570///     r#"{"id_token_hint":"eyJ...","state":"xyz"}"#
1571/// ).unwrap();
1572/// assert!(req.post_logout_redirect_uri.is_none());
1573/// ```
1574#[derive(Deserialize)]
1575pub struct EndSessionRequest {
1576    pub id_token_hint: Option<String>,
1577    pub post_logout_redirect_uri: Option<String>,
1578    pub state: Option<String>,
1579}
1580
1581impl std::fmt::Debug for EndSessionRequest {
1582    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1583        let mut d = f.debug_struct("EndSessionRequest");
1584        d.field(
1585            "id_token_hint",
1586            &crate::utils::redact::redacted(&self.id_token_hint),
1587        );
1588        d.field("post_logout_redirect_uri", &self.post_logout_redirect_uri);
1589        d.field("state", &self.state);
1590        d.finish()
1591    }
1592}
1593
1594/// OIDC RP-Initiated Logout (OpenID Connect RP-Initiated Logout 1.0).
1595///
1596/// Revokes the token from `id_token_hint` (if valid) and, when a
1597/// registered `post_logout_redirect_uri` is provided, redirects the
1598/// user-agent there.
1599///
1600/// # Example
1601/// ```rust,ignore
1602/// // GET /oauth/end_session?id_token_hint=eyJ...&state=xyz
1603/// let resp = end_session(State(state), Query(params)).await;
1604/// ```
1605pub async fn end_session(
1606    State(state): State<ApiState>,
1607    Query(params): Query<EndSessionRequest>,
1608) -> impl IntoResponse {
1609    // If an id_token_hint is provided, revoke it
1610    if let Some(ref token) = params.id_token_hint
1611        && let Ok(claims) = state
1612            .auth_framework
1613            .token_manager()
1614            .validate_jwt_token(token)
1615    {
1616        let revoked_key = format!("oauth2_revoked_token:{}", token);
1617        if let Err(e) = state
1618            .auth_framework
1619            .storage()
1620            .store_kv(
1621                &revoked_key,
1622                b"revoked",
1623                Some(std::time::Duration::from_secs(86400 * 7)),
1624            )
1625            .await
1626        {
1627            tracing::warn!("Failed to revoke token during OIDC end_session: {}", e);
1628        }
1629        tracing::info!("OIDC end_session: revoked token for user {}", claims.sub);
1630    }
1631
1632    // Redirect to post_logout_redirect_uri only if it matches a registered URI for the
1633    // client identified by id_token_hint.  Without this check an attacker could craft a
1634    // link that redirects users to an arbitrary URL (open redirect / phishing).
1635    if let Some(ref redirect_uri) = params.post_logout_redirect_uri {
1636        // Look up the client's registered redirect URIs via the id_token_hint's `azp` or `aud` claim.
1637        let allowed = if let Some(ref token) = params.id_token_hint {
1638            // Try to extract client_id from the token (azp > aud)
1639            let client_id = state
1640                .auth_framework
1641                .token_manager()
1642                .validate_jwt_token(token)
1643                .ok()
1644                .and_then(|claims| {
1645                    // client_id claim identifies the OAuth client
1646                    if let Some(ref cid) = claims.client_id
1647                        && !cid.is_empty()
1648                    {
1649                        return Some(cid.clone());
1650                    }
1651                    // Fallback: aud may contain the client_id
1652                    if !claims.aud.is_empty() {
1653                        Some(claims.aud.clone())
1654                    } else {
1655                        None
1656                    }
1657                });
1658            if let Some(cid) = client_id {
1659                let client_key = format!("oauth2_client:{}", cid);
1660                match state.auth_framework.storage().get_kv(&client_key).await {
1661                    Ok(Some(data)) => {
1662                        let client: serde_json::Value =
1663                            serde_json::from_slice(&data).unwrap_or_default();
1664                        let uris: Vec<String> = client["redirect_uris"]
1665                            .as_array()
1666                            .map(|a| {
1667                                a.iter()
1668                                    .filter_map(|v| v.as_str().map(String::from))
1669                                    .collect()
1670                            })
1671                            .unwrap_or_default();
1672                        uris.iter().any(|r| redirect_uri_matches(redirect_uri, r))
1673                    }
1674                    _ => false,
1675                }
1676            } else {
1677                false
1678            }
1679        } else {
1680            false
1681        };
1682
1683        if allowed {
1684            if let Ok(mut parsed) = Url::parse(redirect_uri) {
1685                if let Some(ref st) = params.state {
1686                    parsed.query_pairs_mut().append_pair("state", st);
1687                }
1688                return Redirect::to(parsed.as_str()).into_response();
1689            }
1690        } else {
1691            tracing::warn!(
1692                "end_session: post_logout_redirect_uri rejected — not registered for the client"
1693            );
1694        }
1695    }
1696
1697    // No redirect — return a simple JSON acknowledgement
1698    (
1699        StatusCode::OK,
1700        Json(serde_json::json!({ "status": "logged_out" })),
1701    )
1702        .into_response()
1703}
1704
1705// ---------------------------------------------------------------------------
1706// Dynamic Client Registration (RFC 7591)
1707// ---------------------------------------------------------------------------
1708
1709/// Dynamic client registration request per [RFC 7591](https://datatracker.ietf.org/doc/html/rfc7591).
1710///
1711/// # Example
1712/// ```rust
1713/// use auth_framework::api::oauth2::ClientRegistrationRequest;
1714///
1715/// let req: ClientRegistrationRequest = serde_json::from_str(
1716///     r#"{"redirect_uris":["https://example.com/cb"]}"#
1717/// ).unwrap();
1718/// assert_eq!(req.redirect_uris.len(), 1);
1719/// ```
1720#[derive(Debug, Deserialize)]
1721pub struct ClientRegistrationRequest {
1722    pub redirect_uris: Vec<String>,
1723    #[serde(default)]
1724    pub client_name: Option<String>,
1725    #[serde(default)]
1726    pub token_endpoint_auth_method: Option<String>,
1727    #[serde(default)]
1728    pub grant_types: Option<Vec<String>>,
1729    #[serde(default)]
1730    pub response_types: Option<Vec<String>>,
1731    #[serde(default)]
1732    pub scope: Option<String>,
1733}
1734
1735/// POST /oauth/register — dynamically register a new OAuth 2.0 client
1736/// ([RFC 7591](https://datatracker.ietf.org/doc/html/rfc7591)).
1737///
1738/// Requires a valid Bearer token with `admin` role, or an Initial Access
1739/// Token stored in KV at `oauth2_initial_access_token`. Unauthenticated
1740/// callers are rejected to prevent resource exhaustion.
1741///
1742/// # Example
1743/// ```rust,ignore
1744/// let resp = register_client(
1745///     State(state),
1746///     headers,   // with Authorization: Bearer <admin-token>
1747///     Json(ClientRegistrationRequest {
1748///         redirect_uris: vec!["https://example.com/cb".into()],
1749///         client_name: Some("My App".into()),
1750///         ..Default::default()
1751///     }),
1752/// ).await;
1753/// ```
1754pub async fn register_client(
1755    State(state): State<ApiState>,
1756    headers: HeaderMap,
1757    Json(req): Json<ClientRegistrationRequest>,
1758) -> impl IntoResponse {
1759    // RFC 7591 §1.2: require authentication via Bearer token
1760    let token_str = match extract_bearer_token(&headers) {
1761        Some(t) => t,
1762        None => {
1763            return (
1764                StatusCode::UNAUTHORIZED,
1765                Json(serde_json::json!({
1766                    "error": "invalid_token",
1767                    "error_description": "A valid Bearer token is required for dynamic client registration"
1768                })),
1769            )
1770                .into_response();
1771        }
1772    };
1773
1774    // Option 1: check if this is the pre-configured Initial Access Token
1775    let is_initial_access_token = match state
1776        .auth_framework
1777        .storage()
1778        .get_kv("oauth2_initial_access_token")
1779        .await
1780    {
1781        Ok(Some(stored)) => {
1782            let stored_str = String::from_utf8_lossy(&stored);
1783            subtle::ConstantTimeEq::ct_eq(token_str.as_bytes(), stored_str.trim().as_bytes()).into()
1784        }
1785        _ => false,
1786    };
1787
1788    // Option 2: validate as a normal JWT and check for admin role
1789    let is_admin = if !is_initial_access_token {
1790        match validate_api_token(&state.auth_framework, &token_str).await {
1791            Ok(auth_token) => auth_token.roles.contains("admin"),
1792            Err(_) => false,
1793        }
1794    } else {
1795        false
1796    };
1797
1798    if !is_initial_access_token && !is_admin {
1799        return (
1800            StatusCode::FORBIDDEN,
1801            Json(serde_json::json!({
1802                "error": "insufficient_scope",
1803                "error_description": "Dynamic client registration requires admin privileges or a valid Initial Access Token"
1804            })),
1805        )
1806            .into_response();
1807    }
1808    // Validate all redirect_uris are well-formed URLs with safe schemes
1809    for uri in &req.redirect_uris {
1810        match Url::parse(uri) {
1811            Ok(parsed) => {
1812                match parsed.scheme() {
1813                    "https" => {}
1814                    "http" => {
1815                        // Allow plain HTTP only for loopback addresses (development)
1816                        if !matches!(parsed.host_str(), Some("localhost" | "127.0.0.1" | "[::1]")) {
1817                            return (
1818                                StatusCode::BAD_REQUEST,
1819                                Json(serde_json::json!({
1820                                    "error": "invalid_redirect_uri",
1821                                    "error_description": format!("Non-loopback HTTP redirect_uri not allowed: {}", uri)
1822                                })),
1823                            )
1824                                .into_response();
1825                        }
1826                    }
1827                    scheme => {
1828                        return (
1829                            StatusCode::BAD_REQUEST,
1830                            Json(serde_json::json!({
1831                                "error": "invalid_redirect_uri",
1832                                "error_description": format!("Disallowed URI scheme '{}' in redirect_uri: {}", scheme, uri)
1833                            })),
1834                        )
1835                            .into_response();
1836                    }
1837                }
1838            }
1839            Err(_) => {
1840                return (
1841                    StatusCode::BAD_REQUEST,
1842                    Json(serde_json::json!({
1843                        "error": "invalid_redirect_uri",
1844                        "error_description": format!("Invalid redirect_uri: {}", uri)
1845                    })),
1846                )
1847                    .into_response();
1848            }
1849        }
1850    }
1851
1852    if req.redirect_uris.is_empty() {
1853        return (
1854            StatusCode::BAD_REQUEST,
1855            Json(serde_json::json!({
1856                "error": "invalid_client_metadata",
1857                "error_description": "At least one redirect_uri is required"
1858            })),
1859        )
1860            .into_response();
1861    }
1862
1863    let client_id = Uuid::new_v4().to_string();
1864    let client_secret = Uuid::new_v4().to_string();
1865    // Only the hash is stored; the secret itself is returned once, below.
1866    let client_secret_hash = match super::client_secret::hash_secret(&client_secret).await {
1867        Ok(hash) => hash,
1868        Err(e) => {
1869            tracing::error!("Failed to hash a client secret: {}", e);
1870            return (
1871                StatusCode::INTERNAL_SERVER_ERROR,
1872                Json(serde_json::json!({
1873                    "error": "server_error",
1874                    "error_description": "Failed to register client"
1875                })),
1876            )
1877                .into_response();
1878        }
1879    };
1880
1881    let client_data = serde_json::json!({
1882        "client_id": client_id,
1883        "client_secret_hash": client_secret_hash,
1884        "client_name": req.client_name,
1885        "redirect_uris": req.redirect_uris,
1886        "token_endpoint_auth_method": req.token_endpoint_auth_method.as_deref().unwrap_or("client_secret_basic"),
1887        "grant_types": req.grant_types.as_deref().unwrap_or(&["authorization_code".to_string()]),
1888        "response_types": req.response_types.as_deref().unwrap_or(&["code".to_string()]),
1889        "scope": req.scope.as_deref().unwrap_or("openid"),
1890    });
1891
1892    let key = format!("oauth2_client:{}", client_id);
1893    if let Err(e) = state
1894        .auth_framework
1895        .storage()
1896        .store_kv(&key, client_data.to_string().as_bytes(), None)
1897        .await
1898    {
1899        tracing::error!("Failed to store client registration: {}", e);
1900        return (
1901            StatusCode::INTERNAL_SERVER_ERROR,
1902            Json(serde_json::json!({
1903                "error": "server_error",
1904                "error_description": "Failed to register client"
1905            })),
1906        )
1907            .into_response();
1908    }
1909
1910    tracing::info!("Dynamic client registered: client_id={}", client_id);
1911
1912    (
1913        StatusCode::CREATED,
1914        Json(serde_json::json!({
1915            "client_id": client_id,
1916            "client_secret": client_secret,
1917            "client_name": req.client_name,
1918            "redirect_uris": req.redirect_uris,
1919            "token_endpoint_auth_method": req.token_endpoint_auth_method.as_deref().unwrap_or("client_secret_basic"),
1920            "grant_types": req.grant_types.as_deref().unwrap_or(&["authorization_code".to_string()]),
1921            "response_types": req.response_types.as_deref().unwrap_or(&["code".to_string()]),
1922            "scope": req.scope.as_deref().unwrap_or("openid"),
1923        })),
1924    )
1925        .into_response()
1926}
1927
1928// ---------------------------------------------------------------------------
1929// /users/me — alias for the authenticated user's profile
1930// ---------------------------------------------------------------------------
1931
1932/// GET /users/me — returns the authenticated user's profile.
1933///
1934/// Convenience alias that delegates to [`userinfo`].
1935///
1936/// # Example
1937/// ```rust,ignore
1938/// // GET /users/me  Authorization: Bearer <token>
1939/// let resp = users_me(state, headers).await;
1940/// ```
1941pub async fn users_me(state: State<ApiState>, headers: HeaderMap) -> impl IntoResponse {
1942    // Delegate to the existing userinfo handler
1943    userinfo(state, headers).await
1944}