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 let revocation_key = format!("revoked_token:{}", claims.jti);
412 let storage = state.auth_framework.storage();
414 let mut revoked = !matches!(storage.get_kv(&revocation_key).await, Ok(None));
415 if !revoked
417 && crate::auth::ensure_account_active(storage.as_ref(), &claims.sub, false)
418 .await
419 .is_err()
420 {
421 revoked = true;
422 }
423 if !revoked && claims.token_use().is_some() && !claims.is_refresh_token() {
426 revoked = true;
427 }
428 if !revoked && claims.is_refresh_token() {
430 revoked = !matches!(
431 storage
432 .get_kv(&format!("refresh_consumed:{}", claims.jti))
433 .await,
434 Ok(None)
435 ) || !matches!(
436 storage
437 .get_kv(&format!("revoked_family:{}", claims.refresh_family()))
438 .await,
439 Ok(None)
440 );
441 }
442 if revoked {
443 audit_introspection(
444 &state,
445 &audit_client,
446 true,
447 "inactive_revoked_or_unusable",
448 Some(&claims.sub),
449 Some(&claims.jti),
450 )
451 .await;
452 debug!(
453 "Token introspection: token has been revoked (jti: {})",
454 claims.jti
455 );
456 return Ok(Json(IntrospectResponse {
457 active: false,
458 sub: None,
459 client_id: None,
460 scope: None,
461 exp: None,
462 iat: None,
463 nbf: None,
464 iss: None,
465 aud: None,
466 jti: None,
467 token_type: None,
468 username: None,
469 }));
470 }
471
472 debug_assert!(!claims.sub.is_empty(), "Token subject should not be empty");
473 audit_introspection(
474 &state,
475 &audit_client,
476 true,
477 "active",
478 Some(&claims.sub),
479 Some(&claims.jti),
480 )
481 .await;
482 Ok(Json(IntrospectResponse {
483 active: true,
484 sub: Some(claims.sub.clone()),
485 client_id: claims.client_id.clone(),
486 scope: Some(claims.scope.clone()),
487 exp: Some(claims.exp),
488 iat: Some(claims.iat),
489 nbf: Some(claims.nbf),
490 iss: Some(claims.iss.clone()),
491 aud: Some(JsonValue::String(claims.aud.clone())),
492 jti: Some(claims.jti.clone()),
493 token_type: Some(if claims.is_refresh_token() {
494 "refresh_token".to_string()
495 } else {
496 "Bearer".to_string()
497 }),
498 username: Some(claims.sub),
499 }))
500 }
501 Err(_e) => {
502 audit_introspection(&state, &audit_client, true, "inactive_invalid", None, None).await;
503 debug!("Token introspection: token is inactive");
504 Ok(Json(IntrospectResponse {
506 active: false,
507 sub: None,
508 client_id: None,
509 scope: None,
510 exp: None,
511 iat: None,
512 nbf: None,
513 iss: None,
514 aud: None,
515 jti: None,
516 token_type: None,
517 username: None,
518 }))
519 }
520 }
521}
522
523pub async fn pushed_authorization_request(
532 State(state): State<ApiState>,
533 Form(req): Form<PARRequest>,
534) -> (StatusCode, Json<PARResponse>) {
535 debug!("Processing PAR request for client_id={}", req.client_id);
536
537 if Url::parse(&req.redirect_uri).is_err() {
539 return (
540 StatusCode::BAD_REQUEST,
541 Json(PARResponse {
542 request_uri: String::new(),
543 expires_in: 0,
544 }),
545 );
546 }
547
548 let request_id = Uuid::new_v4().to_string();
550 let request_uri = format!("urn:ietf:params:oauth:request_uri:{}", request_id);
551
552 let par_data = json!({
555 "response_type": req.response_type,
556 "client_id": req.client_id,
557 "redirect_uri": req.redirect_uri,
558 "scope": req.scope,
559 "state": req.state,
560 "nonce": req.nonce,
561 "code_challenge": req.code_challenge,
562 "code_challenge_method": req.code_challenge_method,
563 });
564 let storage_key = format!("par_request:{}", request_id);
565 if let Err(e) = state
566 .auth_framework
567 .storage()
568 .store_kv(
569 &storage_key,
570 par_data.to_string().as_bytes(),
571 Some(std::time::Duration::from_secs(90)),
572 )
573 .await
574 {
575 error!("Failed to store PAR request: {}", e);
576 return (
579 StatusCode::INTERNAL_SERVER_ERROR,
580 Json(PARResponse {
581 request_uri: String::new(),
582 expires_in: 0,
583 }),
584 );
585 }
586
587 (
588 StatusCode::CREATED,
589 Json(PARResponse {
590 request_uri,
591 expires_in: 90,
592 }),
593 )
594}
595
596pub async fn device_authorization(
602 State(state): State<ApiState>,
603 Form(form): Form<HashMap<String, String>>,
604) -> Result<Json<JsonValue>, (StatusCode, Json<JsonValue>)> {
605 if form.get("client_id").map(|s| s.is_empty()).unwrap_or(true) {
607 return Err((
608 StatusCode::BAD_REQUEST,
609 Json(json!({
610 "error": "invalid_request",
611 "error_description": "client_id is required"
612 })),
613 ));
614 }
615
616 let device_code = format!("dc_{}", Uuid::new_v4().simple());
618 let user_code = generate_user_code();
619 let verification_uri = "/device";
620 let expires_in: u64 = 600; let device_data = json!({
624 "client_id": form.get("client_id").cloned().unwrap_or_default(),
625 "scope": form.get("scope").cloned().unwrap_or_default(),
626 "user_code": user_code,
627 "authorized": false
628 });
629 state
630 .auth_framework
631 .storage()
632 .store_kv(
633 &format!("device:{}", device_code),
634 device_data.to_string().as_bytes(),
635 Some(std::time::Duration::from_secs(expires_in)),
636 )
637 .await
638 .map_err(|e| {
639 error!("Failed to store device authorization request: {}", e);
640 (
641 StatusCode::INTERNAL_SERVER_ERROR,
642 Json(json!({
643 "error": "server_error",
644 "error_description": "Failed to initiate device authorization flow"
645 })),
646 )
647 })?;
648
649 debug!(
650 "Device authorization initiated for client_id={}",
651 form.get("client_id")
652 .map(String::as_str)
653 .unwrap_or_default()
654 );
655
656 Ok(Json(json!({
657 "device_code": device_code,
658 "user_code": user_code,
659 "verification_uri": verification_uri,
660 "verification_uri_complete": format!("{}?user_code={}", verification_uri, user_code),
661 "expires_in": expires_in,
662 "interval": 5
663 })))
664}
665
666pub async fn ciba_backchannel_auth(
672 State(state): State<ApiState>,
673 Form(form): Form<HashMap<String, String>>,
674) -> Result<Json<JsonValue>, (StatusCode, Json<JsonValue>)> {
675 let login_hint = form
677 .get("login_hint")
678 .or_else(|| form.get("login_hint_token"))
679 .or_else(|| form.get("id_token_hint"))
680 .cloned()
681 .ok_or_else(|| {
682 (
683 StatusCode::BAD_REQUEST,
684 Json(json!({
685 "error": "invalid_request",
686 "error_description":
687 "One of login_hint, login_hint_token, or id_token_hint is required"
688 })),
689 )
690 })?;
691
692 let auth_req_id = Uuid::new_v4().to_string();
693 let expires_in: u64 = 120; let ciba_data = json!({
697 "login_hint": login_hint,
698 "client_id": form.get("client_id").cloned().unwrap_or_default(),
699 "scope": form.get("scope").cloned().unwrap_or_default(),
700 "binding_message": form.get("binding_message").cloned(),
701 "status": "pending"
702 });
703 state
704 .auth_framework
705 .storage()
706 .store_kv(
707 &format!("ciba:{}", auth_req_id),
708 ciba_data.to_string().as_bytes(),
709 Some(std::time::Duration::from_secs(expires_in)),
710 )
711 .await
712 .map_err(|e| {
713 error!("Failed to store CIBA request: {}", e);
714 (
715 StatusCode::INTERNAL_SERVER_ERROR,
716 Json(json!({
717 "error": "server_error",
718 "error_description": "Failed to initiate backchannel authentication"
719 })),
720 )
721 })?;
722
723 debug!(
724 "CIBA request created: auth_req_id={}",
725 crate::utils::redact::fingerprint(&auth_req_id)
726 );
727
728 Ok(Json(json!({
729 "auth_req_id": auth_req_id,
730 "expires_in": expires_in,
731 "interval": 5
732 })))
733}
734
735fn generate_user_code() -> String {
742 use rand::RngExt;
743 const CHARS: &[u8] = b"ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
744 let mut rng = rand::rng();
745 (0..8)
746 .map(|_| CHARS[rng.random_range(0..CHARS.len())] as char)
747 .collect()
748}