1use crate::api::{ApiResponse, ApiState, extract_bearer_token, validate_api_token};
7use crate::oauth2_server::AuthorizationRequest;
8pub 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
24fn redirect_uri_matches(candidate: &str, registered: &str) -> bool {
29 match (Url::parse(candidate), Url::parse(registered)) {
30 (Ok(a), Ok(b)) => {
31 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 _ => candidate == registered,
45 }
46}
47
48#[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 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 pub fn description(mut self, desc: impl Into<String>) -> Self {
87 self.error_description = Some(desc.into());
88 self
89 }
90
91 pub fn state(mut self, state: impl Into<String>) -> Self {
93 self.state = Some(state.into());
94 self
95 }
96
97 pub fn maybe_state(mut self, state: Option<String>) -> Self {
99 self.state = state;
100 self
101 }
102
103 pub fn error_uri(mut self, uri: impl Into<String>) -> Self {
105 self.error_uri = Some(uri.into());
106 self
107 }
108}
109
110#[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#[derive(Deserialize)]
148pub struct RevokeRequest {
149 pub token: String,
150 #[serde(default)]
151 pub token_type_hint: Option<String>, }
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#[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
194pub 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 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 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(¶ms.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 let is_public_client = client_data
287 .get("client_secret")
288 .and_then(|v| v.as_str())
289 .is_none_or(|s| s.is_empty());
290 if is_public_client && params.code_challenge.is_none() {
291 let error = OAuthError::new("invalid_request")
292 .description("Public clients must use PKCE: code_challenge is required")
293 .maybe_state(params.state);
294 return (StatusCode::BAD_REQUEST, Json(error)).into_response();
295 }
296 }
297 Ok(None) => {
298 tracing::warn!(client_id = %params.client_id, "OAuth authorize: unknown client_id");
299 let error = OAuthError::new("invalid_client")
300 .description("Unknown client_id")
301 .maybe_state(params.state);
302 return (StatusCode::BAD_REQUEST, Json(error)).into_response();
303 }
304 Err(e) => {
305 tracing::error!(
306 client_id = %params.client_id,
307 error = %e,
308 "OAuth authorize: storage error looking up client"
309 );
310 let error = OAuthError::new("server_error")
311 .description("Authorization server error")
312 .maybe_state(params.state);
313 return (StatusCode::INTERNAL_SERVER_ERROR, Json(error)).into_response();
314 }
315 }
316
317 let auth_code = format!("ac_{}", uuid::Uuid::new_v4().to_string().replace("-", ""));
318
319 if let Some(ref resources) = params.resource
321 && let Err(e) =
322 crate::server::oauth::resource_indicators::validate_resource_indicators(resources)
323 {
324 let error = OAuthError::new("invalid_target")
325 .description(e.to_string())
326 .maybe_state(params.state);
327 return (StatusCode::BAD_REQUEST, Json(error)).into_response();
328 }
329
330 let code_data = serde_json::json!({
331 "client_id": params.client_id,
332 "redirect_uri": params.redirect_uri,
333 "scope": params.scope.clone().unwrap_or_else(|| "openid profile email".to_string()),
334 "state": params.state.clone(),
335 "code_challenge": params.code_challenge,
336 "code_challenge_method": params.code_challenge_method,
337 "user_id": user_id,
338 "resource": params.resource,
339 "created_at": chrono::Utc::now().to_rfc3339(),
340 "expires_at": (chrono::Utc::now() + chrono::Duration::minutes(10)).to_rfc3339(),
341 "used": false,
342 });
343
344 let storage_key = format!("oauth2_code:{}", auth_code);
345 let code_data_str = match serde_json::to_string(&code_data) {
346 Ok(s) => s,
347 Err(e) => {
348 tracing::error!("Failed to serialize OAuth authorization code data: {:?}", e);
349 let error =
350 OAuthError::new("server_error").description("Authorization server internal error");
351 return (StatusCode::INTERNAL_SERVER_ERROR, Json(error)).into_response();
352 }
353 };
354
355 if let Err(e) = state
356 .auth_framework
357 .storage()
358 .store_kv(
359 &storage_key,
360 code_data_str.as_bytes(),
361 Some(std::time::Duration::from_secs(600)),
362 )
363 .await
364 {
365 tracing::error!("Failed to store OAuth authorization code: {:?}", e);
366 let error = OAuthError::new("server_error")
367 .description("Authorization server error")
368 .maybe_state(params.state);
369 return (StatusCode::INTERNAL_SERVER_ERROR, Json(error)).into_response();
370 }
371
372 let encoded_state: Option<String> = params.state.as_deref().map(|st| {
375 st.bytes()
376 .flat_map(|b| {
377 if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~') {
378 vec![b as char]
379 } else {
380 format!("%{:02X}", b).chars().collect()
381 }
382 })
383 .collect()
384 });
385
386 let mut redirect_url = params.redirect_uri;
387 redirect_url.push_str(&format!("?code={}", auth_code));
388 if let Some(ref st) = encoded_state {
389 redirect_url.push_str(&format!("&state={}", st));
390 }
391
392 tracing::info!(
393 client_id = %params.client_id,
394 user_id = %user_id,
395 "OAuth authorization code issued"
396 );
397 Redirect::to(&redirect_url).into_response()
398}
399
400pub async fn token(
414 State(state): State<ApiState>,
415 Json(req): Json<TokenRequest>,
416) -> ApiResponse<TokenResponse> {
417 match req.grant_type.as_str() {
418 "authorization_code" => handle_authorization_code_grant(state, req).await,
419 "refresh_token" => handle_refresh_token_grant(state, req).await,
420 _ => ApiResponse::error_typed(
421 "unsupported_grant_type",
422 "Supported grant types: authorization_code, refresh_token",
423 ),
424 }
425}
426
427async fn handle_authorization_code_grant(
428 state: ApiState,
429 req: TokenRequest,
430) -> ApiResponse<TokenResponse> {
431 let code = match req.code {
432 Some(c) => c,
433 None => {
434 return ApiResponse::validation_error_typed(
435 "code is required for authorization_code grant",
436 );
437 }
438 };
439
440 let client_id = match req.client_id {
441 Some(c) => c,
442 None => return ApiResponse::validation_error_typed("client_id is required"),
443 };
444
445 let consumed_key = format!("oauth2_code_consumed:{}", code);
449 if let Ok(Some(_)) = state.auth_framework.storage().get_kv(&consumed_key).await {
450 return ApiResponse::error_typed("invalid_grant", "Authorization code already used");
451 }
452 if let Err(e) = state
454 .auth_framework
455 .storage()
456 .store_kv(
457 &consumed_key,
458 b"1",
459 Some(std::time::Duration::from_secs(600)),
460 )
461 .await
462 {
463 tracing::warn!("Failed to store code consumed marker: {:?}", e);
464 }
465
466 let storage_key = format!("oauth2_code:{}", code);
467 let code_data = match state.auth_framework.storage().get_kv(&storage_key).await {
468 Ok(Some(data)) => match serde_json::from_slice::<serde_json::Value>(&data) {
469 Ok(json) => json,
470 Err(e) => {
471 tracing::error!("Failed to parse stored authorization code data: {:?}", e);
472 return ApiResponse::error_typed("invalid_grant", "Invalid authorization code");
473 }
474 },
475 Ok(None) => {
476 return ApiResponse::error_typed(
477 "invalid_grant",
478 "Authorization code not found or expired",
479 );
480 }
481 Err(e) => {
482 tracing::error!("Failed to retrieve authorization code: {:?}", e);
483 return ApiResponse::error_typed(
484 "server_error",
485 "Failed to validate authorization code",
486 );
487 }
488 };
489
490 if let Err(e) = state.auth_framework.storage().delete_kv(&storage_key).await {
492 tracing::error!("Failed to delete authorization code from storage: {:?}", e);
493 return ApiResponse::error_typed("server_error", "Failed to process authorization code");
494 }
495
496 if code_data["client_id"].as_str() != Some(&client_id) {
498 return ApiResponse::error_typed("invalid_grant", "client_id mismatch");
499 }
500
501 if let Some(redirect_uri) = &req.redirect_uri {
503 let stored_uri = code_data["redirect_uri"].as_str().unwrap_or_default();
504 if !redirect_uri_matches(redirect_uri, stored_uri) {
505 return ApiResponse::error_typed("invalid_grant", "redirect_uri mismatch");
506 }
507 }
508
509 let stored_challenge = code_data["code_challenge"].as_str();
511 let challenge_method = code_data["code_challenge_method"]
512 .as_str()
513 .unwrap_or("plain");
514
515 if let Some(stored) = stored_challenge {
516 let code_verifier = match &req.code_verifier {
518 Some(verifier) => verifier,
519 None => {
520 return ApiResponse::error_typed(
521 "invalid_request",
522 "code_verifier is required when PKCE challenge was provided",
523 );
524 }
525 };
526
527 let computed_challenge = match challenge_method {
528 "S256" => {
529 let mut hasher = Sha256::new();
530 hasher.update(code_verifier.as_bytes());
531 URL_SAFE_NO_PAD.encode(hasher.finalize())
532 }
533 "plain" => code_verifier.clone(),
534 _ => {
535 return ApiResponse::error_typed(
536 "invalid_request",
537 "Unsupported code_challenge_method",
538 );
539 }
540 };
541
542 if computed_challenge != stored {
543 return ApiResponse::error_typed("invalid_grant", "PKCE verification failed");
544 }
545 } else if req.code_verifier.is_some() {
546 return ApiResponse::error_typed(
548 "invalid_request",
549 "code_verifier provided but no PKCE challenge was used in authorization",
550 );
551 } else if req.client_secret.is_none() {
552 return ApiResponse::error_typed(
556 "invalid_request",
557 "Public clients must use PKCE: provide code_challenge in authorization and code_verifier in token request",
558 );
559 }
560
561 let authz_resources: Vec<String> = code_data["resource"]
566 .as_array()
567 .map(|arr| {
568 arr.iter()
569 .filter_map(|v| v.as_str().map(String::from))
570 .collect()
571 })
572 .unwrap_or_default();
573
574 if let Some(ref token_resources) = req.resource {
575 if let Err(e) =
576 crate::server::oauth::resource_indicators::validate_resource_indicators(token_resources)
577 {
578 return ApiResponse::error_typed("invalid_target", e.to_string());
579 }
580 if let Err(e) = crate::server::oauth::resource_indicators::validate_token_resource_subset(
581 token_resources,
582 &authz_resources,
583 ) {
584 return ApiResponse::error_typed("invalid_target", e.to_string());
585 }
586 }
587
588 let scope = code_data["scope"]
590 .as_str()
591 .unwrap_or("openid profile email");
592 let scopes: Vec<String> = scope.split_whitespace().map(|s| s.to_string()).collect();
593
594 let user_id = match code_data["user_id"].as_str() {
598 Some(uid) if !uid.is_empty() => uid.to_string(),
599 _ => {
600 tracing::error!("Authorization code missing user_id field");
601 return ApiResponse::error_typed("server_error", "Malformed authorization code");
602 }
603 };
604
605 let token = match state.auth_framework.token_manager().create_auth_token(
606 &user_id,
607 scopes.clone(),
608 "oauth2",
609 None,
610 ) {
611 Ok(token) => token,
612 Err(e) => {
613 tracing::error!("Failed to create access token: {:?}", e);
614 return ApiResponse::error_typed("server_error", "Failed to create access token");
615 }
616 };
617
618 let refresh_token_value = uuid::Uuid::new_v4().to_string().replace("-", "");
620 let refresh_data = serde_json::json!({
621 "user_id": user_id,
622 "client_id": client_id,
623 "scopes": scope,
624 });
625 let refresh_key = format!("oauth2_refresh_token:{}", refresh_token_value);
626 if let Err(e) = state
627 .auth_framework
628 .storage()
629 .store_kv(
630 &refresh_key,
631 serde_json::to_string(&refresh_data)
632 .unwrap_or_default()
633 .as_bytes(),
634 Some(std::time::Duration::from_secs(30 * 24 * 3600)),
635 )
636 .await
637 {
638 tracing::warn!("Failed to store refresh token: {:?}", e);
639 }
640
641 let expires_in = (token.expires_at - token.issued_at).num_seconds().max(0) as u64;
642 let response = TokenResponse {
643 access_token: token.access_token,
644 token_type: "Bearer".to_string(),
645 expires_in,
646 refresh_token: Some(refresh_token_value),
647 scope: Some(scope.to_string()),
648 id_token: None,
649 };
650
651 tracing::info!("OAuth2 tokens issued for client: {}", client_id);
652 ApiResponse::success(response)
653}
654
655async fn handle_refresh_token_grant(
656 state: ApiState,
657 req: TokenRequest,
658) -> ApiResponse<TokenResponse> {
659 let refresh_token_str = match req.refresh_token {
660 Some(t) => t,
661 None => return ApiResponse::validation_error_typed("refresh_token is required"),
662 };
663
664 let revoked_key = format!("oauth2_revoked_token:{}", refresh_token_str);
670 match state.auth_framework.storage().get_kv(&revoked_key).await {
671 Ok(Some(_)) => {
672 return ApiResponse::error_typed("invalid_grant", "Refresh token has been revoked");
673 }
674 Ok(None) => {} Err(e) => {
676 tracing::error!("Refresh token revocation check failed: {:?}", e);
677 return ApiResponse::error_typed("server_error", "Failed to validate refresh token");
678 }
679 }
680
681 let consumed_key = format!("oauth2_refresh_consumed:{}", refresh_token_str);
684 if let Ok(Some(_)) = state.auth_framework.storage().get_kv(&consumed_key).await {
685 return ApiResponse::error_typed("invalid_grant", "Refresh token already consumed");
686 }
687 if let Err(e) = state
688 .auth_framework
689 .storage()
690 .store_kv(
691 &consumed_key,
692 b"1",
693 Some(std::time::Duration::from_secs(600)),
694 )
695 .await
696 {
697 tracing::warn!("Failed to store refresh consumed marker: {:?}", e);
698 }
699
700 let refresh_key = format!("oauth2_refresh_token:{}", refresh_token_str);
702 let stored = match state.auth_framework.storage().get_kv(&refresh_key).await {
703 Ok(Some(data)) => match serde_json::from_slice::<serde_json::Value>(&data) {
704 Ok(v) => v,
705 Err(_) => return ApiResponse::error_typed("invalid_grant", "Invalid refresh token"),
706 },
707 Ok(None) => {
708 return ApiResponse::error_typed("invalid_grant", "Refresh token not found or expired");
709 }
710 Err(e) => {
711 tracing::error!("Failed to retrieve refresh token: {:?}", e);
712 return ApiResponse::error_typed("server_error", "Failed to validate refresh token");
713 }
714 };
715
716 let user_id = match stored["user_id"].as_str() {
717 Some(u) => u.to_string(),
718 None => return ApiResponse::error_typed("invalid_grant", "Malformed refresh token data"),
719 };
720 let client_id = stored["client_id"].as_str().map(|s| s.to_string());
721 let scope = stored["scopes"]
722 .as_str()
723 .unwrap_or("openid profile email")
724 .to_string();
725 let scopes: Vec<String> = scope.split_whitespace().map(|s| s.to_string()).collect();
726
727 let token = match state
728 .auth_framework
729 .token_manager()
730 .create_auth_token(&user_id, scopes, "oauth2", None)
731 {
732 Ok(t) => t,
733 Err(e) => {
734 tracing::error!("Failed to create access token on refresh: {:?}", e);
735 return ApiResponse::error_typed("server_error", "Failed to issue access token");
736 }
737 };
738
739 let new_refresh_token = uuid::Uuid::new_v4().to_string().replace("-", "");
742 let new_refresh_data = serde_json::json!({
743 "user_id": user_id,
744 "client_id": client_id,
745 "scopes": scope,
746 });
747 let new_refresh_key = format!("oauth2_refresh_token:{}", new_refresh_token);
748 if let Err(e) = state
749 .auth_framework
750 .storage()
751 .store_kv(
752 &new_refresh_key,
753 serde_json::to_string(&new_refresh_data)
754 .unwrap_or_default()
755 .as_bytes(),
756 Some(std::time::Duration::from_secs(30 * 24 * 3600)),
757 )
758 .await
759 {
760 tracing::error!("Failed to store new refresh token: {:?}", e);
761 return ApiResponse::error_typed("server_error", "Failed to issue refresh token");
762 }
763
764 if let Err(e) = state.auth_framework.storage().delete_kv(&refresh_key).await {
766 tracing::warn!(
767 "Failed to delete old refresh token during rotation: {:?}",
768 e
769 );
770 }
771
772 let expires_in = (token.expires_at - token.issued_at).num_seconds().max(0) as u64;
773 let response = TokenResponse {
774 access_token: token.access_token,
775 token_type: "Bearer".to_string(),
776 expires_in,
777 refresh_token: Some(new_refresh_token),
778 scope: Some(scope),
779 id_token: None,
780 };
781
782 tracing::info!("OAuth2 token refreshed for user: {}", user_id);
783 ApiResponse::success(response)
784}
785
786pub async fn revoke(
809 State(state): State<ApiState>,
810 Json(req): Json<RevokeRequest>,
811) -> ApiResponse<serde_json::Value> {
812 let revoked_token_key = format!("oauth2_revoked_token:{}", req.token);
815 let revoked_data = serde_json::json!({
816 "token": req.token,
817 "revoked_at": chrono::Utc::now().to_rfc3339(),
818 "token_type_hint": req.token_type_hint
819 });
820
821 if let Err(e) = state
822 .auth_framework
823 .storage()
824 .store_kv(
825 &revoked_token_key,
826 serde_json::to_string(&revoked_data)
827 .unwrap_or_default()
828 .as_bytes(),
829 Some(std::time::Duration::from_secs(86400 * 30)),
835 )
836 .await
837 {
838 tracing::error!("Failed to store revoked token: {:?}", e);
839 return ApiResponse::error_typed("server_error", "Failed to revoke token");
840 }
841
842 let refresh_key = format!("oauth2_refresh_token:{}", req.token);
847 if let Err(e) = state.auth_framework.storage().delete_kv(&refresh_key).await {
848 tracing::warn!("Failed to delete refresh token on revoke: {:?}", e);
849 }
850
851 if let Ok(claims) = state
856 .auth_framework
857 .token_manager()
858 .validate_jwt_token(&req.token)
859 {
860 let now = chrono::Utc::now().timestamp();
861 let remaining_secs = (claims.exp - now + 60).max(60) as u64;
862 let jti_key = format!("revoked_token:{}", claims.jti);
863 if let Err(e) = state
864 .auth_framework
865 .storage()
866 .store_kv(
867 &jti_key,
868 b"1",
869 Some(std::time::Duration::from_secs(remaining_secs)),
870 )
871 .await
872 {
873 tracing::warn!("Failed to store JWT JTI revocation entry: {:?}", e);
874 } else {
875 tracing::info!("JWT token revoked via jti: {}", claims.jti);
876 }
877 }
878
879 tracing::info!(
880 "OAuth2 token revoked: {}",
881 &req.token[..10.min(req.token.len())]
882 );
883
884 ApiResponse::success(serde_json::json!({
885 "message": "Token revoked successfully"
886 }))
887}
888
889pub async fn userinfo(
902 State(state): State<ApiState>,
903 headers: HeaderMap,
904) -> ApiResponse<UserInfoResponse> {
905 let token = match extract_bearer_token(&headers) {
907 Some(t) => t,
908 None => {
909 return ApiResponse::error_typed("invalid_token", "Authorization header required");
910 }
911 };
912
913 let revoked_token_key = format!("oauth2_revoked_token:{}", token);
915 if let Ok(Some(_)) = state
916 .auth_framework
917 .storage()
918 .get_kv(&revoked_token_key)
919 .await
920 {
921 return ApiResponse::error_typed("invalid_token", "Token has been revoked");
922 }
923
924 let claims = match state
926 .auth_framework
927 .token_manager()
928 .validate_jwt_token(&token)
929 {
930 Ok(c) => c,
931 Err(_) => {
932 return ApiResponse::error_typed("invalid_token", "Access token is invalid");
933 }
934 };
935
936 let user_profile = match state.auth_framework.get_user_profile(&claims.sub).await {
938 Ok(profile) => profile,
939 Err(e) => {
940 tracing::error!("Failed to get user profile: {:?}", e);
941 return ApiResponse::error_typed("server_error", "Failed to retrieve user information");
942 }
943 };
944
945 let userinfo = UserInfoResponse {
946 sub: claims.sub.clone(),
947 name: user_profile.username.clone(),
948 email: if claims.scope.split_whitespace().any(|s| s == "email") {
950 user_profile.email.clone()
951 } else {
952 None
953 },
954 picture: user_profile.picture.clone(),
955 updated_at: Some(chrono::Utc::now().timestamp()),
956 };
957
958 tracing::info!("OAuth2 UserInfo requested for user: {}", claims.sub);
959 ApiResponse::success(userinfo)
960}
961
962pub async fn get_client_info(
970 State(state): State<ApiState>,
971 Path(client_id): Path<String>,
972) -> impl IntoResponse {
973 let client_key = format!("oauth2_client:{}", client_id);
974 match state.auth_framework.storage().get_kv(&client_key).await {
975 Ok(Some(data)) => match serde_json::from_slice::<ClientInfo>(&data) {
976 Ok(client) => (
977 StatusCode::OK,
978 Json(serde_json::json!({ "success": true, "data": client })),
979 )
980 .into_response(),
981 Err(e) => {
982 tracing::error!(client_id = %client_id, error = %e, "Failed to deserialize client record");
983 (
984 StatusCode::INTERNAL_SERVER_ERROR,
985 Json(serde_json::json!({
986 "success": false,
987 "error": "server_error",
988 "message": "Failed to read client record"
989 })),
990 )
991 .into_response()
992 }
993 },
994 Ok(None) => (
995 StatusCode::NOT_FOUND,
996 Json(serde_json::json!({
997 "success": false,
998 "error": "invalid_client",
999 "message": "Unknown client_id"
1000 })),
1001 )
1002 .into_response(),
1003 Err(e) => {
1004 tracing::error!(client_id = %client_id, error = %e, "Storage error looking up client");
1005 (
1006 StatusCode::INTERNAL_SERVER_ERROR,
1007 Json(serde_json::json!({
1008 "success": false,
1009 "error": "server_error",
1010 "message": "Authorization server error"
1011 })),
1012 )
1013 .into_response()
1014 }
1015 }
1016}
1017
1018pub async fn openid_configuration(State(state): State<ApiState>) -> impl IntoResponse {
1034 let issuer = {
1035 let configured = state.auth_framework.config().issuer.clone();
1036 if configured.is_empty() {
1037 "https://auth.example.com".to_string()
1038 } else {
1039 configured
1040 }
1041 };
1042
1043 let config = serde_json::json!({
1044 "issuer": issuer,
1045 "authorization_endpoint": format!("{}/api/v1/oauth/authorize", issuer),
1046 "token_endpoint": format!("{}/api/v1/oauth/token", issuer),
1047 "userinfo_endpoint": format!("{}/api/v1/oauth/userinfo", issuer),
1048 "revocation_endpoint": format!("{}/api/v1/oauth/revoke", issuer),
1049 "introspection_endpoint": format!("{}/api/v1/oauth/introspect", issuer),
1050 "jwks_uri": format!("{}/api/v1/.well-known/jwks.json", issuer),
1051 "end_session_endpoint": format!("{}/api/v1/oauth/end_session", issuer),
1052 "pushed_authorization_request_endpoint": format!("{}/api/v1/oauth/par", issuer),
1053 "registration_endpoint": format!("{}/api/v1/oauth/register", issuer),
1054 "response_types_supported": ["code"],
1055 "grant_types_supported": [
1056 "authorization_code",
1057 "refresh_token"
1058 ],
1059 "subject_types_supported": ["public"],
1060 "id_token_signing_alg_values_supported": ["HS256"],
1061 "token_endpoint_auth_methods_supported": [
1062 "client_secret_basic",
1063 "client_secret_post"
1064 ],
1065 "code_challenge_methods_supported": ["S256"],
1066 "scopes_supported": ["openid", "profile", "email"]
1067 });
1068
1069 (StatusCode::OK, Json(config))
1070}
1071
1072pub async fn jwks(State(_state): State<ApiState>) -> impl IntoResponse {
1089 (StatusCode::OK, Json(serde_json::json!({ "keys": [] })))
1090}
1091
1092#[derive(Deserialize)]
1108pub struct EndSessionRequest {
1109 pub id_token_hint: Option<String>,
1110 pub post_logout_redirect_uri: Option<String>,
1111 pub state: Option<String>,
1112}
1113
1114impl std::fmt::Debug for EndSessionRequest {
1115 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1116 let mut d = f.debug_struct("EndSessionRequest");
1117 d.field(
1118 "id_token_hint",
1119 &crate::utils::redact::redacted(&self.id_token_hint),
1120 );
1121 d.field("post_logout_redirect_uri", &self.post_logout_redirect_uri);
1122 d.field("state", &self.state);
1123 d.finish()
1124 }
1125}
1126
1127pub async fn end_session(
1139 State(state): State<ApiState>,
1140 Query(params): Query<EndSessionRequest>,
1141) -> impl IntoResponse {
1142 if let Some(ref token) = params.id_token_hint
1144 && let Ok(claims) = state
1145 .auth_framework
1146 .token_manager()
1147 .validate_jwt_token(token)
1148 {
1149 let revoked_key = format!("oauth2_revoked_token:{}", token);
1150 if let Err(e) = state
1151 .auth_framework
1152 .storage()
1153 .store_kv(
1154 &revoked_key,
1155 b"revoked",
1156 Some(std::time::Duration::from_secs(86400 * 7)),
1157 )
1158 .await
1159 {
1160 tracing::warn!("Failed to revoke token during OIDC end_session: {}", e);
1161 }
1162 tracing::info!("OIDC end_session: revoked token for user {}", claims.sub);
1163 }
1164
1165 if let Some(ref redirect_uri) = params.post_logout_redirect_uri {
1169 let allowed = if let Some(ref token) = params.id_token_hint {
1171 let client_id = state
1173 .auth_framework
1174 .token_manager()
1175 .validate_jwt_token(token)
1176 .ok()
1177 .and_then(|claims| {
1178 if let Some(ref cid) = claims.client_id
1180 && !cid.is_empty()
1181 {
1182 return Some(cid.clone());
1183 }
1184 if !claims.aud.is_empty() {
1186 Some(claims.aud.clone())
1187 } else {
1188 None
1189 }
1190 });
1191 if let Some(cid) = client_id {
1192 let client_key = format!("oauth2_client:{}", cid);
1193 match state.auth_framework.storage().get_kv(&client_key).await {
1194 Ok(Some(data)) => {
1195 let client: serde_json::Value =
1196 serde_json::from_slice(&data).unwrap_or_default();
1197 let uris: Vec<String> = client["redirect_uris"]
1198 .as_array()
1199 .map(|a| {
1200 a.iter()
1201 .filter_map(|v| v.as_str().map(String::from))
1202 .collect()
1203 })
1204 .unwrap_or_default();
1205 uris.iter().any(|r| redirect_uri_matches(redirect_uri, r))
1206 }
1207 _ => false,
1208 }
1209 } else {
1210 false
1211 }
1212 } else {
1213 false
1214 };
1215
1216 if allowed {
1217 if let Ok(mut parsed) = Url::parse(redirect_uri) {
1218 if let Some(ref st) = params.state {
1219 parsed.query_pairs_mut().append_pair("state", st);
1220 }
1221 return Redirect::to(parsed.as_str()).into_response();
1222 }
1223 } else {
1224 tracing::warn!(
1225 "end_session: post_logout_redirect_uri rejected — not registered for the client"
1226 );
1227 }
1228 }
1229
1230 (
1232 StatusCode::OK,
1233 Json(serde_json::json!({ "status": "logged_out" })),
1234 )
1235 .into_response()
1236}
1237
1238#[derive(Debug, Deserialize)]
1254pub struct ClientRegistrationRequest {
1255 pub redirect_uris: Vec<String>,
1256 #[serde(default)]
1257 pub client_name: Option<String>,
1258 #[serde(default)]
1259 pub token_endpoint_auth_method: Option<String>,
1260 #[serde(default)]
1261 pub grant_types: Option<Vec<String>>,
1262 #[serde(default)]
1263 pub response_types: Option<Vec<String>>,
1264 #[serde(default)]
1265 pub scope: Option<String>,
1266}
1267
1268pub async fn register_client(
1288 State(state): State<ApiState>,
1289 headers: HeaderMap,
1290 Json(req): Json<ClientRegistrationRequest>,
1291) -> impl IntoResponse {
1292 let token_str = match extract_bearer_token(&headers) {
1294 Some(t) => t,
1295 None => {
1296 return (
1297 StatusCode::UNAUTHORIZED,
1298 Json(serde_json::json!({
1299 "error": "invalid_token",
1300 "error_description": "A valid Bearer token is required for dynamic client registration"
1301 })),
1302 )
1303 .into_response();
1304 }
1305 };
1306
1307 let is_initial_access_token = match state
1309 .auth_framework
1310 .storage()
1311 .get_kv("oauth2_initial_access_token")
1312 .await
1313 {
1314 Ok(Some(stored)) => {
1315 let stored_str = String::from_utf8_lossy(&stored);
1316 subtle::ConstantTimeEq::ct_eq(token_str.as_bytes(), stored_str.trim().as_bytes()).into()
1317 }
1318 _ => false,
1319 };
1320
1321 let is_admin = if !is_initial_access_token {
1323 match validate_api_token(&state.auth_framework, &token_str).await {
1324 Ok(auth_token) => auth_token.roles.contains("admin"),
1325 Err(_) => false,
1326 }
1327 } else {
1328 false
1329 };
1330
1331 if !is_initial_access_token && !is_admin {
1332 return (
1333 StatusCode::FORBIDDEN,
1334 Json(serde_json::json!({
1335 "error": "insufficient_scope",
1336 "error_description": "Dynamic client registration requires admin privileges or a valid Initial Access Token"
1337 })),
1338 )
1339 .into_response();
1340 }
1341 for uri in &req.redirect_uris {
1343 match Url::parse(uri) {
1344 Ok(parsed) => {
1345 match parsed.scheme() {
1346 "https" => {}
1347 "http" => {
1348 if !matches!(parsed.host_str(), Some("localhost" | "127.0.0.1" | "[::1]")) {
1350 return (
1351 StatusCode::BAD_REQUEST,
1352 Json(serde_json::json!({
1353 "error": "invalid_redirect_uri",
1354 "error_description": format!("Non-loopback HTTP redirect_uri not allowed: {}", uri)
1355 })),
1356 )
1357 .into_response();
1358 }
1359 }
1360 scheme => {
1361 return (
1362 StatusCode::BAD_REQUEST,
1363 Json(serde_json::json!({
1364 "error": "invalid_redirect_uri",
1365 "error_description": format!("Disallowed URI scheme '{}' in redirect_uri: {}", scheme, uri)
1366 })),
1367 )
1368 .into_response();
1369 }
1370 }
1371 }
1372 Err(_) => {
1373 return (
1374 StatusCode::BAD_REQUEST,
1375 Json(serde_json::json!({
1376 "error": "invalid_redirect_uri",
1377 "error_description": format!("Invalid redirect_uri: {}", uri)
1378 })),
1379 )
1380 .into_response();
1381 }
1382 }
1383 }
1384
1385 if req.redirect_uris.is_empty() {
1386 return (
1387 StatusCode::BAD_REQUEST,
1388 Json(serde_json::json!({
1389 "error": "invalid_client_metadata",
1390 "error_description": "At least one redirect_uri is required"
1391 })),
1392 )
1393 .into_response();
1394 }
1395
1396 let client_id = Uuid::new_v4().to_string();
1397 let client_secret = Uuid::new_v4().to_string();
1398
1399 let client_data = serde_json::json!({
1400 "client_id": client_id,
1401 "client_secret": client_secret,
1402 "client_name": req.client_name,
1403 "redirect_uris": req.redirect_uris,
1404 "token_endpoint_auth_method": req.token_endpoint_auth_method.as_deref().unwrap_or("client_secret_basic"),
1405 "grant_types": req.grant_types.as_deref().unwrap_or(&["authorization_code".to_string()]),
1406 "response_types": req.response_types.as_deref().unwrap_or(&["code".to_string()]),
1407 "scope": req.scope.as_deref().unwrap_or("openid"),
1408 });
1409
1410 let key = format!("oauth2_client:{}", client_id);
1411 if let Err(e) = state
1412 .auth_framework
1413 .storage()
1414 .store_kv(&key, client_data.to_string().as_bytes(), None)
1415 .await
1416 {
1417 tracing::error!("Failed to store client registration: {}", e);
1418 return (
1419 StatusCode::INTERNAL_SERVER_ERROR,
1420 Json(serde_json::json!({
1421 "error": "server_error",
1422 "error_description": "Failed to register client"
1423 })),
1424 )
1425 .into_response();
1426 }
1427
1428 tracing::info!("Dynamic client registered: client_id={}", client_id);
1429
1430 (
1431 StatusCode::CREATED,
1432 Json(serde_json::json!({
1433 "client_id": client_id,
1434 "client_secret": client_secret,
1435 "client_name": req.client_name,
1436 "redirect_uris": req.redirect_uris,
1437 "token_endpoint_auth_method": req.token_endpoint_auth_method.as_deref().unwrap_or("client_secret_basic"),
1438 "grant_types": req.grant_types.as_deref().unwrap_or(&["authorization_code".to_string()]),
1439 "response_types": req.response_types.as_deref().unwrap_or(&["code".to_string()]),
1440 "scope": req.scope.as_deref().unwrap_or("openid"),
1441 })),
1442 )
1443 .into_response()
1444}
1445
1446pub async fn users_me(state: State<ApiState>, headers: HeaderMap) -> impl IntoResponse {
1460 userinfo(state, headers).await
1462}