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(Debug, 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
43#[derive(Debug, Serialize)]
45pub struct IntrospectResponse {
46 pub active: bool,
48
49 #[serde(skip_serializing_if = "Option::is_none")]
51 pub sub: Option<String>,
52
53 #[serde(skip_serializing_if = "Option::is_none")]
55 pub client_id: Option<String>,
56
57 #[serde(skip_serializing_if = "Option::is_none")]
59 pub scope: Option<String>,
60
61 #[serde(skip_serializing_if = "Option::is_none")]
63 pub exp: Option<i64>,
64
65 #[serde(skip_serializing_if = "Option::is_none")]
67 pub iat: Option<i64>,
68
69 #[serde(skip_serializing_if = "Option::is_none")]
71 pub nbf: Option<i64>,
72
73 #[serde(skip_serializing_if = "Option::is_none")]
75 pub iss: Option<String>,
76
77 #[serde(skip_serializing_if = "Option::is_none")]
79 pub aud: Option<JsonValue>,
80
81 #[serde(skip_serializing_if = "Option::is_none")]
83 pub jti: Option<String>,
84
85 #[serde(skip_serializing_if = "Option::is_none")]
87 pub token_type: Option<String>,
88
89 #[serde(skip_serializing_if = "Option::is_none")]
91 pub username: Option<String>,
92}
93
94#[derive(Debug, Deserialize)]
99pub struct PARRequest {
100 pub response_type: String,
102
103 pub client_id: String,
105
106 pub redirect_uri: String,
108
109 pub scope: Option<String>,
111
112 pub state: Option<String>,
114
115 pub nonce: Option<String>,
117
118 pub code_challenge: Option<String>,
120
121 pub code_challenge_method: Option<String>,
123}
124
125#[derive(Debug, Serialize)]
127pub struct PARResponse {
128 pub request_uri: String,
130
131 pub expires_in: u64,
133}
134
135async fn verify_client_credentials(
146 state: &State<ApiState>,
147 client_id: &str,
148 client_secret: &str,
149) -> Result<bool, (StatusCode, Json<JsonValue>)> {
150 let client_key = format!("oauth2_client:{}", client_id);
151 let client_data = match state.auth_framework.storage().get_kv(&client_key).await {
152 Ok(Some(bytes)) => match serde_json::from_slice::<serde_json::Value>(&bytes) {
153 Ok(v) => v,
154 Err(_) => {
155 error!(
156 "Introspect: failed to deserialize client record for {}",
157 client_id
158 );
159 return Err((
160 StatusCode::INTERNAL_SERVER_ERROR,
161 Json(json!({
162 "error": "server_error",
163 "error_description": "Internal server error"
164 })),
165 ));
166 }
167 },
168 Ok(None) => {
169 return Ok(false);
171 }
172 Err(e) => {
173 error!(
174 "Introspect: storage error looking up client {}: {}",
175 client_id, e
176 );
177 return Err((
178 StatusCode::INTERNAL_SERVER_ERROR,
179 Json(json!({
180 "error": "server_error",
181 "error_description": "Internal server error"
182 })),
183 ));
184 }
185 };
186
187 let stored_secret = client_data["client_secret"].as_str().unwrap_or("");
188 Ok(
190 crate::security::timing_protection::constant_time_string_compare(
191 client_secret,
192 stored_secret,
193 ),
194 )
195}
196
197pub async fn introspect_token(
208 state: State<ApiState>,
209 headers: HeaderMap,
210 form: Form<IntrospectRequest>,
211) -> Result<Json<IntrospectResponse>, (StatusCode, Json<JsonValue>)> {
212 debug!("Processing token introspection request");
213
214 let auth_header = headers.get(axum::http::header::AUTHORIZATION);
216
217 let authenticated = match auth_header {
218 Some(value) => {
219 let value_str = value.to_str().unwrap_or("");
220 if value_str.starts_with("Bearer ") {
221 debug!("Introspect rejected: Bearer auth is not allowed");
223 return Err((
224 StatusCode::UNAUTHORIZED,
225 Json(json!({
226 "error": "invalid_client",
227 "error_description": "Bearer token authentication is not supported for token introspection"
228 })),
229 ));
230 } else if let Some(encoded) = value_str.strip_prefix("Basic ") {
231 match general_purpose::STANDARD.decode(encoded) {
233 Ok(decoded_bytes) => {
234 let decoded = String::from_utf8_lossy(&decoded_bytes);
235 let mut parts = decoded.splitn(2, ':');
236 let basic_client_id = parts.next().unwrap_or("").to_string();
237 let basic_client_secret = parts.next().unwrap_or("").to_string();
238 verify_client_credentials(&state, &basic_client_id, &basic_client_secret)
239 .await?
240 }
241 Err(_) => {
242 debug!("Introspect rejected: invalid Basic auth encoding");
243 return Err((
244 StatusCode::UNAUTHORIZED,
245 Json(json!({
246 "error": "invalid_client",
247 "error_description": "Invalid Basic authentication encoding"
248 })),
249 ));
250 }
251 }
252 } else {
253 debug!("Introspect rejected: unknown auth scheme");
255 return Err((
256 StatusCode::UNAUTHORIZED,
257 Json(json!({
258 "error": "invalid_client",
259 "error_description": "Unsupported authentication scheme"
260 })),
261 ));
262 }
263 }
264 None => {
265 match (&form.client_id, &form.client_secret) {
267 (Some(id), Some(secret)) => verify_client_credentials(&state, id, secret).await?,
268 _ => {
269 debug!("Introspect rejected: missing client credentials");
270 return Err((
271 StatusCode::UNAUTHORIZED,
272 Json(json!({
273 "error": "invalid_client",
274 "error_description": "client_id and client_secret are required"
275 })),
276 ));
277 }
278 }
279 }
280 };
281
282 if !authenticated {
283 debug!("Introspect rejected: invalid client credentials");
284 return Err((
285 StatusCode::UNAUTHORIZED,
286 Json(json!({
287 "error": "invalid_client",
288 "error_description": "Client authentication failed"
289 })),
290 ));
291 }
292
293 let token_manager = state.auth_framework.token_manager();
295
296 match token_manager.validate_jwt_token(&form.token) {
297 Ok(claims) => {
298 let revocation_key = format!("revoked_token:{}", claims.jti);
302 let storage = state.auth_framework.storage();
304 let mut revoked = !matches!(storage.get_kv(&revocation_key).await, Ok(None));
305 if !revoked
307 && crate::auth::ensure_account_active(storage.as_ref(), &claims.sub, false)
308 .await
309 .is_err()
310 {
311 revoked = true;
312 }
313 if !revoked && claims.token_use().is_some() && !claims.is_refresh_token() {
316 revoked = true;
317 }
318 if !revoked && claims.is_refresh_token() {
320 revoked = !matches!(
321 storage
322 .get_kv(&format!("refresh_consumed:{}", claims.jti))
323 .await,
324 Ok(None)
325 ) || !matches!(
326 storage
327 .get_kv(&format!("revoked_family:{}", claims.refresh_family()))
328 .await,
329 Ok(None)
330 );
331 }
332 if revoked {
333 debug!(
334 "Token introspection: token has been revoked (jti: {})",
335 claims.jti
336 );
337 return Ok(Json(IntrospectResponse {
338 active: false,
339 sub: None,
340 client_id: None,
341 scope: None,
342 exp: None,
343 iat: None,
344 nbf: None,
345 iss: None,
346 aud: None,
347 jti: None,
348 token_type: None,
349 username: None,
350 }));
351 }
352
353 debug_assert!(!claims.sub.is_empty(), "Token subject should not be empty");
354 Ok(Json(IntrospectResponse {
355 active: true,
356 sub: Some(claims.sub.clone()),
357 client_id: claims.client_id.clone(),
358 scope: Some(claims.scope.clone()),
359 exp: Some(claims.exp),
360 iat: Some(claims.iat),
361 nbf: Some(claims.nbf),
362 iss: Some(claims.iss.clone()),
363 aud: Some(JsonValue::String(claims.aud.clone())),
364 jti: Some(claims.jti.clone()),
365 token_type: Some(if claims.is_refresh_token() {
366 "refresh_token".to_string()
367 } else {
368 "Bearer".to_string()
369 }),
370 username: Some(claims.sub),
371 }))
372 }
373 Err(_e) => {
374 debug!("Token introspection: token is inactive");
375 Ok(Json(IntrospectResponse {
377 active: false,
378 sub: None,
379 client_id: None,
380 scope: None,
381 exp: None,
382 iat: None,
383 nbf: None,
384 iss: None,
385 aud: None,
386 jti: None,
387 token_type: None,
388 username: None,
389 }))
390 }
391 }
392}
393
394pub async fn pushed_authorization_request(
403 State(state): State<ApiState>,
404 Form(req): Form<PARRequest>,
405) -> (StatusCode, Json<PARResponse>) {
406 debug!("Processing PAR request for client_id={}", req.client_id);
407
408 if Url::parse(&req.redirect_uri).is_err() {
410 return (
411 StatusCode::BAD_REQUEST,
412 Json(PARResponse {
413 request_uri: String::new(),
414 expires_in: 0,
415 }),
416 );
417 }
418
419 let request_id = Uuid::new_v4().to_string();
421 let request_uri = format!("urn:ietf:params:oauth:request_uri:{}", request_id);
422
423 let par_data = json!({
426 "response_type": req.response_type,
427 "client_id": req.client_id,
428 "redirect_uri": req.redirect_uri,
429 "scope": req.scope,
430 "state": req.state,
431 "nonce": req.nonce,
432 "code_challenge": req.code_challenge,
433 "code_challenge_method": req.code_challenge_method,
434 });
435 let storage_key = format!("par_request:{}", request_id);
436 if let Err(e) = state
437 .auth_framework
438 .storage()
439 .store_kv(
440 &storage_key,
441 par_data.to_string().as_bytes(),
442 Some(std::time::Duration::from_secs(90)),
443 )
444 .await
445 {
446 error!("Failed to store PAR request: {}", e);
447 return (
450 StatusCode::INTERNAL_SERVER_ERROR,
451 Json(PARResponse {
452 request_uri: String::new(),
453 expires_in: 0,
454 }),
455 );
456 }
457
458 (
459 StatusCode::CREATED,
460 Json(PARResponse {
461 request_uri,
462 expires_in: 90,
463 }),
464 )
465}
466
467pub async fn device_authorization(
473 State(state): State<ApiState>,
474 Form(form): Form<HashMap<String, String>>,
475) -> Result<Json<JsonValue>, (StatusCode, Json<JsonValue>)> {
476 if form.get("client_id").map(|s| s.is_empty()).unwrap_or(true) {
478 return Err((
479 StatusCode::BAD_REQUEST,
480 Json(json!({
481 "error": "invalid_request",
482 "error_description": "client_id is required"
483 })),
484 ));
485 }
486
487 let device_code = format!("dc_{}", Uuid::new_v4().simple());
489 let user_code = generate_user_code();
490 let verification_uri = "/device";
491 let expires_in: u64 = 600; let device_data = json!({
495 "client_id": form.get("client_id").cloned().unwrap_or_default(),
496 "scope": form.get("scope").cloned().unwrap_or_default(),
497 "user_code": user_code,
498 "authorized": false
499 });
500 state
501 .auth_framework
502 .storage()
503 .store_kv(
504 &format!("device:{}", device_code),
505 device_data.to_string().as_bytes(),
506 Some(std::time::Duration::from_secs(expires_in)),
507 )
508 .await
509 .map_err(|e| {
510 error!("Failed to store device authorization request: {}", e);
511 (
512 StatusCode::INTERNAL_SERVER_ERROR,
513 Json(json!({
514 "error": "server_error",
515 "error_description": "Failed to initiate device authorization flow"
516 })),
517 )
518 })?;
519
520 debug!(
521 "Device authorization initiated for client_id={}",
522 form.get("client_id")
523 .map(String::as_str)
524 .unwrap_or_default()
525 );
526
527 Ok(Json(json!({
528 "device_code": device_code,
529 "user_code": user_code,
530 "verification_uri": verification_uri,
531 "verification_uri_complete": format!("{}?user_code={}", verification_uri, user_code),
532 "expires_in": expires_in,
533 "interval": 5
534 })))
535}
536
537pub async fn ciba_backchannel_auth(
543 State(state): State<ApiState>,
544 Form(form): Form<HashMap<String, String>>,
545) -> Result<Json<JsonValue>, (StatusCode, Json<JsonValue>)> {
546 let login_hint = form
548 .get("login_hint")
549 .or_else(|| form.get("login_hint_token"))
550 .or_else(|| form.get("id_token_hint"))
551 .cloned()
552 .ok_or_else(|| {
553 (
554 StatusCode::BAD_REQUEST,
555 Json(json!({
556 "error": "invalid_request",
557 "error_description":
558 "One of login_hint, login_hint_token, or id_token_hint is required"
559 })),
560 )
561 })?;
562
563 let auth_req_id = Uuid::new_v4().to_string();
564 let expires_in: u64 = 120; let ciba_data = json!({
568 "login_hint": login_hint,
569 "client_id": form.get("client_id").cloned().unwrap_or_default(),
570 "scope": form.get("scope").cloned().unwrap_or_default(),
571 "binding_message": form.get("binding_message").cloned(),
572 "status": "pending"
573 });
574 state
575 .auth_framework
576 .storage()
577 .store_kv(
578 &format!("ciba:{}", auth_req_id),
579 ciba_data.to_string().as_bytes(),
580 Some(std::time::Duration::from_secs(expires_in)),
581 )
582 .await
583 .map_err(|e| {
584 error!("Failed to store CIBA request: {}", e);
585 (
586 StatusCode::INTERNAL_SERVER_ERROR,
587 Json(json!({
588 "error": "server_error",
589 "error_description": "Failed to initiate backchannel authentication"
590 })),
591 )
592 })?;
593
594 debug!("CIBA request created: auth_req_id={}", auth_req_id);
595
596 Ok(Json(json!({
597 "auth_req_id": auth_req_id,
598 "expires_in": expires_in,
599 "interval": 5
600 })))
601}
602
603fn generate_user_code() -> String {
610 use rand::RngExt;
611 const CHARS: &[u8] = b"ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
612 let mut rng = rand::rng();
613 (0..8)
614 .map(|_| CHARS[rng.random_range(0..CHARS.len())] as char)
615 .collect()
616}