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