1use crate::api::ApiState;
10use axum::{
11 Form,
12 extract::State,
13 http::{HeaderMap, StatusCode},
14 response::Json,
15};
16use base64::{Engine as _, engine::general_purpose};
17use serde::{Deserialize, Serialize};
18use serde_json::{Value as JsonValue, json};
19use std::collections::HashMap;
20use tracing::{debug, error};
21use url::Url;
22use uuid::Uuid;
23
24#[derive(Deserialize)]
26pub struct IntrospectRequest {
27 pub token: String,
29
30 #[serde(skip_serializing_if = "Option::is_none")]
32 pub token_type_hint: Option<String>,
33
34 #[serde(skip_serializing_if = "Option::is_none")]
36 pub client_id: Option<String>,
37
38 #[serde(skip_serializing_if = "Option::is_none")]
40 pub client_secret: Option<String>,
41}
42
43impl std::fmt::Debug for IntrospectRequest {
44 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
45 let mut d = f.debug_struct("IntrospectRequest");
46 d.field("token", &crate::utils::redact::redacted(&self.token));
47 d.field("token_type_hint", &self.token_type_hint);
48 d.field("client_id", &self.client_id);
49 d.field(
50 "client_secret",
51 &crate::utils::redact::redacted(&self.client_secret),
52 );
53 d.finish()
54 }
55}
56
57#[derive(Debug, Serialize)]
59pub struct IntrospectResponse {
60 pub active: bool,
62
63 #[serde(skip_serializing_if = "Option::is_none")]
65 pub sub: Option<String>,
66
67 #[serde(skip_serializing_if = "Option::is_none")]
69 pub client_id: Option<String>,
70
71 #[serde(skip_serializing_if = "Option::is_none")]
73 pub scope: Option<String>,
74
75 #[serde(skip_serializing_if = "Option::is_none")]
77 pub exp: Option<i64>,
78
79 #[serde(skip_serializing_if = "Option::is_none")]
81 pub iat: Option<i64>,
82
83 #[serde(skip_serializing_if = "Option::is_none")]
85 pub nbf: Option<i64>,
86
87 #[serde(skip_serializing_if = "Option::is_none")]
89 pub iss: Option<String>,
90
91 #[serde(skip_serializing_if = "Option::is_none")]
93 pub aud: Option<JsonValue>,
94
95 #[serde(skip_serializing_if = "Option::is_none")]
97 pub jti: Option<String>,
98
99 #[serde(skip_serializing_if = "Option::is_none")]
101 pub token_type: Option<String>,
102
103 #[serde(skip_serializing_if = "Option::is_none")]
105 pub username: Option<String>,
106}
107
108#[derive(Debug, Deserialize)]
113pub struct PARRequest {
114 pub response_type: String,
116
117 pub client_id: String,
119
120 pub redirect_uri: String,
122
123 pub scope: Option<String>,
125
126 pub state: Option<String>,
128
129 pub nonce: Option<String>,
131
132 pub code_challenge: Option<String>,
134
135 pub code_challenge_method: Option<String>,
137}
138
139#[derive(Serialize)]
141pub struct PARResponse {
142 pub request_uri: String,
144
145 pub expires_in: u64,
147}
148
149impl std::fmt::Debug for PARResponse {
150 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
151 let mut d = f.debug_struct("PARResponse");
152 d.field(
153 "request_uri",
154 &crate::utils::redact::redacted(&self.request_uri),
155 );
156 d.field("expires_in", &self.expires_in);
157 d.finish()
158 }
159}
160
161async fn verify_client_credentials(
172 state: &State<ApiState>,
173 client_id: &str,
174 client_secret: &str,
175) -> Result<bool, (StatusCode, Json<JsonValue>)> {
176 let client_key = format!("oauth2_client:{}", client_id);
177 let client_data = match state.auth_framework.storage().get_kv(&client_key).await {
178 Ok(Some(bytes)) => match serde_json::from_slice::<serde_json::Value>(&bytes) {
179 Ok(v) => v,
180 Err(_) => {
181 error!(
182 "Introspect: failed to deserialize client record for {}",
183 client_id
184 );
185 return Err((
186 StatusCode::INTERNAL_SERVER_ERROR,
187 Json(json!({
188 "error": "server_error",
189 "error_description": "Internal server error"
190 })),
191 ));
192 }
193 },
194 Ok(None) => {
195 return Ok(false);
197 }
198 Err(e) => {
199 error!(
200 "Introspect: storage error looking up client {}: {}",
201 client_id, e
202 );
203 return Err((
204 StatusCode::INTERNAL_SERVER_ERROR,
205 Json(json!({
206 "error": "server_error",
207 "error_description": "Internal server error"
208 })),
209 ));
210 }
211 };
212
213 if super::client_secret::is_confidential(&client_data) {
214 let authenticated = super::client_secret::authenticate(
217 state.auth_framework.storage().as_ref(),
218 client_id,
219 &client_data,
220 client_secret,
221 )
222 .await;
223 if authenticated
226 && let Err(limited) = super::client_rate_limit::check(state, client_id).await
227 {
228 return Err(match limited {
229 super::client_rate_limit::ClientLimited::Exceeded { retry_after_secs } => (
230 StatusCode::TOO_MANY_REQUESTS,
231 Json(json!({
232 "error": "rate_limit_exceeded",
233 "error_description": "This client is making too many requests",
234 "retry_after": retry_after_secs
235 })),
236 ),
237 super::client_rate_limit::ClientLimited::Unavailable => (
238 StatusCode::SERVICE_UNAVAILABLE,
239 Json(json!({
240 "error": "temporarily_unavailable",
241 "error_description": "Rate limiting is temporarily unavailable"
242 })),
243 ),
244 });
245 }
246 return Ok(authenticated);
247 }
248 Ok(false)
252}
253
254async fn audit_introspection(
257 state: &State<ApiState>,
258 client_id: &str,
259 success: bool,
260 result: &str,
261 subject: Option<&str>,
262 jti: Option<&str>,
263) {
264 use crate::audit::{AuditEvent, AuditEventType, EventOutcome, RiskLevel};
265 let mut event = AuditEvent::builder(
266 AuditEventType::TokenIntrospected,
267 format!("OAuth2 token introspection: {result}"),
268 )
269 .outcome(if success {
270 EventOutcome::Success
271 } else {
272 EventOutcome::Failure
273 })
274 .risk_level(if success {
275 RiskLevel::Low
276 } else {
277 RiskLevel::Medium
278 })
279 .with_actor("oauth_client", client_id)
280 .detail("endpoint", "/oauth/introspect")
281 .detail("result", result);
282 if let Some(subject) = subject {
283 event = event.user_id(subject);
284 }
285 if let Some(jti) = jti {
286 event = event.detail("jti", jti);
287 }
288 state.auth_framework.record_audit_event(event.build()).await;
289}
290
291pub async fn introspect_token(
302 state: State<ApiState>,
303 headers: HeaderMap,
304 form: Form<IntrospectRequest>,
305) -> Result<Json<IntrospectResponse>, (StatusCode, Json<JsonValue>)> {
306 debug!("Processing token introspection request");
307
308 let auth_header = headers.get(axum::http::header::AUTHORIZATION);
310
311 let presented_client_id: Option<String>;
313 let authenticated = match auth_header {
314 Some(value) => {
315 let value_str = value.to_str().unwrap_or("");
316 if value_str.starts_with("Bearer ") {
317 debug!("Introspect rejected: Bearer auth is not allowed");
319 return Err((
320 StatusCode::UNAUTHORIZED,
321 Json(json!({
322 "error": "invalid_client",
323 "error_description": "Bearer token authentication is not supported for token introspection"
324 })),
325 ));
326 } else if let Some(encoded) = value_str.strip_prefix("Basic ") {
327 match general_purpose::STANDARD.decode(encoded) {
329 Ok(decoded_bytes) => {
330 let decoded = String::from_utf8_lossy(&decoded_bytes);
331 let mut parts = decoded.splitn(2, ':');
332 let basic_client_id = parts.next().unwrap_or("").to_string();
333 let basic_client_secret = parts.next().unwrap_or("").to_string();
334 presented_client_id = Some(basic_client_id.clone());
335 verify_client_credentials(&state, &basic_client_id, &basic_client_secret)
336 .await?
337 }
338 Err(_) => {
339 debug!("Introspect rejected: invalid Basic auth encoding");
340 return Err((
341 StatusCode::UNAUTHORIZED,
342 Json(json!({
343 "error": "invalid_client",
344 "error_description": "Invalid Basic authentication encoding"
345 })),
346 ));
347 }
348 }
349 } else {
350 debug!("Introspect rejected: unknown auth scheme");
352 return Err((
353 StatusCode::UNAUTHORIZED,
354 Json(json!({
355 "error": "invalid_client",
356 "error_description": "Unsupported authentication scheme"
357 })),
358 ));
359 }
360 }
361 None => {
362 match (&form.client_id, &form.client_secret) {
364 (Some(id), Some(secret)) => {
365 presented_client_id = Some(id.clone());
366 verify_client_credentials(&state, id, secret).await?
367 }
368 _ => {
369 debug!("Introspect rejected: missing client credentials");
370 return Err((
371 StatusCode::UNAUTHORIZED,
372 Json(json!({
373 "error": "invalid_client",
374 "error_description": "client_id and client_secret are required"
375 })),
376 ));
377 }
378 }
379 }
380 };
381
382 let audit_client = presented_client_id.unwrap_or_default();
383 if !authenticated {
384 audit_introspection(
385 &state,
386 &audit_client,
387 false,
388 "client_authentication_failed",
389 None,
390 None,
391 )
392 .await;
393 debug!("Introspect rejected: invalid client credentials");
394 return Err((
395 StatusCode::UNAUTHORIZED,
396 Json(json!({
397 "error": "invalid_client",
398 "error_description": "Client authentication failed"
399 })),
400 ));
401 }
402
403 let token_manager = state.auth_framework.token_manager();
405
406 match token_manager.validate_jwt_token(&form.token) {
407 Ok(claims) => {
408 if claims
413 .client_id
414 .as_deref()
415 .is_some_and(|owner| owner != audit_client)
416 {
417 audit_introspection(
418 &state,
419 &audit_client,
420 true,
421 "inactive_not_issued_to_caller",
422 None,
423 None,
424 )
425 .await;
426 debug!("Token introspection: token was issued to another client");
427 return Ok(Json(IntrospectResponse {
428 active: false,
429 sub: None,
430 client_id: None,
431 scope: None,
432 exp: None,
433 iat: None,
434 nbf: None,
435 iss: None,
436 aud: None,
437 jti: None,
438 token_type: None,
439 username: None,
440 }));
441 }
442 let revocation_key = format!("revoked_token:{}", claims.jti);
446 let storage = state.auth_framework.storage();
448 let mut revoked = !matches!(storage.get_kv(&revocation_key).await, Ok(None));
449 if !revoked
451 && crate::auth::ensure_account_active(storage.as_ref(), &claims.sub, false)
452 .await
453 .is_err()
454 {
455 revoked = true;
456 }
457 if !revoked && claims.token_use().is_some() && !claims.is_refresh_token() {
460 revoked = true;
461 }
462 if !revoked && claims.is_refresh_token() {
464 revoked = !matches!(
465 storage
466 .get_kv(&format!("refresh_consumed:{}", claims.jti))
467 .await,
468 Ok(None)
469 ) || !matches!(
470 storage
471 .get_kv(&format!("revoked_family:{}", claims.refresh_family()))
472 .await,
473 Ok(None)
474 );
475 }
476 if revoked {
477 audit_introspection(
478 &state,
479 &audit_client,
480 true,
481 "inactive_revoked_or_unusable",
482 Some(&claims.sub),
483 Some(&claims.jti),
484 )
485 .await;
486 debug!(
487 "Token introspection: token has been revoked (jti: {})",
488 claims.jti
489 );
490 return Ok(Json(IntrospectResponse {
491 active: false,
492 sub: None,
493 client_id: None,
494 scope: None,
495 exp: None,
496 iat: None,
497 nbf: None,
498 iss: None,
499 aud: None,
500 jti: None,
501 token_type: None,
502 username: None,
503 }));
504 }
505
506 debug_assert!(!claims.sub.is_empty(), "Token subject should not be empty");
507 audit_introspection(
508 &state,
509 &audit_client,
510 true,
511 "active",
512 Some(&claims.sub),
513 Some(&claims.jti),
514 )
515 .await;
516 Ok(Json(IntrospectResponse {
517 active: true,
518 sub: Some(claims.sub.clone()),
519 client_id: claims.client_id.clone(),
520 scope: Some(claims.scope.clone()),
521 exp: Some(claims.exp),
522 iat: Some(claims.iat),
523 nbf: Some(claims.nbf),
524 iss: Some(claims.iss.clone()),
525 aud: Some(JsonValue::String(claims.aud.clone())),
526 jti: Some(claims.jti.clone()),
527 token_type: Some(if claims.is_refresh_token() {
528 "refresh_token".to_string()
529 } else {
530 "Bearer".to_string()
531 }),
532 username: Some(claims.sub),
533 }))
534 }
535 Err(_e) => {
536 audit_introspection(&state, &audit_client, true, "inactive_invalid", None, None).await;
537 debug!("Token introspection: token is inactive");
538 Ok(Json(IntrospectResponse {
540 active: false,
541 sub: None,
542 client_id: None,
543 scope: None,
544 exp: None,
545 iat: None,
546 nbf: None,
547 iss: None,
548 aud: None,
549 jti: None,
550 token_type: None,
551 username: None,
552 }))
553 }
554 }
555}
556
557pub async fn pushed_authorization_request(
566 State(state): State<ApiState>,
567 Form(req): Form<PARRequest>,
568) -> (StatusCode, Json<PARResponse>) {
569 debug!("Processing PAR request for client_id={}", req.client_id);
570
571 if Url::parse(&req.redirect_uri).is_err() {
573 return (
574 StatusCode::BAD_REQUEST,
575 Json(PARResponse {
576 request_uri: String::new(),
577 expires_in: 0,
578 }),
579 );
580 }
581
582 let request_id = Uuid::new_v4().to_string();
584 let request_uri = format!("urn:ietf:params:oauth:request_uri:{}", request_id);
585
586 let par_data = json!({
589 "response_type": req.response_type,
590 "client_id": req.client_id,
591 "redirect_uri": req.redirect_uri,
592 "scope": req.scope,
593 "state": req.state,
594 "nonce": req.nonce,
595 "code_challenge": req.code_challenge,
596 "code_challenge_method": req.code_challenge_method,
597 });
598 let storage_key = format!("par_request:{}", request_id);
599 if let Err(e) = state
600 .auth_framework
601 .storage()
602 .store_kv(
603 &storage_key,
604 par_data.to_string().as_bytes(),
605 Some(std::time::Duration::from_secs(90)),
606 )
607 .await
608 {
609 error!("Failed to store PAR request: {}", e);
610 return (
613 StatusCode::INTERNAL_SERVER_ERROR,
614 Json(PARResponse {
615 request_uri: String::new(),
616 expires_in: 0,
617 }),
618 );
619 }
620
621 (
622 StatusCode::CREATED,
623 Json(PARResponse {
624 request_uri,
625 expires_in: 90,
626 }),
627 )
628}
629
630pub async fn device_authorization(
636 State(state): State<ApiState>,
637 Form(form): Form<HashMap<String, String>>,
638) -> Result<Json<JsonValue>, (StatusCode, Json<JsonValue>)> {
639 if form.get("client_id").map(|s| s.is_empty()).unwrap_or(true) {
641 return Err((
642 StatusCode::BAD_REQUEST,
643 Json(json!({
644 "error": "invalid_request",
645 "error_description": "client_id is required"
646 })),
647 ));
648 }
649
650 let device_code = format!("dc_{}", Uuid::new_v4().simple());
652 let user_code = generate_user_code();
653 let verification_uri = "/device";
654 let expires_in: u64 = 600; let device_data = json!({
658 "client_id": form.get("client_id").cloned().unwrap_or_default(),
659 "scope": form.get("scope").cloned().unwrap_or_default(),
660 "user_code": user_code,
661 "authorized": false
662 });
663 state
664 .auth_framework
665 .storage()
666 .store_kv(
667 &format!("device:{}", device_code),
668 device_data.to_string().as_bytes(),
669 Some(std::time::Duration::from_secs(expires_in)),
670 )
671 .await
672 .map_err(|e| {
673 error!("Failed to store device authorization request: {}", e);
674 (
675 StatusCode::INTERNAL_SERVER_ERROR,
676 Json(json!({
677 "error": "server_error",
678 "error_description": "Failed to initiate device authorization flow"
679 })),
680 )
681 })?;
682
683 debug!(
684 "Device authorization initiated for client_id={}",
685 form.get("client_id")
686 .map(String::as_str)
687 .unwrap_or_default()
688 );
689
690 Ok(Json(json!({
691 "device_code": device_code,
692 "user_code": user_code,
693 "verification_uri": verification_uri,
694 "verification_uri_complete": format!("{}?user_code={}", verification_uri, user_code),
695 "expires_in": expires_in,
696 "interval": 5
697 })))
698}
699
700pub async fn ciba_backchannel_auth(
706 State(state): State<ApiState>,
707 Form(form): Form<HashMap<String, String>>,
708) -> Result<Json<JsonValue>, (StatusCode, Json<JsonValue>)> {
709 let login_hint = form
711 .get("login_hint")
712 .or_else(|| form.get("login_hint_token"))
713 .or_else(|| form.get("id_token_hint"))
714 .cloned()
715 .ok_or_else(|| {
716 (
717 StatusCode::BAD_REQUEST,
718 Json(json!({
719 "error": "invalid_request",
720 "error_description":
721 "One of login_hint, login_hint_token, or id_token_hint is required"
722 })),
723 )
724 })?;
725
726 let auth_req_id = Uuid::new_v4().to_string();
727 let expires_in: u64 = 120; let ciba_data = json!({
731 "login_hint": login_hint,
732 "client_id": form.get("client_id").cloned().unwrap_or_default(),
733 "scope": form.get("scope").cloned().unwrap_or_default(),
734 "binding_message": form.get("binding_message").cloned(),
735 "status": "pending"
736 });
737 state
738 .auth_framework
739 .storage()
740 .store_kv(
741 &format!("ciba:{}", auth_req_id),
742 ciba_data.to_string().as_bytes(),
743 Some(std::time::Duration::from_secs(expires_in)),
744 )
745 .await
746 .map_err(|e| {
747 error!("Failed to store CIBA request: {}", e);
748 (
749 StatusCode::INTERNAL_SERVER_ERROR,
750 Json(json!({
751 "error": "server_error",
752 "error_description": "Failed to initiate backchannel authentication"
753 })),
754 )
755 })?;
756
757 debug!(
758 "CIBA request created: auth_req_id={}",
759 crate::utils::redact::fingerprint(&auth_req_id)
760 );
761
762 Ok(Json(json!({
763 "auth_req_id": auth_req_id,
764 "expires_in": expires_in,
765 "interval": 5
766 })))
767}
768
769fn generate_user_code() -> String {
776 use rand::RngExt;
777 const CHARS: &[u8] = b"ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
778 let mut rng = rand::rng();
779 (0..8)
780 .map(|_| CHARS[rng.random_range(0..CHARS.len())] as char)
781 .collect()
782}