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(std::time::Duration::from_secs(30 * 24 * 3600)),
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.
838async fn authorize_refresh_client(
839    state: &ApiState,
840    stored_client: &str,
841    presented_id: Option<&str>,
842    presented_secret: Option<&str>,
843) -> std::result::Result<(), Box<ApiResponse<TokenResponse>>> {
844    let not_issued_to_you = || {
845        refusal(
846            "invalid_grant",
847            "Refresh token was not issued to this client",
848        )
849    };
850
851    let Some(stored_record) = load_client_record(state, stored_client).await? else {
852        return Err(refusal(
853            "invalid_grant",
854            "Refresh token was issued to a client that is no longer registered",
855        ));
856    };
857
858    if client_secret_of(&stored_record).is_none() {
859        // Public client: it identifies itself, nothing more.
860        return match presented_id {
861            Some(id) if id == stored_client => Ok(()),
862            _ => Err(not_issued_to_you()),
863        };
864    }
865
866    // Confidential client: authenticate whoever is asking against THEIR record.
867    let (Some(presented_id), Some(presented_secret)) = (presented_id, presented_secret) else {
868        return Err(refusal(
869            "invalid_client",
870            "Client authentication is required",
871        ));
872    };
873    let presented_record = if presented_id == stored_client {
874        Some(stored_record)
875    } else {
876        load_client_record(state, presented_id).await?
877    };
878    let authenticated = presented_record
879        .as_ref()
880        .and_then(client_secret_of)
881        .is_some_and(|secret| {
882            crate::security::timing_protection::constant_time_string_compare(
883                presented_secret,
884                secret,
885            )
886        });
887    if !authenticated {
888        return Err(refusal("invalid_client", "Client authentication failed"));
889    }
890    if presented_id != stored_client {
891        return Err(not_issued_to_you());
892    }
893    Ok(())
894}
895
896async fn handle_refresh_token_grant(
897    state: ApiState,
898    req: TokenRequest,
899) -> ApiResponse<TokenResponse> {
900    let refresh_token_str = match req.refresh_token {
901        Some(t) => t,
902        None => return ApiResponse::validation_error_typed("refresh_token is required"),
903    };
904
905    // A revoked refresh token must not mint new access tokens, regardless of
906    // whether its own storage entry has been deleted yet (see `revoke`). Fail
907    // closed on a storage error here -- matching the equivalent check in
908    // `api/auth.rs`'s refresh handler -- rather than treating "couldn't check"
909    // as "not revoked".
910    let revoked_key = format!("oauth2_revoked_token:{}", refresh_token_str);
911    match state.auth_framework.storage().get_kv(&revoked_key).await {
912        Ok(Some(_)) => {
913            return ApiResponse::error_typed("invalid_grant", "Refresh token has been revoked");
914        }
915        Ok(None) => {} // Not revoked -- proceed
916        Err(e) => {
917            tracing::error!("Refresh token revocation check failed: {:?}", e);
918            return ApiResponse::error_typed("server_error", "Failed to validate refresh token");
919        }
920    }
921
922    let consumed_key = format!("oauth2_refresh_consumed:{}", refresh_token_str);
923
924    // Validate the refresh token against persistent storage.
925    let refresh_key = format!("oauth2_refresh_token:{}", refresh_token_str);
926    let stored = match state.auth_framework.storage().get_kv(&refresh_key).await {
927        Ok(Some(data)) => match serde_json::from_slice::<serde_json::Value>(&data) {
928            Ok(v) => v,
929            Err(_) => return ApiResponse::error_typed("invalid_grant", "Invalid refresh token"),
930        },
931        Ok(None) => {
932            return ApiResponse::error_typed("invalid_grant", "Refresh token not found or expired");
933        }
934        Err(e) => {
935            tracing::error!("Failed to retrieve refresh token: {:?}", e);
936            return ApiResponse::error_typed("server_error", "Failed to validate refresh token");
937        }
938    };
939
940    // Claim the token: of any number of simultaneous redemptions exactly one proceeds (atomic
941    // set-if-absent). The marker is only written for a token that exists.
942    match state
943        .auth_framework
944        .storage()
945        .store_kv_if_absent(
946            &consumed_key,
947            b"1",
948            Some(std::time::Duration::from_secs(600)),
949        )
950        .await
951    {
952        Ok(true) => {}
953        Ok(false) => {
954            return ApiResponse::error_typed("invalid_grant", "Refresh token already consumed");
955        }
956        Err(e) => {
957            tracing::error!("Failed to claim refresh token: {:?}", e);
958            return ApiResponse::error_typed("server_error", "Failed to validate refresh token");
959        }
960    }
961
962    let user_id = match stored["user_id"].as_str() {
963        Some(u) => u.to_string(),
964        None => return ApiResponse::error_typed("invalid_grant", "Malformed refresh token data"),
965    };
966    let client_id = match &stored["client_id"] {
967        serde_json::Value::Null => None,
968        serde_json::Value::String(s) => Some(s.clone()),
969        // A client_id of some other type cannot be checked: fail closed
970        // instead of silently skipping the binding.
971        _ => return ApiResponse::error_typed("invalid_grant", "Malformed refresh token data"),
972    };
973
974    // A token issued to a client is redeemable only by that client. A refused
975    // attempt releases the consumed marker set above, so merely seeing a
976    // refresh token (and presenting it wrongly) cannot burn it.
977    if let Some(stored_client) = client_id.as_deref()
978        && let Err(refusal) = authorize_refresh_client(
979            &state,
980            stored_client,
981            req.client_id.as_deref(),
982            req.client_secret.as_deref(),
983        )
984        .await
985    {
986        if let Err(e) = state
987            .auth_framework
988            .storage()
989            .delete_kv(&consumed_key)
990            .await
991        {
992            tracing::warn!("Failed to release refresh consumed marker: {:?}", e);
993        }
994        return *refusal;
995    }
996
997    let mut scopes: Vec<String> = stored["scopes"]
998        .as_str()
999        .unwrap_or("openid profile email")
1000        .split_whitespace()
1001        .map(|s| s.to_string())
1002        .collect();
1003    // A refreshed token never exceeds what the client is registered for NOW, whatever the
1004    // stored record carries (older records, or a registration narrowed since).
1005    if let Some(client) = stored["client_id"].as_str() {
1006        let record = match load_client_record(&state, client).await {
1007            Ok(Some(record)) => record,
1008            Ok(None) => {
1009                let _ = state
1010                    .auth_framework
1011                    .storage()
1012                    .delete_kv(&consumed_key)
1013                    .await;
1014                return ApiResponse::error_typed("invalid_client", "Unknown client");
1015            }
1016            Err(refused) => {
1017                let _ = state
1018                    .auth_framework
1019                    .storage()
1020                    .delete_kv(&consumed_key)
1021                    .await;
1022                return *refused;
1023            }
1024        };
1025        let allowed = allowed_scopes(&record);
1026        scopes.retain(|s| allowed.iter().any(|a| a == s));
1027        if scopes.is_empty() {
1028            let _ = state
1029                .auth_framework
1030                .storage()
1031                .delete_kv(&consumed_key)
1032                .await;
1033            return ApiResponse::error_typed(
1034                "invalid_scope",
1035                "No granted scope is allowed for this client",
1036            );
1037        }
1038    }
1039    let scope = scopes.join(" ");
1040
1041    let minted = match client_id.as_deref() {
1042        Some(client) => state
1043            .auth_framework
1044            .token_manager()
1045            .create_client_auth_token(&user_id, scopes, "oauth2", client, None),
1046        // A stored refresh record without a client (written by an older version) still came
1047        // from an OAuth grant: its access token is delegated, never a user session.
1048        None => state
1049            .auth_framework
1050            .token_manager()
1051            .create_client_auth_token(&user_id, scopes, "oauth2", "unknown-client", None),
1052    };
1053    let token = match minted {
1054        Ok(t) => t,
1055        Err(e) => {
1056            tracing::error!("Failed to create access token on refresh: {:?}", e);
1057            return ApiResponse::error_typed("server_error", "Failed to issue access token");
1058        }
1059    };
1060
1061    // Issue a new refresh token (rotation).
1062    // Store the new token BEFORE deleting the old one to avoid data loss on failure.
1063    let new_refresh_token = uuid::Uuid::new_v4().to_string().replace("-", "");
1064    let new_refresh_data = serde_json::json!({
1065        "user_id": user_id,
1066        "client_id": client_id,
1067        "scopes": scope,
1068    });
1069    let new_refresh_key = format!("oauth2_refresh_token:{}", new_refresh_token);
1070    if let Err(e) = state
1071        .auth_framework
1072        .storage()
1073        .store_kv(
1074            &new_refresh_key,
1075            serde_json::to_string(&new_refresh_data)
1076                .unwrap_or_default()
1077                .as_bytes(),
1078            Some(std::time::Duration::from_secs(30 * 24 * 3600)),
1079        )
1080        .await
1081    {
1082        tracing::error!("Failed to store new refresh token: {:?}", e);
1083        return ApiResponse::error_typed("server_error", "Failed to issue refresh token");
1084    }
1085
1086    // Now that the new token is safely stored, delete the old one (single-use enforcement).
1087    if let Err(e) = state.auth_framework.storage().delete_kv(&refresh_key).await {
1088        tracing::warn!(
1089            "Failed to delete old refresh token during rotation: {:?}",
1090            e
1091        );
1092    }
1093
1094    let expires_in = (token.expires_at - token.issued_at).num_seconds().max(0) as u64;
1095    let response = TokenResponse {
1096        access_token: token.access_token,
1097        token_type: "Bearer".to_string(),
1098        expires_in,
1099        refresh_token: Some(new_refresh_token),
1100        scope: Some(scope),
1101        id_token: None,
1102    };
1103
1104    tracing::info!("OAuth2 token refreshed for user: {}", user_id);
1105    ApiResponse::success(response)
1106}
1107
1108/// POST /api/v1/oauth/revoke — revoke an access or refresh token.
1109///
1110/// Stores a revocation marker in KV (`oauth2_revoked_token:{token}`,
1111/// TTL'd to the refresh token's own 30-day lifetime -- not just the 7
1112/// days access-token revocation needs -- since this one marker has to
1113/// outlive whichever token type was actually revoked) and, for JWT
1114/// tokens, also stores a JTI-based marker (`revoked_token:{jti}`) so
1115/// that all authenticated endpoints reject the token immediately. If
1116/// the token is a refresh token, also deletes its `oauth2_refresh_token:`
1117/// storage entry outright -- `handle_refresh_token_grant` also checks
1118/// the revocation marker directly (failing closed on a storage error
1119/// there), so revocation is effective for the marker's full TTL even if
1120/// the delete itself fails.
1121///
1122/// # Example
1123/// ```rust,ignore
1124/// let resp = revoke(State(state), Json(RevokeRequest {
1125///     token: "access_token_value".into(),
1126///     token_type_hint: Some("access_token".into()),
1127/// })).await;
1128/// assert!(resp.success);
1129/// ```
1130pub async fn revoke(
1131    State(state): State<ApiState>,
1132    Json(req): Json<RevokeRequest>,
1133) -> ApiResponse<serde_json::Value> {
1134    // The token becomes part of a storage key: bound its size.
1135    if req.token.is_empty() || req.token.len() > 8192 {
1136        return ApiResponse::error_typed("invalid_request", "Invalid token");
1137    }
1138
1139    // Store the revoked token in a blacklist for immediate invalidation.
1140    // Key by the raw token value so the userinfo endpoint can check it too.
1141    let revoked_token_key = format!("oauth2_revoked_token:{}", req.token);
1142    let revoked_data = serde_json::json!({
1143        "token": req.token,
1144        "revoked_at": chrono::Utc::now().to_rfc3339(),
1145        "token_type_hint": req.token_type_hint
1146    });
1147
1148    if let Err(e) = state
1149        .auth_framework
1150        .storage()
1151        .store_kv(
1152            &revoked_token_key,
1153            serde_json::to_string(&revoked_data)
1154                .unwrap_or_default()
1155                .as_bytes(),
1156            // 30 days: must outlive the longest-lived token type this
1157            // endpoint can revoke (the refresh token's own 30-day TTL),
1158            // not just the 7 days an access token's JWT markers need --
1159            // otherwise a revoked refresh token whose delete somehow
1160            // failed would become usable again once this marker expired.
1161            Some(std::time::Duration::from_secs(86400 * 30)),
1162        )
1163        .await
1164    {
1165        tracing::error!("Failed to store revoked token: {:?}", e);
1166        return ApiResponse::error_typed("server_error", "Failed to revoke token");
1167    }
1168
1169    // If this is a refresh token, delete its storage entry outright so it
1170    // can no longer be used to mint new access tokens. A no-op (and not an
1171    // error) if `req.token` isn't a refresh token at all -- the key simply
1172    // won't exist.
1173    let refresh_key = format!("oauth2_refresh_token:{}", req.token);
1174    if let Err(e) = state.auth_framework.storage().delete_kv(&refresh_key).await {
1175        tracing::warn!("Failed to delete refresh token on revoke: {:?}", e);
1176    }
1177
1178    // If the token is a JWT, also store revoked_token:{jti} so the authentication
1179    // middleware (validate_api_token in api/mod.rs) blocks it on all protected
1180    // endpoints. Without this step, the revocation would only be visible to the
1181    // userinfo endpoint, leaving all other authenticated routes unprotected.
1182    if let Ok(claims) = state
1183        .auth_framework
1184        .token_manager()
1185        .validate_jwt_token(&req.token)
1186    {
1187        let now = chrono::Utc::now().timestamp();
1188        let remaining_secs = (claims.exp - now + 60).max(60) as u64;
1189        let jti_key = format!("revoked_token:{}", claims.jti);
1190        if let Err(e) = state
1191            .auth_framework
1192            .storage()
1193            .store_kv(
1194                &jti_key,
1195                b"1",
1196                Some(std::time::Duration::from_secs(remaining_secs)),
1197            )
1198            .await
1199        {
1200            tracing::warn!("Failed to store JWT JTI revocation entry: {:?}", e);
1201        } else {
1202            tracing::info!("JWT token revoked via jti: {}", claims.jti);
1203        }
1204    }
1205
1206    tracing::info!(
1207        "OAuth2 token revoked: {}",
1208        &req.token[..10.min(req.token.len())]
1209    );
1210
1211    ApiResponse::success(serde_json::json!({
1212        "message": "Token revoked successfully"
1213    }))
1214}
1215
1216/// GET /api/v1/oauth/userinfo — return claims about the authenticated user.
1217///
1218/// The caller must supply a valid Bearer access token. If the token has been
1219/// revoked, an `invalid_token` error is returned. Email is included only
1220/// when the `email` scope is present in the token.
1221///
1222/// # Example
1223/// ```rust,ignore
1224/// // GET /api/v1/oauth/userinfo  Authorization: Bearer <token>
1225/// let resp = userinfo(State(state), headers).await;
1226/// assert_eq!(resp.data.unwrap().sub, "user-1");
1227/// ```
1228pub async fn userinfo(
1229    State(state): State<ApiState>,
1230    headers: HeaderMap,
1231) -> ApiResponse<UserInfoResponse> {
1232    // Extract and validate access token
1233    let token = match extract_bearer_token(&headers) {
1234        Some(t) => t,
1235        None => {
1236            return ApiResponse::error_typed("invalid_token", "Authorization header required");
1237        }
1238    };
1239
1240    // Check if token is revoked first
1241    let revoked_token_key = format!("oauth2_revoked_token:{}", token);
1242    if let Ok(Some(_)) = state
1243        .auth_framework
1244        .storage()
1245        .get_kv(&revoked_token_key)
1246        .await
1247    {
1248        return ApiResponse::error_typed("invalid_token", "Token has been revoked");
1249    }
1250
1251    // Validate the access token
1252    let claims = match state.auth_framework.validate_delegated_jwt(&token).await {
1253        Ok(c) => c,
1254        Err(_) => {
1255            return ApiResponse::error_typed("invalid_token", "Access token is invalid");
1256        }
1257    };
1258
1259    // Get user profile
1260    let user_profile = match state.auth_framework.get_user_profile(&claims.sub).await {
1261        Ok(profile) => profile,
1262        Err(e) => {
1263            tracing::error!("Failed to get user profile: {:?}", e);
1264            return ApiResponse::error_typed("server_error", "Failed to retrieve user information");
1265        }
1266    };
1267
1268    let userinfo = UserInfoResponse {
1269        sub: claims.sub.clone(),
1270        name: user_profile.username.clone(),
1271        // Only include email if the token's scopes include "email"
1272        email: if claims.scope.split_whitespace().any(|s| s == "email") {
1273            user_profile.email.clone()
1274        } else {
1275            None
1276        },
1277        picture: user_profile.picture.clone(),
1278        updated_at: Some(chrono::Utc::now().timestamp()),
1279    };
1280
1281    tracing::info!("OAuth2 UserInfo requested for user: {}", claims.sub);
1282    ApiResponse::success(userinfo)
1283}
1284
1285/// GET /oauth/clients/{client_id} — return the stored metadata for a
1286/// registered OAuth 2.0 client.
1287///
1288/// # Example
1289/// ```rust,ignore
1290/// let resp = get_client_info(State(state), Path("my-client-id".into())).await;
1291/// ```
1292pub async fn get_client_info(
1293    State(state): State<ApiState>,
1294    Path(client_id): Path<String>,
1295) -> impl IntoResponse {
1296    let client_key = format!("oauth2_client:{}", client_id);
1297    match state.auth_framework.storage().get_kv(&client_key).await {
1298        Ok(Some(data)) => match serde_json::from_slice::<ClientInfo>(&data) {
1299            Ok(client) => (
1300                StatusCode::OK,
1301                Json(serde_json::json!({ "success": true, "data": client })),
1302            )
1303                .into_response(),
1304            Err(e) => {
1305                tracing::error!(client_id = %client_id, error = %e, "Failed to deserialize client record");
1306                (
1307                    StatusCode::INTERNAL_SERVER_ERROR,
1308                    Json(serde_json::json!({
1309                        "success": false,
1310                        "error": "server_error",
1311                        "message": "Failed to read client record"
1312                    })),
1313                )
1314                    .into_response()
1315            }
1316        },
1317        Ok(None) => (
1318            StatusCode::NOT_FOUND,
1319            Json(serde_json::json!({
1320                "success": false,
1321                "error": "invalid_client",
1322                "message": "Unknown client_id"
1323            })),
1324        )
1325            .into_response(),
1326        Err(e) => {
1327            tracing::error!(client_id = %client_id, error = %e, "Storage error looking up client");
1328            (
1329                StatusCode::INTERNAL_SERVER_ERROR,
1330                Json(serde_json::json!({
1331                    "success": false,
1332                    "error": "server_error",
1333                    "message": "Authorization server error"
1334                })),
1335            )
1336                .into_response()
1337        }
1338    }
1339}
1340
1341// ---------------------------------------------------------------------------
1342// OpenID Connect Discovery (RFC 8414 / OpenID Connect Discovery 1.0)
1343// ---------------------------------------------------------------------------
1344
1345/// OpenID Connect Discovery endpoint (RFC 8414 / OpenID Connect Discovery 1.0).
1346///
1347/// Returns server authorization metadata so clients can auto-configure
1348/// (issuer, endpoints, supported grants, signing algorithms, etc.).
1349///
1350/// # Example
1351/// ```rust,ignore
1352/// // GET /.well-known/openid-configuration
1353/// let (status, Json(config)) = openid_configuration(State(state)).await;
1354/// assert_eq!(status, StatusCode::OK);
1355/// ```
1356pub async fn openid_configuration(State(state): State<ApiState>) -> impl IntoResponse {
1357    let issuer = {
1358        let configured = state.auth_framework.config().issuer.clone();
1359        if configured.is_empty() {
1360            "https://auth.example.com".to_string()
1361        } else {
1362            configured
1363        }
1364    };
1365
1366    let config = serde_json::json!({
1367        "issuer": issuer,
1368        "authorization_endpoint": format!("{}/api/v1/oauth/authorize", issuer),
1369        "token_endpoint": format!("{}/api/v1/oauth/token", issuer),
1370        "userinfo_endpoint": format!("{}/api/v1/oauth/userinfo", issuer),
1371        "revocation_endpoint": format!("{}/api/v1/oauth/revoke", issuer),
1372        "introspection_endpoint": format!("{}/api/v1/oauth/introspect", issuer),
1373        "jwks_uri": format!("{}/api/v1/.well-known/jwks.json", issuer),
1374        "end_session_endpoint": format!("{}/api/v1/oauth/end_session", issuer),
1375        "pushed_authorization_request_endpoint": format!("{}/api/v1/oauth/par", issuer),
1376        "registration_endpoint": format!("{}/api/v1/oauth/register", issuer),
1377        "response_types_supported": ["code"],
1378        "grant_types_supported": [
1379            "authorization_code",
1380            "refresh_token"
1381        ],
1382        "subject_types_supported": ["public"],
1383        "id_token_signing_alg_values_supported": ["HS256"],
1384        "token_endpoint_auth_methods_supported": [
1385            "client_secret_basic",
1386            "client_secret_post"
1387        ],
1388        "code_challenge_methods_supported": ["S256"],
1389        "scopes_supported": ["openid", "profile", "email"]
1390    });
1391
1392    (StatusCode::OK, Json(config))
1393}
1394
1395// ---------------------------------------------------------------------------
1396// JWKS endpoint (RFC 7517)
1397// ---------------------------------------------------------------------------
1398
1399/// JSON Web Key Set (JWKS) endpoint ([RFC 7517](https://datatracker.ietf.org/doc/html/rfc7517)).
1400///
1401/// Returns the public keys used to verify tokens. Currently returns an
1402/// empty key set because HS256 (symmetric) signing is used; clients
1403/// should use the introspection endpoint for token validation.
1404///
1405/// # Example
1406/// ```rust,ignore
1407/// // GET /.well-known/jwks.json
1408/// let (status, Json(jwks)) = jwks(State(state)).await;
1409/// assert!(jwks["keys"].as_array().unwrap().is_empty());
1410/// ```
1411pub async fn jwks(State(_state): State<ApiState>) -> impl IntoResponse {
1412    (StatusCode::OK, Json(serde_json::json!({ "keys": [] })))
1413}
1414
1415// ---------------------------------------------------------------------------
1416// OIDC RP-Initiated Logout (OpenID Connect RP-Initiated Logout 1.0)
1417// ---------------------------------------------------------------------------
1418
1419/// Request parameters for OpenID Connect RP-Initiated Logout.
1420///
1421/// # Example
1422/// ```rust
1423/// use auth_framework::api::oauth2::EndSessionRequest;
1424///
1425/// let req: EndSessionRequest = serde_json::from_str(
1426///     r#"{"id_token_hint":"eyJ...","state":"xyz"}"#
1427/// ).unwrap();
1428/// assert!(req.post_logout_redirect_uri.is_none());
1429/// ```
1430#[derive(Debug, Deserialize)]
1431pub struct EndSessionRequest {
1432    pub id_token_hint: Option<String>,
1433    pub post_logout_redirect_uri: Option<String>,
1434    pub state: Option<String>,
1435}
1436
1437/// OIDC RP-Initiated Logout (OpenID Connect RP-Initiated Logout 1.0).
1438///
1439/// Revokes the token from `id_token_hint` (if valid) and, when a
1440/// registered `post_logout_redirect_uri` is provided, redirects the
1441/// user-agent there.
1442///
1443/// # Example
1444/// ```rust,ignore
1445/// // GET /oauth/end_session?id_token_hint=eyJ...&state=xyz
1446/// let resp = end_session(State(state), Query(params)).await;
1447/// ```
1448pub async fn end_session(
1449    State(state): State<ApiState>,
1450    Query(params): Query<EndSessionRequest>,
1451) -> impl IntoResponse {
1452    // If an id_token_hint is provided, revoke it
1453    if let Some(ref token) = params.id_token_hint
1454        && let Ok(claims) = state
1455            .auth_framework
1456            .token_manager()
1457            .validate_jwt_token(token)
1458    {
1459        let revoked_key = format!("oauth2_revoked_token:{}", token);
1460        if let Err(e) = state
1461            .auth_framework
1462            .storage()
1463            .store_kv(
1464                &revoked_key,
1465                b"revoked",
1466                Some(std::time::Duration::from_secs(86400 * 7)),
1467            )
1468            .await
1469        {
1470            tracing::warn!("Failed to revoke token during OIDC end_session: {}", e);
1471        }
1472        // the marker every bearer-token validation path reads
1473        if let Err(e) = state
1474            .auth_framework
1475            .storage()
1476            .store_kv(
1477                &format!("revoked_token:{}", claims.jti),
1478                b"revoked",
1479                Some(std::time::Duration::from_secs(
1480                    (claims.exp - chrono::Utc::now().timestamp()).max(60) as u64,
1481                )),
1482            )
1483            .await
1484        {
1485            tracing::warn!(
1486                "Failed to record jti revocation during OIDC end_session: {}",
1487                e
1488            );
1489        }
1490        tracing::info!("OIDC end_session: revoked token for user {}", claims.sub);
1491    }
1492
1493    // Redirect to post_logout_redirect_uri only if it matches a registered URI for the
1494    // client identified by id_token_hint.  Without this check an attacker could craft a
1495    // link that redirects users to an arbitrary URL (open redirect / phishing).
1496    if let Some(ref redirect_uri) = params.post_logout_redirect_uri {
1497        // Look up the client's registered redirect URIs via the id_token_hint's `azp` or `aud` claim.
1498        let allowed = if let Some(ref token) = params.id_token_hint {
1499            // Try to extract client_id from the token (azp > aud)
1500            let client_id = state
1501                .auth_framework
1502                .token_manager()
1503                .validate_jwt_token(token)
1504                .ok()
1505                .and_then(|claims| {
1506                    // client_id claim identifies the OAuth client
1507                    if let Some(ref cid) = claims.client_id
1508                        && !cid.is_empty()
1509                    {
1510                        return Some(cid.clone());
1511                    }
1512                    // Fallback: aud may contain the client_id
1513                    if !claims.aud.is_empty() {
1514                        Some(claims.aud.clone())
1515                    } else {
1516                        None
1517                    }
1518                });
1519            if let Some(cid) = client_id {
1520                let client_key = format!("oauth2_client:{}", cid);
1521                match state.auth_framework.storage().get_kv(&client_key).await {
1522                    Ok(Some(data)) => {
1523                        let client: serde_json::Value =
1524                            serde_json::from_slice(&data).unwrap_or_default();
1525                        let uris: Vec<String> = client["redirect_uris"]
1526                            .as_array()
1527                            .map(|a| {
1528                                a.iter()
1529                                    .filter_map(|v| v.as_str().map(String::from))
1530                                    .collect()
1531                            })
1532                            .unwrap_or_default();
1533                        uris.iter().any(|r| redirect_uri_matches(redirect_uri, r))
1534                    }
1535                    _ => false,
1536                }
1537            } else {
1538                false
1539            }
1540        } else {
1541            false
1542        };
1543
1544        if allowed {
1545            if let Ok(mut parsed) = Url::parse(redirect_uri) {
1546                if let Some(ref st) = params.state {
1547                    parsed.query_pairs_mut().append_pair("state", st);
1548                }
1549                return Redirect::to(parsed.as_str()).into_response();
1550            }
1551        } else {
1552            tracing::warn!(
1553                "end_session: post_logout_redirect_uri rejected — not registered for the client"
1554            );
1555        }
1556    }
1557
1558    // No redirect — return a simple JSON acknowledgement
1559    (
1560        StatusCode::OK,
1561        Json(serde_json::json!({ "status": "logged_out" })),
1562    )
1563        .into_response()
1564}
1565
1566// ---------------------------------------------------------------------------
1567// Dynamic Client Registration (RFC 7591)
1568// ---------------------------------------------------------------------------
1569
1570/// Dynamic client registration request per [RFC 7591](https://datatracker.ietf.org/doc/html/rfc7591).
1571///
1572/// # Example
1573/// ```rust
1574/// use auth_framework::api::oauth2::ClientRegistrationRequest;
1575///
1576/// let req: ClientRegistrationRequest = serde_json::from_str(
1577///     r#"{"redirect_uris":["https://example.com/cb"]}"#
1578/// ).unwrap();
1579/// assert_eq!(req.redirect_uris.len(), 1);
1580/// ```
1581#[derive(Debug, Deserialize)]
1582pub struct ClientRegistrationRequest {
1583    pub redirect_uris: Vec<String>,
1584    #[serde(default)]
1585    pub client_name: Option<String>,
1586    #[serde(default)]
1587    pub token_endpoint_auth_method: Option<String>,
1588    #[serde(default)]
1589    pub grant_types: Option<Vec<String>>,
1590    #[serde(default)]
1591    pub response_types: Option<Vec<String>>,
1592    #[serde(default)]
1593    pub scope: Option<String>,
1594}
1595
1596/// POST /oauth/register — dynamically register a new OAuth 2.0 client
1597/// ([RFC 7591](https://datatracker.ietf.org/doc/html/rfc7591)).
1598///
1599/// Requires a valid Bearer token with `admin` role, or an Initial Access
1600/// Token stored in KV at `oauth2_initial_access_token`. Unauthenticated
1601/// callers are rejected to prevent resource exhaustion.
1602///
1603/// # Example
1604/// ```rust,ignore
1605/// let resp = register_client(
1606///     State(state),
1607///     headers,   // with Authorization: Bearer <admin-token>
1608///     Json(ClientRegistrationRequest {
1609///         redirect_uris: vec!["https://example.com/cb".into()],
1610///         client_name: Some("My App".into()),
1611///         ..Default::default()
1612///     }),
1613/// ).await;
1614/// ```
1615pub async fn register_client(
1616    State(state): State<ApiState>,
1617    headers: HeaderMap,
1618    Json(req): Json<ClientRegistrationRequest>,
1619) -> impl IntoResponse {
1620    // RFC 7591 §1.2: require authentication via Bearer token
1621    let token_str = match extract_bearer_token(&headers) {
1622        Some(t) => t,
1623        None => {
1624            return (
1625                StatusCode::UNAUTHORIZED,
1626                Json(serde_json::json!({
1627                    "error": "invalid_token",
1628                    "error_description": "A valid Bearer token is required for dynamic client registration"
1629                })),
1630            )
1631                .into_response();
1632        }
1633    };
1634
1635    // Option 1: check if this is the pre-configured Initial Access Token
1636    let is_initial_access_token = match state
1637        .auth_framework
1638        .storage()
1639        .get_kv("oauth2_initial_access_token")
1640        .await
1641    {
1642        Ok(Some(stored)) => {
1643            let stored_str = String::from_utf8_lossy(&stored);
1644            subtle::ConstantTimeEq::ct_eq(token_str.as_bytes(), stored_str.trim().as_bytes()).into()
1645        }
1646        _ => false,
1647    };
1648
1649    // Option 2: validate as a normal JWT and check for admin role
1650    let is_admin = if !is_initial_access_token {
1651        match validate_api_token(&state.auth_framework, &token_str).await {
1652            Ok(auth_token) => auth_token.roles.contains("admin"),
1653            Err(_) => false,
1654        }
1655    } else {
1656        false
1657    };
1658
1659    if !is_initial_access_token && !is_admin {
1660        return (
1661            StatusCode::FORBIDDEN,
1662            Json(serde_json::json!({
1663                "error": "insufficient_scope",
1664                "error_description": "Dynamic client registration requires admin privileges or a valid Initial Access Token"
1665            })),
1666        )
1667            .into_response();
1668    }
1669    // Validate all redirect_uris are well-formed URLs with safe schemes
1670    for uri in &req.redirect_uris {
1671        match Url::parse(uri) {
1672            Ok(parsed) => {
1673                match parsed.scheme() {
1674                    "https" => {}
1675                    "http" => {
1676                        // Allow plain HTTP only for loopback addresses (development)
1677                        if !matches!(parsed.host_str(), Some("localhost" | "127.0.0.1" | "[::1]")) {
1678                            return (
1679                                StatusCode::BAD_REQUEST,
1680                                Json(serde_json::json!({
1681                                    "error": "invalid_redirect_uri",
1682                                    "error_description": format!("Non-loopback HTTP redirect_uri not allowed: {}", uri)
1683                                })),
1684                            )
1685                                .into_response();
1686                        }
1687                    }
1688                    scheme => {
1689                        return (
1690                            StatusCode::BAD_REQUEST,
1691                            Json(serde_json::json!({
1692                                "error": "invalid_redirect_uri",
1693                                "error_description": format!("Disallowed URI scheme '{}' in redirect_uri: {}", scheme, uri)
1694                            })),
1695                        )
1696                            .into_response();
1697                    }
1698                }
1699            }
1700            Err(_) => {
1701                return (
1702                    StatusCode::BAD_REQUEST,
1703                    Json(serde_json::json!({
1704                        "error": "invalid_redirect_uri",
1705                        "error_description": format!("Invalid redirect_uri: {}", uri)
1706                    })),
1707                )
1708                    .into_response();
1709            }
1710        }
1711    }
1712
1713    if req.redirect_uris.is_empty() {
1714        return (
1715            StatusCode::BAD_REQUEST,
1716            Json(serde_json::json!({
1717                "error": "invalid_client_metadata",
1718                "error_description": "At least one redirect_uri is required"
1719            })),
1720        )
1721            .into_response();
1722    }
1723
1724    let client_id = Uuid::new_v4().to_string();
1725    let client_secret = Uuid::new_v4().to_string();
1726
1727    let client_data = serde_json::json!({
1728        "client_id": client_id,
1729        "client_secret": client_secret,
1730        "client_name": req.client_name,
1731        "redirect_uris": req.redirect_uris,
1732        "token_endpoint_auth_method": req.token_endpoint_auth_method.as_deref().unwrap_or("client_secret_basic"),
1733        "grant_types": req.grant_types.as_deref().unwrap_or(&["authorization_code".to_string()]),
1734        "response_types": req.response_types.as_deref().unwrap_or(&["code".to_string()]),
1735        "scope": req.scope.as_deref().unwrap_or("openid"),
1736    });
1737
1738    let key = format!("oauth2_client:{}", client_id);
1739    if let Err(e) = state
1740        .auth_framework
1741        .storage()
1742        .store_kv(&key, client_data.to_string().as_bytes(), None)
1743        .await
1744    {
1745        tracing::error!("Failed to store client registration: {}", e);
1746        return (
1747            StatusCode::INTERNAL_SERVER_ERROR,
1748            Json(serde_json::json!({
1749                "error": "server_error",
1750                "error_description": "Failed to register client"
1751            })),
1752        )
1753            .into_response();
1754    }
1755
1756    tracing::info!("Dynamic client registered: client_id={}", client_id);
1757
1758    (
1759        StatusCode::CREATED,
1760        Json(serde_json::json!({
1761            "client_id": client_id,
1762            "client_secret": client_secret,
1763            "client_name": req.client_name,
1764            "redirect_uris": req.redirect_uris,
1765            "token_endpoint_auth_method": req.token_endpoint_auth_method.as_deref().unwrap_or("client_secret_basic"),
1766            "grant_types": req.grant_types.as_deref().unwrap_or(&["authorization_code".to_string()]),
1767            "response_types": req.response_types.as_deref().unwrap_or(&["code".to_string()]),
1768            "scope": req.scope.as_deref().unwrap_or("openid"),
1769        })),
1770    )
1771        .into_response()
1772}
1773
1774// ---------------------------------------------------------------------------
1775// /users/me — alias for the authenticated user's profile
1776// ---------------------------------------------------------------------------
1777
1778/// GET /users/me — returns the authenticated user's profile.
1779///
1780/// Convenience alias that delegates to [`userinfo`].
1781///
1782/// # Example
1783/// ```rust,ignore
1784/// // GET /users/me  Authorization: Bearer <token>
1785/// let resp = users_me(state, headers).await;
1786/// ```
1787pub async fn users_me(state: State<ApiState>, headers: HeaderMap) -> impl IntoResponse {
1788    // Delegate to the existing userinfo handler
1789    userinfo(state, headers).await
1790}