Skip to main content

auth_framework/api/
oauth2.rs

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