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    // Defense-in-depth: Use a consumed marker to mitigate the non-atomic get+delete
462    // race condition (TOCTOU). If a concurrent request already marked the code as
463    // consumed, reject this request immediately.
464    let consumed_key = format!("oauth2_code_consumed:{}", code);
465    if let Ok(Some(_)) = state.auth_framework.storage().get_kv(&consumed_key).await {
466        return ApiResponse::error_typed("invalid_grant", "Authorization code already used");
467    }
468    // Mark code as consumed BEFORE reading it, narrowing the race window.
469    if let Err(e) = state
470        .auth_framework
471        .storage()
472        .store_kv(
473            &consumed_key,
474            b"1",
475            Some(std::time::Duration::from_secs(600)),
476        )
477        .await
478    {
479        tracing::warn!("Failed to store code consumed marker: {:?}", e);
480    }
481
482    let storage_key = format!("oauth2_code:{}", code);
483    let code_data = match state.auth_framework.storage().get_kv(&storage_key).await {
484        Ok(Some(data)) => match serde_json::from_slice::<serde_json::Value>(&data) {
485            Ok(json) => json,
486            Err(e) => {
487                tracing::error!("Failed to parse stored authorization code data: {:?}", e);
488                return ApiResponse::error_typed("invalid_grant", "Invalid authorization code");
489            }
490        },
491        Ok(None) => {
492            return ApiResponse::error_typed(
493                "invalid_grant",
494                "Authorization code not found or expired",
495            );
496        }
497        Err(e) => {
498            tracing::error!("Failed to retrieve authorization code: {:?}", e);
499            return ApiResponse::error_typed(
500                "server_error",
501                "Failed to validate authorization code",
502            );
503        }
504    };
505
506    // A code issued to a different client is refused and left intact (with its
507    // consumed marker released), so presenting someone else's code cannot burn it.
508    if code_data["client_id"].as_str() != Some(&client_id) {
509        if let Err(e) = state
510            .auth_framework
511            .storage()
512            .delete_kv(&consumed_key)
513            .await
514        {
515            tracing::warn!("Failed to release code consumed marker: {:?}", e);
516        }
517        return ApiResponse::error_typed("invalid_grant", "client_id mismatch");
518    }
519
520    // Immediately delete the code to prevent reuse (single-use enforcement).
521    if let Err(e) = state.auth_framework.storage().delete_kv(&storage_key).await {
522        tracing::error!("Failed to delete authorization code from storage: {:?}", e);
523        return ApiResponse::error_typed("server_error", "Failed to process authorization code");
524    }
525
526    // Validate redirect_uri if provided
527    if let Some(redirect_uri) = &req.redirect_uri {
528        let stored_uri = code_data["redirect_uri"].as_str().unwrap_or_default();
529        if !redirect_uri_matches(redirect_uri, stored_uri) {
530            return ApiResponse::error_typed("invalid_grant", "redirect_uri mismatch");
531        }
532    }
533
534    // Check if PKCE was used in authorization - if so, code_verifier is required
535    let stored_challenge = code_data["code_challenge"].as_str();
536    let challenge_method = code_data["code_challenge_method"]
537        .as_str()
538        .unwrap_or("plain");
539
540    if let Some(stored) = stored_challenge {
541        // PKCE was used in authorization, so code_verifier is required
542        let code_verifier = match &req.code_verifier {
543            Some(verifier) => verifier,
544            None => {
545                return ApiResponse::error_typed(
546                    "invalid_request",
547                    "code_verifier is required when PKCE challenge was provided",
548                );
549            }
550        };
551
552        let computed_challenge = match challenge_method {
553            "S256" => {
554                let mut hasher = Sha256::new();
555                hasher.update(code_verifier.as_bytes());
556                URL_SAFE_NO_PAD.encode(hasher.finalize())
557            }
558            "plain" => code_verifier.clone(),
559            _ => {
560                return ApiResponse::error_typed(
561                    "invalid_request",
562                    "Unsupported code_challenge_method",
563                );
564            }
565        };
566
567        if computed_challenge != stored {
568            return ApiResponse::error_typed("invalid_grant", "PKCE verification failed");
569        }
570    } else if req.code_verifier.is_some() {
571        // code_verifier provided but no challenge was used - this is suspicious
572        return ApiResponse::error_typed(
573            "invalid_request",
574            "code_verifier provided but no PKCE challenge was used in authorization",
575        );
576    } else if client_kind == ClientKind::Public {
577        // S8: Public clients (registered without a secret) MUST use PKCE.
578        // Whether a client is public comes from its registration, not from whether
579        // the request happens to carry a secret.
580        return ApiResponse::error_typed(
581            "invalid_request",
582            "Public clients must use PKCE: provide code_challenge in authorization and code_verifier in token request",
583        );
584    }
585
586    // Code was already atomically deleted above (delete-first approach).
587    // No need to mark as used — the code is permanently consumed.
588
589    // RFC 8707: Validate resource indicators on the token request.
590    let authz_resources: Vec<String> = code_data["resource"]
591        .as_array()
592        .map(|arr| {
593            arr.iter()
594                .filter_map(|v| v.as_str().map(String::from))
595                .collect()
596        })
597        .unwrap_or_default();
598
599    if let Some(ref token_resources) = req.resource {
600        if let Err(e) =
601            crate::server::oauth::resource_indicators::validate_resource_indicators(token_resources)
602        {
603            return ApiResponse::error_typed("invalid_target", e.to_string());
604        }
605        if let Err(e) = crate::server::oauth::resource_indicators::validate_token_resource_subset(
606            token_resources,
607            &authz_resources,
608        ) {
609            return ApiResponse::error_typed("invalid_target", e.to_string());
610        }
611    }
612
613    // Create access and refresh tokens
614    let scope = code_data["scope"]
615        .as_str()
616        .unwrap_or("openid profile email");
617    let scopes: Vec<String> = scope.split_whitespace().map(|s| s.to_string()).collect();
618
619    // Use the user_id that was recorded in the authorization code when the resource owner
620    // authenticated via the /oauth/authorize endpoint.  This ensures tokens are bound to the
621    // actual user rather than a fabricated identifier derived from the client_id.
622    let user_id = match code_data["user_id"].as_str() {
623        Some(uid) if !uid.is_empty() => uid.to_string(),
624        _ => {
625            tracing::error!("Authorization code missing user_id field");
626            return ApiResponse::error_typed("server_error", "Malformed authorization code");
627        }
628    };
629
630    let token = match state.auth_framework.token_manager().create_auth_token(
631        &user_id,
632        scopes.clone(),
633        "oauth2",
634        None,
635    ) {
636        Ok(token) => token,
637        Err(e) => {
638            tracing::error!("Failed to create access token: {:?}", e);
639            return ApiResponse::error_typed("server_error", "Failed to create access token");
640        }
641    };
642
643    // Persist a storage-backed refresh token so the refresh grant can validate and rotate it.
644    let refresh_token_value = uuid::Uuid::new_v4().to_string().replace("-", "");
645    let refresh_data = serde_json::json!({
646        "user_id": user_id,
647        "client_id": client_id,
648        "scopes": scope,
649    });
650    let refresh_key = format!("oauth2_refresh_token:{}", refresh_token_value);
651    if let Err(e) = state
652        .auth_framework
653        .storage()
654        .store_kv(
655            &refresh_key,
656            serde_json::to_string(&refresh_data)
657                .unwrap_or_default()
658                .as_bytes(),
659            Some(std::time::Duration::from_secs(30 * 24 * 3600)),
660        )
661        .await
662    {
663        tracing::warn!("Failed to store refresh token: {:?}", e);
664    }
665
666    let expires_in = (token.expires_at - token.issued_at).num_seconds().max(0) as u64;
667    let response = TokenResponse {
668        access_token: token.access_token,
669        token_type: "Bearer".to_string(),
670        expires_in,
671        refresh_token: Some(refresh_token_value),
672        scope: Some(scope.to_string()),
673        id_token: None,
674    };
675
676    tracing::info!("OAuth2 tokens issued for client: {}", client_id);
677    ApiResponse::success(response)
678}
679
680/// A boxed error response (keeps the `Err` variant of the client-check helpers small).
681fn refusal(code: &str, message: &str) -> Box<ApiResponse<TokenResponse>> {
682    Box::new(ApiResponse::error_typed(code, message))
683}
684
685/// Load a registered client's record from `oauth2_client:{client_id}`.
686async fn load_client_record(
687    state: &ApiState,
688    client_id: &str,
689) -> std::result::Result<Option<serde_json::Value>, Box<ApiResponse<TokenResponse>>> {
690    let key = format!("oauth2_client:{client_id}");
691    match state.auth_framework.storage().get_kv(&key).await {
692        Ok(Some(data)) => serde_json::from_slice(&data).map(Some).map_err(|e| {
693            tracing::error!("Unreadable client record for {client_id}: {e}");
694            refusal("server_error", "Failed to validate client")
695        }),
696        Ok(None) => Ok(None),
697        Err(e) => {
698            tracing::error!("Failed to load client {client_id}: {e:?}");
699            Err(refusal("server_error", "Failed to validate client"))
700        }
701    }
702}
703
704/// How a client identified itself at the token endpoint.
705#[derive(Clone, Copy, PartialEq, Eq)]
706enum ClientKind {
707    /// Registered without a secret: identified by `client_id` alone (PKCE is mandatory).
708    Public,
709    /// Registered with a secret and authenticated with it.
710    Confidential,
711}
712
713/// Authenticate the client of an authorization-code exchange (RFC 6749 section 3.2.1).
714///
715/// The client must be registered (`oauth2_client:{id}`). A client whose record holds a
716/// secret (hashed, or a legacy plain one) is confidential and MUST present exactly that secret;
717/// a missing or wrong secret is `invalid_client`. Whether a client is public is decided by its
718/// registration, never by what the request carries.
719async fn authenticate_token_client(
720    state: &ApiState,
721    client_id: &str,
722    presented_secret: Option<&str>,
723) -> std::result::Result<ClientKind, Box<ApiResponse<TokenResponse>>> {
724    let Some(record) = load_client_record(state, client_id).await? else {
725        return Err(refusal("invalid_client", "Unknown client"));
726    };
727    match super::client_secret::is_confidential(&record) {
728        false => Ok(ClientKind::Public),
729        true => {
730            let authenticated = match presented_secret {
731                Some(presented) => {
732                    super::client_secret::authenticate(
733                        state.auth_framework.storage().as_ref(),
734                        client_id,
735                        &record,
736                        presented,
737                    )
738                    .await
739                }
740                None => false,
741            };
742            if authenticated {
743                Ok(ClientKind::Confidential)
744            } else {
745                Err(refusal("invalid_client", "Client authentication failed"))
746            }
747        }
748    }
749}
750
751async fn handle_refresh_token_grant(
752    state: ApiState,
753    req: TokenRequest,
754) -> ApiResponse<TokenResponse> {
755    let refresh_token_str = match req.refresh_token {
756        Some(t) => t,
757        None => return ApiResponse::validation_error_typed("refresh_token is required"),
758    };
759
760    // A revoked refresh token must not mint new access tokens, regardless of
761    // whether its own storage entry has been deleted yet (see `revoke`). Fail
762    // closed on a storage error here -- matching the equivalent check in
763    // `api/auth.rs`'s refresh handler -- rather than treating "couldn't check"
764    // as "not revoked".
765    let revoked_key = format!("oauth2_revoked_token:{}", refresh_token_str);
766    match state.auth_framework.storage().get_kv(&revoked_key).await {
767        Ok(Some(_)) => {
768            return ApiResponse::error_typed("invalid_grant", "Refresh token has been revoked");
769        }
770        Ok(None) => {} // Not revoked -- proceed
771        Err(e) => {
772            tracing::error!("Refresh token revocation check failed: {:?}", e);
773            return ApiResponse::error_typed("server_error", "Failed to validate refresh token");
774        }
775    }
776
777    // Defense-in-depth: Use a consumed marker to mitigate the non-atomic get+delete
778    // race condition. If a concurrent request already consumed this refresh token, reject.
779    let consumed_key = format!("oauth2_refresh_consumed:{}", refresh_token_str);
780    if let Ok(Some(_)) = state.auth_framework.storage().get_kv(&consumed_key).await {
781        return ApiResponse::error_typed("invalid_grant", "Refresh token already consumed");
782    }
783    if let Err(e) = state
784        .auth_framework
785        .storage()
786        .store_kv(
787            &consumed_key,
788            b"1",
789            Some(std::time::Duration::from_secs(600)),
790        )
791        .await
792    {
793        tracing::warn!("Failed to store refresh consumed marker: {:?}", e);
794    }
795
796    // Validate the refresh token against persistent storage.
797    let refresh_key = format!("oauth2_refresh_token:{}", refresh_token_str);
798    let stored = match state.auth_framework.storage().get_kv(&refresh_key).await {
799        Ok(Some(data)) => match serde_json::from_slice::<serde_json::Value>(&data) {
800            Ok(v) => v,
801            Err(_) => return ApiResponse::error_typed("invalid_grant", "Invalid refresh token"),
802        },
803        Ok(None) => {
804            return ApiResponse::error_typed("invalid_grant", "Refresh token not found or expired");
805        }
806        Err(e) => {
807            tracing::error!("Failed to retrieve refresh token: {:?}", e);
808            return ApiResponse::error_typed("server_error", "Failed to validate refresh token");
809        }
810    };
811
812    let user_id = match stored["user_id"].as_str() {
813        Some(u) => u.to_string(),
814        None => return ApiResponse::error_typed("invalid_grant", "Malformed refresh token data"),
815    };
816    let client_id = stored["client_id"].as_str().map(|s| s.to_string());
817    let scope = stored["scopes"]
818        .as_str()
819        .unwrap_or("openid profile email")
820        .to_string();
821    let scopes: Vec<String> = scope.split_whitespace().map(|s| s.to_string()).collect();
822
823    let token = match state
824        .auth_framework
825        .token_manager()
826        .create_auth_token(&user_id, scopes, "oauth2", None)
827    {
828        Ok(t) => t,
829        Err(e) => {
830            tracing::error!("Failed to create access token on refresh: {:?}", e);
831            return ApiResponse::error_typed("server_error", "Failed to issue access token");
832        }
833    };
834
835    // Issue a new refresh token (rotation).
836    // Store the new token BEFORE deleting the old one to avoid data loss on failure.
837    let new_refresh_token = uuid::Uuid::new_v4().to_string().replace("-", "");
838    let new_refresh_data = serde_json::json!({
839        "user_id": user_id,
840        "client_id": client_id,
841        "scopes": scope,
842    });
843    let new_refresh_key = format!("oauth2_refresh_token:{}", new_refresh_token);
844    if let Err(e) = state
845        .auth_framework
846        .storage()
847        .store_kv(
848            &new_refresh_key,
849            serde_json::to_string(&new_refresh_data)
850                .unwrap_or_default()
851                .as_bytes(),
852            Some(std::time::Duration::from_secs(30 * 24 * 3600)),
853        )
854        .await
855    {
856        tracing::error!("Failed to store new refresh token: {:?}", e);
857        return ApiResponse::error_typed("server_error", "Failed to issue refresh token");
858    }
859
860    // Now that the new token is safely stored, delete the old one (single-use enforcement).
861    if let Err(e) = state.auth_framework.storage().delete_kv(&refresh_key).await {
862        tracing::warn!(
863            "Failed to delete old refresh token during rotation: {:?}",
864            e
865        );
866    }
867
868    let expires_in = (token.expires_at - token.issued_at).num_seconds().max(0) as u64;
869    let response = TokenResponse {
870        access_token: token.access_token,
871        token_type: "Bearer".to_string(),
872        expires_in,
873        refresh_token: Some(new_refresh_token),
874        scope: Some(scope),
875        id_token: None,
876    };
877
878    tracing::info!("OAuth2 token refreshed for user: {}", user_id);
879    ApiResponse::success(response)
880}
881
882/// Whether the caller of `/oauth/revoke` is the client `owner`, who the token was issued to:
883/// it names itself with HTTP Basic or the `client_id` / `client_secret` body fields, and a
884/// client that has a secret must present it.
885async fn revocation_caller_is(
886    state: &ApiState,
887    headers: &HeaderMap,
888    req: &RevokeRequest,
889    owner: &str,
890) -> bool {
891    use base64::engine::general_purpose::STANDARD;
892    let basic = headers
893        .get(axum::http::header::AUTHORIZATION)
894        .and_then(|value| value.to_str().ok())
895        .and_then(|value| value.strip_prefix("Basic "))
896        .and_then(|encoded| STANDARD.decode(encoded).ok())
897        .and_then(|decoded| String::from_utf8(decoded).ok())
898        .map(|decoded| match decoded.split_once(':') {
899            Some((id, secret)) => (id.to_string(), Some(secret.to_string())),
900            None => (decoded, None),
901        });
902    let (presented_id, presented_secret) = match basic {
903        Some(pair) => pair,
904        None => match &req.client_id {
905            Some(id) => (id.clone(), req.client_secret.clone()),
906            None => return false,
907        },
908    };
909    if presented_id != owner {
910        return false;
911    }
912    let key = format!("oauth2_client:{owner}");
913    let record: serde_json::Value = match state.auth_framework.storage().get_kv(&key).await {
914        Ok(Some(data)) => match serde_json::from_slice(&data) {
915            Ok(record) => record,
916            Err(_) => return false,
917        },
918        _ => return false,
919    };
920    if !super::client_secret::is_confidential(&record) {
921        return true;
922    }
923    match presented_secret {
924        Some(secret) => {
925            super::client_secret::authenticate(
926                state.auth_framework.storage().as_ref(),
927                owner,
928                &record,
929                &secret,
930            )
931            .await
932        }
933        None => false,
934    }
935}
936
937/// POST /api/v1/oauth/revoke — revoke an access or refresh token.
938///
939/// Stores a revocation marker in KV (`oauth2_revoked_token:{token}`,
940/// TTL'd to the refresh token's own 30-day lifetime -- not just the 7
941/// days access-token revocation needs -- since this one marker has to
942/// outlive whichever token type was actually revoked) and, for JWT
943/// tokens, also stores a JTI-based marker (`revoked_token:{jti}`) so
944/// that all authenticated endpoints reject the token immediately. If
945/// the token is a refresh token, also deletes its `oauth2_refresh_token:`
946/// storage entry outright -- `handle_refresh_token_grant` also checks
947/// the revocation marker directly (failing closed on a storage error
948/// there), so revocation is effective for the marker's full TTL even if
949/// the delete itself fails.
950///
951/// Only a token this server issued is acted on; anything else is a no-op that answers like
952/// success (RFC 7009 section 2.2) and stores nothing. A refresh token issued to an OAuth client
953/// is revoked only by that client (RFC 7009 section 2.1): a confidential client authenticates
954/// with HTTP Basic or `client_id` / `client_secret` in the body, a public one names itself with
955/// `client_id`; otherwise `invalid_client`. A JWT, which carries no client on this line, is
956/// revoked by whoever holds it.
957///
958/// # Example
959/// ```rust,ignore
960/// let resp = revoke(State(state), HeaderMap::new(), Json(RevokeRequest {
961///     token: "access_token_value".into(),
962///     token_type_hint: Some("access_token".into()),
963///     client_id: None,
964///     client_secret: None,
965/// })).await;
966/// assert!(resp.success);
967/// ```
968pub async fn revoke(
969    State(state): State<ApiState>,
970    headers: HeaderMap,
971    Json(req): Json<RevokeRequest>,
972) -> ApiResponse<serde_json::Value> {
973    // The token becomes part of a storage key: bound its size.
974    if req.token.is_empty() || req.token.len() > 8192 {
975        return ApiResponse::error_typed("invalid_request", "Invalid token");
976    }
977
978    // Only a token this server issued is revoked. Anything else (a guess, junk, an expired
979    // or foreign JWT) is a no-op that answers like success (RFC 7009 section 2.2): the request
980    // must not make the server store a marker for an arbitrary string.
981    let issued_jwt = state
982        .auth_framework
983        .token_manager()
984        .validate_jwt_token(&req.token)
985        .ok();
986    let refresh_record: Option<serde_json::Value> = match state
987        .auth_framework
988        .storage()
989        .get_kv(&format!("oauth2_refresh_token:{}", req.token))
990        .await
991    {
992        Ok(Some(data)) => serde_json::from_slice(&data).ok(),
993        Ok(None) => None,
994        Err(e) => {
995            tracing::error!("Failed to look up the token to revoke: {:?}", e);
996            return ApiResponse::error_typed("server_error", "Failed to revoke token");
997        }
998    };
999    if issued_jwt.is_none() && refresh_record.is_none() {
1000        return ApiResponse::success(serde_json::json!({
1001            "message": "Token revoked successfully"
1002        }));
1003    }
1004
1005    // A token issued to an OAuth client is revoked only by that client (RFC 7009 section 2.1):
1006    // a confidential client authenticates, a public one identifies itself.
1007    // On this line only refresh tokens are issued to a client, but a JWT that carries a client
1008    // is bound to it too, so the check does not depend on that staying true.
1009    let owner_client = issued_jwt
1010        .as_ref()
1011        .and_then(|claims| claims.client_id.clone())
1012        .or_else(|| {
1013            refresh_record
1014                .as_ref()
1015                .and_then(|record| record["client_id"].as_str().map(String::from))
1016        });
1017    if let Some(owner) = owner_client
1018        && !revocation_caller_is(&state, &headers, &req, &owner).await
1019    {
1020        return ApiResponse::error_typed("invalid_client", "Client authentication failed");
1021    }
1022    // Store the revoked token in a blacklist for immediate invalidation.
1023    // Key by the raw token value so the userinfo endpoint can check it too.
1024    let revoked_token_key = format!("oauth2_revoked_token:{}", req.token);
1025    let revoked_data = serde_json::json!({
1026        "token": req.token,
1027        "revoked_at": chrono::Utc::now().to_rfc3339(),
1028        "token_type_hint": req.token_type_hint
1029    });
1030
1031    if let Err(e) = state
1032        .auth_framework
1033        .storage()
1034        .store_kv(
1035            &revoked_token_key,
1036            serde_json::to_string(&revoked_data)
1037                .unwrap_or_default()
1038                .as_bytes(),
1039            // 30 days: must outlive the longest-lived token type this
1040            // endpoint can revoke (the refresh token's own 30-day TTL),
1041            // not just the 7 days an access token's JWT markers need --
1042            // otherwise a revoked refresh token whose delete somehow
1043            // failed would become usable again once this marker expired.
1044            Some(std::time::Duration::from_secs(86400 * 30)),
1045        )
1046        .await
1047    {
1048        tracing::error!("Failed to store revoked token: {:?}", e);
1049        return ApiResponse::error_typed("server_error", "Failed to revoke token");
1050    }
1051
1052    // If this is a refresh token, delete its storage entry outright so it
1053    // can no longer be used to mint new access tokens. A no-op (and not an
1054    // error) if `req.token` isn't a refresh token at all -- the key simply
1055    // won't exist.
1056    let refresh_key = format!("oauth2_refresh_token:{}", req.token);
1057    if let Err(e) = state.auth_framework.storage().delete_kv(&refresh_key).await {
1058        tracing::warn!("Failed to delete refresh token on revoke: {:?}", e);
1059    }
1060
1061    // If the token is a JWT, also store revoked_token:{jti} so the authentication
1062    // middleware (validate_api_token in api/mod.rs) blocks it on all protected
1063    // endpoints. Without this step, the revocation would only be visible to the
1064    // userinfo endpoint, leaving all other authenticated routes unprotected.
1065    if let Ok(claims) = state
1066        .auth_framework
1067        .token_manager()
1068        .validate_jwt_token(&req.token)
1069    {
1070        let now = chrono::Utc::now().timestamp();
1071        let remaining_secs = (claims.exp - now + 60).max(60) as u64;
1072        let jti_key = format!("revoked_token:{}", claims.jti);
1073        if let Err(e) = state
1074            .auth_framework
1075            .storage()
1076            .store_kv(
1077                &jti_key,
1078                b"1",
1079                Some(std::time::Duration::from_secs(remaining_secs)),
1080            )
1081            .await
1082        {
1083            tracing::warn!("Failed to store JWT JTI revocation entry: {:?}", e);
1084        } else {
1085            tracing::info!("JWT token revoked via jti: {}", claims.jti);
1086        }
1087    }
1088
1089    tracing::info!(
1090        "OAuth2 token revoked: {}",
1091        &req.token[..10.min(req.token.len())]
1092    );
1093
1094    ApiResponse::success(serde_json::json!({
1095        "message": "Token revoked successfully"
1096    }))
1097}
1098
1099/// GET /api/v1/oauth/userinfo — return claims about the authenticated user.
1100///
1101/// The caller must supply a valid Bearer access token. If the token has been
1102/// revoked, an `invalid_token` error is returned. Email is included only
1103/// when the `email` scope is present in the token.
1104///
1105/// # Example
1106/// ```rust,ignore
1107/// // GET /api/v1/oauth/userinfo  Authorization: Bearer <token>
1108/// let resp = userinfo(State(state), headers).await;
1109/// assert_eq!(resp.data.unwrap().sub, "user-1");
1110/// ```
1111pub async fn userinfo(
1112    State(state): State<ApiState>,
1113    headers: HeaderMap,
1114) -> ApiResponse<UserInfoResponse> {
1115    // Extract and validate access token
1116    let token = match extract_bearer_token(&headers) {
1117        Some(t) => t,
1118        None => {
1119            return ApiResponse::error_typed("invalid_token", "Authorization header required");
1120        }
1121    };
1122
1123    // Check if token is revoked first
1124    let revoked_token_key = format!("oauth2_revoked_token:{}", token);
1125    if let Ok(Some(_)) = state
1126        .auth_framework
1127        .storage()
1128        .get_kv(&revoked_token_key)
1129        .await
1130    {
1131        return ApiResponse::error_typed("invalid_token", "Token has been revoked");
1132    }
1133
1134    // Validate the access token
1135    let claims = match state
1136        .auth_framework
1137        .token_manager()
1138        .validate_jwt_token(&token)
1139    {
1140        Ok(c) => c,
1141        Err(_) => {
1142            return ApiResponse::error_typed("invalid_token", "Access token is invalid");
1143        }
1144    };
1145
1146    // Get user profile
1147    let user_profile = match state.auth_framework.get_user_profile(&claims.sub).await {
1148        Ok(profile) => profile,
1149        Err(e) => {
1150            tracing::error!("Failed to get user profile: {:?}", e);
1151            return ApiResponse::error_typed("server_error", "Failed to retrieve user information");
1152        }
1153    };
1154
1155    let userinfo = UserInfoResponse {
1156        sub: claims.sub.clone(),
1157        name: user_profile.username.clone(),
1158        // Only include email if the token's scopes include "email"
1159        email: if claims.scope.split_whitespace().any(|s| s == "email") {
1160            user_profile.email.clone()
1161        } else {
1162            None
1163        },
1164        picture: user_profile.picture.clone(),
1165        updated_at: Some(chrono::Utc::now().timestamp()),
1166    };
1167
1168    tracing::info!("OAuth2 UserInfo requested for user: {}", claims.sub);
1169    ApiResponse::success(userinfo)
1170}
1171
1172/// GET /oauth/clients/{client_id} — return the stored metadata for a
1173/// registered OAuth 2.0 client.
1174///
1175/// # Example
1176/// ```rust,ignore
1177/// let resp = get_client_info(State(state), Path("my-client-id".into())).await;
1178/// ```
1179pub async fn get_client_info(
1180    State(state): State<ApiState>,
1181    Path(client_id): Path<String>,
1182) -> impl IntoResponse {
1183    let client_key = format!("oauth2_client:{}", client_id);
1184    match state.auth_framework.storage().get_kv(&client_key).await {
1185        Ok(Some(data)) => match serde_json::from_slice::<ClientInfo>(&data) {
1186            Ok(client) => (
1187                StatusCode::OK,
1188                Json(serde_json::json!({ "success": true, "data": client })),
1189            )
1190                .into_response(),
1191            Err(e) => {
1192                tracing::error!(client_id = %client_id, error = %e, "Failed to deserialize client record");
1193                (
1194                    StatusCode::INTERNAL_SERVER_ERROR,
1195                    Json(serde_json::json!({
1196                        "success": false,
1197                        "error": "server_error",
1198                        "message": "Failed to read client record"
1199                    })),
1200                )
1201                    .into_response()
1202            }
1203        },
1204        Ok(None) => (
1205            StatusCode::NOT_FOUND,
1206            Json(serde_json::json!({
1207                "success": false,
1208                "error": "invalid_client",
1209                "message": "Unknown client_id"
1210            })),
1211        )
1212            .into_response(),
1213        Err(e) => {
1214            tracing::error!(client_id = %client_id, error = %e, "Storage error looking up client");
1215            (
1216                StatusCode::INTERNAL_SERVER_ERROR,
1217                Json(serde_json::json!({
1218                    "success": false,
1219                    "error": "server_error",
1220                    "message": "Authorization server error"
1221                })),
1222            )
1223                .into_response()
1224        }
1225    }
1226}
1227
1228// ---------------------------------------------------------------------------
1229// OpenID Connect Discovery (RFC 8414 / OpenID Connect Discovery 1.0)
1230// ---------------------------------------------------------------------------
1231
1232/// OpenID Connect Discovery endpoint (RFC 8414 / OpenID Connect Discovery 1.0).
1233///
1234/// Returns server authorization metadata so clients can auto-configure
1235/// (issuer, endpoints, supported grants, signing algorithms, etc.).
1236///
1237/// # Example
1238/// ```rust,ignore
1239/// // GET /.well-known/openid-configuration
1240/// let (status, Json(config)) = openid_configuration(State(state)).await;
1241/// assert_eq!(status, StatusCode::OK);
1242/// ```
1243pub async fn openid_configuration(State(state): State<ApiState>) -> impl IntoResponse {
1244    let issuer = {
1245        let configured = state.auth_framework.config().issuer.clone();
1246        if configured.is_empty() {
1247            "https://auth.example.com".to_string()
1248        } else {
1249            configured
1250        }
1251    };
1252
1253    let config = serde_json::json!({
1254        "issuer": issuer,
1255        "authorization_endpoint": format!("{}/api/v1/oauth/authorize", issuer),
1256        "token_endpoint": format!("{}/api/v1/oauth/token", issuer),
1257        "userinfo_endpoint": format!("{}/api/v1/oauth/userinfo", issuer),
1258        "revocation_endpoint": format!("{}/api/v1/oauth/revoke", issuer),
1259        "introspection_endpoint": format!("{}/api/v1/oauth/introspect", issuer),
1260        "jwks_uri": format!("{}/api/v1/.well-known/jwks.json", issuer),
1261        "end_session_endpoint": format!("{}/api/v1/oauth/end_session", issuer),
1262        "pushed_authorization_request_endpoint": format!("{}/api/v1/oauth/par", issuer),
1263        "registration_endpoint": format!("{}/api/v1/oauth/register", issuer),
1264        "response_types_supported": ["code"],
1265        "grant_types_supported": [
1266            "authorization_code",
1267            "refresh_token"
1268        ],
1269        "subject_types_supported": ["public"],
1270        "id_token_signing_alg_values_supported": ["HS256"],
1271        "token_endpoint_auth_methods_supported": [
1272            "client_secret_basic",
1273            "client_secret_post"
1274        ],
1275        "code_challenge_methods_supported": ["S256"],
1276        "scopes_supported": ["openid", "profile", "email"]
1277    });
1278
1279    (StatusCode::OK, Json(config))
1280}
1281
1282// ---------------------------------------------------------------------------
1283// JWKS endpoint (RFC 7517)
1284// ---------------------------------------------------------------------------
1285
1286/// JSON Web Key Set (JWKS) endpoint ([RFC 7517](https://datatracker.ietf.org/doc/html/rfc7517)).
1287///
1288/// Returns the public keys used to verify tokens. Currently returns an
1289/// empty key set because HS256 (symmetric) signing is used; clients
1290/// should use the introspection endpoint for token validation.
1291///
1292/// # Example
1293/// ```rust,ignore
1294/// // GET /.well-known/jwks.json
1295/// let (status, Json(jwks)) = jwks(State(state)).await;
1296/// assert!(jwks["keys"].as_array().unwrap().is_empty());
1297/// ```
1298pub async fn jwks(State(_state): State<ApiState>) -> impl IntoResponse {
1299    (StatusCode::OK, Json(serde_json::json!({ "keys": [] })))
1300}
1301
1302// ---------------------------------------------------------------------------
1303// OIDC RP-Initiated Logout (OpenID Connect RP-Initiated Logout 1.0)
1304// ---------------------------------------------------------------------------
1305
1306/// Request parameters for OpenID Connect RP-Initiated Logout.
1307///
1308/// # Example
1309/// ```rust
1310/// use auth_framework::api::oauth2::EndSessionRequest;
1311///
1312/// let req: EndSessionRequest = serde_json::from_str(
1313///     r#"{"id_token_hint":"eyJ...","state":"xyz"}"#
1314/// ).unwrap();
1315/// assert!(req.post_logout_redirect_uri.is_none());
1316/// ```
1317#[derive(Deserialize)]
1318pub struct EndSessionRequest {
1319    pub id_token_hint: Option<String>,
1320    pub post_logout_redirect_uri: Option<String>,
1321    pub state: Option<String>,
1322}
1323
1324impl std::fmt::Debug for EndSessionRequest {
1325    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1326        let mut d = f.debug_struct("EndSessionRequest");
1327        d.field(
1328            "id_token_hint",
1329            &crate::utils::redact::redacted(&self.id_token_hint),
1330        );
1331        d.field("post_logout_redirect_uri", &self.post_logout_redirect_uri);
1332        d.field("state", &self.state);
1333        d.finish()
1334    }
1335}
1336
1337/// OIDC RP-Initiated Logout (OpenID Connect RP-Initiated Logout 1.0).
1338///
1339/// Revokes the token from `id_token_hint` (if valid) and, when a
1340/// registered `post_logout_redirect_uri` is provided, redirects the
1341/// user-agent there.
1342///
1343/// # Example
1344/// ```rust,ignore
1345/// // GET /oauth/end_session?id_token_hint=eyJ...&state=xyz
1346/// let resp = end_session(State(state), Query(params)).await;
1347/// ```
1348pub async fn end_session(
1349    State(state): State<ApiState>,
1350    Query(params): Query<EndSessionRequest>,
1351) -> impl IntoResponse {
1352    // If an id_token_hint is provided, revoke it
1353    if let Some(ref token) = params.id_token_hint
1354        && let Ok(claims) = state
1355            .auth_framework
1356            .token_manager()
1357            .validate_jwt_token(token)
1358    {
1359        let revoked_key = format!("oauth2_revoked_token:{}", token);
1360        if let Err(e) = state
1361            .auth_framework
1362            .storage()
1363            .store_kv(
1364                &revoked_key,
1365                b"revoked",
1366                Some(std::time::Duration::from_secs(86400 * 7)),
1367            )
1368            .await
1369        {
1370            tracing::warn!("Failed to revoke token during OIDC end_session: {}", e);
1371        }
1372        tracing::info!("OIDC end_session: revoked token for user {}", claims.sub);
1373    }
1374
1375    // Redirect to post_logout_redirect_uri only if it matches a registered URI for the
1376    // client identified by id_token_hint.  Without this check an attacker could craft a
1377    // link that redirects users to an arbitrary URL (open redirect / phishing).
1378    if let Some(ref redirect_uri) = params.post_logout_redirect_uri {
1379        // Look up the client's registered redirect URIs via the id_token_hint's `azp` or `aud` claim.
1380        let allowed = if let Some(ref token) = params.id_token_hint {
1381            // Try to extract client_id from the token (azp > aud)
1382            let client_id = state
1383                .auth_framework
1384                .token_manager()
1385                .validate_jwt_token(token)
1386                .ok()
1387                .and_then(|claims| {
1388                    // client_id claim identifies the OAuth client
1389                    if let Some(ref cid) = claims.client_id
1390                        && !cid.is_empty()
1391                    {
1392                        return Some(cid.clone());
1393                    }
1394                    // Fallback: aud may contain the client_id
1395                    if !claims.aud.is_empty() {
1396                        Some(claims.aud.clone())
1397                    } else {
1398                        None
1399                    }
1400                });
1401            if let Some(cid) = client_id {
1402                let client_key = format!("oauth2_client:{}", cid);
1403                match state.auth_framework.storage().get_kv(&client_key).await {
1404                    Ok(Some(data)) => {
1405                        let client: serde_json::Value =
1406                            serde_json::from_slice(&data).unwrap_or_default();
1407                        let uris: Vec<String> = client["redirect_uris"]
1408                            .as_array()
1409                            .map(|a| {
1410                                a.iter()
1411                                    .filter_map(|v| v.as_str().map(String::from))
1412                                    .collect()
1413                            })
1414                            .unwrap_or_default();
1415                        uris.iter().any(|r| redirect_uri_matches(redirect_uri, r))
1416                    }
1417                    _ => false,
1418                }
1419            } else {
1420                false
1421            }
1422        } else {
1423            false
1424        };
1425
1426        if allowed {
1427            if let Ok(mut parsed) = Url::parse(redirect_uri) {
1428                if let Some(ref st) = params.state {
1429                    parsed.query_pairs_mut().append_pair("state", st);
1430                }
1431                return Redirect::to(parsed.as_str()).into_response();
1432            }
1433        } else {
1434            tracing::warn!(
1435                "end_session: post_logout_redirect_uri rejected — not registered for the client"
1436            );
1437        }
1438    }
1439
1440    // No redirect — return a simple JSON acknowledgement
1441    (
1442        StatusCode::OK,
1443        Json(serde_json::json!({ "status": "logged_out" })),
1444    )
1445        .into_response()
1446}
1447
1448// ---------------------------------------------------------------------------
1449// Dynamic Client Registration (RFC 7591)
1450// ---------------------------------------------------------------------------
1451
1452/// Dynamic client registration request per [RFC 7591](https://datatracker.ietf.org/doc/html/rfc7591).
1453///
1454/// # Example
1455/// ```rust
1456/// use auth_framework::api::oauth2::ClientRegistrationRequest;
1457///
1458/// let req: ClientRegistrationRequest = serde_json::from_str(
1459///     r#"{"redirect_uris":["https://example.com/cb"]}"#
1460/// ).unwrap();
1461/// assert_eq!(req.redirect_uris.len(), 1);
1462/// ```
1463#[derive(Debug, Deserialize)]
1464pub struct ClientRegistrationRequest {
1465    pub redirect_uris: Vec<String>,
1466    #[serde(default)]
1467    pub client_name: Option<String>,
1468    #[serde(default)]
1469    pub token_endpoint_auth_method: Option<String>,
1470    #[serde(default)]
1471    pub grant_types: Option<Vec<String>>,
1472    #[serde(default)]
1473    pub response_types: Option<Vec<String>>,
1474    #[serde(default)]
1475    pub scope: Option<String>,
1476}
1477
1478/// POST /oauth/register — dynamically register a new OAuth 2.0 client
1479/// ([RFC 7591](https://datatracker.ietf.org/doc/html/rfc7591)).
1480///
1481/// Requires a valid Bearer token with `admin` role, or an Initial Access
1482/// Token stored in KV at `oauth2_initial_access_token`. Unauthenticated
1483/// callers are rejected to prevent resource exhaustion.
1484///
1485/// # Example
1486/// ```rust,ignore
1487/// let resp = register_client(
1488///     State(state),
1489///     headers,   // with Authorization: Bearer <admin-token>
1490///     Json(ClientRegistrationRequest {
1491///         redirect_uris: vec!["https://example.com/cb".into()],
1492///         client_name: Some("My App".into()),
1493///         ..Default::default()
1494///     }),
1495/// ).await;
1496/// ```
1497pub async fn register_client(
1498    State(state): State<ApiState>,
1499    headers: HeaderMap,
1500    Json(req): Json<ClientRegistrationRequest>,
1501) -> impl IntoResponse {
1502    // RFC 7591 §1.2: require authentication via Bearer token
1503    let token_str = match extract_bearer_token(&headers) {
1504        Some(t) => t,
1505        None => {
1506            return (
1507                StatusCode::UNAUTHORIZED,
1508                Json(serde_json::json!({
1509                    "error": "invalid_token",
1510                    "error_description": "A valid Bearer token is required for dynamic client registration"
1511                })),
1512            )
1513                .into_response();
1514        }
1515    };
1516
1517    // Option 1: check if this is the pre-configured Initial Access Token
1518    let is_initial_access_token = match state
1519        .auth_framework
1520        .storage()
1521        .get_kv("oauth2_initial_access_token")
1522        .await
1523    {
1524        Ok(Some(stored)) => {
1525            let stored_str = String::from_utf8_lossy(&stored);
1526            subtle::ConstantTimeEq::ct_eq(token_str.as_bytes(), stored_str.trim().as_bytes()).into()
1527        }
1528        _ => false,
1529    };
1530
1531    // Option 2: validate as a normal JWT and check for admin role
1532    let is_admin = if !is_initial_access_token {
1533        match validate_api_token(&state.auth_framework, &token_str).await {
1534            Ok(auth_token) => auth_token.roles.contains("admin"),
1535            Err(_) => false,
1536        }
1537    } else {
1538        false
1539    };
1540
1541    if !is_initial_access_token && !is_admin {
1542        return (
1543            StatusCode::FORBIDDEN,
1544            Json(serde_json::json!({
1545                "error": "insufficient_scope",
1546                "error_description": "Dynamic client registration requires admin privileges or a valid Initial Access Token"
1547            })),
1548        )
1549            .into_response();
1550    }
1551    // Validate all redirect_uris are well-formed URLs with safe schemes
1552    for uri in &req.redirect_uris {
1553        match Url::parse(uri) {
1554            Ok(parsed) => {
1555                match parsed.scheme() {
1556                    "https" => {}
1557                    "http" => {
1558                        // Allow plain HTTP only for loopback addresses (development)
1559                        if !matches!(parsed.host_str(), Some("localhost" | "127.0.0.1" | "[::1]")) {
1560                            return (
1561                                StatusCode::BAD_REQUEST,
1562                                Json(serde_json::json!({
1563                                    "error": "invalid_redirect_uri",
1564                                    "error_description": format!("Non-loopback HTTP redirect_uri not allowed: {}", uri)
1565                                })),
1566                            )
1567                                .into_response();
1568                        }
1569                    }
1570                    scheme => {
1571                        return (
1572                            StatusCode::BAD_REQUEST,
1573                            Json(serde_json::json!({
1574                                "error": "invalid_redirect_uri",
1575                                "error_description": format!("Disallowed URI scheme '{}' in redirect_uri: {}", scheme, uri)
1576                            })),
1577                        )
1578                            .into_response();
1579                    }
1580                }
1581            }
1582            Err(_) => {
1583                return (
1584                    StatusCode::BAD_REQUEST,
1585                    Json(serde_json::json!({
1586                        "error": "invalid_redirect_uri",
1587                        "error_description": format!("Invalid redirect_uri: {}", uri)
1588                    })),
1589                )
1590                    .into_response();
1591            }
1592        }
1593    }
1594
1595    if req.redirect_uris.is_empty() {
1596        return (
1597            StatusCode::BAD_REQUEST,
1598            Json(serde_json::json!({
1599                "error": "invalid_client_metadata",
1600                "error_description": "At least one redirect_uri is required"
1601            })),
1602        )
1603            .into_response();
1604    }
1605
1606    let client_id = Uuid::new_v4().to_string();
1607    let client_secret = Uuid::new_v4().to_string();
1608    // Only the hash is stored; the secret itself is returned once, below.
1609    let client_secret_hash = match super::client_secret::hash_secret(&client_secret).await {
1610        Ok(hash) => hash,
1611        Err(e) => {
1612            tracing::error!("Failed to hash a client secret: {}", e);
1613            return (
1614                StatusCode::INTERNAL_SERVER_ERROR,
1615                Json(serde_json::json!({
1616                    "error": "server_error",
1617                    "error_description": "Failed to register client"
1618                })),
1619            )
1620                .into_response();
1621        }
1622    };
1623
1624    let client_data = serde_json::json!({
1625        "client_id": client_id,
1626        "client_secret_hash": client_secret_hash,
1627        "client_name": req.client_name,
1628        "redirect_uris": req.redirect_uris,
1629        "token_endpoint_auth_method": req.token_endpoint_auth_method.as_deref().unwrap_or("client_secret_basic"),
1630        "grant_types": req.grant_types.as_deref().unwrap_or(&["authorization_code".to_string()]),
1631        "response_types": req.response_types.as_deref().unwrap_or(&["code".to_string()]),
1632        "scope": req.scope.as_deref().unwrap_or("openid"),
1633    });
1634
1635    let key = format!("oauth2_client:{}", client_id);
1636    if let Err(e) = state
1637        .auth_framework
1638        .storage()
1639        .store_kv(&key, client_data.to_string().as_bytes(), None)
1640        .await
1641    {
1642        tracing::error!("Failed to store client registration: {}", e);
1643        return (
1644            StatusCode::INTERNAL_SERVER_ERROR,
1645            Json(serde_json::json!({
1646                "error": "server_error",
1647                "error_description": "Failed to register client"
1648            })),
1649        )
1650            .into_response();
1651    }
1652
1653    tracing::info!("Dynamic client registered: client_id={}", client_id);
1654
1655    (
1656        StatusCode::CREATED,
1657        Json(serde_json::json!({
1658            "client_id": client_id,
1659            "client_secret": client_secret,
1660            "client_name": req.client_name,
1661            "redirect_uris": req.redirect_uris,
1662            "token_endpoint_auth_method": req.token_endpoint_auth_method.as_deref().unwrap_or("client_secret_basic"),
1663            "grant_types": req.grant_types.as_deref().unwrap_or(&["authorization_code".to_string()]),
1664            "response_types": req.response_types.as_deref().unwrap_or(&["code".to_string()]),
1665            "scope": req.scope.as_deref().unwrap_or("openid"),
1666        })),
1667    )
1668        .into_response()
1669}
1670
1671// ---------------------------------------------------------------------------
1672// /users/me — alias for the authenticated user's profile
1673// ---------------------------------------------------------------------------
1674
1675/// GET /users/me — returns the authenticated user's profile.
1676///
1677/// Convenience alias that delegates to [`userinfo`].
1678///
1679/// # Example
1680/// ```rust,ignore
1681/// // GET /users/me  Authorization: Bearer <token>
1682/// let resp = users_me(state, headers).await;
1683/// ```
1684pub async fn users_me(state: State<ApiState>, headers: HeaderMap) -> impl IntoResponse {
1685    // Delegate to the existing userinfo handler
1686    userinfo(state, headers).await
1687}