Skip to main content

auth_framework/api/
oauth2.rs

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