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", &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(Debug, Serialize)]
141pub struct PARResponse {
142 pub request_uri: String,
144
145 pub expires_in: u64,
147}
148
149async fn verify_client_credentials(
160 state: &State<ApiState>,
161 client_id: &str,
162 client_secret: &str,
163) -> Result<bool, (StatusCode, Json<JsonValue>)> {
164 let client_key = format!("oauth2_client:{}", client_id);
165 let client_data = match state.auth_framework.storage().get_kv(&client_key).await {
166 Ok(Some(bytes)) => match serde_json::from_slice::<serde_json::Value>(&bytes) {
167 Ok(v) => v,
168 Err(_) => {
169 error!(
170 "Introspect: failed to deserialize client record for {}",
171 client_id
172 );
173 return Err((
174 StatusCode::INTERNAL_SERVER_ERROR,
175 Json(json!({
176 "error": "server_error",
177 "error_description": "Internal server error"
178 })),
179 ));
180 }
181 },
182 Ok(None) => {
183 return Ok(false);
185 }
186 Err(e) => {
187 error!(
188 "Introspect: storage error looking up client {}: {}",
189 client_id, e
190 );
191 return Err((
192 StatusCode::INTERNAL_SERVER_ERROR,
193 Json(json!({
194 "error": "server_error",
195 "error_description": "Internal server error"
196 })),
197 ));
198 }
199 };
200
201 let stored_secret = client_data["client_secret"].as_str().unwrap_or("");
202 Ok(
204 crate::security::timing_protection::constant_time_string_compare(
205 client_secret,
206 stored_secret,
207 ),
208 )
209}
210
211pub async fn introspect_token(
222 state: State<ApiState>,
223 headers: HeaderMap,
224 form: Form<IntrospectRequest>,
225) -> Result<Json<IntrospectResponse>, (StatusCode, Json<JsonValue>)> {
226 debug!("Processing token introspection request");
227
228 let auth_header = headers.get(axum::http::header::AUTHORIZATION);
230
231 let authenticated = match auth_header {
232 Some(value) => {
233 let value_str = value.to_str().unwrap_or("");
234 if value_str.starts_with("Bearer ") {
235 debug!("Introspect rejected: Bearer auth is not allowed");
237 return Err((
238 StatusCode::UNAUTHORIZED,
239 Json(json!({
240 "error": "invalid_client",
241 "error_description": "Bearer token authentication is not supported for token introspection"
242 })),
243 ));
244 } else if let Some(encoded) = value_str.strip_prefix("Basic ") {
245 match general_purpose::STANDARD.decode(encoded) {
247 Ok(decoded_bytes) => {
248 let decoded = String::from_utf8_lossy(&decoded_bytes);
249 let mut parts = decoded.splitn(2, ':');
250 let basic_client_id = parts.next().unwrap_or("").to_string();
251 let basic_client_secret = parts.next().unwrap_or("").to_string();
252 verify_client_credentials(&state, &basic_client_id, &basic_client_secret)
253 .await?
254 }
255 Err(_) => {
256 debug!("Introspect rejected: invalid Basic auth encoding");
257 return Err((
258 StatusCode::UNAUTHORIZED,
259 Json(json!({
260 "error": "invalid_client",
261 "error_description": "Invalid Basic authentication encoding"
262 })),
263 ));
264 }
265 }
266 } else {
267 debug!("Introspect rejected: unknown auth scheme");
269 return Err((
270 StatusCode::UNAUTHORIZED,
271 Json(json!({
272 "error": "invalid_client",
273 "error_description": "Unsupported authentication scheme"
274 })),
275 ));
276 }
277 }
278 None => {
279 match (&form.client_id, &form.client_secret) {
281 (Some(id), Some(secret)) => verify_client_credentials(&state, id, secret).await?,
282 _ => {
283 debug!("Introspect rejected: missing client credentials");
284 return Err((
285 StatusCode::UNAUTHORIZED,
286 Json(json!({
287 "error": "invalid_client",
288 "error_description": "client_id and client_secret are required"
289 })),
290 ));
291 }
292 }
293 }
294 };
295
296 if !authenticated {
297 debug!("Introspect rejected: invalid client credentials");
298 return Err((
299 StatusCode::UNAUTHORIZED,
300 Json(json!({
301 "error": "invalid_client",
302 "error_description": "Client authentication failed"
303 })),
304 ));
305 }
306
307 let token_manager = state.auth_framework.token_manager();
309
310 match token_manager.validate_jwt_token(&form.token) {
311 Ok(claims) => {
312 let revocation_key = format!("revoked_token:{}", claims.jti);
316 let storage = state.auth_framework.storage();
318 let mut revoked = !matches!(storage.get_kv(&revocation_key).await, Ok(None));
319 if !revoked
321 && crate::auth::ensure_account_active(storage.as_ref(), &claims.sub, false)
322 .await
323 .is_err()
324 {
325 revoked = true;
326 }
327 if !revoked && claims.token_use().is_some() && !claims.is_refresh_token() {
330 revoked = true;
331 }
332 if !revoked && claims.is_refresh_token() {
334 revoked = !matches!(
335 storage
336 .get_kv(&format!("refresh_consumed:{}", claims.jti))
337 .await,
338 Ok(None)
339 ) || !matches!(
340 storage
341 .get_kv(&format!("revoked_family:{}", claims.refresh_family()))
342 .await,
343 Ok(None)
344 );
345 }
346 if revoked {
347 debug!(
348 "Token introspection: token has been revoked (jti: {})",
349 claims.jti
350 );
351 return Ok(Json(IntrospectResponse {
352 active: false,
353 sub: None,
354 client_id: None,
355 scope: None,
356 exp: None,
357 iat: None,
358 nbf: None,
359 iss: None,
360 aud: None,
361 jti: None,
362 token_type: None,
363 username: None,
364 }));
365 }
366
367 debug_assert!(!claims.sub.is_empty(), "Token subject should not be empty");
368 Ok(Json(IntrospectResponse {
369 active: true,
370 sub: Some(claims.sub.clone()),
371 client_id: claims.client_id.clone(),
372 scope: Some(claims.scope.clone()),
373 exp: Some(claims.exp),
374 iat: Some(claims.iat),
375 nbf: Some(claims.nbf),
376 iss: Some(claims.iss.clone()),
377 aud: Some(JsonValue::String(claims.aud.clone())),
378 jti: Some(claims.jti.clone()),
379 token_type: Some(if claims.is_refresh_token() {
380 "refresh_token".to_string()
381 } else {
382 "Bearer".to_string()
383 }),
384 username: Some(claims.sub),
385 }))
386 }
387 Err(_e) => {
388 debug!("Token introspection: token is inactive");
389 Ok(Json(IntrospectResponse {
391 active: false,
392 sub: None,
393 client_id: None,
394 scope: None,
395 exp: None,
396 iat: None,
397 nbf: None,
398 iss: None,
399 aud: None,
400 jti: None,
401 token_type: None,
402 username: None,
403 }))
404 }
405 }
406}
407
408pub async fn pushed_authorization_request(
417 State(state): State<ApiState>,
418 Form(req): Form<PARRequest>,
419) -> (StatusCode, Json<PARResponse>) {
420 debug!("Processing PAR request for client_id={}", req.client_id);
421
422 if Url::parse(&req.redirect_uri).is_err() {
424 return (
425 StatusCode::BAD_REQUEST,
426 Json(PARResponse {
427 request_uri: String::new(),
428 expires_in: 0,
429 }),
430 );
431 }
432
433 let request_id = Uuid::new_v4().to_string();
435 let request_uri = format!("urn:ietf:params:oauth:request_uri:{}", request_id);
436
437 let par_data = json!({
440 "response_type": req.response_type,
441 "client_id": req.client_id,
442 "redirect_uri": req.redirect_uri,
443 "scope": req.scope,
444 "state": req.state,
445 "nonce": req.nonce,
446 "code_challenge": req.code_challenge,
447 "code_challenge_method": req.code_challenge_method,
448 });
449 let storage_key = format!("par_request:{}", request_id);
450 if let Err(e) = state
451 .auth_framework
452 .storage()
453 .store_kv(
454 &storage_key,
455 par_data.to_string().as_bytes(),
456 Some(std::time::Duration::from_secs(90)),
457 )
458 .await
459 {
460 error!("Failed to store PAR request: {}", e);
461 return (
464 StatusCode::INTERNAL_SERVER_ERROR,
465 Json(PARResponse {
466 request_uri: String::new(),
467 expires_in: 0,
468 }),
469 );
470 }
471
472 (
473 StatusCode::CREATED,
474 Json(PARResponse {
475 request_uri,
476 expires_in: 90,
477 }),
478 )
479}
480
481pub async fn device_authorization(
487 State(state): State<ApiState>,
488 Form(form): Form<HashMap<String, String>>,
489) -> Result<Json<JsonValue>, (StatusCode, Json<JsonValue>)> {
490 if form.get("client_id").map(|s| s.is_empty()).unwrap_or(true) {
492 return Err((
493 StatusCode::BAD_REQUEST,
494 Json(json!({
495 "error": "invalid_request",
496 "error_description": "client_id is required"
497 })),
498 ));
499 }
500
501 let device_code = format!("dc_{}", Uuid::new_v4().simple());
503 let user_code = generate_user_code();
504 let verification_uri = "/device";
505 let expires_in: u64 = 600; let device_data = json!({
509 "client_id": form.get("client_id").cloned().unwrap_or_default(),
510 "scope": form.get("scope").cloned().unwrap_or_default(),
511 "user_code": user_code,
512 "authorized": false
513 });
514 state
515 .auth_framework
516 .storage()
517 .store_kv(
518 &format!("device:{}", device_code),
519 device_data.to_string().as_bytes(),
520 Some(std::time::Duration::from_secs(expires_in)),
521 )
522 .await
523 .map_err(|e| {
524 error!("Failed to store device authorization request: {}", e);
525 (
526 StatusCode::INTERNAL_SERVER_ERROR,
527 Json(json!({
528 "error": "server_error",
529 "error_description": "Failed to initiate device authorization flow"
530 })),
531 )
532 })?;
533
534 debug!(
535 "Device authorization initiated for client_id={}",
536 form.get("client_id")
537 .map(String::as_str)
538 .unwrap_or_default()
539 );
540
541 Ok(Json(json!({
542 "device_code": device_code,
543 "user_code": user_code,
544 "verification_uri": verification_uri,
545 "verification_uri_complete": format!("{}?user_code={}", verification_uri, user_code),
546 "expires_in": expires_in,
547 "interval": 5
548 })))
549}
550
551pub async fn ciba_backchannel_auth(
557 State(state): State<ApiState>,
558 Form(form): Form<HashMap<String, String>>,
559) -> Result<Json<JsonValue>, (StatusCode, Json<JsonValue>)> {
560 let login_hint = form
562 .get("login_hint")
563 .or_else(|| form.get("login_hint_token"))
564 .or_else(|| form.get("id_token_hint"))
565 .cloned()
566 .ok_or_else(|| {
567 (
568 StatusCode::BAD_REQUEST,
569 Json(json!({
570 "error": "invalid_request",
571 "error_description":
572 "One of login_hint, login_hint_token, or id_token_hint is required"
573 })),
574 )
575 })?;
576
577 let auth_req_id = Uuid::new_v4().to_string();
578 let expires_in: u64 = 120; let ciba_data = json!({
582 "login_hint": login_hint,
583 "client_id": form.get("client_id").cloned().unwrap_or_default(),
584 "scope": form.get("scope").cloned().unwrap_or_default(),
585 "binding_message": form.get("binding_message").cloned(),
586 "status": "pending"
587 });
588 state
589 .auth_framework
590 .storage()
591 .store_kv(
592 &format!("ciba:{}", auth_req_id),
593 ciba_data.to_string().as_bytes(),
594 Some(std::time::Duration::from_secs(expires_in)),
595 )
596 .await
597 .map_err(|e| {
598 error!("Failed to store CIBA request: {}", e);
599 (
600 StatusCode::INTERNAL_SERVER_ERROR,
601 Json(json!({
602 "error": "server_error",
603 "error_description": "Failed to initiate backchannel authentication"
604 })),
605 )
606 })?;
607
608 debug!("CIBA request created: auth_req_id={}", auth_req_id);
609
610 Ok(Json(json!({
611 "auth_req_id": auth_req_id,
612 "expires_in": expires_in,
613 "interval": 5
614 })))
615}
616
617fn generate_user_code() -> String {
624 use rand::RngExt;
625 const CHARS: &[u8] = b"ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
626 let mut rng = rand::rng();
627 (0..8)
628 .map(|_| CHARS[rng.random_range(0..CHARS.len())] as char)
629 .collect()
630}