Skip to main content

auth_framework/api/
oauth2.rs

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