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(Debug, Deserialize)]
148pub struct RevokeRequest {
149 pub token: String,
150 #[serde(default)]
151 pub token_type_hint: Option<String>, }
153
154#[derive(Debug, Serialize)]
173pub struct UserInfoResponse {
174 pub sub: String,
175 #[serde(skip_serializing_if = "Option::is_none")]
176 pub name: Option<String>,
177 #[serde(skip_serializing_if = "Option::is_none")]
178 pub email: Option<String>,
179 #[serde(skip_serializing_if = "Option::is_none")]
180 pub picture: Option<String>,
181 #[serde(skip_serializing_if = "Option::is_none")]
182 pub updated_at: Option<i64>,
183}
184
185pub async fn authorize(
194 State(state): State<ApiState>,
195 headers: HeaderMap,
196 Query(params): Query<AuthorizationRequest>,
197) -> impl IntoResponse {
198 if params.response_type != "code" {
199 let error = OAuthError::new("unsupported_response_type")
200 .description("Only 'code' response type is supported")
201 .maybe_state(params.state);
202 return (StatusCode::BAD_REQUEST, Json(error)).into_response();
203 }
204
205 if params.client_id.is_empty() {
206 let error = OAuthError::new("invalid_request")
207 .description("client_id is required")
208 .maybe_state(params.state);
209 return (StatusCode::BAD_REQUEST, Json(error)).into_response();
210 }
211
212 if params.redirect_uri.is_empty() {
213 let error = OAuthError::new("invalid_request")
214 .description("redirect_uri is required")
215 .maybe_state(params.state);
216 return (StatusCode::BAD_REQUEST, Json(error)).into_response();
217 }
218
219 let user_id = {
223 let token_str = match extract_bearer_token(&headers) {
224 Some(t) => t,
225 None => {
226 let error = OAuthError::new("unauthorized_client")
227 .description(
228 "User authentication required: supply your access token as \
229 'Authorization: Bearer <token>'",
230 )
231 .maybe_state(params.state);
232 return (StatusCode::UNAUTHORIZED, Json(error)).into_response();
233 }
234 };
235 match validate_api_token(&state.auth_framework, &token_str).await {
236 Ok(auth_token) => auth_token.user_id,
237 Err(_) => {
238 let error = OAuthError::new("unauthorized_client")
239 .description("Invalid or expired user access token")
240 .maybe_state(params.state);
241 return (StatusCode::UNAUTHORIZED, Json(error)).into_response();
242 }
243 }
244 };
245
246 let client_key = format!("oauth2_client:{}", params.client_id);
249 match state.auth_framework.storage().get_kv(&client_key).await {
250 Ok(Some(data)) => {
251 let client_data: serde_json::Value = serde_json::from_slice(&data).unwrap_or_default();
252 let registered_uris: Vec<String> = client_data["redirect_uris"]
253 .as_array()
254 .map(|arr| {
255 arr.iter()
256 .filter_map(|v| v.as_str().map(String::from))
257 .collect()
258 })
259 .unwrap_or_default();
260
261 if !registered_uris
262 .iter()
263 .any(|r| redirect_uri_matches(¶ms.redirect_uri, r))
264 {
265 tracing::warn!(
266 client_id = %params.client_id,
267 redirect_uri = %params.redirect_uri,
268 "OAuth authorize: redirect_uri not registered for client"
269 );
270 let error = OAuthError::new("invalid_request")
271 .description("redirect_uri is not registered for this client")
272 .maybe_state(params.state);
273 return (StatusCode::BAD_REQUEST, Json(error)).into_response();
274 }
275
276 let is_public_client = client_data
278 .get("client_secret")
279 .and_then(|v| v.as_str())
280 .map_or(true, |s| s.is_empty());
281 if is_public_client && params.code_challenge.is_none() {
282 let error = OAuthError::new("invalid_request")
283 .description("Public clients must use PKCE: code_challenge is required")
284 .maybe_state(params.state);
285 return (StatusCode::BAD_REQUEST, Json(error)).into_response();
286 }
287 }
288 Ok(None) => {
289 tracing::warn!(client_id = %params.client_id, "OAuth authorize: unknown client_id");
290 let error = OAuthError::new("invalid_client")
291 .description("Unknown client_id")
292 .maybe_state(params.state);
293 return (StatusCode::BAD_REQUEST, Json(error)).into_response();
294 }
295 Err(e) => {
296 tracing::error!(
297 client_id = %params.client_id,
298 error = %e,
299 "OAuth authorize: storage error looking up client"
300 );
301 let error = OAuthError::new("server_error")
302 .description("Authorization server error")
303 .maybe_state(params.state);
304 return (StatusCode::INTERNAL_SERVER_ERROR, Json(error)).into_response();
305 }
306 }
307
308 let auth_code = format!("ac_{}", uuid::Uuid::new_v4().to_string().replace("-", ""));
309
310 if let Some(ref resources) = params.resource {
312 if let Err(e) =
313 crate::server::oauth::resource_indicators::validate_resource_indicators(resources)
314 {
315 let error = OAuthError::new("invalid_target")
316 .description(e.to_string())
317 .maybe_state(params.state);
318 return (StatusCode::BAD_REQUEST, Json(error)).into_response();
319 }
320 }
321
322 let code_data = serde_json::json!({
323 "client_id": params.client_id,
324 "redirect_uri": params.redirect_uri,
325 "scope": params.scope.clone().unwrap_or_else(|| "openid profile email".to_string()),
326 "state": params.state.clone(),
327 "code_challenge": params.code_challenge,
328 "code_challenge_method": params.code_challenge_method,
329 "user_id": user_id,
330 "resource": params.resource,
331 "created_at": chrono::Utc::now().to_rfc3339(),
332 "expires_at": (chrono::Utc::now() + chrono::Duration::minutes(10)).to_rfc3339(),
333 "used": false,
334 });
335
336 let storage_key = format!("oauth2_code:{}", auth_code);
337 let code_data_str = match serde_json::to_string(&code_data) {
338 Ok(s) => s,
339 Err(e) => {
340 tracing::error!("Failed to serialize OAuth authorization code data: {:?}", e);
341 let error =
342 OAuthError::new("server_error").description("Authorization server internal error");
343 return (StatusCode::INTERNAL_SERVER_ERROR, Json(error)).into_response();
344 }
345 };
346
347 if let Err(e) = state
348 .auth_framework
349 .storage()
350 .store_kv(
351 &storage_key,
352 code_data_str.as_bytes(),
353 Some(std::time::Duration::from_secs(600)),
354 )
355 .await
356 {
357 tracing::error!("Failed to store OAuth authorization code: {:?}", e);
358 let error = OAuthError::new("server_error")
359 .description("Authorization server error")
360 .maybe_state(params.state);
361 return (StatusCode::INTERNAL_SERVER_ERROR, Json(error)).into_response();
362 }
363
364 let encoded_state: Option<String> = params.state.as_deref().map(|st| {
367 st.bytes()
368 .flat_map(|b| {
369 if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~') {
370 vec![b as char]
371 } else {
372 format!("%{:02X}", b).chars().collect()
373 }
374 })
375 .collect()
376 });
377
378 let mut redirect_url = params.redirect_uri;
379 redirect_url.push_str(&format!("?code={}", auth_code));
380 if let Some(ref st) = encoded_state {
381 redirect_url.push_str(&format!("&state={}", st));
382 }
383
384 tracing::info!(
385 client_id = %params.client_id,
386 user_id = %user_id,
387 "OAuth authorization code issued"
388 );
389 Redirect::to(&redirect_url).into_response()
390}
391
392pub async fn token(
406 State(state): State<ApiState>,
407 Json(req): Json<TokenRequest>,
408) -> ApiResponse<TokenResponse> {
409 match req.grant_type.as_str() {
410 "authorization_code" => handle_authorization_code_grant(state, req).await,
411 "refresh_token" => handle_refresh_token_grant(state, req).await,
412 _ => ApiResponse::error_typed(
413 "unsupported_grant_type",
414 "Supported grant types: authorization_code, refresh_token",
415 ),
416 }
417}
418
419async fn handle_authorization_code_grant(
420 state: ApiState,
421 req: TokenRequest,
422) -> ApiResponse<TokenResponse> {
423 let code = match req.code {
424 Some(c) => c,
425 None => {
426 return ApiResponse::validation_error_typed(
427 "code is required for authorization_code grant",
428 );
429 }
430 };
431
432 let client_id = match req.client_id {
433 Some(c) => c,
434 None => return ApiResponse::validation_error_typed("client_id is required"),
435 };
436
437 let consumed_key = format!("oauth2_code_consumed:{}", code);
441 if let Ok(Some(_)) = state.auth_framework.storage().get_kv(&consumed_key).await {
442 return ApiResponse::error_typed("invalid_grant", "Authorization code already used");
443 }
444 if let Err(e) = state
446 .auth_framework
447 .storage()
448 .store_kv(
449 &consumed_key,
450 b"1",
451 Some(std::time::Duration::from_secs(600)),
452 )
453 .await
454 {
455 tracing::warn!("Failed to store code consumed marker: {:?}", e);
456 }
457
458 let storage_key = format!("oauth2_code:{}", code);
459 let code_data = match state.auth_framework.storage().get_kv(&storage_key).await {
460 Ok(Some(data)) => match serde_json::from_slice::<serde_json::Value>(&data) {
461 Ok(json) => json,
462 Err(e) => {
463 tracing::error!("Failed to parse stored authorization code data: {:?}", e);
464 return ApiResponse::error_typed("invalid_grant", "Invalid authorization code");
465 }
466 },
467 Ok(None) => {
468 return ApiResponse::error_typed(
469 "invalid_grant",
470 "Authorization code not found or expired",
471 );
472 }
473 Err(e) => {
474 tracing::error!("Failed to retrieve authorization code: {:?}", e);
475 return ApiResponse::error_typed(
476 "server_error",
477 "Failed to validate authorization code",
478 );
479 }
480 };
481
482 if let Err(e) = state.auth_framework.storage().delete_kv(&storage_key).await {
484 tracing::error!("Failed to delete authorization code from storage: {:?}", e);
485 return ApiResponse::error_typed("server_error", "Failed to process authorization code");
486 }
487
488 if code_data["client_id"].as_str() != Some(&client_id) {
490 return ApiResponse::error_typed("invalid_grant", "client_id mismatch");
491 }
492
493 if let Some(redirect_uri) = &req.redirect_uri {
495 let stored_uri = code_data["redirect_uri"].as_str().unwrap_or_default();
496 if !redirect_uri_matches(redirect_uri, stored_uri) {
497 return ApiResponse::error_typed("invalid_grant", "redirect_uri mismatch");
498 }
499 }
500
501 let stored_challenge = code_data["code_challenge"].as_str();
503 let challenge_method = code_data["code_challenge_method"]
504 .as_str()
505 .unwrap_or("plain");
506
507 if let Some(stored) = stored_challenge {
508 let code_verifier = match &req.code_verifier {
510 Some(verifier) => verifier,
511 None => {
512 return ApiResponse::error_typed(
513 "invalid_request",
514 "code_verifier is required when PKCE challenge was provided",
515 );
516 }
517 };
518
519 let computed_challenge = match challenge_method {
520 "S256" => {
521 let mut hasher = Sha256::new();
522 hasher.update(code_verifier.as_bytes());
523 URL_SAFE_NO_PAD.encode(hasher.finalize())
524 }
525 "plain" => code_verifier.clone(),
526 _ => {
527 return ApiResponse::error_typed(
528 "invalid_request",
529 "Unsupported code_challenge_method",
530 );
531 }
532 };
533
534 if computed_challenge != stored {
535 return ApiResponse::error_typed("invalid_grant", "PKCE verification failed");
536 }
537 } else if req.code_verifier.is_some() {
538 return ApiResponse::error_typed(
540 "invalid_request",
541 "code_verifier provided but no PKCE challenge was used in authorization",
542 );
543 } else if req.client_secret.is_none() {
544 return ApiResponse::error_typed(
548 "invalid_request",
549 "Public clients must use PKCE: provide code_challenge in authorization and code_verifier in token request",
550 );
551 }
552
553 let authz_resources: Vec<String> = code_data["resource"]
558 .as_array()
559 .map(|arr| {
560 arr.iter()
561 .filter_map(|v| v.as_str().map(String::from))
562 .collect()
563 })
564 .unwrap_or_default();
565
566 if let Some(ref token_resources) = req.resource {
567 if let Err(e) =
568 crate::server::oauth::resource_indicators::validate_resource_indicators(token_resources)
569 {
570 return ApiResponse::error_typed("invalid_target", &e.to_string());
571 }
572 if let Err(e) = crate::server::oauth::resource_indicators::validate_token_resource_subset(
573 token_resources,
574 &authz_resources,
575 ) {
576 return ApiResponse::error_typed("invalid_target", &e.to_string());
577 }
578 }
579
580 let scope = code_data["scope"]
582 .as_str()
583 .unwrap_or("openid profile email");
584 let scopes: Vec<String> = scope.split_whitespace().map(|s| s.to_string()).collect();
585
586 let user_id = match code_data["user_id"].as_str() {
590 Some(uid) if !uid.is_empty() => uid.to_string(),
591 _ => {
592 tracing::error!("Authorization code missing user_id field");
593 return ApiResponse::error_typed("server_error", "Malformed authorization code");
594 }
595 };
596
597 let token = match state.auth_framework.token_manager().create_auth_token(
598 &user_id,
599 scopes.clone(),
600 "oauth2",
601 None,
602 ) {
603 Ok(token) => token,
604 Err(e) => {
605 tracing::error!("Failed to create access token: {:?}", e);
606 return ApiResponse::error_typed("server_error", "Failed to create access token");
607 }
608 };
609
610 let refresh_token_value = uuid::Uuid::new_v4().to_string().replace("-", "");
612 let refresh_data = serde_json::json!({
613 "user_id": user_id,
614 "client_id": client_id,
615 "scopes": scope,
616 });
617 let refresh_key = format!("oauth2_refresh_token:{}", refresh_token_value);
618 if let Err(e) = state
619 .auth_framework
620 .storage()
621 .store_kv(
622 &refresh_key,
623 serde_json::to_string(&refresh_data)
624 .unwrap_or_default()
625 .as_bytes(),
626 Some(std::time::Duration::from_secs(30 * 24 * 3600)),
627 )
628 .await
629 {
630 tracing::warn!("Failed to store refresh token: {:?}", e);
631 }
632
633 let expires_in = (token.expires_at - token.issued_at).num_seconds().max(0) as u64;
634 let response = TokenResponse {
635 access_token: token.access_token,
636 token_type: "Bearer".to_string(),
637 expires_in,
638 refresh_token: Some(refresh_token_value),
639 scope: Some(scope.to_string()),
640 id_token: None,
641 };
642
643 tracing::info!("OAuth2 tokens issued for client: {}", client_id);
644 ApiResponse::success(response)
645}
646
647async fn handle_refresh_token_grant(
648 state: ApiState,
649 req: TokenRequest,
650) -> ApiResponse<TokenResponse> {
651 let refresh_token_str = match req.refresh_token {
652 Some(t) => t,
653 None => return ApiResponse::validation_error_typed("refresh_token is required"),
654 };
655
656 let revoked_key = format!("oauth2_revoked_token:{}", refresh_token_str);
662 match state.auth_framework.storage().get_kv(&revoked_key).await {
663 Ok(Some(_)) => {
664 return ApiResponse::error_typed("invalid_grant", "Refresh token has been revoked");
665 }
666 Ok(None) => {} Err(e) => {
668 tracing::error!("Refresh token revocation check failed: {:?}", e);
669 return ApiResponse::error_typed("server_error", "Failed to validate refresh token");
670 }
671 }
672
673 let consumed_key = format!("oauth2_refresh_consumed:{}", refresh_token_str);
676 if let Ok(Some(_)) = state.auth_framework.storage().get_kv(&consumed_key).await {
677 return ApiResponse::error_typed("invalid_grant", "Refresh token already consumed");
678 }
679 if let Err(e) = state
680 .auth_framework
681 .storage()
682 .store_kv(
683 &consumed_key,
684 b"1",
685 Some(std::time::Duration::from_secs(600)),
686 )
687 .await
688 {
689 tracing::warn!("Failed to store refresh consumed marker: {:?}", e);
690 }
691
692 let refresh_key = format!("oauth2_refresh_token:{}", refresh_token_str);
694 let stored = match state.auth_framework.storage().get_kv(&refresh_key).await {
695 Ok(Some(data)) => match serde_json::from_slice::<serde_json::Value>(&data) {
696 Ok(v) => v,
697 Err(_) => return ApiResponse::error_typed("invalid_grant", "Invalid refresh token"),
698 },
699 Ok(None) => {
700 return ApiResponse::error_typed("invalid_grant", "Refresh token not found or expired");
701 }
702 Err(e) => {
703 tracing::error!("Failed to retrieve refresh token: {:?}", e);
704 return ApiResponse::error_typed("server_error", "Failed to validate refresh token");
705 }
706 };
707
708 let user_id = match stored["user_id"].as_str() {
709 Some(u) => u.to_string(),
710 None => return ApiResponse::error_typed("invalid_grant", "Malformed refresh token data"),
711 };
712 let client_id = stored["client_id"].as_str().map(|s| s.to_string());
713 let scope = stored["scopes"]
714 .as_str()
715 .unwrap_or("openid profile email")
716 .to_string();
717 let scopes: Vec<String> = scope.split_whitespace().map(|s| s.to_string()).collect();
718
719 let token = match state
720 .auth_framework
721 .token_manager()
722 .create_auth_token(&user_id, scopes, "oauth2", None)
723 {
724 Ok(t) => t,
725 Err(e) => {
726 tracing::error!("Failed to create access token on refresh: {:?}", e);
727 return ApiResponse::error_typed("server_error", "Failed to issue access token");
728 }
729 };
730
731 let new_refresh_token = uuid::Uuid::new_v4().to_string().replace("-", "");
734 let new_refresh_data = serde_json::json!({
735 "user_id": user_id,
736 "client_id": client_id,
737 "scopes": scope,
738 });
739 let new_refresh_key = format!("oauth2_refresh_token:{}", new_refresh_token);
740 if let Err(e) = state
741 .auth_framework
742 .storage()
743 .store_kv(
744 &new_refresh_key,
745 serde_json::to_string(&new_refresh_data)
746 .unwrap_or_default()
747 .as_bytes(),
748 Some(std::time::Duration::from_secs(30 * 24 * 3600)),
749 )
750 .await
751 {
752 tracing::error!("Failed to store new refresh token: {:?}", e);
753 return ApiResponse::error_typed("server_error", "Failed to issue refresh token");
754 }
755
756 if let Err(e) = state.auth_framework.storage().delete_kv(&refresh_key).await {
758 tracing::warn!(
759 "Failed to delete old refresh token during rotation: {:?}",
760 e
761 );
762 }
763
764 let expires_in = (token.expires_at - token.issued_at).num_seconds().max(0) as u64;
765 let response = TokenResponse {
766 access_token: token.access_token,
767 token_type: "Bearer".to_string(),
768 expires_in,
769 refresh_token: Some(new_refresh_token),
770 scope: Some(scope),
771 id_token: None,
772 };
773
774 tracing::info!("OAuth2 token refreshed for user: {}", user_id);
775 ApiResponse::success(response)
776}
777
778pub async fn revoke(
801 State(state): State<ApiState>,
802 Json(req): Json<RevokeRequest>,
803) -> ApiResponse<serde_json::Value> {
804 let revoked_token_key = format!("oauth2_revoked_token:{}", req.token);
807 let revoked_data = serde_json::json!({
808 "token": req.token,
809 "revoked_at": chrono::Utc::now().to_rfc3339(),
810 "token_type_hint": req.token_type_hint
811 });
812
813 if let Err(e) = state
814 .auth_framework
815 .storage()
816 .store_kv(
817 &revoked_token_key,
818 serde_json::to_string(&revoked_data)
819 .unwrap_or_default()
820 .as_bytes(),
821 Some(std::time::Duration::from_secs(86400 * 30)),
827 )
828 .await
829 {
830 tracing::error!("Failed to store revoked token: {:?}", e);
831 return ApiResponse::error_typed("server_error", "Failed to revoke token");
832 }
833
834 let refresh_key = format!("oauth2_refresh_token:{}", req.token);
839 if let Err(e) = state.auth_framework.storage().delete_kv(&refresh_key).await {
840 tracing::warn!("Failed to delete refresh token on revoke: {:?}", e);
841 }
842
843 if let Ok(claims) = state
848 .auth_framework
849 .token_manager()
850 .validate_jwt_token(&req.token)
851 {
852 let now = chrono::Utc::now().timestamp();
853 let remaining_secs = (claims.exp - now + 60).max(60) as u64;
854 let jti_key = format!("revoked_token:{}", claims.jti);
855 if let Err(e) = state
856 .auth_framework
857 .storage()
858 .store_kv(
859 &jti_key,
860 b"1",
861 Some(std::time::Duration::from_secs(remaining_secs)),
862 )
863 .await
864 {
865 tracing::warn!("Failed to store JWT JTI revocation entry: {:?}", e);
866 } else {
867 tracing::info!("JWT token revoked via jti: {}", claims.jti);
868 }
869 }
870
871 tracing::info!(
872 "OAuth2 token revoked: {}",
873 &req.token[..10.min(req.token.len())]
874 );
875
876 ApiResponse::success(serde_json::json!({
877 "message": "Token revoked successfully"
878 }))
879}
880
881pub async fn userinfo(
894 State(state): State<ApiState>,
895 headers: HeaderMap,
896) -> ApiResponse<UserInfoResponse> {
897 let token = match extract_bearer_token(&headers) {
899 Some(t) => t,
900 None => {
901 return ApiResponse::error_typed("invalid_token", "Authorization header required");
902 }
903 };
904
905 let revoked_token_key = format!("oauth2_revoked_token:{}", token);
907 if let Ok(Some(_)) = state
908 .auth_framework
909 .storage()
910 .get_kv(&revoked_token_key)
911 .await
912 {
913 return ApiResponse::error_typed("invalid_token", "Token has been revoked");
914 }
915
916 let claims = match state
918 .auth_framework
919 .token_manager()
920 .validate_jwt_token(&token)
921 {
922 Ok(c) => c,
923 Err(_) => {
924 return ApiResponse::error_typed("invalid_token", "Access token is invalid");
925 }
926 };
927
928 let user_profile = match state.auth_framework.get_user_profile(&claims.sub).await {
930 Ok(profile) => profile,
931 Err(e) => {
932 tracing::error!("Failed to get user profile: {:?}", e);
933 return ApiResponse::error_typed("server_error", "Failed to retrieve user information");
934 }
935 };
936
937 let userinfo = UserInfoResponse {
938 sub: claims.sub.clone(),
939 name: user_profile.username.clone(),
940 email: if claims.scope.split_whitespace().any(|s| s == "email") {
942 user_profile.email.clone()
943 } else {
944 None
945 },
946 picture: user_profile.picture.clone(),
947 updated_at: Some(chrono::Utc::now().timestamp()),
948 };
949
950 tracing::info!("OAuth2 UserInfo requested for user: {}", claims.sub);
951 ApiResponse::success(userinfo)
952}
953
954pub async fn get_client_info(
962 State(state): State<ApiState>,
963 Path(client_id): Path<String>,
964) -> impl IntoResponse {
965 let client_key = format!("oauth2_client:{}", client_id);
966 match state.auth_framework.storage().get_kv(&client_key).await {
967 Ok(Some(data)) => match serde_json::from_slice::<ClientInfo>(&data) {
968 Ok(client) => (
969 StatusCode::OK,
970 Json(serde_json::json!({ "success": true, "data": client })),
971 )
972 .into_response(),
973 Err(e) => {
974 tracing::error!(client_id = %client_id, error = %e, "Failed to deserialize client record");
975 (
976 StatusCode::INTERNAL_SERVER_ERROR,
977 Json(serde_json::json!({
978 "success": false,
979 "error": "server_error",
980 "message": "Failed to read client record"
981 })),
982 )
983 .into_response()
984 }
985 },
986 Ok(None) => (
987 StatusCode::NOT_FOUND,
988 Json(serde_json::json!({
989 "success": false,
990 "error": "invalid_client",
991 "message": "Unknown client_id"
992 })),
993 )
994 .into_response(),
995 Err(e) => {
996 tracing::error!(client_id = %client_id, error = %e, "Storage error looking up client");
997 (
998 StatusCode::INTERNAL_SERVER_ERROR,
999 Json(serde_json::json!({
1000 "success": false,
1001 "error": "server_error",
1002 "message": "Authorization server error"
1003 })),
1004 )
1005 .into_response()
1006 }
1007 }
1008}
1009
1010pub async fn openid_configuration(State(state): State<ApiState>) -> impl IntoResponse {
1026 let issuer = {
1027 let configured = state.auth_framework.config().issuer.clone();
1028 if configured.is_empty() {
1029 "https://auth.example.com".to_string()
1030 } else {
1031 configured
1032 }
1033 };
1034
1035 let config = serde_json::json!({
1036 "issuer": issuer,
1037 "authorization_endpoint": format!("{}/api/v1/oauth/authorize", issuer),
1038 "token_endpoint": format!("{}/api/v1/oauth/token", issuer),
1039 "userinfo_endpoint": format!("{}/api/v1/oauth/userinfo", issuer),
1040 "revocation_endpoint": format!("{}/api/v1/oauth/revoke", issuer),
1041 "introspection_endpoint": format!("{}/api/v1/oauth/introspect", issuer),
1042 "jwks_uri": format!("{}/api/v1/.well-known/jwks.json", issuer),
1043 "end_session_endpoint": format!("{}/api/v1/oauth/end_session", issuer),
1044 "pushed_authorization_request_endpoint": format!("{}/api/v1/oauth/par", issuer),
1045 "registration_endpoint": format!("{}/api/v1/oauth/register", issuer),
1046 "response_types_supported": ["code"],
1047 "grant_types_supported": [
1048 "authorization_code",
1049 "refresh_token"
1050 ],
1051 "subject_types_supported": ["public"],
1052 "id_token_signing_alg_values_supported": ["HS256"],
1053 "token_endpoint_auth_methods_supported": [
1054 "client_secret_basic",
1055 "client_secret_post"
1056 ],
1057 "code_challenge_methods_supported": ["S256"],
1058 "scopes_supported": ["openid", "profile", "email"]
1059 });
1060
1061 (StatusCode::OK, Json(config))
1062}
1063
1064pub async fn jwks(State(_state): State<ApiState>) -> impl IntoResponse {
1081 (StatusCode::OK, Json(serde_json::json!({ "keys": [] })))
1082}
1083
1084#[derive(Debug, Deserialize)]
1100pub struct EndSessionRequest {
1101 pub id_token_hint: Option<String>,
1102 pub post_logout_redirect_uri: Option<String>,
1103 pub state: Option<String>,
1104}
1105
1106pub async fn end_session(
1118 State(state): State<ApiState>,
1119 Query(params): Query<EndSessionRequest>,
1120) -> impl IntoResponse {
1121 if let Some(ref token) = params.id_token_hint {
1123 if let Ok(claims) = state
1124 .auth_framework
1125 .token_manager()
1126 .validate_jwt_token(token)
1127 {
1128 let revoked_key = format!("oauth2_revoked_token:{}", token);
1129 if let Err(e) = state
1130 .auth_framework
1131 .storage()
1132 .store_kv(
1133 &revoked_key,
1134 b"revoked",
1135 Some(std::time::Duration::from_secs(86400 * 7)),
1136 )
1137 .await
1138 {
1139 tracing::warn!("Failed to revoke token during OIDC end_session: {}", e);
1140 }
1141 tracing::info!("OIDC end_session: revoked token for user {}", claims.sub);
1142 }
1143 }
1144
1145 if let Some(ref redirect_uri) = params.post_logout_redirect_uri {
1149 let allowed = if let Some(ref token) = params.id_token_hint {
1151 let client_id = state
1153 .auth_framework
1154 .token_manager()
1155 .validate_jwt_token(token)
1156 .ok()
1157 .and_then(|claims| {
1158 if let Some(ref cid) = claims.client_id {
1160 if !cid.is_empty() {
1161 return Some(cid.clone());
1162 }
1163 }
1164 if !claims.aud.is_empty() {
1166 Some(claims.aud.clone())
1167 } else {
1168 None
1169 }
1170 });
1171 if let Some(cid) = client_id {
1172 let client_key = format!("oauth2_client:{}", cid);
1173 match state.auth_framework.storage().get_kv(&client_key).await {
1174 Ok(Some(data)) => {
1175 let client: serde_json::Value =
1176 serde_json::from_slice(&data).unwrap_or_default();
1177 let uris: Vec<String> = client["redirect_uris"]
1178 .as_array()
1179 .map(|a| {
1180 a.iter()
1181 .filter_map(|v| v.as_str().map(String::from))
1182 .collect()
1183 })
1184 .unwrap_or_default();
1185 uris.iter().any(|r| redirect_uri_matches(redirect_uri, r))
1186 }
1187 _ => false,
1188 }
1189 } else {
1190 false
1191 }
1192 } else {
1193 false
1194 };
1195
1196 if allowed {
1197 if let Ok(mut parsed) = Url::parse(redirect_uri) {
1198 if let Some(ref st) = params.state {
1199 parsed.query_pairs_mut().append_pair("state", st);
1200 }
1201 return Redirect::to(parsed.as_str()).into_response();
1202 }
1203 } else {
1204 tracing::warn!(
1205 "end_session: post_logout_redirect_uri rejected — not registered for the client"
1206 );
1207 }
1208 }
1209
1210 (
1212 StatusCode::OK,
1213 Json(serde_json::json!({ "status": "logged_out" })),
1214 )
1215 .into_response()
1216}
1217
1218#[derive(Debug, Deserialize)]
1234pub struct ClientRegistrationRequest {
1235 pub redirect_uris: Vec<String>,
1236 #[serde(default)]
1237 pub client_name: Option<String>,
1238 #[serde(default)]
1239 pub token_endpoint_auth_method: Option<String>,
1240 #[serde(default)]
1241 pub grant_types: Option<Vec<String>>,
1242 #[serde(default)]
1243 pub response_types: Option<Vec<String>>,
1244 #[serde(default)]
1245 pub scope: Option<String>,
1246}
1247
1248pub async fn register_client(
1268 State(state): State<ApiState>,
1269 headers: HeaderMap,
1270 Json(req): Json<ClientRegistrationRequest>,
1271) -> impl IntoResponse {
1272 let token_str = match extract_bearer_token(&headers) {
1274 Some(t) => t,
1275 None => {
1276 return (
1277 StatusCode::UNAUTHORIZED,
1278 Json(serde_json::json!({
1279 "error": "invalid_token",
1280 "error_description": "A valid Bearer token is required for dynamic client registration"
1281 })),
1282 )
1283 .into_response();
1284 }
1285 };
1286
1287 let is_initial_access_token = match state
1289 .auth_framework
1290 .storage()
1291 .get_kv("oauth2_initial_access_token")
1292 .await
1293 {
1294 Ok(Some(stored)) => {
1295 let stored_str = String::from_utf8_lossy(&stored);
1296 subtle::ConstantTimeEq::ct_eq(token_str.as_bytes(), stored_str.trim().as_bytes()).into()
1297 }
1298 _ => false,
1299 };
1300
1301 let is_admin = if !is_initial_access_token {
1303 match validate_api_token(&state.auth_framework, &token_str).await {
1304 Ok(auth_token) => auth_token.roles.contains(&"admin".to_string()),
1305 Err(_) => false,
1306 }
1307 } else {
1308 false
1309 };
1310
1311 if !is_initial_access_token && !is_admin {
1312 return (
1313 StatusCode::FORBIDDEN,
1314 Json(serde_json::json!({
1315 "error": "insufficient_scope",
1316 "error_description": "Dynamic client registration requires admin privileges or a valid Initial Access Token"
1317 })),
1318 )
1319 .into_response();
1320 }
1321 for uri in &req.redirect_uris {
1323 match Url::parse(uri) {
1324 Ok(parsed) => {
1325 match parsed.scheme() {
1326 "https" => {}
1327 "http" => {
1328 if !matches!(parsed.host_str(), Some("localhost" | "127.0.0.1" | "[::1]")) {
1330 return (
1331 StatusCode::BAD_REQUEST,
1332 Json(serde_json::json!({
1333 "error": "invalid_redirect_uri",
1334 "error_description": format!("Non-loopback HTTP redirect_uri not allowed: {}", uri)
1335 })),
1336 )
1337 .into_response();
1338 }
1339 }
1340 scheme => {
1341 return (
1342 StatusCode::BAD_REQUEST,
1343 Json(serde_json::json!({
1344 "error": "invalid_redirect_uri",
1345 "error_description": format!("Disallowed URI scheme '{}' in redirect_uri: {}", scheme, uri)
1346 })),
1347 )
1348 .into_response();
1349 }
1350 }
1351 }
1352 Err(_) => {
1353 return (
1354 StatusCode::BAD_REQUEST,
1355 Json(serde_json::json!({
1356 "error": "invalid_redirect_uri",
1357 "error_description": format!("Invalid redirect_uri: {}", uri)
1358 })),
1359 )
1360 .into_response();
1361 }
1362 }
1363 }
1364
1365 if req.redirect_uris.is_empty() {
1366 return (
1367 StatusCode::BAD_REQUEST,
1368 Json(serde_json::json!({
1369 "error": "invalid_client_metadata",
1370 "error_description": "At least one redirect_uri is required"
1371 })),
1372 )
1373 .into_response();
1374 }
1375
1376 let client_id = Uuid::new_v4().to_string();
1377 let client_secret = Uuid::new_v4().to_string();
1378
1379 let client_data = serde_json::json!({
1380 "client_id": client_id,
1381 "client_secret": client_secret,
1382 "client_name": req.client_name,
1383 "redirect_uris": req.redirect_uris,
1384 "token_endpoint_auth_method": req.token_endpoint_auth_method.as_deref().unwrap_or("client_secret_basic"),
1385 "grant_types": req.grant_types.as_deref().unwrap_or(&["authorization_code".to_string()]),
1386 "response_types": req.response_types.as_deref().unwrap_or(&["code".to_string()]),
1387 "scope": req.scope.as_deref().unwrap_or("openid"),
1388 });
1389
1390 let key = format!("oauth2_client:{}", client_id);
1391 if let Err(e) = state
1392 .auth_framework
1393 .storage()
1394 .store_kv(&key, client_data.to_string().as_bytes(), None)
1395 .await
1396 {
1397 tracing::error!("Failed to store client registration: {}", e);
1398 return (
1399 StatusCode::INTERNAL_SERVER_ERROR,
1400 Json(serde_json::json!({
1401 "error": "server_error",
1402 "error_description": "Failed to register client"
1403 })),
1404 )
1405 .into_response();
1406 }
1407
1408 tracing::info!("Dynamic client registered: client_id={}", client_id);
1409
1410 (
1411 StatusCode::CREATED,
1412 Json(serde_json::json!({
1413 "client_id": client_id,
1414 "client_secret": client_secret,
1415 "client_name": req.client_name,
1416 "redirect_uris": req.redirect_uris,
1417 "token_endpoint_auth_method": req.token_endpoint_auth_method.as_deref().unwrap_or("client_secret_basic"),
1418 "grant_types": req.grant_types.as_deref().unwrap_or(&["authorization_code".to_string()]),
1419 "response_types": req.response_types.as_deref().unwrap_or(&["code".to_string()]),
1420 "scope": req.scope.as_deref().unwrap_or("openid"),
1421 })),
1422 )
1423 .into_response()
1424}
1425
1426pub async fn users_me(state: State<ApiState>, headers: HeaderMap) -> impl IntoResponse {
1440 userinfo(state, headers).await
1442}