use crate::constants::TokenType;
use crate::error::{GarrisonError, GarrisonResult};
use crate::oauth2_server::client::OAuth2ClientStore;
use crate::oauth2_server::token::TokenHandler;
use serde::{Deserialize, Serialize};
use std::sync::Arc;
#[derive(Debug, Clone, Deserialize)]
pub struct IntrospectRequest {
pub token: String,
pub token_type_hint: Option<String>,
pub client_id: String,
pub client_secret: String,
}
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct IntrospectResponse {
pub active: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub token_type: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub scope: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub client_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub exp: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub sub: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub username: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub iat: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub nbf: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub aud: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub iss: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub jti: Option<String>,
}
const OAUTH2_ISSUER: &str = "garrison-oauth2-server";
impl IntrospectResponse {
pub fn inactive() -> Self {
Self {
active: false,
token_type: None,
scope: None,
client_id: None,
exp: None,
sub: None,
username: None,
iat: None,
nbf: None,
aud: None,
iss: None,
jti: None,
}
}
}
pub struct IntrospectHandler {
store: Arc<dyn OAuth2ClientStore>,
token_handler: Arc<TokenHandler>,
}
impl IntrospectHandler {
pub fn new(store: Arc<dyn OAuth2ClientStore>, token_handler: Arc<TokenHandler>) -> Self {
Self {
store,
token_handler,
}
}
pub async fn handle(&self, req: &IntrospectRequest) -> GarrisonResult<IntrospectResponse> {
let client = self.store.get(&req.client_id).await?.ok_or_else(|| {
GarrisonError::OAuth2(format!(
"oauth2-server-introspect-invalid-client::{}",
req.client_id
))
})?;
if !client.verify_secret(&req.client_secret)? {
return Err(GarrisonError::OAuth2(
"oauth2-server-introspect-invalid-client-secret".into(),
));
}
let record = self
.token_handler
.get_access_token_record(&req.token)
.await?;
match record {
Some(record) => {
let scope = if record.scopes.is_empty() {
None
} else {
Some(record.scopes.join(" "))
};
let iat_ts = record.issued_at.timestamp();
Ok(IntrospectResponse {
active: true,
token_type: Some(TokenType::Bearer.to_string()),
scope,
client_id: Some(record.client_id.clone()),
exp: Some(record.expires_at.timestamp()),
sub: record.user_id.map(|id| id.to_string()),
username: record.username,
iat: Some(iat_ts),
nbf: Some(iat_ts), aud: Some(record.client_id), iss: Some(OAUTH2_ISSUER.into()),
jti: record.jti,
})
},
None => Ok(IntrospectResponse::inactive()),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::dao::MockDao;
use crate::oauth2_server::authorize::AuthorizeHandler;
use crate::oauth2_server::client::{DaoOAuth2ClientStore, GrantType, OAuth2Client};
use crate::oauth2_server::token::{TokenHandler, TokenRequest};
fn make_handlers() -> (IntrospectHandler, Arc<MockDao>, Arc<TokenHandler>) {
let dao = Arc::new(MockDao::new());
let store = Arc::new(DaoOAuth2ClientStore::new(dao.clone()));
let authorize_handler = Arc::new(AuthorizeHandler::new(
store.clone(),
dao.clone(),
"https://auth.example.com/login".into(),
));
let token_handler = Arc::new(TokenHandler::new(
store.clone(),
dao.clone(),
authorize_handler,
));
let introspect_handler = IntrospectHandler::new(store, token_handler.clone());
(introspect_handler, dao, token_handler)
}
fn make_client(id: &str) -> OAuth2Client {
OAuth2Client::new(
id,
"secret-123",
vec!["https://app.example.com/cb".into()],
vec![GrantType::ClientCredentials],
vec!["read".into(), "write".into()],
)
.unwrap()
}
async fn issue_token(token_handler: &TokenHandler, client_id: &str) -> String {
let req = TokenRequest {
grant_type: "client_credentials".into(),
client_id: client_id.into(),
client_secret: "secret-123".into(),
code: None,
redirect_uri: None,
code_verifier: None,
refresh_token: None,
scope: Some("read write".into()),
username: None,
password: None,
};
token_handler.handle(&req).await.unwrap().access_token
}
#[tokio::test]
async fn introspect_active_token() {
let (handler, _, token_handler) = make_handlers();
handler.store.create(make_client("int-001")).await.unwrap();
let token = issue_token(&token_handler, "int-001").await;
let req = IntrospectRequest {
token,
token_type_hint: Some("access_token".into()),
client_id: "int-001".into(),
client_secret: "secret-123".into(),
};
let resp = handler.handle(&req).await.expect("内省");
assert!(resp.active);
assert_eq!(resp.token_type.as_deref(), Some("Bearer"));
assert_eq!(resp.client_id.as_deref(), Some("int-001"));
assert_eq!(resp.scope.as_deref(), Some("read write"));
assert!(resp.exp.is_some());
assert!(resp.sub.is_none(), "client_credentials 无 user_id");
assert!(resp.iat.is_some(), "iat 必须有值");
assert!(resp.nbf.is_some(), "nbf 必须有值");
assert_eq!(resp.iat, resp.nbf, "OAuth2 token 签发即生效,nbf = iat");
assert_eq!(resp.aud.as_deref(), Some("int-001"), "aud = client_id");
assert_eq!(resp.iss.as_deref(), Some("garrison-oauth2-server"));
assert!(resp.jti.is_some(), "jti 必须有值");
assert!(resp.username.is_none(), "client_credentials 无 username");
}
#[tokio::test]
async fn introspect_nonexistent_token_returns_inactive() {
let (handler, _, _) = make_handlers();
handler.store.create(make_client("int-002")).await.unwrap();
let req = IntrospectRequest {
token: "nonexistent".into(),
token_type_hint: None,
client_id: "int-002".into(),
client_secret: "secret-123".into(),
};
let resp = handler.handle(&req).await.expect("内省");
assert!(!resp.active);
assert!(resp.token_type.is_none());
assert!(resp.client_id.is_none());
}
#[tokio::test]
async fn introspect_revoked_token_returns_inactive() {
let (handler, _, token_handler) = make_handlers();
handler.store.create(make_client("int-003")).await.unwrap();
let token = issue_token(&token_handler, "int-003").await;
token_handler.revoke_token(&token).await.unwrap();
let req = IntrospectRequest {
token,
token_type_hint: None,
client_id: "int-003".into(),
client_secret: "secret-123".into(),
};
let resp = handler.handle(&req).await.expect("内省");
assert!(!resp.active, "撤销后的 token 应返回 inactive");
}
#[tokio::test]
async fn introspect_invalid_client_id() {
let (handler, _, _) = make_handlers();
let req = IntrospectRequest {
token: "some-token".into(),
token_type_hint: None,
client_id: "no-such".into(),
client_secret: "secret".into(),
};
let err = handler.handle(&req).await.unwrap_err();
assert!(err
.to_string()
.contains("oauth2-server-introspect-invalid-client"));
}
#[tokio::test]
async fn introspect_invalid_client_secret() {
let (handler, _, _) = make_handlers();
handler.store.create(make_client("int-004")).await.unwrap();
let req = IntrospectRequest {
token: "some-token".into(),
token_type_hint: None,
client_id: "int-004".into(),
client_secret: "wrong".into(),
};
let err = handler.handle(&req).await.unwrap_err();
assert!(err
.to_string()
.contains("oauth2-server-introspect-invalid-client"));
}
#[test]
fn inactive_response_all_none() {
let resp = IntrospectResponse::inactive();
assert!(!resp.active);
assert!(resp.token_type.is_none());
assert!(resp.scope.is_none());
assert!(resp.client_id.is_none());
assert!(resp.exp.is_none());
assert!(resp.sub.is_none());
assert!(resp.username.is_none());
assert!(resp.iat.is_none());
assert!(resp.nbf.is_none());
assert!(resp.aud.is_none());
assert!(resp.iss.is_none());
assert!(resp.jti.is_none());
}
}