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 let stored_secret = client_data["client_secret"].as_str().unwrap_or("");
214 Ok(
216 crate::security::timing_protection::constant_time_string_compare(
217 client_secret,
218 stored_secret,
219 ),
220 )
221}
222
223pub async fn introspect_token(
234 state: State<ApiState>,
235 headers: HeaderMap,
236 form: Form<IntrospectRequest>,
237) -> Result<Json<IntrospectResponse>, (StatusCode, Json<JsonValue>)> {
238 debug!("Processing token introspection request");
239
240 let auth_header = headers.get(axum::http::header::AUTHORIZATION);
242
243 let authenticated = match auth_header {
244 Some(value) => {
245 let value_str = value.to_str().unwrap_or("");
246 if value_str.starts_with("Bearer ") {
247 debug!("Introspect rejected: Bearer auth is not allowed");
249 return Err((
250 StatusCode::UNAUTHORIZED,
251 Json(json!({
252 "error": "invalid_client",
253 "error_description": "Bearer token authentication is not supported for token introspection"
254 })),
255 ));
256 } else if let Some(encoded) = value_str.strip_prefix("Basic ") {
257 match general_purpose::STANDARD.decode(encoded) {
259 Ok(decoded_bytes) => {
260 let decoded = String::from_utf8_lossy(&decoded_bytes);
261 let mut parts = decoded.splitn(2, ':');
262 let basic_client_id = parts.next().unwrap_or("").to_string();
263 let basic_client_secret = parts.next().unwrap_or("").to_string();
264 verify_client_credentials(&state, &basic_client_id, &basic_client_secret)
265 .await?
266 }
267 Err(_) => {
268 debug!("Introspect rejected: invalid Basic auth encoding");
269 return Err((
270 StatusCode::UNAUTHORIZED,
271 Json(json!({
272 "error": "invalid_client",
273 "error_description": "Invalid Basic authentication encoding"
274 })),
275 ));
276 }
277 }
278 } else {
279 debug!("Introspect rejected: unknown auth scheme");
281 return Err((
282 StatusCode::UNAUTHORIZED,
283 Json(json!({
284 "error": "invalid_client",
285 "error_description": "Unsupported authentication scheme"
286 })),
287 ));
288 }
289 }
290 None => {
291 match (&form.client_id, &form.client_secret) {
293 (Some(id), Some(secret)) => verify_client_credentials(&state, id, secret).await?,
294 _ => {
295 debug!("Introspect rejected: missing client credentials");
296 return Err((
297 StatusCode::UNAUTHORIZED,
298 Json(json!({
299 "error": "invalid_client",
300 "error_description": "client_id and client_secret are required"
301 })),
302 ));
303 }
304 }
305 }
306 };
307
308 if !authenticated {
309 debug!("Introspect rejected: invalid client credentials");
310 return Err((
311 StatusCode::UNAUTHORIZED,
312 Json(json!({
313 "error": "invalid_client",
314 "error_description": "Client authentication failed"
315 })),
316 ));
317 }
318
319 let token_manager = state.auth_framework.token_manager();
321
322 match token_manager.validate_jwt_token(&form.token) {
323 Ok(claims) => {
324 let revocation_key = format!("revoked_token:{}", claims.jti);
328 let storage = state.auth_framework.storage();
330 let mut revoked = !matches!(storage.get_kv(&revocation_key).await, Ok(None));
331 if !revoked
333 && crate::auth::ensure_account_active(storage.as_ref(), &claims.sub, false)
334 .await
335 .is_err()
336 {
337 revoked = true;
338 }
339 if !revoked && claims.token_use().is_some() && !claims.is_refresh_token() {
342 revoked = true;
343 }
344 if !revoked && claims.is_refresh_token() {
346 revoked = !matches!(
347 storage
348 .get_kv(&format!("refresh_consumed:{}", claims.jti))
349 .await,
350 Ok(None)
351 ) || !matches!(
352 storage
353 .get_kv(&format!("revoked_family:{}", claims.refresh_family()))
354 .await,
355 Ok(None)
356 );
357 }
358 if revoked {
359 debug!(
360 "Token introspection: token has been revoked (jti: {})",
361 claims.jti
362 );
363 return Ok(Json(IntrospectResponse {
364 active: false,
365 sub: None,
366 client_id: None,
367 scope: None,
368 exp: None,
369 iat: None,
370 nbf: None,
371 iss: None,
372 aud: None,
373 jti: None,
374 token_type: None,
375 username: None,
376 }));
377 }
378
379 debug_assert!(!claims.sub.is_empty(), "Token subject should not be empty");
380 Ok(Json(IntrospectResponse {
381 active: true,
382 sub: Some(claims.sub.clone()),
383 client_id: claims.client_id.clone(),
384 scope: Some(claims.scope.clone()),
385 exp: Some(claims.exp),
386 iat: Some(claims.iat),
387 nbf: Some(claims.nbf),
388 iss: Some(claims.iss.clone()),
389 aud: Some(JsonValue::String(claims.aud.clone())),
390 jti: Some(claims.jti.clone()),
391 token_type: Some(if claims.is_refresh_token() {
392 "refresh_token".to_string()
393 } else {
394 "Bearer".to_string()
395 }),
396 username: Some(claims.sub),
397 }))
398 }
399 Err(_e) => {
400 debug!("Token introspection: token is inactive");
401 Ok(Json(IntrospectResponse {
403 active: false,
404 sub: None,
405 client_id: None,
406 scope: None,
407 exp: None,
408 iat: None,
409 nbf: None,
410 iss: None,
411 aud: None,
412 jti: None,
413 token_type: None,
414 username: None,
415 }))
416 }
417 }
418}
419
420pub async fn pushed_authorization_request(
429 State(state): State<ApiState>,
430 Form(req): Form<PARRequest>,
431) -> (StatusCode, Json<PARResponse>) {
432 debug!("Processing PAR request for client_id={}", req.client_id);
433
434 if Url::parse(&req.redirect_uri).is_err() {
436 return (
437 StatusCode::BAD_REQUEST,
438 Json(PARResponse {
439 request_uri: String::new(),
440 expires_in: 0,
441 }),
442 );
443 }
444
445 let request_id = Uuid::new_v4().to_string();
447 let request_uri = format!("urn:ietf:params:oauth:request_uri:{}", request_id);
448
449 let par_data = json!({
452 "response_type": req.response_type,
453 "client_id": req.client_id,
454 "redirect_uri": req.redirect_uri,
455 "scope": req.scope,
456 "state": req.state,
457 "nonce": req.nonce,
458 "code_challenge": req.code_challenge,
459 "code_challenge_method": req.code_challenge_method,
460 });
461 let storage_key = format!("par_request:{}", request_id);
462 if let Err(e) = state
463 .auth_framework
464 .storage()
465 .store_kv(
466 &storage_key,
467 par_data.to_string().as_bytes(),
468 Some(std::time::Duration::from_secs(90)),
469 )
470 .await
471 {
472 error!("Failed to store PAR request: {}", e);
473 return (
476 StatusCode::INTERNAL_SERVER_ERROR,
477 Json(PARResponse {
478 request_uri: String::new(),
479 expires_in: 0,
480 }),
481 );
482 }
483
484 (
485 StatusCode::CREATED,
486 Json(PARResponse {
487 request_uri,
488 expires_in: 90,
489 }),
490 )
491}
492
493pub async fn device_authorization(
499 State(state): State<ApiState>,
500 Form(form): Form<HashMap<String, String>>,
501) -> Result<Json<JsonValue>, (StatusCode, Json<JsonValue>)> {
502 if form.get("client_id").map(|s| s.is_empty()).unwrap_or(true) {
504 return Err((
505 StatusCode::BAD_REQUEST,
506 Json(json!({
507 "error": "invalid_request",
508 "error_description": "client_id is required"
509 })),
510 ));
511 }
512
513 let device_code = format!("dc_{}", Uuid::new_v4().simple());
515 let user_code = generate_user_code();
516 let verification_uri = "/device";
517 let expires_in: u64 = 600; let device_data = json!({
521 "client_id": form.get("client_id").cloned().unwrap_or_default(),
522 "scope": form.get("scope").cloned().unwrap_or_default(),
523 "user_code": user_code,
524 "authorized": false
525 });
526 state
527 .auth_framework
528 .storage()
529 .store_kv(
530 &format!("device:{}", device_code),
531 device_data.to_string().as_bytes(),
532 Some(std::time::Duration::from_secs(expires_in)),
533 )
534 .await
535 .map_err(|e| {
536 error!("Failed to store device authorization request: {}", e);
537 (
538 StatusCode::INTERNAL_SERVER_ERROR,
539 Json(json!({
540 "error": "server_error",
541 "error_description": "Failed to initiate device authorization flow"
542 })),
543 )
544 })?;
545
546 debug!(
547 "Device authorization initiated for client_id={}",
548 form.get("client_id")
549 .map(String::as_str)
550 .unwrap_or_default()
551 );
552
553 Ok(Json(json!({
554 "device_code": device_code,
555 "user_code": user_code,
556 "verification_uri": verification_uri,
557 "verification_uri_complete": format!("{}?user_code={}", verification_uri, user_code),
558 "expires_in": expires_in,
559 "interval": 5
560 })))
561}
562
563pub async fn ciba_backchannel_auth(
569 State(state): State<ApiState>,
570 Form(form): Form<HashMap<String, String>>,
571) -> Result<Json<JsonValue>, (StatusCode, Json<JsonValue>)> {
572 let login_hint = form
574 .get("login_hint")
575 .or_else(|| form.get("login_hint_token"))
576 .or_else(|| form.get("id_token_hint"))
577 .cloned()
578 .ok_or_else(|| {
579 (
580 StatusCode::BAD_REQUEST,
581 Json(json!({
582 "error": "invalid_request",
583 "error_description":
584 "One of login_hint, login_hint_token, or id_token_hint is required"
585 })),
586 )
587 })?;
588
589 let auth_req_id = Uuid::new_v4().to_string();
590 let expires_in: u64 = 120; let ciba_data = json!({
594 "login_hint": login_hint,
595 "client_id": form.get("client_id").cloned().unwrap_or_default(),
596 "scope": form.get("scope").cloned().unwrap_or_default(),
597 "binding_message": form.get("binding_message").cloned(),
598 "status": "pending"
599 });
600 state
601 .auth_framework
602 .storage()
603 .store_kv(
604 &format!("ciba:{}", auth_req_id),
605 ciba_data.to_string().as_bytes(),
606 Some(std::time::Duration::from_secs(expires_in)),
607 )
608 .await
609 .map_err(|e| {
610 error!("Failed to store CIBA request: {}", e);
611 (
612 StatusCode::INTERNAL_SERVER_ERROR,
613 Json(json!({
614 "error": "server_error",
615 "error_description": "Failed to initiate backchannel authentication"
616 })),
617 )
618 })?;
619
620 debug!(
621 "CIBA request created: auth_req_id={}",
622 crate::utils::redact::fingerprint(&auth_req_id)
623 );
624
625 Ok(Json(json!({
626 "auth_req_id": auth_req_id,
627 "expires_in": expires_in,
628 "interval": 5
629 })))
630}
631
632fn generate_user_code() -> String {
639 use rand::RngExt;
640 const CHARS: &[u8] = b"ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
641 let mut rng = rand::rng();
642 (0..8)
643 .map(|_| CHARS[rng.random_range(0..CHARS.len())] as char)
644 .collect()
645}