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