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