Skip to main content

auth_framework/api/
oauth2.rs

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