Skip to main content

auth_framework/api/
oauth2.rs

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