Skip to main content

auth_framework/api/
oauth2.rs

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