Skip to main content

auth_framework/api/
oauth2.rs

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