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    let token = match state
667        .auth_framework
668        .token_manager()
669        .create_client_auth_token(&user_id, scopes.clone(), "oauth2", &client_id, None)
670    {
671        Ok(token) => token,
672        Err(e) => {
673            tracing::error!("Failed to create access token: {:?}", e);
674            return ApiResponse::error_typed("server_error", "Failed to create access token");
675        }
676    };
677
678    // Persist a storage-backed refresh token so the refresh grant can validate and rotate it.
679    let refresh_token_value = uuid::Uuid::new_v4().to_string().replace("-", "");
680    let refresh_data = serde_json::json!({
681        "user_id": user_id,
682        "client_id": client_id,
683        "scopes": scope,
684    });
685    let refresh_key = format!("oauth2_refresh_token:{}", refresh_token_value);
686    if let Err(e) = state
687        .auth_framework
688        .storage()
689        .store_kv(
690            &refresh_key,
691            serde_json::to_string(&refresh_data)
692                .unwrap_or_default()
693                .as_bytes(),
694            Some(REFRESH_TOKEN_TTL),
695        )
696        .await
697    {
698        tracing::warn!("Failed to store refresh token: {:?}", e);
699    }
700
701    let expires_in = (token.expires_at - token.issued_at).num_seconds().max(0) as u64;
702    let response = TokenResponse {
703        access_token: token.access_token,
704        token_type: "Bearer".to_string(),
705        expires_in,
706        refresh_token: Some(refresh_token_value),
707        scope: Some(scope.to_string()),
708        id_token: None,
709    };
710
711    tracing::info!("OAuth2 tokens issued for client: {}", client_id);
712    ApiResponse::success(response)
713}
714
715/// A boxed error response (keeps the `Err` variant of the client-check helpers small).
716fn refusal(code: &str, message: &str) -> Box<ApiResponse<TokenResponse>> {
717    Box::new(ApiResponse::error_typed(code, message))
718}
719
720/// Load a registered client's record from `oauth2_client:{client_id}`.
721async fn load_client_record(
722    state: &ApiState,
723    client_id: &str,
724) -> std::result::Result<Option<serde_json::Value>, Box<ApiResponse<TokenResponse>>> {
725    let key = format!("oauth2_client:{client_id}");
726    match state.auth_framework.storage().get_kv(&key).await {
727        Ok(Some(data)) => serde_json::from_slice(&data).map(Some).map_err(|e| {
728            tracing::error!("Unreadable client record for {client_id}: {e}");
729            refusal("server_error", "Failed to validate client")
730        }),
731        Ok(None) => Ok(None),
732        Err(e) => {
733            tracing::error!("Failed to load client {client_id}: {e:?}");
734            Err(refusal("server_error", "Failed to validate client"))
735        }
736    }
737}
738
739/// Scopes granted to clients that were registered without any scope information.
740const DEFAULT_CLIENT_SCOPES: [&str; 3] = ["openid", "profile", "email"];
741
742/// The scopes a client may be granted: those it was registered for (the `scope` string
743/// and/or the `scopes` list). A record that names neither key predates scope registration
744/// and gets the OpenID defaults; a record that names a key but yields no scope (empty, or
745/// of an unexpected type) is granted nothing.
746fn allowed_scopes(record: &serde_json::Value) -> Vec<String> {
747    if record.get("scope").is_none_or(|v| v.is_null())
748        && record.get("scopes").is_none_or(|v| v.is_null())
749    {
750        return DEFAULT_CLIENT_SCOPES
751            .iter()
752            .map(|s| s.to_string())
753            .collect();
754    }
755    let mut allowed: Vec<String> = Vec::new();
756    if let Some(s) = record["scope"].as_str() {
757        allowed.extend(s.split_whitespace().map(String::from));
758    }
759    if let Some(list) = record["scopes"].as_array() {
760        for item in list.iter().filter_map(|v| v.as_str()) {
761            allowed.extend(item.split_whitespace().map(String::from));
762        }
763    }
764    allowed.sort();
765    allowed.dedup();
766    allowed
767}
768
769/// The scope to grant for a request: the requested scopes if every one is allowed
770/// (RFC 6749 section 3.3), otherwise `Err(invalid_scope description)`. With no scope
771/// requested, the client gets everything it is registered for.
772fn effective_scope(
773    record: &serde_json::Value,
774    requested: Option<&str>,
775) -> std::result::Result<String, String> {
776    let allowed = allowed_scopes(record);
777    let requested: Vec<&str> = requested
778        .map(|s| s.split_whitespace().collect())
779        .unwrap_or_default();
780    if requested.is_empty() {
781        return if allowed.is_empty() {
782            Err("this client is not registered for any scope".to_string())
783        } else {
784            Ok(allowed.join(" "))
785        };
786    }
787    if let Some(bad) = requested.iter().find(|s| !allowed.iter().any(|a| a == **s)) {
788        let shown: String = bad.chars().take(64).collect();
789        return Err(format!("scope '{shown}' is not allowed for this client"));
790    }
791    let mut granted: Vec<&str> = Vec::with_capacity(requested.len());
792    for s in requested {
793        if !granted.contains(&s) {
794            granted.push(s);
795        }
796    }
797    Ok(granted.join(" "))
798}
799
800/// How a client identified itself at the token endpoint.
801#[derive(Clone, Copy, PartialEq, Eq)]
802enum ClientKind {
803    /// Registered without a secret: identified by `client_id` alone (PKCE is mandatory).
804    Public,
805    /// Registered with a secret and authenticated with it.
806    Confidential,
807}
808
809/// Authenticate the client of an authorization-code exchange (RFC 6749 section 3.2.1).
810///
811/// The client must be registered (`oauth2_client:{id}`). A client whose record holds a
812/// secret (hashed, or a legacy plain one) is confidential and MUST present exactly that secret;
813/// a missing or wrong secret is `invalid_client`. Whether a client is public is decided by its
814/// registration, never by what the request carries.
815async fn authenticate_token_client(
816    state: &ApiState,
817    client_id: &str,
818    presented_secret: Option<&str>,
819) -> std::result::Result<ClientKind, Box<ApiResponse<TokenResponse>>> {
820    let Some(record) = load_client_record(state, client_id).await? else {
821        return Err(refusal("invalid_client", "Unknown client"));
822    };
823    match super::client_secret::is_confidential(&record) {
824        false => Ok(ClientKind::Public),
825        true => {
826            let authenticated = match presented_secret {
827                Some(presented) => {
828                    super::client_secret::authenticate(
829                        state.auth_framework.storage().as_ref(),
830                        client_id,
831                        &record,
832                        presented,
833                    )
834                    .await
835                }
836                None => false,
837            };
838            if authenticated {
839                // An authenticated client is limited by its own identity, whatever address it
840                // uses (#92); a failed attempt is not counted against the client it names.
841                limit_client(state, client_id).await?;
842                Ok(ClientKind::Confidential)
843            } else {
844                Err(refusal("invalid_client", "Client authentication failed"))
845            }
846        }
847    }
848}
849
850/// Count a request from the authenticated client `client_id` against its own bucket (#92).
851async fn limit_client(
852    state: &ApiState,
853    client_id: &str,
854) -> std::result::Result<(), Box<ApiResponse<TokenResponse>>> {
855    match super::client_rate_limit::check(state, client_id).await {
856        Ok(()) => Ok(()),
857        Err(super::client_rate_limit::ClientLimited::Exceeded { .. }) => Err(refusal(
858            "rate_limit_exceeded",
859            "This client is making too many requests",
860        )),
861        Err(super::client_rate_limit::ClientLimited::Unavailable) => Err(refusal(
862            "temporarily_unavailable",
863            "Rate limiting is temporarily unavailable",
864        )),
865    }
866}
867
868/// RFC 6749 §6 / §10.4: a refresh token issued to `stored_client` is
869/// redeemable only by that client.
870///
871/// * A **confidential** client (its record holds a secret) must authenticate,
872///   and the client that authenticated must be `stored_client`:
873///   missing/invalid credentials are `invalid_client`, a different (validly
874///   authenticated) client is `invalid_grant`.
875/// * A **public** client must present a `client_id` equal to `stored_client`:
876///   missing or different is `invalid_grant`.
877///
878/// There is no "check it only if it is present" path, and a token whose
879/// client is no longer registered fails closed.
880/// Lifetime of a stored refresh token, and of the marker that records it was redeemed.
881const REFRESH_TOKEN_TTL: std::time::Duration = std::time::Duration::from_secs(30 * 24 * 3600);
882
883async fn authorize_refresh_client(
884    state: &ApiState,
885    stored_client: &str,
886    presented_id: Option<&str>,
887    presented_secret: Option<&str>,
888) -> std::result::Result<(), Box<ApiResponse<TokenResponse>>> {
889    let not_issued_to_you = || {
890        refusal(
891            "invalid_grant",
892            "Refresh token was not issued to this client",
893        )
894    };
895
896    let Some(stored_record) = load_client_record(state, stored_client).await? else {
897        return Err(refusal(
898            "invalid_grant",
899            "Refresh token was issued to a client that is no longer registered",
900        ));
901    };
902
903    if !super::client_secret::is_confidential(&stored_record) {
904        // Public client: it identifies itself, nothing more.
905        return match presented_id {
906            Some(id) if id == stored_client => Ok(()),
907            _ => Err(not_issued_to_you()),
908        };
909    }
910
911    // Confidential client: authenticate whoever is asking against THEIR record.
912    let (Some(presented_id), Some(presented_secret)) = (presented_id, presented_secret) else {
913        return Err(refusal(
914            "invalid_client",
915            "Client authentication is required",
916        ));
917    };
918    let presented_record = if presented_id == stored_client {
919        Some(stored_record)
920    } else {
921        load_client_record(state, presented_id).await?
922    };
923    let authenticated = match presented_record.as_ref() {
924        Some(record) => {
925            super::client_secret::authenticate(
926                state.auth_framework.storage().as_ref(),
927                presented_id,
928                record,
929                presented_secret,
930            )
931            .await
932        }
933        None => false,
934    };
935    if !authenticated {
936        return Err(refusal("invalid_client", "Client authentication failed"));
937    }
938    // The client has proved who it is: it is limited by its own identity (#92), including
939    // when it presents a token issued to another client.
940    limit_client(state, presented_id).await?;
941    if presented_id != stored_client {
942        return Err(not_issued_to_you());
943    }
944    Ok(())
945}
946
947async fn handle_refresh_token_grant(
948    state: ApiState,
949    req: TokenRequest,
950) -> ApiResponse<TokenResponse> {
951    let refresh_token_str = match req.refresh_token {
952        Some(t) => t,
953        None => return ApiResponse::validation_error_typed("refresh_token is required"),
954    };
955
956    // A revoked refresh token must not mint new access tokens, regardless of
957    // whether its own storage entry has been deleted yet (see `revoke`). Fail
958    // closed on a storage error here -- matching the equivalent check in
959    // `api/auth.rs`'s refresh handler -- rather than treating "couldn't check"
960    // as "not revoked".
961    let revoked_key = format!("oauth2_revoked_token:{}", refresh_token_str);
962    match state.auth_framework.storage().get_kv(&revoked_key).await {
963        Ok(Some(_)) => {
964            return ApiResponse::error_typed("invalid_grant", "Refresh token has been revoked");
965        }
966        Ok(None) => {} // Not revoked -- proceed
967        Err(e) => {
968            tracing::error!("Refresh token revocation check failed: {:?}", e);
969            return ApiResponse::error_typed("server_error", "Failed to validate refresh token");
970        }
971    }
972
973    let consumed_key = format!("oauth2_refresh_consumed:{}", refresh_token_str);
974
975    // Validate the refresh token against persistent storage.
976    let refresh_key = format!("oauth2_refresh_token:{}", refresh_token_str);
977    let stored = match state.auth_framework.storage().get_kv(&refresh_key).await {
978        Ok(Some(data)) => match serde_json::from_slice::<serde_json::Value>(&data) {
979            Ok(v) => v,
980            Err(_) => return ApiResponse::error_typed("invalid_grant", "Invalid refresh token"),
981        },
982        Ok(None) => {
983            return ApiResponse::error_typed("invalid_grant", "Refresh token not found or expired");
984        }
985        Err(e) => {
986            tracing::error!("Failed to retrieve refresh token: {:?}", e);
987            return ApiResponse::error_typed("server_error", "Failed to validate refresh token");
988        }
989    };
990
991    // Claim the token: of any number of simultaneous redemptions exactly one proceeds (atomic
992    // set-if-absent). The marker is only written for a token that exists. It must outlive the
993    // token: if the old record's delete fails during rotation (below), this marker is the only
994    // thing that stops the rotated-out token being redeemed again (#117).
995    match state
996        .auth_framework
997        .storage()
998        .store_kv_if_absent(&consumed_key, b"1", Some(REFRESH_TOKEN_TTL))
999        .await
1000    {
1001        Ok(true) => {}
1002        Ok(false) => {
1003            return ApiResponse::error_typed("invalid_grant", "Refresh token already consumed");
1004        }
1005        Err(e) => {
1006            tracing::error!("Failed to claim refresh token: {:?}", e);
1007            return ApiResponse::error_typed("server_error", "Failed to validate refresh token");
1008        }
1009    }
1010
1011    let user_id = match stored["user_id"].as_str() {
1012        Some(u) => u.to_string(),
1013        None => return ApiResponse::error_typed("invalid_grant", "Malformed refresh token data"),
1014    };
1015    let client_id = match &stored["client_id"] {
1016        serde_json::Value::Null => None,
1017        serde_json::Value::String(s) => Some(s.clone()),
1018        // A client_id of some other type cannot be checked: fail closed
1019        // instead of silently skipping the binding.
1020        _ => return ApiResponse::error_typed("invalid_grant", "Malformed refresh token data"),
1021    };
1022
1023    // A token issued to a client is redeemable only by that client. A refused
1024    // attempt releases the consumed marker set above, so merely seeing a
1025    // refresh token (and presenting it wrongly) cannot burn it.
1026    if let Some(stored_client) = client_id.as_deref()
1027        && let Err(refusal) = authorize_refresh_client(
1028            &state,
1029            stored_client,
1030            req.client_id.as_deref(),
1031            req.client_secret.as_deref(),
1032        )
1033        .await
1034    {
1035        if let Err(e) = state
1036            .auth_framework
1037            .storage()
1038            .delete_kv(&consumed_key)
1039            .await
1040        {
1041            tracing::warn!("Failed to release refresh consumed marker: {:?}", e);
1042        }
1043        return *refusal;
1044    }
1045
1046    let mut scopes: Vec<String> = stored["scopes"]
1047        .as_str()
1048        .unwrap_or("openid profile email")
1049        .split_whitespace()
1050        .map(|s| s.to_string())
1051        .collect();
1052    // A refreshed token never exceeds what the client is registered for NOW, whatever the
1053    // stored record carries (older records, or a registration narrowed since).
1054    if let Some(client) = stored["client_id"].as_str() {
1055        let record = match load_client_record(&state, client).await {
1056            Ok(Some(record)) => record,
1057            Ok(None) => {
1058                let _ = state
1059                    .auth_framework
1060                    .storage()
1061                    .delete_kv(&consumed_key)
1062                    .await;
1063                return ApiResponse::error_typed("invalid_client", "Unknown client");
1064            }
1065            Err(refused) => {
1066                let _ = state
1067                    .auth_framework
1068                    .storage()
1069                    .delete_kv(&consumed_key)
1070                    .await;
1071                return *refused;
1072            }
1073        };
1074        let allowed = allowed_scopes(&record);
1075        scopes.retain(|s| allowed.iter().any(|a| a == s));
1076        if scopes.is_empty() {
1077            let _ = state
1078                .auth_framework
1079                .storage()
1080                .delete_kv(&consumed_key)
1081                .await;
1082            return ApiResponse::error_typed(
1083                "invalid_scope",
1084                "No granted scope is allowed for this client",
1085            );
1086        }
1087    }
1088    let scope = scopes.join(" ");
1089
1090    let minted = match client_id.as_deref() {
1091        Some(client) => state
1092            .auth_framework
1093            .token_manager()
1094            .create_client_auth_token(&user_id, scopes, "oauth2", client, None),
1095        // A stored refresh record without a client (written by an older version) still came
1096        // from an OAuth grant: its access token is delegated, never a user session.
1097        None => state
1098            .auth_framework
1099            .token_manager()
1100            .create_client_auth_token(&user_id, scopes, "oauth2", "unknown-client", None),
1101    };
1102    let token = match minted {
1103        Ok(t) => t,
1104        Err(e) => {
1105            tracing::error!("Failed to create access token on refresh: {:?}", e);
1106            // Nothing was issued and the old record is untouched: release the claim so the
1107            // client can retry instead of losing the session for the marker's 30 days.
1108            let _ = state
1109                .auth_framework
1110                .storage()
1111                .delete_kv(&consumed_key)
1112                .await;
1113            return ApiResponse::error_typed("server_error", "Failed to issue access token");
1114        }
1115    };
1116
1117    // Issue a new refresh token (rotation).
1118    // Store the new token BEFORE deleting the old one to avoid data loss on failure.
1119    let new_refresh_token = uuid::Uuid::new_v4().to_string().replace("-", "");
1120    let new_refresh_data = serde_json::json!({
1121        "user_id": user_id,
1122        "client_id": client_id,
1123        "scopes": scope,
1124    });
1125    let new_refresh_key = format!("oauth2_refresh_token:{}", new_refresh_token);
1126    if let Err(e) = state
1127        .auth_framework
1128        .storage()
1129        .store_kv(
1130            &new_refresh_key,
1131            serde_json::to_string(&new_refresh_data)
1132                .unwrap_or_default()
1133                .as_bytes(),
1134            Some(REFRESH_TOKEN_TTL),
1135        )
1136        .await
1137    {
1138        tracing::error!("Failed to store new refresh token: {:?}", e);
1139        // Same as above: no rotation happened, so the old token must stay redeemable.
1140        let _ = state
1141            .auth_framework
1142            .storage()
1143            .delete_kv(&consumed_key)
1144            .await;
1145        return ApiResponse::error_typed("server_error", "Failed to issue refresh token");
1146    }
1147
1148    // Now that the new token is safely stored, delete the old one (single-use enforcement).
1149    if let Err(e) = state.auth_framework.storage().delete_kv(&refresh_key).await {
1150        tracing::warn!(
1151            "Failed to delete old refresh token during rotation: {:?}",
1152            e
1153        );
1154    }
1155
1156    let expires_in = (token.expires_at - token.issued_at).num_seconds().max(0) as u64;
1157    let response = TokenResponse {
1158        access_token: token.access_token,
1159        token_type: "Bearer".to_string(),
1160        expires_in,
1161        refresh_token: Some(new_refresh_token),
1162        scope: Some(scope),
1163        id_token: None,
1164    };
1165
1166    tracing::info!("OAuth2 token refreshed for user: {}", user_id);
1167    ApiResponse::success(response)
1168}
1169
1170/// Whether the caller of `/oauth/revoke` is the client `owner`, who the token was issued to:
1171/// it names itself with HTTP Basic or the `client_id` / `client_secret` body fields, and a
1172/// client that has a secret must present it.
1173async fn revocation_caller_is(
1174    state: &ApiState,
1175    headers: &HeaderMap,
1176    req: &RevokeRequest,
1177    owner: &str,
1178) -> Result<bool, super::client_rate_limit::ClientLimited> {
1179    use base64::engine::general_purpose::STANDARD;
1180    let basic = headers
1181        .get(axum::http::header::AUTHORIZATION)
1182        .and_then(|value| value.to_str().ok())
1183        .and_then(|value| value.strip_prefix("Basic "))
1184        .and_then(|encoded| STANDARD.decode(encoded).ok())
1185        .and_then(|decoded| String::from_utf8(decoded).ok())
1186        .map(|decoded| match decoded.split_once(':') {
1187            Some((id, secret)) => (id.to_string(), Some(secret.to_string())),
1188            None => (decoded, None),
1189        });
1190    let (presented_id, presented_secret) = match basic {
1191        Some(pair) => pair,
1192        None => match &req.client_id {
1193            Some(id) => (id.clone(), req.client_secret.clone()),
1194            None => return Ok(false),
1195        },
1196    };
1197    if presented_id != owner {
1198        return Ok(false);
1199    }
1200    let key = format!("oauth2_client:{owner}");
1201    let record: serde_json::Value = match state.auth_framework.storage().get_kv(&key).await {
1202        Ok(Some(data)) => match serde_json::from_slice(&data) {
1203            Ok(record) => record,
1204            Err(_) => return Ok(false),
1205        },
1206        _ => return Ok(false),
1207    };
1208    if !super::client_secret::is_confidential(&record) {
1209        return Ok(true);
1210    }
1211    let authenticated = match presented_secret {
1212        Some(secret) => {
1213            super::client_secret::authenticate(
1214                state.auth_framework.storage().as_ref(),
1215                owner,
1216                &record,
1217                &secret,
1218            )
1219            .await
1220        }
1221        None => false,
1222    };
1223    // An authenticated client is limited by its own identity (#92); a failed attempt is not
1224    // counted against the client it names.
1225    if authenticated {
1226        super::client_rate_limit::check(state, owner).await?;
1227    }
1228    Ok(authenticated)
1229}
1230
1231/// POST /api/v1/oauth/revoke — revoke an access or refresh token.
1232///
1233/// Stores a revocation marker in KV (`oauth2_revoked_token:{token}`,
1234/// TTL'd to the refresh token's own 30-day lifetime -- not just the 7
1235/// days access-token revocation needs -- since this one marker has to
1236/// outlive whichever token type was actually revoked) and, for JWT
1237/// tokens, also stores a JTI-based marker (`revoked_token:{jti}`) so
1238/// that all authenticated endpoints reject the token immediately. If
1239/// the token is a refresh token, also deletes its `oauth2_refresh_token:`
1240/// storage entry outright -- `handle_refresh_token_grant` also checks
1241/// the revocation marker directly (failing closed on a storage error
1242/// there), so revocation is effective for the marker's full TTL even if
1243/// the delete itself fails.
1244///
1245/// Only a token this server issued is acted on; anything else is a no-op that answers like
1246/// success (RFC 7009 section 2.2) and stores nothing. A token issued to an OAuth client
1247/// (it carries a `client_id`) is revoked only by that client (RFC 7009 section 2.1): a
1248/// confidential client authenticates with HTTP Basic or `client_id` / `client_secret` in the
1249/// body, a public one names itself with `client_id`; otherwise `invalid_client`. A token
1250/// with no client (a first-party session token) is revoked by whoever holds it.
1251///
1252/// # Example
1253/// ```rust,ignore
1254/// let resp = revoke(State(state), HeaderMap::new(), Json(RevokeRequest {
1255///     token: "access_token_value".into(),
1256///     token_type_hint: Some("access_token".into()),
1257///     client_id: None,
1258///     client_secret: None,
1259/// })).await;
1260/// assert!(resp.success);
1261/// ```
1262pub async fn revoke(
1263    State(state): State<ApiState>,
1264    headers: HeaderMap,
1265    Json(req): Json<RevokeRequest>,
1266) -> ApiResponse<serde_json::Value> {
1267    // The token becomes part of a storage key: bound its size.
1268    if req.token.is_empty() || req.token.len() > 8192 {
1269        return ApiResponse::error_typed("invalid_request", "Invalid token");
1270    }
1271
1272    // Only a token this server issued is revoked. Anything else (a guess, junk, an expired
1273    // or foreign JWT) is a no-op that answers like success (RFC 7009 section 2.2): the request
1274    // must not make the server store a marker for an arbitrary string.
1275    let issued_jwt = state
1276        .auth_framework
1277        .token_manager()
1278        .validate_jwt_token(&req.token)
1279        .ok();
1280    let refresh_record: Option<serde_json::Value> = match state
1281        .auth_framework
1282        .storage()
1283        .get_kv(&format!("oauth2_refresh_token:{}", req.token))
1284        .await
1285    {
1286        Ok(Some(data)) => serde_json::from_slice(&data).ok(),
1287        Ok(None) => None,
1288        Err(e) => {
1289            tracing::error!("Failed to look up the token to revoke: {:?}", e);
1290            return ApiResponse::error_typed("server_error", "Failed to revoke token");
1291        }
1292    };
1293    if issued_jwt.is_none() && refresh_record.is_none() {
1294        return ApiResponse::success(serde_json::json!({
1295            "message": "Token revoked successfully"
1296        }));
1297    }
1298
1299    // A token issued to an OAuth client is revoked only by that client (RFC 7009 section 2.1):
1300    // a confidential client authenticates, a public one identifies itself.
1301    let owner_client = issued_jwt
1302        .as_ref()
1303        .and_then(|claims| claims.client_id.clone())
1304        .or_else(|| {
1305            refresh_record
1306                .as_ref()
1307                .and_then(|record| record["client_id"].as_str().map(String::from))
1308        });
1309    if let Some(owner) = owner_client.as_deref() {
1310        match revocation_caller_is(&state, &headers, &req, owner).await {
1311            Ok(true) => {}
1312            Ok(false) => {
1313                return ApiResponse::error_typed("invalid_client", "Client authentication failed");
1314            }
1315            Err(super::client_rate_limit::ClientLimited::Exceeded { .. }) => {
1316                return ApiResponse::error_typed(
1317                    "rate_limit_exceeded",
1318                    "This client is making too many requests",
1319                );
1320            }
1321            Err(super::client_rate_limit::ClientLimited::Unavailable) => {
1322                return ApiResponse::error_typed(
1323                    "temporarily_unavailable",
1324                    "Rate limiting is temporarily unavailable",
1325                );
1326            }
1327        }
1328    }
1329
1330    // Store the revoked token in a blacklist for immediate invalidation.
1331    // Key by the raw token value so the userinfo endpoint can check it too.
1332    let revoked_token_key = format!("oauth2_revoked_token:{}", req.token);
1333    let revoked_data = serde_json::json!({
1334        "token": req.token,
1335        "revoked_at": chrono::Utc::now().to_rfc3339(),
1336        "token_type_hint": req.token_type_hint
1337    });
1338
1339    if let Err(e) = state
1340        .auth_framework
1341        .storage()
1342        .store_kv(
1343            &revoked_token_key,
1344            serde_json::to_string(&revoked_data)
1345                .unwrap_or_default()
1346                .as_bytes(),
1347            // 30 days: must outlive the longest-lived token type this
1348            // endpoint can revoke (the refresh token's own 30-day TTL),
1349            // not just the 7 days an access token's JWT markers need --
1350            // otherwise a revoked refresh token whose delete somehow
1351            // failed would become usable again once this marker expired.
1352            Some(REFRESH_TOKEN_TTL),
1353        )
1354        .await
1355    {
1356        tracing::error!("Failed to store revoked token: {:?}", e);
1357        return ApiResponse::error_typed("server_error", "Failed to revoke token");
1358    }
1359
1360    // If this is a refresh token, delete its storage entry outright so it
1361    // can no longer be used to mint new access tokens. A no-op (and not an
1362    // error) if `req.token` isn't a refresh token at all -- the key simply
1363    // won't exist.
1364    let refresh_key = format!("oauth2_refresh_token:{}", req.token);
1365    if let Err(e) = state.auth_framework.storage().delete_kv(&refresh_key).await {
1366        tracing::warn!("Failed to delete refresh token on revoke: {:?}", e);
1367    }
1368
1369    // If the token is a JWT, also store revoked_token:{jti} so the authentication
1370    // middleware (validate_api_token in api/mod.rs) blocks it on all protected
1371    // endpoints. Without this step, the revocation would only be visible to the
1372    // userinfo endpoint, leaving all other authenticated routes unprotected.
1373    let mut revoked_subject: Option<String> = None;
1374    let mut revoked_jti: Option<String> = None;
1375    if let Ok(claims) = state
1376        .auth_framework
1377        .token_manager()
1378        .validate_jwt_token(&req.token)
1379    {
1380        let now = chrono::Utc::now().timestamp();
1381        let remaining_secs = (claims.exp - now + 60).max(60) as u64;
1382        let jti_key = format!("revoked_token:{}", claims.jti);
1383        revoked_subject = Some(claims.sub.clone());
1384        revoked_jti = Some(claims.jti.clone());
1385        if let Err(e) = state
1386            .auth_framework
1387            .storage()
1388            .store_kv(
1389                &jti_key,
1390                b"1",
1391                Some(std::time::Duration::from_secs(remaining_secs)),
1392            )
1393            .await
1394        {
1395            tracing::warn!("Failed to store JWT JTI revocation entry: {:?}", e);
1396        } else {
1397            tracing::info!("JWT token revoked via jti: {}", claims.jti);
1398        }
1399    }
1400
1401    tracing::info!(
1402        "OAuth2 token revoked: {}",
1403        crate::utils::redact::fingerprint(&req.token)
1404    );
1405
1406    // Audit trail: that a token was revoked, which one (its fingerprint, and `jti` when it is a
1407    // JWT) and whose it was; never the token itself. The actor is the client the token was
1408    // issued to (it authenticated above), or unauthenticated for a first-party token.
1409    {
1410        use crate::audit::{AuditEvent, AuditEventType, EventOutcome, RiskLevel};
1411        let mut event = AuditEvent::builder(
1412            AuditEventType::TokenRevoked,
1413            "OAuth2 token revoked via /oauth/revoke",
1414        )
1415        .outcome(EventOutcome::Success)
1416        .risk_level(RiskLevel::Low)
1417        .with_actor(
1418            "api_caller",
1419            owner_client.as_deref().unwrap_or("unauthenticated"),
1420        )
1421        .detail("endpoint", "/oauth/revoke")
1422        .detail(
1423            "token_fingerprint",
1424            crate::utils::redact::fingerprint(&req.token).to_string(),
1425        );
1426        if let Some(subject) = revoked_subject {
1427            event = event.user_id(subject);
1428        }
1429        if let Some(jti) = revoked_jti {
1430            event = event.detail("jti", jti);
1431        }
1432        state.auth_framework.record_audit_event(event.build()).await;
1433    }
1434
1435    ApiResponse::success(serde_json::json!({
1436        "message": "Token revoked successfully"
1437    }))
1438}
1439
1440/// GET /api/v1/oauth/userinfo — return claims about the authenticated user.
1441///
1442/// The caller must supply a valid Bearer access token. If the token has been
1443/// revoked, an `invalid_token` error is returned. Email is included only
1444/// when the `email` scope is present in the token.
1445///
1446/// # Example
1447/// ```rust,ignore
1448/// // GET /api/v1/oauth/userinfo  Authorization: Bearer <token>
1449/// let resp = userinfo(State(state), headers).await;
1450/// assert_eq!(resp.data.unwrap().sub, "user-1");
1451/// ```
1452pub async fn userinfo(
1453    State(state): State<ApiState>,
1454    headers: HeaderMap,
1455) -> ApiResponse<UserInfoResponse> {
1456    // Extract and validate access token
1457    let token = match extract_bearer_token(&headers) {
1458        Some(t) => t,
1459        None => {
1460            return ApiResponse::error_typed("invalid_token", "Authorization header required");
1461        }
1462    };
1463
1464    // Check if token is revoked first
1465    let revoked_token_key = format!("oauth2_revoked_token:{}", token);
1466    if let Ok(Some(_)) = state
1467        .auth_framework
1468        .storage()
1469        .get_kv(&revoked_token_key)
1470        .await
1471    {
1472        return ApiResponse::error_typed("invalid_token", "Token has been revoked");
1473    }
1474
1475    // Validate the access token
1476    let claims = match state.auth_framework.validate_delegated_jwt(&token).await {
1477        Ok(c) => c,
1478        Err(_) => {
1479            return ApiResponse::error_typed("invalid_token", "Access token is invalid");
1480        }
1481    };
1482
1483    // Get user profile
1484    let user_profile = match state.auth_framework.get_user_profile(&claims.sub).await {
1485        Ok(profile) => profile,
1486        Err(e) => {
1487            tracing::error!("Failed to get user profile: {:?}", e);
1488            return ApiResponse::error_typed("server_error", "Failed to retrieve user information");
1489        }
1490    };
1491
1492    let userinfo = UserInfoResponse {
1493        sub: claims.sub.clone(),
1494        name: user_profile.username.clone(),
1495        // Only include email if the token's scopes include "email"
1496        email: if claims.scope.split_whitespace().any(|s| s == "email") {
1497            user_profile.email.clone()
1498        } else {
1499            None
1500        },
1501        picture: user_profile.picture.clone(),
1502        updated_at: Some(chrono::Utc::now().timestamp()),
1503    };
1504
1505    tracing::info!("OAuth2 UserInfo requested for user: {}", claims.sub);
1506    ApiResponse::success(userinfo)
1507}
1508
1509/// GET /oauth/clients/{client_id} — return the stored metadata for a
1510/// registered OAuth 2.0 client.
1511///
1512/// # Example
1513/// ```rust,ignore
1514/// let resp = get_client_info(State(state), Path("my-client-id".into())).await;
1515/// ```
1516pub async fn get_client_info(
1517    State(state): State<ApiState>,
1518    Path(client_id): Path<String>,
1519) -> impl IntoResponse {
1520    let client_key = format!("oauth2_client:{}", client_id);
1521    match state.auth_framework.storage().get_kv(&client_key).await {
1522        Ok(Some(data)) => match serde_json::from_slice::<ClientInfo>(&data) {
1523            Ok(client) => (
1524                StatusCode::OK,
1525                Json(serde_json::json!({ "success": true, "data": client })),
1526            )
1527                .into_response(),
1528            Err(e) => {
1529                tracing::error!(client_id = %client_id, error = %e, "Failed to deserialize client record");
1530                (
1531                    StatusCode::INTERNAL_SERVER_ERROR,
1532                    Json(serde_json::json!({
1533                        "success": false,
1534                        "error": "server_error",
1535                        "message": "Failed to read client record"
1536                    })),
1537                )
1538                    .into_response()
1539            }
1540        },
1541        Ok(None) => (
1542            StatusCode::NOT_FOUND,
1543            Json(serde_json::json!({
1544                "success": false,
1545                "error": "invalid_client",
1546                "message": "Unknown client_id"
1547            })),
1548        )
1549            .into_response(),
1550        Err(e) => {
1551            tracing::error!(client_id = %client_id, error = %e, "Storage error looking up client");
1552            (
1553                StatusCode::INTERNAL_SERVER_ERROR,
1554                Json(serde_json::json!({
1555                    "success": false,
1556                    "error": "server_error",
1557                    "message": "Authorization server error"
1558                })),
1559            )
1560                .into_response()
1561        }
1562    }
1563}
1564
1565// ---------------------------------------------------------------------------
1566// OpenID Connect Discovery (RFC 8414 / OpenID Connect Discovery 1.0)
1567// ---------------------------------------------------------------------------
1568
1569/// OpenID Connect Discovery endpoint (RFC 8414 / OpenID Connect Discovery 1.0).
1570///
1571/// Returns server authorization metadata so clients can auto-configure
1572/// (issuer, endpoints, supported grants, signing algorithms, etc.).
1573///
1574/// # Example
1575/// ```rust,ignore
1576/// // GET /.well-known/openid-configuration
1577/// let (status, Json(config)) = openid_configuration(State(state)).await;
1578/// assert_eq!(status, StatusCode::OK);
1579/// ```
1580pub async fn openid_configuration(State(state): State<ApiState>) -> impl IntoResponse {
1581    let issuer = {
1582        let configured = state.auth_framework.config().issuer.clone();
1583        if configured.is_empty() {
1584            "https://auth.example.com".to_string()
1585        } else {
1586            configured
1587        }
1588    };
1589
1590    let config = serde_json::json!({
1591        "issuer": issuer,
1592        "authorization_endpoint": format!("{}/api/v1/oauth/authorize", issuer),
1593        "token_endpoint": format!("{}/api/v1/oauth/token", issuer),
1594        "userinfo_endpoint": format!("{}/api/v1/oauth/userinfo", issuer),
1595        "revocation_endpoint": format!("{}/api/v1/oauth/revoke", issuer),
1596        "introspection_endpoint": format!("{}/api/v1/oauth/introspect", issuer),
1597        "jwks_uri": format!("{}/api/v1/.well-known/jwks.json", issuer),
1598        "end_session_endpoint": format!("{}/api/v1/oauth/end_session", issuer),
1599        "pushed_authorization_request_endpoint": format!("{}/api/v1/oauth/par", issuer),
1600        "registration_endpoint": format!("{}/api/v1/oauth/register", issuer),
1601        "response_types_supported": ["code"],
1602        "grant_types_supported": [
1603            "authorization_code",
1604            "refresh_token"
1605        ],
1606        "subject_types_supported": ["public"],
1607        "id_token_signing_alg_values_supported": ["HS256"],
1608        "token_endpoint_auth_methods_supported": [
1609            "client_secret_basic",
1610            "client_secret_post"
1611        ],
1612        "code_challenge_methods_supported": ["S256"],
1613        "scopes_supported": ["openid", "profile", "email"]
1614    });
1615
1616    (StatusCode::OK, Json(config))
1617}
1618
1619// ---------------------------------------------------------------------------
1620// JWKS endpoint (RFC 7517)
1621// ---------------------------------------------------------------------------
1622
1623/// JSON Web Key Set (JWKS) endpoint ([RFC 7517](https://datatracker.ietf.org/doc/html/rfc7517)).
1624///
1625/// Returns the public keys used to verify tokens. Currently returns an
1626/// empty key set because HS256 (symmetric) signing is used; clients
1627/// should use the introspection endpoint for token validation.
1628///
1629/// # Example
1630/// ```rust,ignore
1631/// // GET /.well-known/jwks.json
1632/// let (status, Json(jwks)) = jwks(State(state)).await;
1633/// assert!(jwks["keys"].as_array().unwrap().is_empty());
1634/// ```
1635pub async fn jwks(State(_state): State<ApiState>) -> impl IntoResponse {
1636    (StatusCode::OK, Json(serde_json::json!({ "keys": [] })))
1637}
1638
1639// ---------------------------------------------------------------------------
1640// OIDC RP-Initiated Logout (OpenID Connect RP-Initiated Logout 1.0)
1641// ---------------------------------------------------------------------------
1642
1643/// Request parameters for OpenID Connect RP-Initiated Logout.
1644///
1645/// # Example
1646/// ```rust
1647/// use auth_framework::api::oauth2::EndSessionRequest;
1648///
1649/// let req: EndSessionRequest = serde_json::from_str(
1650///     r#"{"id_token_hint":"eyJ...","state":"xyz"}"#
1651/// ).unwrap();
1652/// assert!(req.post_logout_redirect_uri.is_none());
1653/// ```
1654#[derive(Deserialize)]
1655pub struct EndSessionRequest {
1656    pub id_token_hint: Option<String>,
1657    pub post_logout_redirect_uri: Option<String>,
1658    pub state: Option<String>,
1659}
1660
1661impl std::fmt::Debug for EndSessionRequest {
1662    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1663        let mut d = f.debug_struct("EndSessionRequest");
1664        d.field(
1665            "id_token_hint",
1666            &crate::utils::redact::redacted(&self.id_token_hint),
1667        );
1668        d.field("post_logout_redirect_uri", &self.post_logout_redirect_uri);
1669        d.field("state", &self.state);
1670        d.finish()
1671    }
1672}
1673
1674/// OIDC RP-Initiated Logout (OpenID Connect RP-Initiated Logout 1.0).
1675///
1676/// Revokes the token from `id_token_hint` (if valid) and, when a
1677/// registered `post_logout_redirect_uri` is provided, redirects the
1678/// user-agent there.
1679///
1680/// # Example
1681/// ```rust,ignore
1682/// // GET /oauth/end_session?id_token_hint=eyJ...&state=xyz
1683/// let resp = end_session(State(state), Query(params)).await;
1684/// ```
1685pub async fn end_session(
1686    State(state): State<ApiState>,
1687    Query(params): Query<EndSessionRequest>,
1688) -> impl IntoResponse {
1689    // If an id_token_hint is provided, revoke it
1690    if let Some(ref token) = params.id_token_hint
1691        && let Ok(claims) = state
1692            .auth_framework
1693            .token_manager()
1694            .validate_jwt_token(token)
1695    {
1696        let revoked_key = format!("oauth2_revoked_token:{}", token);
1697        if let Err(e) = state
1698            .auth_framework
1699            .storage()
1700            .store_kv(
1701                &revoked_key,
1702                b"revoked",
1703                Some(std::time::Duration::from_secs(86400 * 7)),
1704            )
1705            .await
1706        {
1707            tracing::warn!("Failed to revoke token during OIDC end_session: {}", e);
1708        }
1709        // the marker every bearer-token validation path reads
1710        if let Err(e) = state
1711            .auth_framework
1712            .storage()
1713            .store_kv(
1714                &format!("revoked_token:{}", claims.jti),
1715                b"revoked",
1716                Some(std::time::Duration::from_secs(
1717                    (claims.exp - chrono::Utc::now().timestamp()).max(60) as u64,
1718                )),
1719            )
1720            .await
1721        {
1722            tracing::warn!(
1723                "Failed to record jti revocation during OIDC end_session: {}",
1724                e
1725            );
1726        }
1727        tracing::info!("OIDC end_session: revoked token for user {}", claims.sub);
1728    }
1729
1730    // Redirect to post_logout_redirect_uri only if it matches a registered URI for the
1731    // client identified by id_token_hint.  Without this check an attacker could craft a
1732    // link that redirects users to an arbitrary URL (open redirect / phishing).
1733    if let Some(ref redirect_uri) = params.post_logout_redirect_uri {
1734        // Look up the client's registered redirect URIs via the id_token_hint's `azp` or `aud` claim.
1735        let allowed = if let Some(ref token) = params.id_token_hint {
1736            // Try to extract client_id from the token (azp > aud)
1737            let client_id = state
1738                .auth_framework
1739                .token_manager()
1740                .validate_jwt_token(token)
1741                .ok()
1742                .and_then(|claims| {
1743                    // client_id claim identifies the OAuth client
1744                    if let Some(ref cid) = claims.client_id
1745                        && !cid.is_empty()
1746                    {
1747                        return Some(cid.clone());
1748                    }
1749                    // Fallback: aud may contain the client_id
1750                    if !claims.aud.is_empty() {
1751                        Some(claims.aud.clone())
1752                    } else {
1753                        None
1754                    }
1755                });
1756            if let Some(cid) = client_id {
1757                let client_key = format!("oauth2_client:{}", cid);
1758                match state.auth_framework.storage().get_kv(&client_key).await {
1759                    Ok(Some(data)) => {
1760                        let client: serde_json::Value =
1761                            serde_json::from_slice(&data).unwrap_or_default();
1762                        let uris: Vec<String> = client["redirect_uris"]
1763                            .as_array()
1764                            .map(|a| {
1765                                a.iter()
1766                                    .filter_map(|v| v.as_str().map(String::from))
1767                                    .collect()
1768                            })
1769                            .unwrap_or_default();
1770                        uris.iter().any(|r| redirect_uri_matches(redirect_uri, r))
1771                    }
1772                    _ => false,
1773                }
1774            } else {
1775                false
1776            }
1777        } else {
1778            false
1779        };
1780
1781        if allowed {
1782            if let Ok(mut parsed) = Url::parse(redirect_uri) {
1783                if let Some(ref st) = params.state {
1784                    parsed.query_pairs_mut().append_pair("state", st);
1785                }
1786                return Redirect::to(parsed.as_str()).into_response();
1787            }
1788        } else {
1789            tracing::warn!(
1790                "end_session: post_logout_redirect_uri rejected — not registered for the client"
1791            );
1792        }
1793    }
1794
1795    // No redirect — return a simple JSON acknowledgement
1796    (
1797        StatusCode::OK,
1798        Json(serde_json::json!({ "status": "logged_out" })),
1799    )
1800        .into_response()
1801}
1802
1803// ---------------------------------------------------------------------------
1804// Dynamic Client Registration (RFC 7591)
1805// ---------------------------------------------------------------------------
1806
1807/// Dynamic client registration request per [RFC 7591](https://datatracker.ietf.org/doc/html/rfc7591).
1808///
1809/// # Example
1810/// ```rust
1811/// use auth_framework::api::oauth2::ClientRegistrationRequest;
1812///
1813/// let req: ClientRegistrationRequest = serde_json::from_str(
1814///     r#"{"redirect_uris":["https://example.com/cb"]}"#
1815/// ).unwrap();
1816/// assert_eq!(req.redirect_uris.len(), 1);
1817/// ```
1818#[derive(Debug, Deserialize)]
1819pub struct ClientRegistrationRequest {
1820    pub redirect_uris: Vec<String>,
1821    #[serde(default)]
1822    pub client_name: Option<String>,
1823    #[serde(default)]
1824    pub token_endpoint_auth_method: Option<String>,
1825    #[serde(default)]
1826    pub grant_types: Option<Vec<String>>,
1827    #[serde(default)]
1828    pub response_types: Option<Vec<String>>,
1829    #[serde(default)]
1830    pub scope: Option<String>,
1831}
1832
1833/// POST /oauth/register — dynamically register a new OAuth 2.0 client
1834/// ([RFC 7591](https://datatracker.ietf.org/doc/html/rfc7591)).
1835///
1836/// Requires a valid Bearer token with `admin` role, or an Initial Access
1837/// Token stored in KV at `oauth2_initial_access_token`. Unauthenticated
1838/// callers are rejected to prevent resource exhaustion.
1839///
1840/// # Example
1841/// ```rust,ignore
1842/// let resp = register_client(
1843///     State(state),
1844///     headers,   // with Authorization: Bearer <admin-token>
1845///     Json(ClientRegistrationRequest {
1846///         redirect_uris: vec!["https://example.com/cb".into()],
1847///         client_name: Some("My App".into()),
1848///         ..Default::default()
1849///     }),
1850/// ).await;
1851/// ```
1852pub async fn register_client(
1853    State(state): State<ApiState>,
1854    headers: HeaderMap,
1855    Json(req): Json<ClientRegistrationRequest>,
1856) -> impl IntoResponse {
1857    // RFC 7591 §1.2: require authentication via Bearer token
1858    let token_str = match extract_bearer_token(&headers) {
1859        Some(t) => t,
1860        None => {
1861            return (
1862                StatusCode::UNAUTHORIZED,
1863                Json(serde_json::json!({
1864                    "error": "invalid_token",
1865                    "error_description": "A valid Bearer token is required for dynamic client registration"
1866                })),
1867            )
1868                .into_response();
1869        }
1870    };
1871
1872    // Option 1: check if this is the pre-configured Initial Access Token
1873    let is_initial_access_token = match state
1874        .auth_framework
1875        .storage()
1876        .get_kv("oauth2_initial_access_token")
1877        .await
1878    {
1879        Ok(Some(stored)) => {
1880            let stored_str = String::from_utf8_lossy(&stored);
1881            subtle::ConstantTimeEq::ct_eq(token_str.as_bytes(), stored_str.trim().as_bytes()).into()
1882        }
1883        _ => false,
1884    };
1885
1886    // Option 2: validate as a normal JWT and check for admin role
1887    let is_admin = if !is_initial_access_token {
1888        match validate_api_token(&state.auth_framework, &token_str).await {
1889            Ok(auth_token) => auth_token.roles.contains("admin"),
1890            Err(_) => false,
1891        }
1892    } else {
1893        false
1894    };
1895
1896    if !is_initial_access_token && !is_admin {
1897        return (
1898            StatusCode::FORBIDDEN,
1899            Json(serde_json::json!({
1900                "error": "insufficient_scope",
1901                "error_description": "Dynamic client registration requires admin privileges or a valid Initial Access Token"
1902            })),
1903        )
1904            .into_response();
1905    }
1906    // Validate all redirect_uris are well-formed URLs with safe schemes
1907    for uri in &req.redirect_uris {
1908        match Url::parse(uri) {
1909            Ok(parsed) => {
1910                match parsed.scheme() {
1911                    "https" => {}
1912                    "http" => {
1913                        // Allow plain HTTP only for loopback addresses (development)
1914                        if !matches!(parsed.host_str(), Some("localhost" | "127.0.0.1" | "[::1]")) {
1915                            return (
1916                                StatusCode::BAD_REQUEST,
1917                                Json(serde_json::json!({
1918                                    "error": "invalid_redirect_uri",
1919                                    "error_description": format!("Non-loopback HTTP redirect_uri not allowed: {}", uri)
1920                                })),
1921                            )
1922                                .into_response();
1923                        }
1924                    }
1925                    scheme => {
1926                        return (
1927                            StatusCode::BAD_REQUEST,
1928                            Json(serde_json::json!({
1929                                "error": "invalid_redirect_uri",
1930                                "error_description": format!("Disallowed URI scheme '{}' in redirect_uri: {}", scheme, uri)
1931                            })),
1932                        )
1933                            .into_response();
1934                    }
1935                }
1936            }
1937            Err(_) => {
1938                return (
1939                    StatusCode::BAD_REQUEST,
1940                    Json(serde_json::json!({
1941                        "error": "invalid_redirect_uri",
1942                        "error_description": format!("Invalid redirect_uri: {}", uri)
1943                    })),
1944                )
1945                    .into_response();
1946            }
1947        }
1948    }
1949
1950    if req.redirect_uris.is_empty() {
1951        return (
1952            StatusCode::BAD_REQUEST,
1953            Json(serde_json::json!({
1954                "error": "invalid_client_metadata",
1955                "error_description": "At least one redirect_uri is required"
1956            })),
1957        )
1958            .into_response();
1959    }
1960
1961    let client_id = Uuid::new_v4().to_string();
1962    let client_secret = Uuid::new_v4().to_string();
1963    // Only the hash is stored; the secret itself is returned once, below.
1964    let client_secret_hash = match super::client_secret::hash_secret(&client_secret).await {
1965        Ok(hash) => hash,
1966        Err(e) => {
1967            tracing::error!("Failed to hash a client secret: {}", e);
1968            return (
1969                StatusCode::INTERNAL_SERVER_ERROR,
1970                Json(serde_json::json!({
1971                    "error": "server_error",
1972                    "error_description": "Failed to register client"
1973                })),
1974            )
1975                .into_response();
1976        }
1977    };
1978
1979    let client_data = serde_json::json!({
1980        "client_id": client_id,
1981        "client_secret_hash": client_secret_hash,
1982        "client_name": req.client_name,
1983        "redirect_uris": req.redirect_uris,
1984        "token_endpoint_auth_method": req.token_endpoint_auth_method.as_deref().unwrap_or("client_secret_basic"),
1985        "grant_types": req.grant_types.as_deref().unwrap_or(&["authorization_code".to_string()]),
1986        "response_types": req.response_types.as_deref().unwrap_or(&["code".to_string()]),
1987        "scope": req.scope.as_deref().unwrap_or("openid"),
1988    });
1989
1990    let key = format!("oauth2_client:{}", client_id);
1991    if let Err(e) = state
1992        .auth_framework
1993        .storage()
1994        .store_kv(&key, client_data.to_string().as_bytes(), None)
1995        .await
1996    {
1997        tracing::error!("Failed to store client registration: {}", e);
1998        return (
1999            StatusCode::INTERNAL_SERVER_ERROR,
2000            Json(serde_json::json!({
2001                "error": "server_error",
2002                "error_description": "Failed to register client"
2003            })),
2004        )
2005            .into_response();
2006    }
2007
2008    tracing::info!("Dynamic client registered: client_id={}", client_id);
2009
2010    (
2011        StatusCode::CREATED,
2012        Json(serde_json::json!({
2013            "client_id": client_id,
2014            "client_secret": client_secret,
2015            "client_name": req.client_name,
2016            "redirect_uris": req.redirect_uris,
2017            "token_endpoint_auth_method": req.token_endpoint_auth_method.as_deref().unwrap_or("client_secret_basic"),
2018            "grant_types": req.grant_types.as_deref().unwrap_or(&["authorization_code".to_string()]),
2019            "response_types": req.response_types.as_deref().unwrap_or(&["code".to_string()]),
2020            "scope": req.scope.as_deref().unwrap_or("openid"),
2021        })),
2022    )
2023        .into_response()
2024}
2025
2026// ---------------------------------------------------------------------------
2027// /users/me — alias for the authenticated user's profile
2028// ---------------------------------------------------------------------------
2029
2030/// GET /users/me — returns the authenticated user's profile.
2031///
2032/// Convenience alias that delegates to [`userinfo`].
2033///
2034/// # Example
2035/// ```rust,ignore
2036/// // GET /users/me  Authorization: Bearer <token>
2037/// let resp = users_me(state, headers).await;
2038/// ```
2039pub async fn users_me(state: State<ApiState>, headers: HeaderMap) -> impl IntoResponse {
2040    // Delegate to the existing userinfo handler
2041    userinfo(state, headers).await
2042}