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(Debug, Deserialize)]
148pub struct RevokeRequest {
149    pub token: String,
150    #[serde(default)]
151    pub token_type_hint: Option<String>, // "access_token" or "refresh_token"
152}
153
154/// OpenID Connect UserInfo response.
155///
156/// Contains claims about the authenticated user, filtered by the scopes
157/// granted to the access token.
158///
159/// # Example
160/// ```rust
161/// use auth_framework::api::oauth2::UserInfoResponse;
162///
163/// let info = UserInfoResponse {
164///     sub: "user-1".into(),
165///     name: Some("Alice".into()),
166///     email: None,
167///     picture: None,
168///     updated_at: None,
169/// };
170/// assert_eq!(info.sub, "user-1");
171/// ```
172#[derive(Debug, Serialize)]
173pub struct UserInfoResponse {
174    pub sub: String,
175    #[serde(skip_serializing_if = "Option::is_none")]
176    pub name: Option<String>,
177    #[serde(skip_serializing_if = "Option::is_none")]
178    pub email: Option<String>,
179    #[serde(skip_serializing_if = "Option::is_none")]
180    pub picture: Option<String>,
181    #[serde(skip_serializing_if = "Option::is_none")]
182    pub updated_at: Option<i64>,
183}
184
185/// GET /oauth/authorize
186/// OAuth 2.0 authorization endpoint — validates the client and redirect_uri, generates
187/// an authorization code, and redirects the user-agent back to the client (RFC 6749 §4.1.2).
188///
189/// SECURITY: The caller must supply their access token as `Authorization: Bearer <token>`.
190/// The authenticated user's identity is recorded in the authorization code so it can be
191/// used when the client exchanges the code for tokens.  Issuing codes without a verified
192/// user identity would allow any party that knows a valid client_id to obtain tokens.
193pub async fn authorize(
194    State(state): State<ApiState>,
195    headers: HeaderMap,
196    Query(params): Query<AuthorizationRequest>,
197) -> impl IntoResponse {
198    if params.response_type != "code" {
199        let error = OAuthError::new("unsupported_response_type")
200            .description("Only 'code' response type is supported")
201            .maybe_state(params.state);
202        return (StatusCode::BAD_REQUEST, Json(error)).into_response();
203    }
204
205    if params.client_id.is_empty() {
206        let error = OAuthError::new("invalid_request")
207            .description("client_id is required")
208            .maybe_state(params.state);
209        return (StatusCode::BAD_REQUEST, Json(error)).into_response();
210    }
211
212    if params.redirect_uri.is_empty() {
213        let error = OAuthError::new("invalid_request")
214            .description("redirect_uri is required")
215            .maybe_state(params.state);
216        return (StatusCode::BAD_REQUEST, Json(error)).into_response();
217    }
218
219    // SECURITY: Require the resource owner to be authenticated before issuing codes.
220    // The user must supply their Bearer access token.  Without this check, any caller
221    // that knows a registered client_id could obtain a code and exchange it for tokens.
222    let user_id = {
223        let token_str = match extract_bearer_token(&headers) {
224            Some(t) => t,
225            None => {
226                let error = OAuthError::new("unauthorized_client")
227                    .description(
228                        "User authentication required: supply your access token as \
229                         'Authorization: Bearer <token>'",
230                    )
231                    .maybe_state(params.state);
232                return (StatusCode::UNAUTHORIZED, Json(error)).into_response();
233            }
234        };
235        match validate_api_token(&state.auth_framework, &token_str).await {
236            Ok(auth_token) => auth_token.user_id,
237            Err(_) => {
238                let error = OAuthError::new("unauthorized_client")
239                    .description("Invalid or expired user access token")
240                    .maybe_state(params.state);
241                return (StatusCode::UNAUTHORIZED, Json(error)).into_response();
242            }
243        }
244    };
245
246    // SECURITY: Validate client_id and verify the redirect_uri is pre-registered.
247    // Redirecting to an unregistered URI would let an attacker steal the authorization code.
248    let client_key = format!("oauth2_client:{}", params.client_id);
249    match state.auth_framework.storage().get_kv(&client_key).await {
250        Ok(Some(data)) => {
251            let client_data: serde_json::Value = serde_json::from_slice(&data).unwrap_or_default();
252            let registered_uris: Vec<String> = client_data["redirect_uris"]
253                .as_array()
254                .map(|arr| {
255                    arr.iter()
256                        .filter_map(|v| v.as_str().map(String::from))
257                        .collect()
258                })
259                .unwrap_or_default();
260
261            if !registered_uris
262                .iter()
263                .any(|r| redirect_uri_matches(&params.redirect_uri, r))
264            {
265                tracing::warn!(
266                    client_id = %params.client_id,
267                    redirect_uri = %params.redirect_uri,
268                    "OAuth authorize: redirect_uri not registered for client"
269                );
270                let error = OAuthError::new("invalid_request")
271                    .description("redirect_uri is not registered for this client")
272                    .maybe_state(params.state);
273                return (StatusCode::BAD_REQUEST, Json(error)).into_response();
274            }
275
276            // S8: Public clients (no client_secret) MUST provide a PKCE code_challenge.
277            let is_public_client = client_data
278                .get("client_secret")
279                .and_then(|v| v.as_str())
280                .map_or(true, |s| s.is_empty());
281            if is_public_client && params.code_challenge.is_none() {
282                let error = OAuthError::new("invalid_request")
283                    .description("Public clients must use PKCE: code_challenge is required")
284                    .maybe_state(params.state);
285                return (StatusCode::BAD_REQUEST, Json(error)).into_response();
286            }
287        }
288        Ok(None) => {
289            tracing::warn!(client_id = %params.client_id, "OAuth authorize: unknown client_id");
290            let error = OAuthError::new("invalid_client")
291                .description("Unknown client_id")
292                .maybe_state(params.state);
293            return (StatusCode::BAD_REQUEST, Json(error)).into_response();
294        }
295        Err(e) => {
296            tracing::error!(
297                client_id = %params.client_id,
298                error = %e,
299                "OAuth authorize: storage error looking up client"
300            );
301            let error = OAuthError::new("server_error")
302                .description("Authorization server error")
303                .maybe_state(params.state);
304            return (StatusCode::INTERNAL_SERVER_ERROR, Json(error)).into_response();
305        }
306    }
307
308    let auth_code = format!("ac_{}", uuid::Uuid::new_v4().to_string().replace("-", ""));
309
310    // RFC 8707: Validate resource indicators if present.
311    if let Some(ref resources) = params.resource {
312        if let Err(e) =
313            crate::server::oauth::resource_indicators::validate_resource_indicators(resources)
314        {
315            let error = OAuthError::new("invalid_target")
316                .description(e.to_string())
317                .maybe_state(params.state);
318            return (StatusCode::BAD_REQUEST, Json(error)).into_response();
319        }
320    }
321
322    let code_data = serde_json::json!({
323        "client_id": params.client_id,
324        "redirect_uri": params.redirect_uri,
325        "scope": params.scope.clone().unwrap_or_else(|| "openid profile email".to_string()),
326        "state": params.state.clone(),
327        "code_challenge": params.code_challenge,
328        "code_challenge_method": params.code_challenge_method,
329        "user_id": user_id,
330        "resource": params.resource,
331        "created_at": chrono::Utc::now().to_rfc3339(),
332        "expires_at": (chrono::Utc::now() + chrono::Duration::minutes(10)).to_rfc3339(),
333        "used": false,
334    });
335
336    let storage_key = format!("oauth2_code:{}", auth_code);
337    let code_data_str = match serde_json::to_string(&code_data) {
338        Ok(s) => s,
339        Err(e) => {
340            tracing::error!("Failed to serialize OAuth authorization code data: {:?}", e);
341            let error =
342                OAuthError::new("server_error").description("Authorization server internal error");
343            return (StatusCode::INTERNAL_SERVER_ERROR, Json(error)).into_response();
344        }
345    };
346
347    if let Err(e) = state
348        .auth_framework
349        .storage()
350        .store_kv(
351            &storage_key,
352            code_data_str.as_bytes(),
353            Some(std::time::Duration::from_secs(600)),
354        )
355        .await
356    {
357        tracing::error!("Failed to store OAuth authorization code: {:?}", e);
358        let error = OAuthError::new("server_error")
359            .description("Authorization server error")
360            .maybe_state(params.state);
361        return (StatusCode::INTERNAL_SERVER_ERROR, Json(error)).into_response();
362    }
363
364    // SECURITY: URL-encode the state value to prevent parameter injection.
365    // A raw state like "&extra=injected" would append unintended query parameters.
366    let encoded_state: Option<String> = params.state.as_deref().map(|st| {
367        st.bytes()
368            .flat_map(|b| {
369                if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~') {
370                    vec![b as char]
371                } else {
372                    format!("%{:02X}", b).chars().collect()
373                }
374            })
375            .collect()
376    });
377
378    let mut redirect_url = params.redirect_uri;
379    redirect_url.push_str(&format!("?code={}", auth_code));
380    if let Some(ref st) = encoded_state {
381        redirect_url.push_str(&format!("&state={}", st));
382    }
383
384    tracing::info!(
385        client_id = %params.client_id,
386        user_id = %user_id,
387        "OAuth authorization code issued"
388    );
389    Redirect::to(&redirect_url).into_response()
390}
391
392/// POST /oauth/token — exchange an authorization code or refresh token for
393/// an access token (RFC 6749 §4.1.3, §6).
394///
395/// Supported grant types:
396/// - `authorization_code` — requires `code`, `client_id`, and optionally `code_verifier`
397/// - `refresh_token` — requires `refresh_token`
398///
399/// # Example
400/// ```rust,ignore
401/// // POST /oauth/token {"grant_type":"authorization_code","code":"ac_...","client_id":"..."}
402/// let response = token(State(api_state), Json(token_request)).await;
403/// assert!(response.success);
404/// ```
405pub async fn token(
406    State(state): State<ApiState>,
407    Json(req): Json<TokenRequest>,
408) -> ApiResponse<TokenResponse> {
409    match req.grant_type.as_str() {
410        "authorization_code" => handle_authorization_code_grant(state, req).await,
411        "refresh_token" => handle_refresh_token_grant(state, req).await,
412        _ => ApiResponse::error_typed(
413            "unsupported_grant_type",
414            "Supported grant types: authorization_code, refresh_token",
415        ),
416    }
417}
418
419async fn handle_authorization_code_grant(
420    state: ApiState,
421    req: TokenRequest,
422) -> ApiResponse<TokenResponse> {
423    let code = match req.code {
424        Some(c) => c,
425        None => {
426            return ApiResponse::validation_error_typed(
427                "code is required for authorization_code grant",
428            );
429        }
430    };
431
432    let client_id = match req.client_id {
433        Some(c) => c,
434        None => return ApiResponse::validation_error_typed("client_id is required"),
435    };
436
437    // Defense-in-depth: Use a consumed marker to mitigate the non-atomic get+delete
438    // race condition (TOCTOU). If a concurrent request already marked the code as
439    // consumed, reject this request immediately.
440    let consumed_key = format!("oauth2_code_consumed:{}", code);
441    if let Ok(Some(_)) = state.auth_framework.storage().get_kv(&consumed_key).await {
442        return ApiResponse::error_typed("invalid_grant", "Authorization code already used");
443    }
444    // Mark code as consumed BEFORE reading it, narrowing the race window.
445    if let Err(e) = state
446        .auth_framework
447        .storage()
448        .store_kv(
449            &consumed_key,
450            b"1",
451            Some(std::time::Duration::from_secs(600)),
452        )
453        .await
454    {
455        tracing::warn!("Failed to store code consumed marker: {:?}", e);
456    }
457
458    let storage_key = format!("oauth2_code:{}", code);
459    let code_data = match state.auth_framework.storage().get_kv(&storage_key).await {
460        Ok(Some(data)) => match serde_json::from_slice::<serde_json::Value>(&data) {
461            Ok(json) => json,
462            Err(e) => {
463                tracing::error!("Failed to parse stored authorization code data: {:?}", e);
464                return ApiResponse::error_typed("invalid_grant", "Invalid authorization code");
465            }
466        },
467        Ok(None) => {
468            return ApiResponse::error_typed(
469                "invalid_grant",
470                "Authorization code not found or expired",
471            );
472        }
473        Err(e) => {
474            tracing::error!("Failed to retrieve authorization code: {:?}", e);
475            return ApiResponse::error_typed(
476                "server_error",
477                "Failed to validate authorization code",
478            );
479        }
480    };
481
482    // Immediately delete the code to prevent reuse (single-use enforcement).
483    if let Err(e) = state.auth_framework.storage().delete_kv(&storage_key).await {
484        tracing::error!("Failed to delete authorization code from storage: {:?}", e);
485        return ApiResponse::error_typed("server_error", "Failed to process authorization code");
486    }
487
488    // Validate client_id matches
489    if code_data["client_id"].as_str() != Some(&client_id) {
490        return ApiResponse::error_typed("invalid_grant", "client_id mismatch");
491    }
492
493    // Validate redirect_uri if provided
494    if let Some(redirect_uri) = &req.redirect_uri {
495        let stored_uri = code_data["redirect_uri"].as_str().unwrap_or_default();
496        if !redirect_uri_matches(redirect_uri, stored_uri) {
497            return ApiResponse::error_typed("invalid_grant", "redirect_uri mismatch");
498        }
499    }
500
501    // Check if PKCE was used in authorization - if so, code_verifier is required
502    let stored_challenge = code_data["code_challenge"].as_str();
503    let challenge_method = code_data["code_challenge_method"]
504        .as_str()
505        .unwrap_or("plain");
506
507    if let Some(stored) = stored_challenge {
508        // PKCE was used in authorization, so code_verifier is required
509        let code_verifier = match &req.code_verifier {
510            Some(verifier) => verifier,
511            None => {
512                return ApiResponse::error_typed(
513                    "invalid_request",
514                    "code_verifier is required when PKCE challenge was provided",
515                );
516            }
517        };
518
519        let computed_challenge = match challenge_method {
520            "S256" => {
521                let mut hasher = Sha256::new();
522                hasher.update(code_verifier.as_bytes());
523                URL_SAFE_NO_PAD.encode(hasher.finalize())
524            }
525            "plain" => code_verifier.clone(),
526            _ => {
527                return ApiResponse::error_typed(
528                    "invalid_request",
529                    "Unsupported code_challenge_method",
530                );
531            }
532        };
533
534        if computed_challenge != stored {
535            return ApiResponse::error_typed("invalid_grant", "PKCE verification failed");
536        }
537    } else if req.code_verifier.is_some() {
538        // code_verifier provided but no challenge was used - this is suspicious
539        return ApiResponse::error_typed(
540            "invalid_request",
541            "code_verifier provided but no PKCE challenge was used in authorization",
542        );
543    } else if req.client_secret.is_none() {
544        // S8: Public clients (no client_secret) MUST use PKCE.
545        // If no code_challenge was stored and no client_secret is provided,
546        // the request is from an unauthenticated public client without PKCE.
547        return ApiResponse::error_typed(
548            "invalid_request",
549            "Public clients must use PKCE: provide code_challenge in authorization and code_verifier in token request",
550        );
551    }
552
553    // Code was already atomically deleted above (delete-first approach).
554    // No need to mark as used — the code is permanently consumed.
555
556    // RFC 8707: Validate resource indicators on the token request.
557    let authz_resources: Vec<String> = code_data["resource"]
558        .as_array()
559        .map(|arr| {
560            arr.iter()
561                .filter_map(|v| v.as_str().map(String::from))
562                .collect()
563        })
564        .unwrap_or_default();
565
566    if let Some(ref token_resources) = req.resource {
567        if let Err(e) =
568            crate::server::oauth::resource_indicators::validate_resource_indicators(token_resources)
569        {
570            return ApiResponse::error_typed("invalid_target", &e.to_string());
571        }
572        if let Err(e) = crate::server::oauth::resource_indicators::validate_token_resource_subset(
573            token_resources,
574            &authz_resources,
575        ) {
576            return ApiResponse::error_typed("invalid_target", &e.to_string());
577        }
578    }
579
580    // Create access and refresh tokens
581    let scope = code_data["scope"]
582        .as_str()
583        .unwrap_or("openid profile email");
584    let scopes: Vec<String> = scope.split_whitespace().map(|s| s.to_string()).collect();
585
586    // Use the user_id that was recorded in the authorization code when the resource owner
587    // authenticated via the /oauth/authorize endpoint.  This ensures tokens are bound to the
588    // actual user rather than a fabricated identifier derived from the client_id.
589    let user_id = match code_data["user_id"].as_str() {
590        Some(uid) if !uid.is_empty() => uid.to_string(),
591        _ => {
592            tracing::error!("Authorization code missing user_id field");
593            return ApiResponse::error_typed("server_error", "Malformed authorization code");
594        }
595    };
596
597    let token = match state.auth_framework.token_manager().create_auth_token(
598        &user_id,
599        scopes.clone(),
600        "oauth2",
601        None,
602    ) {
603        Ok(token) => token,
604        Err(e) => {
605            tracing::error!("Failed to create access token: {:?}", e);
606            return ApiResponse::error_typed("server_error", "Failed to create access token");
607        }
608    };
609
610    // Persist a storage-backed refresh token so the refresh grant can validate and rotate it.
611    let refresh_token_value = uuid::Uuid::new_v4().to_string().replace("-", "");
612    let refresh_data = serde_json::json!({
613        "user_id": user_id,
614        "client_id": client_id,
615        "scopes": scope,
616    });
617    let refresh_key = format!("oauth2_refresh_token:{}", refresh_token_value);
618    if let Err(e) = state
619        .auth_framework
620        .storage()
621        .store_kv(
622            &refresh_key,
623            serde_json::to_string(&refresh_data)
624                .unwrap_or_default()
625                .as_bytes(),
626            Some(std::time::Duration::from_secs(30 * 24 * 3600)),
627        )
628        .await
629    {
630        tracing::warn!("Failed to store refresh token: {:?}", e);
631    }
632
633    let expires_in = (token.expires_at - token.issued_at).num_seconds().max(0) as u64;
634    let response = TokenResponse {
635        access_token: token.access_token,
636        token_type: "Bearer".to_string(),
637        expires_in,
638        refresh_token: Some(refresh_token_value),
639        scope: Some(scope.to_string()),
640        id_token: None,
641    };
642
643    tracing::info!("OAuth2 tokens issued for client: {}", client_id);
644    ApiResponse::success(response)
645}
646
647async fn handle_refresh_token_grant(
648    state: ApiState,
649    req: TokenRequest,
650) -> ApiResponse<TokenResponse> {
651    let refresh_token_str = match req.refresh_token {
652        Some(t) => t,
653        None => return ApiResponse::validation_error_typed("refresh_token is required"),
654    };
655
656    // Defense-in-depth: Use a consumed marker to mitigate the non-atomic get+delete
657    // race condition. If a concurrent request already consumed this refresh token, reject.
658    let consumed_key = format!("oauth2_refresh_consumed:{}", refresh_token_str);
659    if let Ok(Some(_)) = state.auth_framework.storage().get_kv(&consumed_key).await {
660        return ApiResponse::error_typed("invalid_grant", "Refresh token already consumed");
661    }
662    if let Err(e) = state
663        .auth_framework
664        .storage()
665        .store_kv(
666            &consumed_key,
667            b"1",
668            Some(std::time::Duration::from_secs(600)),
669        )
670        .await
671    {
672        tracing::warn!("Failed to store refresh consumed marker: {:?}", e);
673    }
674
675    // Validate the refresh token against persistent storage.
676    let refresh_key = format!("oauth2_refresh_token:{}", refresh_token_str);
677    let stored = match state.auth_framework.storage().get_kv(&refresh_key).await {
678        Ok(Some(data)) => match serde_json::from_slice::<serde_json::Value>(&data) {
679            Ok(v) => v,
680            Err(_) => return ApiResponse::error_typed("invalid_grant", "Invalid refresh token"),
681        },
682        Ok(None) => {
683            return ApiResponse::error_typed("invalid_grant", "Refresh token not found or expired");
684        }
685        Err(e) => {
686            tracing::error!("Failed to retrieve refresh token: {:?}", e);
687            return ApiResponse::error_typed("server_error", "Failed to validate refresh token");
688        }
689    };
690
691    let user_id = match stored["user_id"].as_str() {
692        Some(u) => u.to_string(),
693        None => return ApiResponse::error_typed("invalid_grant", "Malformed refresh token data"),
694    };
695    let scope = stored["scopes"]
696        .as_str()
697        .unwrap_or("openid profile email")
698        .to_string();
699    let scopes: Vec<String> = scope.split_whitespace().map(|s| s.to_string()).collect();
700
701    let token = match state
702        .auth_framework
703        .token_manager()
704        .create_auth_token(&user_id, scopes, "oauth2", None)
705    {
706        Ok(t) => t,
707        Err(e) => {
708            tracing::error!("Failed to create access token on refresh: {:?}", e);
709            return ApiResponse::error_typed("server_error", "Failed to issue access token");
710        }
711    };
712
713    // Issue a new refresh token (rotation).
714    // Store the new token BEFORE deleting the old one to avoid data loss on failure.
715    let new_refresh_token = uuid::Uuid::new_v4().to_string().replace("-", "");
716    let new_refresh_data = serde_json::json!({ "user_id": user_id, "scopes": scope });
717    let new_refresh_key = format!("oauth2_refresh_token:{}", new_refresh_token);
718    if let Err(e) = state
719        .auth_framework
720        .storage()
721        .store_kv(
722            &new_refresh_key,
723            serde_json::to_string(&new_refresh_data)
724                .unwrap_or_default()
725                .as_bytes(),
726            Some(std::time::Duration::from_secs(30 * 24 * 3600)),
727        )
728        .await
729    {
730        tracing::error!("Failed to store new refresh token: {:?}", e);
731        return ApiResponse::error_typed("server_error", "Failed to issue refresh token");
732    }
733
734    // Now that the new token is safely stored, delete the old one (single-use enforcement).
735    if let Err(e) = state.auth_framework.storage().delete_kv(&refresh_key).await {
736        tracing::warn!(
737            "Failed to delete old refresh token during rotation: {:?}",
738            e
739        );
740    }
741
742    let expires_in = (token.expires_at - token.issued_at).num_seconds().max(0) as u64;
743    let response = TokenResponse {
744        access_token: token.access_token,
745        token_type: "Bearer".to_string(),
746        expires_in,
747        refresh_token: Some(new_refresh_token),
748        scope: Some(scope),
749        id_token: None,
750    };
751
752    tracing::info!("OAuth2 token refreshed for user: {}", user_id);
753    ApiResponse::success(response)
754}
755
756/// POST /api/v1/oauth/revoke — revoke an access or refresh token.
757///
758/// Stores a revocation marker in KV (`oauth2_revoked_token:{token}`) and,
759/// for JWT tokens, also stores a JTI-based marker (`revoked_token:{jti}`)
760/// so that all authenticated endpoints reject the token immediately.
761///
762/// # Example
763/// ```rust,ignore
764/// let resp = revoke(State(state), Json(RevokeRequest {
765///     token: "access_token_value".into(),
766///     token_type_hint: Some("access_token".into()),
767/// })).await;
768/// assert!(resp.success);
769/// ```
770pub async fn revoke(
771    State(state): State<ApiState>,
772    Json(req): Json<RevokeRequest>,
773) -> ApiResponse<serde_json::Value> {
774    // Store the revoked token in a blacklist for immediate invalidation.
775    // Key by the raw token value so the userinfo endpoint can check it too.
776    let revoked_token_key = format!("oauth2_revoked_token:{}", req.token);
777    let revoked_data = serde_json::json!({
778        "token": req.token,
779        "revoked_at": chrono::Utc::now().to_rfc3339(),
780        "token_type_hint": req.token_type_hint
781    });
782
783    if let Err(e) = state
784        .auth_framework
785        .storage()
786        .store_kv(
787            &revoked_token_key,
788            serde_json::to_string(&revoked_data)
789                .unwrap_or_default()
790                .as_bytes(),
791            Some(std::time::Duration::from_secs(86400 * 7)),
792        )
793        .await
794    {
795        tracing::error!("Failed to store revoked token: {:?}", e);
796        return ApiResponse::error_typed("server_error", "Failed to revoke token");
797    }
798
799    // If the token is a JWT, also store revoked_token:{jti} so the authentication
800    // middleware (validate_api_token in api/mod.rs) blocks it on all protected
801    // endpoints. Without this step, the revocation would only be visible to the
802    // userinfo endpoint, leaving all other authenticated routes unprotected.
803    if let Ok(claims) = state
804        .auth_framework
805        .token_manager()
806        .validate_jwt_token(&req.token)
807    {
808        let now = chrono::Utc::now().timestamp();
809        let remaining_secs = (claims.exp - now + 60).max(60) as u64;
810        let jti_key = format!("revoked_token:{}", claims.jti);
811        if let Err(e) = state
812            .auth_framework
813            .storage()
814            .store_kv(
815                &jti_key,
816                b"1",
817                Some(std::time::Duration::from_secs(remaining_secs)),
818            )
819            .await
820        {
821            tracing::warn!("Failed to store JWT JTI revocation entry: {:?}", e);
822        } else {
823            tracing::info!("JWT token revoked via jti: {}", claims.jti);
824        }
825    }
826
827    tracing::info!(
828        "OAuth2 token revoked: {}",
829        &req.token[..10.min(req.token.len())]
830    );
831
832    ApiResponse::success(serde_json::json!({
833        "message": "Token revoked successfully"
834    }))
835}
836
837/// GET /api/v1/oauth/userinfo — return claims about the authenticated user.
838///
839/// The caller must supply a valid Bearer access token. If the token has been
840/// revoked, an `invalid_token` error is returned. Email is included only
841/// when the `email` scope is present in the token.
842///
843/// # Example
844/// ```rust,ignore
845/// // GET /api/v1/oauth/userinfo  Authorization: Bearer <token>
846/// let resp = userinfo(State(state), headers).await;
847/// assert_eq!(resp.data.unwrap().sub, "user-1");
848/// ```
849pub async fn userinfo(
850    State(state): State<ApiState>,
851    headers: HeaderMap,
852) -> ApiResponse<UserInfoResponse> {
853    // Extract and validate access token
854    let token = match extract_bearer_token(&headers) {
855        Some(t) => t,
856        None => {
857            return ApiResponse::error_typed("invalid_token", "Authorization header required");
858        }
859    };
860
861    // Check if token is revoked first
862    let revoked_token_key = format!("oauth2_revoked_token:{}", token);
863    if let Ok(Some(_)) = state
864        .auth_framework
865        .storage()
866        .get_kv(&revoked_token_key)
867        .await
868    {
869        return ApiResponse::error_typed("invalid_token", "Token has been revoked");
870    }
871
872    // Validate the access token
873    let claims = match state
874        .auth_framework
875        .token_manager()
876        .validate_jwt_token(&token)
877    {
878        Ok(c) => c,
879        Err(_) => {
880            return ApiResponse::error_typed("invalid_token", "Access token is invalid");
881        }
882    };
883
884    // Get user profile
885    let user_profile = match state.auth_framework.get_user_profile(&claims.sub).await {
886        Ok(profile) => profile,
887        Err(e) => {
888            tracing::error!("Failed to get user profile: {:?}", e);
889            return ApiResponse::error_typed("server_error", "Failed to retrieve user information");
890        }
891    };
892
893    let userinfo = UserInfoResponse {
894        sub: claims.sub.clone(),
895        name: user_profile.username.clone(),
896        // Only include email if the token's scopes include "email"
897        email: if claims.scope.split_whitespace().any(|s| s == "email") {
898            user_profile.email.clone()
899        } else {
900            None
901        },
902        picture: user_profile.picture.clone(),
903        updated_at: Some(chrono::Utc::now().timestamp()),
904    };
905
906    tracing::info!("OAuth2 UserInfo requested for user: {}", claims.sub);
907    ApiResponse::success(userinfo)
908}
909
910/// GET /oauth/clients/{client_id} — return the stored metadata for a
911/// registered OAuth 2.0 client.
912///
913/// # Example
914/// ```rust,ignore
915/// let resp = get_client_info(State(state), Path("my-client-id".into())).await;
916/// ```
917pub async fn get_client_info(
918    State(state): State<ApiState>,
919    Path(client_id): Path<String>,
920) -> impl IntoResponse {
921    let client_key = format!("oauth2_client:{}", client_id);
922    match state.auth_framework.storage().get_kv(&client_key).await {
923        Ok(Some(data)) => match serde_json::from_slice::<ClientInfo>(&data) {
924            Ok(client) => (
925                StatusCode::OK,
926                Json(serde_json::json!({ "success": true, "data": client })),
927            )
928                .into_response(),
929            Err(e) => {
930                tracing::error!(client_id = %client_id, error = %e, "Failed to deserialize client record");
931                (
932                    StatusCode::INTERNAL_SERVER_ERROR,
933                    Json(serde_json::json!({
934                        "success": false,
935                        "error": "server_error",
936                        "message": "Failed to read client record"
937                    })),
938                )
939                    .into_response()
940            }
941        },
942        Ok(None) => (
943            StatusCode::NOT_FOUND,
944            Json(serde_json::json!({
945                "success": false,
946                "error": "invalid_client",
947                "message": "Unknown client_id"
948            })),
949        )
950            .into_response(),
951        Err(e) => {
952            tracing::error!(client_id = %client_id, error = %e, "Storage error looking up client");
953            (
954                StatusCode::INTERNAL_SERVER_ERROR,
955                Json(serde_json::json!({
956                    "success": false,
957                    "error": "server_error",
958                    "message": "Authorization server error"
959                })),
960            )
961                .into_response()
962        }
963    }
964}
965
966// ---------------------------------------------------------------------------
967// OpenID Connect Discovery (RFC 8414 / OpenID Connect Discovery 1.0)
968// ---------------------------------------------------------------------------
969
970/// OpenID Connect Discovery endpoint (RFC 8414 / OpenID Connect Discovery 1.0).
971///
972/// Returns server authorization metadata so clients can auto-configure
973/// (issuer, endpoints, supported grants, signing algorithms, etc.).
974///
975/// # Example
976/// ```rust,ignore
977/// // GET /.well-known/openid-configuration
978/// let (status, Json(config)) = openid_configuration(State(state)).await;
979/// assert_eq!(status, StatusCode::OK);
980/// ```
981pub async fn openid_configuration(State(state): State<ApiState>) -> impl IntoResponse {
982    let issuer = {
983        let configured = state.auth_framework.config().issuer.clone();
984        if configured.is_empty() {
985            "https://auth.example.com".to_string()
986        } else {
987            configured
988        }
989    };
990
991    let config = serde_json::json!({
992        "issuer": issuer,
993        "authorization_endpoint": format!("{}/api/v1/oauth/authorize", issuer),
994        "token_endpoint": format!("{}/api/v1/oauth/token", issuer),
995        "userinfo_endpoint": format!("{}/api/v1/oauth/userinfo", issuer),
996        "revocation_endpoint": format!("{}/api/v1/oauth/revoke", issuer),
997        "introspection_endpoint": format!("{}/api/v1/oauth/introspect", issuer),
998        "jwks_uri": format!("{}/api/v1/.well-known/jwks.json", issuer),
999        "end_session_endpoint": format!("{}/api/v1/oauth/end_session", issuer),
1000        "pushed_authorization_request_endpoint": format!("{}/api/v1/oauth/par", issuer),
1001        "registration_endpoint": format!("{}/api/v1/oauth/register", issuer),
1002        "response_types_supported": ["code"],
1003        "grant_types_supported": [
1004            "authorization_code",
1005            "refresh_token"
1006        ],
1007        "subject_types_supported": ["public"],
1008        "id_token_signing_alg_values_supported": ["HS256"],
1009        "token_endpoint_auth_methods_supported": [
1010            "client_secret_basic",
1011            "client_secret_post"
1012        ],
1013        "code_challenge_methods_supported": ["S256"],
1014        "scopes_supported": ["openid", "profile", "email"]
1015    });
1016
1017    (StatusCode::OK, Json(config))
1018}
1019
1020// ---------------------------------------------------------------------------
1021// JWKS endpoint (RFC 7517)
1022// ---------------------------------------------------------------------------
1023
1024/// JSON Web Key Set (JWKS) endpoint ([RFC 7517](https://datatracker.ietf.org/doc/html/rfc7517)).
1025///
1026/// Returns the public keys used to verify tokens. Currently returns an
1027/// empty key set because HS256 (symmetric) signing is used; clients
1028/// should use the introspection endpoint for token validation.
1029///
1030/// # Example
1031/// ```rust,ignore
1032/// // GET /.well-known/jwks.json
1033/// let (status, Json(jwks)) = jwks(State(state)).await;
1034/// assert!(jwks["keys"].as_array().unwrap().is_empty());
1035/// ```
1036pub async fn jwks(State(_state): State<ApiState>) -> impl IntoResponse {
1037    (StatusCode::OK, Json(serde_json::json!({ "keys": [] })))
1038}
1039
1040// ---------------------------------------------------------------------------
1041// OIDC RP-Initiated Logout (OpenID Connect RP-Initiated Logout 1.0)
1042// ---------------------------------------------------------------------------
1043
1044/// Request parameters for OpenID Connect RP-Initiated Logout.
1045///
1046/// # Example
1047/// ```rust
1048/// use auth_framework::api::oauth2::EndSessionRequest;
1049///
1050/// let req: EndSessionRequest = serde_json::from_str(
1051///     r#"{"id_token_hint":"eyJ...","state":"xyz"}"#
1052/// ).unwrap();
1053/// assert!(req.post_logout_redirect_uri.is_none());
1054/// ```
1055#[derive(Debug, Deserialize)]
1056pub struct EndSessionRequest {
1057    pub id_token_hint: Option<String>,
1058    pub post_logout_redirect_uri: Option<String>,
1059    pub state: Option<String>,
1060}
1061
1062/// OIDC RP-Initiated Logout (OpenID Connect RP-Initiated Logout 1.0).
1063///
1064/// Revokes the token from `id_token_hint` (if valid) and, when a
1065/// registered `post_logout_redirect_uri` is provided, redirects the
1066/// user-agent there.
1067///
1068/// # Example
1069/// ```rust,ignore
1070/// // GET /oauth/end_session?id_token_hint=eyJ...&state=xyz
1071/// let resp = end_session(State(state), Query(params)).await;
1072/// ```
1073pub async fn end_session(
1074    State(state): State<ApiState>,
1075    Query(params): Query<EndSessionRequest>,
1076) -> impl IntoResponse {
1077    // If an id_token_hint is provided, revoke it
1078    if let Some(ref token) = params.id_token_hint {
1079        if let Ok(claims) = state
1080            .auth_framework
1081            .token_manager()
1082            .validate_jwt_token(token)
1083        {
1084            let revoked_key = format!("oauth2_revoked_token:{}", token);
1085            if let Err(e) = state
1086                .auth_framework
1087                .storage()
1088                .store_kv(
1089                    &revoked_key,
1090                    b"revoked",
1091                    Some(std::time::Duration::from_secs(86400 * 7)),
1092                )
1093                .await
1094            {
1095                tracing::warn!("Failed to revoke token during OIDC end_session: {}", e);
1096            }
1097            tracing::info!("OIDC end_session: revoked token for user {}", claims.sub);
1098        }
1099    }
1100
1101    // Redirect to post_logout_redirect_uri only if it matches a registered URI for the
1102    // client identified by id_token_hint.  Without this check an attacker could craft a
1103    // link that redirects users to an arbitrary URL (open redirect / phishing).
1104    if let Some(ref redirect_uri) = params.post_logout_redirect_uri {
1105        // Look up the client's registered redirect URIs via the id_token_hint's `azp` or `aud` claim.
1106        let allowed = if let Some(ref token) = params.id_token_hint {
1107            // Try to extract client_id from the token (azp > aud)
1108            let client_id = state
1109                .auth_framework
1110                .token_manager()
1111                .validate_jwt_token(token)
1112                .ok()
1113                .and_then(|claims| {
1114                    // client_id claim identifies the OAuth client
1115                    if let Some(ref cid) = claims.client_id {
1116                        if !cid.is_empty() {
1117                            return Some(cid.clone());
1118                        }
1119                    }
1120                    // Fallback: aud may contain the client_id
1121                    if !claims.aud.is_empty() {
1122                        Some(claims.aud.clone())
1123                    } else {
1124                        None
1125                    }
1126                });
1127            if let Some(cid) = client_id {
1128                let client_key = format!("oauth2_client:{}", cid);
1129                match state.auth_framework.storage().get_kv(&client_key).await {
1130                    Ok(Some(data)) => {
1131                        let client: serde_json::Value =
1132                            serde_json::from_slice(&data).unwrap_or_default();
1133                        let uris: Vec<String> = client["redirect_uris"]
1134                            .as_array()
1135                            .map(|a| {
1136                                a.iter()
1137                                    .filter_map(|v| v.as_str().map(String::from))
1138                                    .collect()
1139                            })
1140                            .unwrap_or_default();
1141                        uris.iter().any(|r| redirect_uri_matches(redirect_uri, r))
1142                    }
1143                    _ => false,
1144                }
1145            } else {
1146                false
1147            }
1148        } else {
1149            false
1150        };
1151
1152        if allowed {
1153            if let Ok(mut parsed) = Url::parse(redirect_uri) {
1154                if let Some(ref st) = params.state {
1155                    parsed.query_pairs_mut().append_pair("state", st);
1156                }
1157                return Redirect::to(parsed.as_str()).into_response();
1158            }
1159        } else {
1160            tracing::warn!(
1161                "end_session: post_logout_redirect_uri rejected — not registered for the client"
1162            );
1163        }
1164    }
1165
1166    // No redirect — return a simple JSON acknowledgement
1167    (
1168        StatusCode::OK,
1169        Json(serde_json::json!({ "status": "logged_out" })),
1170    )
1171        .into_response()
1172}
1173
1174// ---------------------------------------------------------------------------
1175// Dynamic Client Registration (RFC 7591)
1176// ---------------------------------------------------------------------------
1177
1178/// Dynamic client registration request per [RFC 7591](https://datatracker.ietf.org/doc/html/rfc7591).
1179///
1180/// # Example
1181/// ```rust
1182/// use auth_framework::api::oauth2::ClientRegistrationRequest;
1183///
1184/// let req: ClientRegistrationRequest = serde_json::from_str(
1185///     r#"{"redirect_uris":["https://example.com/cb"]}"#
1186/// ).unwrap();
1187/// assert_eq!(req.redirect_uris.len(), 1);
1188/// ```
1189#[derive(Debug, Deserialize)]
1190pub struct ClientRegistrationRequest {
1191    pub redirect_uris: Vec<String>,
1192    #[serde(default)]
1193    pub client_name: Option<String>,
1194    #[serde(default)]
1195    pub token_endpoint_auth_method: Option<String>,
1196    #[serde(default)]
1197    pub grant_types: Option<Vec<String>>,
1198    #[serde(default)]
1199    pub response_types: Option<Vec<String>>,
1200    #[serde(default)]
1201    pub scope: Option<String>,
1202}
1203
1204/// POST /oauth/register — dynamically register a new OAuth 2.0 client
1205/// ([RFC 7591](https://datatracker.ietf.org/doc/html/rfc7591)).
1206///
1207/// Requires a valid Bearer token with `admin` role, or an Initial Access
1208/// Token stored in KV at `oauth2_initial_access_token`. Unauthenticated
1209/// callers are rejected to prevent resource exhaustion.
1210///
1211/// # Example
1212/// ```rust,ignore
1213/// let resp = register_client(
1214///     State(state),
1215///     headers,   // with Authorization: Bearer <admin-token>
1216///     Json(ClientRegistrationRequest {
1217///         redirect_uris: vec!["https://example.com/cb".into()],
1218///         client_name: Some("My App".into()),
1219///         ..Default::default()
1220///     }),
1221/// ).await;
1222/// ```
1223pub async fn register_client(
1224    State(state): State<ApiState>,
1225    headers: HeaderMap,
1226    Json(req): Json<ClientRegistrationRequest>,
1227) -> impl IntoResponse {
1228    // RFC 7591 §1.2: require authentication via Bearer token
1229    let token_str = match extract_bearer_token(&headers) {
1230        Some(t) => t,
1231        None => {
1232            return (
1233                StatusCode::UNAUTHORIZED,
1234                Json(serde_json::json!({
1235                    "error": "invalid_token",
1236                    "error_description": "A valid Bearer token is required for dynamic client registration"
1237                })),
1238            )
1239                .into_response();
1240        }
1241    };
1242
1243    // Option 1: check if this is the pre-configured Initial Access Token
1244    let is_initial_access_token = match state
1245        .auth_framework
1246        .storage()
1247        .get_kv("oauth2_initial_access_token")
1248        .await
1249    {
1250        Ok(Some(stored)) => {
1251            let stored_str = String::from_utf8_lossy(&stored);
1252            subtle::ConstantTimeEq::ct_eq(token_str.as_bytes(), stored_str.trim().as_bytes()).into()
1253        }
1254        _ => false,
1255    };
1256
1257    // Option 2: validate as a normal JWT and check for admin role
1258    let is_admin = if !is_initial_access_token {
1259        match validate_api_token(&state.auth_framework, &token_str).await {
1260            Ok(auth_token) => auth_token.roles.contains(&"admin".to_string()),
1261            Err(_) => false,
1262        }
1263    } else {
1264        false
1265    };
1266
1267    if !is_initial_access_token && !is_admin {
1268        return (
1269            StatusCode::FORBIDDEN,
1270            Json(serde_json::json!({
1271                "error": "insufficient_scope",
1272                "error_description": "Dynamic client registration requires admin privileges or a valid Initial Access Token"
1273            })),
1274        )
1275            .into_response();
1276    }
1277    // Validate all redirect_uris are well-formed URLs with safe schemes
1278    for uri in &req.redirect_uris {
1279        match Url::parse(uri) {
1280            Ok(parsed) => {
1281                match parsed.scheme() {
1282                    "https" => {}
1283                    "http" => {
1284                        // Allow plain HTTP only for loopback addresses (development)
1285                        if !matches!(parsed.host_str(), Some("localhost" | "127.0.0.1" | "[::1]")) {
1286                            return (
1287                                StatusCode::BAD_REQUEST,
1288                                Json(serde_json::json!({
1289                                    "error": "invalid_redirect_uri",
1290                                    "error_description": format!("Non-loopback HTTP redirect_uri not allowed: {}", uri)
1291                                })),
1292                            )
1293                                .into_response();
1294                        }
1295                    }
1296                    scheme => {
1297                        return (
1298                            StatusCode::BAD_REQUEST,
1299                            Json(serde_json::json!({
1300                                "error": "invalid_redirect_uri",
1301                                "error_description": format!("Disallowed URI scheme '{}' in redirect_uri: {}", scheme, uri)
1302                            })),
1303                        )
1304                            .into_response();
1305                    }
1306                }
1307            }
1308            Err(_) => {
1309                return (
1310                    StatusCode::BAD_REQUEST,
1311                    Json(serde_json::json!({
1312                        "error": "invalid_redirect_uri",
1313                        "error_description": format!("Invalid redirect_uri: {}", uri)
1314                    })),
1315                )
1316                    .into_response();
1317            }
1318        }
1319    }
1320
1321    if req.redirect_uris.is_empty() {
1322        return (
1323            StatusCode::BAD_REQUEST,
1324            Json(serde_json::json!({
1325                "error": "invalid_client_metadata",
1326                "error_description": "At least one redirect_uri is required"
1327            })),
1328        )
1329            .into_response();
1330    }
1331
1332    let client_id = Uuid::new_v4().to_string();
1333    let client_secret = Uuid::new_v4().to_string();
1334
1335    let client_data = serde_json::json!({
1336        "client_id": client_id,
1337        "client_secret": client_secret,
1338        "client_name": req.client_name,
1339        "redirect_uris": req.redirect_uris,
1340        "token_endpoint_auth_method": req.token_endpoint_auth_method.as_deref().unwrap_or("client_secret_basic"),
1341        "grant_types": req.grant_types.as_deref().unwrap_or(&["authorization_code".to_string()]),
1342        "response_types": req.response_types.as_deref().unwrap_or(&["code".to_string()]),
1343        "scope": req.scope.as_deref().unwrap_or("openid"),
1344    });
1345
1346    let key = format!("oauth2_client:{}", client_id);
1347    if let Err(e) = state
1348        .auth_framework
1349        .storage()
1350        .store_kv(&key, client_data.to_string().as_bytes(), None)
1351        .await
1352    {
1353        tracing::error!("Failed to store client registration: {}", e);
1354        return (
1355            StatusCode::INTERNAL_SERVER_ERROR,
1356            Json(serde_json::json!({
1357                "error": "server_error",
1358                "error_description": "Failed to register client"
1359            })),
1360        )
1361            .into_response();
1362    }
1363
1364    tracing::info!("Dynamic client registered: client_id={}", client_id);
1365
1366    (
1367        StatusCode::CREATED,
1368        Json(serde_json::json!({
1369            "client_id": client_id,
1370            "client_secret": client_secret,
1371            "client_name": req.client_name,
1372            "redirect_uris": req.redirect_uris,
1373            "token_endpoint_auth_method": req.token_endpoint_auth_method.as_deref().unwrap_or("client_secret_basic"),
1374            "grant_types": req.grant_types.as_deref().unwrap_or(&["authorization_code".to_string()]),
1375            "response_types": req.response_types.as_deref().unwrap_or(&["code".to_string()]),
1376            "scope": req.scope.as_deref().unwrap_or("openid"),
1377        })),
1378    )
1379        .into_response()
1380}
1381
1382// ---------------------------------------------------------------------------
1383// /users/me — alias for the authenticated user's profile
1384// ---------------------------------------------------------------------------
1385
1386/// GET /users/me — returns the authenticated user's profile.
1387///
1388/// Convenience alias that delegates to [`userinfo`].
1389///
1390/// # Example
1391/// ```rust,ignore
1392/// // GET /users/me  Authorization: Bearer <token>
1393/// let resp = users_me(state, headers).await;
1394/// ```
1395pub async fn users_me(state: State<ApiState>, headers: HeaderMap) -> impl IntoResponse {
1396    // Delegate to the existing userinfo handler
1397    userinfo(state, headers).await
1398}