use crate::constants::{DaoKeyPrefix, TokenType};
use crate::dao::{GarrisonDao, InMemoryDao};
use crate::error::{GarrisonError, GarrisonResult};
use crate::limiteron::GarrisonDaoDistributedLimiter;
use crate::loc;
use crate::oauth2_server::authorize::AuthorizeHandler;
use crate::oauth2_server::client::{GrantType, OAuth2Client, OAuth2ClientStore};
#[cfg(feature = "db-sqlite")]
use crate::protocol::jwt::refresh::RefreshTokenRotation;
use async_trait::async_trait;
use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD};
use base64::Engine;
use chrono::{DateTime, Duration, Utc};
use limiteron::limiters::DistributedLimiter;
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use std::time::Duration as StdDuration;
fn oauth2_refresh_token_key(token: &str) -> String {
debug_assert!(
!token.contains(':'),
"oauth2 refresh_token key: token must not contain ':' (ambiguous key)"
);
format!("oauth2:rtoken:{}", token)
}
const ACCESS_TOKEN_TTL_SECONDS: u64 = 3600;
const REFRESH_TOKEN_TTL_SECONDS: u64 = 30 * 24 * 3600;
#[derive(Debug, Clone, Deserialize)]
pub struct TokenRequest {
pub grant_type: String,
#[serde(default)]
pub client_id: String,
#[serde(default)]
pub client_secret: String,
pub code: Option<String>,
pub redirect_uri: Option<String>,
pub code_verifier: Option<String>,
pub refresh_token: Option<String>,
pub scope: Option<String>,
pub username: Option<String>,
pub password: Option<String>,
}
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct TokenResponse {
pub access_token: String,
pub token_type: String,
pub expires_in: u64,
#[serde(skip_serializing_if = "Option::is_none")]
pub refresh_token: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub scope: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TokenRecord {
pub token: String,
pub client_id: String,
pub user_id: Option<i64>,
pub scopes: Vec<String>,
pub token_type: String,
pub expires_at: DateTime<Utc>,
pub issued_at: DateTime<Utc>,
pub jti: Option<String>,
pub username: Option<String>,
}
pub(crate) fn parse_basic_auth(header: &str) -> Option<(String, String)> {
let encoded = header.strip_prefix("Basic ")?;
let decoded = STANDARD.decode(encoded.trim()).ok()?;
let decoded_str = String::from_utf8(decoded).ok()?;
let (client_id, client_secret) = decoded_str.split_once(':')?;
Some((client_id.to_string(), client_secret.to_string()))
}
#[async_trait]
pub trait PasswordVerifier: Send + Sync {
async fn verify(&self, username: &str, password: &str) -> GarrisonResult<Option<i64>>;
}
pub struct PasswordRateLimiter {
limiter: GarrisonDaoDistributedLimiter,
dao: Arc<InMemoryDao>,
max_attempts: u32,
window_seconds: u64,
}
impl PasswordRateLimiter {
pub fn new(max_attempts: u32, window_seconds: u64) -> Self {
let dao = Arc::new(InMemoryDao::new());
let limiter = GarrisonDaoDistributedLimiter::new(dao.clone());
Self {
limiter,
dao,
max_attempts: max_attempts.max(1),
window_seconds,
}
}
pub async fn check(&self, username: &str) -> bool {
let key = format!("rate_limit:pw:{}", username);
match self.limiter.get_count(&key).await {
Ok(count) => count < self.max_attempts as u64,
Err(e) => {
tracing::warn!(
"PasswordRateLimiter::check get_count failed (fail-closed, rejecting): {}",
e
);
false
},
}
}
pub async fn record_failure(&self, username: &str) {
let key = format!("rate_limit:pw:{}", username);
let ttl = StdDuration::from_secs(self.window_seconds);
if let Err(e) = self.limiter.incr_with_ttl(&key, 1, ttl).await {
tracing::warn!(
"PasswordRateLimiter::record_failure incr_with_ttl failed: {}",
e
);
}
}
pub async fn reset(&self, username: &str) {
let key = format!("rate_limit:pw:{}", username);
if let Err(e) = self.limiter.reset(&key).await {
tracing::warn!("PasswordRateLimiter::reset failed: {}", e);
}
}
pub async fn entry_count(&self) -> usize {
self.dao
.keys("rate_limit:pw:*")
.await
.map(|v| v.len())
.unwrap_or(0)
}
pub fn window_seconds(&self) -> u64 {
self.window_seconds
}
}
pub struct TokenRateLimiter {
limiter: GarrisonDaoDistributedLimiter,
client_max: u64,
client_window_secs: u64,
username_max: u64,
username_window_secs: u64,
}
impl TokenRateLimiter {
pub fn new() -> Self {
Self::with_limits(10, 1, 5, 60)
}
pub fn with_limits(
client_max: u64,
client_window_secs: u64,
username_max: u64,
username_window_secs: u64,
) -> Self {
let dao = Arc::new(InMemoryDao::new());
let limiter = GarrisonDaoDistributedLimiter::new(dao);
Self {
limiter,
client_max: client_max.max(1),
client_window_secs: client_window_secs.max(1),
username_max: username_max.max(1),
username_window_secs: username_window_secs.max(1),
}
}
pub async fn check_client(&self, client_id: &str) -> bool {
let key = format!("rate_limit:token:client:{}", client_id);
let ttl = StdDuration::from_secs(self.client_window_secs);
match self
.limiter
.atomic_check_and_incr(&key, self.client_max, ttl)
.await
{
Ok(allowed) => allowed,
Err(e) => {
tracing::warn!("TokenRateLimiter::check_client failed: {}", e);
true
},
}
}
pub async fn check_username(&self, username: &str) -> bool {
let key = format!("rate_limit:token:user:{}", username);
let ttl = StdDuration::from_secs(self.username_window_secs);
match self
.limiter
.atomic_check_and_incr(&key, self.username_max, ttl)
.await
{
Ok(allowed) => allowed,
Err(e) => {
tracing::warn!(
"TokenRateLimiter::check_username failed (fail-closed, rejecting): {}",
e
);
false
},
}
}
pub fn window_upper_bound_secs(&self) -> u64 {
self.client_window_secs.max(self.username_window_secs)
}
}
impl Default for TokenRateLimiter {
fn default() -> Self {
Self::new()
}
}
pub struct TokenHandler {
store: Arc<dyn OAuth2ClientStore>,
dao: Arc<dyn GarrisonDao>,
authorize_handler: Arc<AuthorizeHandler>,
password_verifier: Option<Arc<dyn PasswordVerifier>>,
password_rate_limiter: Arc<PasswordRateLimiter>,
token_rate_limiter: Arc<TokenRateLimiter>,
#[cfg(feature = "db-sqlite")]
refresh_rotation: Option<Arc<RefreshTokenRotation>>,
}
impl TokenHandler {
pub fn new(
store: Arc<dyn OAuth2ClientStore>,
dao: Arc<dyn GarrisonDao>,
authorize_handler: Arc<AuthorizeHandler>,
password_rate_limiter: Arc<PasswordRateLimiter>,
token_rate_limiter: Arc<TokenRateLimiter>,
) -> Self {
Self {
store,
dao,
authorize_handler,
password_verifier: None,
password_rate_limiter,
token_rate_limiter,
#[cfg(feature = "db-sqlite")]
refresh_rotation: None,
}
}
pub fn with_password_verifier(mut self, verifier: Arc<dyn PasswordVerifier>) -> Self {
self.password_verifier = Some(verifier);
self
}
#[cfg(feature = "db-sqlite")]
pub fn with_refresh_rotation(mut self, rotation: Arc<RefreshTokenRotation>) -> Self {
self.refresh_rotation = Some(rotation);
self
}
#[cfg(feature = "db-sqlite")]
pub fn has_refresh_rotation(&self) -> bool {
self.refresh_rotation.is_some()
}
pub fn rate_limit_window_upper_bound_secs(&self) -> u64 {
self.token_rate_limiter
.window_upper_bound_secs()
.max(self.password_rate_limiter.window_seconds())
}
pub async fn handle(&self, req: &TokenRequest) -> GarrisonResult<TokenResponse> {
self.handle_with_authorization(req, None).await
}
pub async fn handle_with_authorization(
&self,
req: &TokenRequest,
authorization: Option<&str>,
) -> GarrisonResult<TokenResponse> {
let client_id = authorization
.and_then(parse_basic_auth)
.map(|(id, _)| id)
.unwrap_or_else(|| req.client_id.clone());
if !client_id.is_empty() && !self.token_rate_limiter.check_client(&client_id).await {
return Err(GarrisonError::OAuth2(loc!(
"oauth2-rate-limited-client",
"rate_limited: client requests too frequent, please retry later"
)));
}
let client = self
.authenticate_client_with_authorization(
authorization,
&req.client_id,
&req.client_secret,
)
.await?;
let grant_type: GrantType = req.grant_type.parse()?;
match grant_type {
GrantType::AuthorizationCode => self.handle_authorization_code(&client, req).await,
GrantType::RefreshToken => self.handle_refresh_token(&client, req).await,
GrantType::ClientCredentials => self.handle_client_credentials(&client, req).await,
GrantType::Password => self.handle_password(&client, req).await,
}
}
async fn authenticate_client_with_authorization(
&self,
authorization: Option<&str>,
body_client_id: &str,
body_client_secret: &str,
) -> GarrisonResult<OAuth2Client> {
let (client_id, client_secret) = match authorization.and_then(parse_basic_auth) {
Some((id, secret)) => (id, secret),
None => (body_client_id.to_string(), body_client_secret.to_string()),
};
if client_id.is_empty() {
return Err(GarrisonError::OAuth2(loc!(
"oauth2-client-id-missing",
"invalid_client: client_id missing (provided neither in Authorization header nor body)"
)));
}
let client = self.store.get(&client_id).await?.ok_or_else(|| {
GarrisonError::OAuth2(loc!(
"oauth2-client-not-exist",
format!("invalid_client: client {client_id} does not exist"),
("client_id", client_id.as_str())
))
})?;
if !client.verify_secret(&client_secret)? {
return Err(GarrisonError::OAuth2(loc!(
"oauth2-client-secret-mismatch",
"invalid_client: client_secret mismatch"
)));
}
Ok(client)
}
async fn handle_authorization_code(
&self,
client: &OAuth2Client,
req: &TokenRequest,
) -> GarrisonResult<TokenResponse> {
if !client.allows_grant_type(&GrantType::AuthorizationCode) {
return Err(GarrisonError::OAuth2(loc!(
"oauth2-grant-not-allowed-auth-code",
"unauthorized_client: authorization_code grant type not allowed for this client"
)));
}
let code = req.code.as_ref().ok_or_else(|| {
GarrisonError::OAuth2(loc!(
"oauth2-code-param-missing",
"invalid_request: missing code parameter"
))
})?;
let code_verifier = req.code_verifier.as_ref().ok_or_else(|| {
GarrisonError::OAuth2(loc!(
"oauth2-code-verifier-missing",
"invalid_request: missing code_verifier parameter (PKCE enforced)"
))
})?;
let redirect_uri = req.redirect_uri.as_ref().ok_or_else(|| {
GarrisonError::OAuth2(loc!(
"oauth2-redirect-uri-param-missing",
"invalid_request: missing redirect_uri parameter"
))
})?;
let auth_code = self
.authorize_handler
.consume_code(code)
.await?
.ok_or_else(|| {
GarrisonError::OAuth2(loc!(
"oauth2-code-invalid-or-expired",
"invalid_grant: authorization code invalid or expired"
))
})?;
if auth_code.client_id != client.client_id {
return Err(GarrisonError::OAuth2(loc!(
"oauth2-code-client-mismatch",
"invalid_grant: authorization code does not match client_id"
)));
}
if auth_code.redirect_uri != *redirect_uri {
return Err(GarrisonError::OAuth2(loc!(
"oauth2-redirect-uri-mismatch",
"invalid_grant: redirect_uri differs from the one used at authorization time"
)));
}
if !crate::oauth2_server::authorize::verify_pkce(code_verifier, &auth_code.code_challenge)?
{
return Err(GarrisonError::OAuth2(loc!(
"oauth2-pkce-verify-failed",
"invalid_grant: PKCE code_verifier verification failed"
)));
}
let scopes = auth_code.scopes.clone();
client.validate_scopes(&scopes)?;
let user_id = auth_code.user_id;
self.issue_tokens(
&client.client_id,
Some(user_id),
&scopes,
true, None, )
.await
}
async fn handle_refresh_token(
&self,
client: &OAuth2Client,
req: &TokenRequest,
) -> GarrisonResult<TokenResponse> {
if !client.allows_grant_type(&GrantType::RefreshToken) {
return Err(GarrisonError::OAuth2(loc!(
"oauth2-grant-not-allowed-refresh-token",
"unauthorized_client: refresh_token grant type not allowed for this client"
)));
}
let refresh_token = req.refresh_token.as_ref().ok_or_else(|| {
GarrisonError::OAuth2(loc!(
"oauth2-refresh-token-param-missing",
"invalid_request: missing refresh_token parameter"
))
})?;
#[cfg(feature = "db-sqlite")]
{
if let Some(rotation) = &self.refresh_rotation {
let (new_access, new_refresh) = match rotation.rotate(refresh_token).await {
Ok(t) => t,
Err(GarrisonError::InvalidToken(_)) => {
return Err(GarrisonError::OAuth2(loc!(
"oauth2-refresh-token-invalid-or-expired",
"invalid_grant: refresh_token invalid or expired"
)));
},
Err(e) => return Err(e),
};
let record = rotation.validate(&new_refresh).await?.ok_or_else(|| {
GarrisonError::Internal(loc!(
"oauth2-rotated-token-validate-failed",
"validation failed for rotated refresh_token"
))
})?;
let record_client_id = record.client_id.as_deref().unwrap_or("");
if record_client_id != client.client_id {
return Err(GarrisonError::OAuth2(loc!(
"oauth2-refresh-token-client-mismatch",
"invalid_grant: refresh_token does not match client_id"
)));
}
let scopes: Vec<String> = record
.scopes
.as_ref()
.map(|s| s.split_whitespace().map(|x| x.to_string()).collect())
.unwrap_or_default();
let scope_str = if scopes.is_empty() {
None
} else {
Some(scopes.join(" "))
};
return Ok(TokenResponse {
access_token: new_access,
token_type: TokenType::Bearer.to_string(),
expires_in: ACCESS_TOKEN_TTL_SECONDS,
refresh_token: Some(new_refresh),
scope: scope_str,
});
}
}
tracing::warn!(
"{}",
crate::i18n::translate_detail("logs-oauth2-refresh-rotation-not-configured", &[])
);
let key = oauth2_refresh_token_key(refresh_token);
let json = self.dao.get_and_delete(&key).await?.ok_or_else(|| {
GarrisonError::OAuth2(loc!(
"oauth2-refresh-token-invalid-or-expired",
"invalid_grant: refresh_token invalid or expired"
))
})?;
let record: TokenRecord = serde_json::from_str(&json).map_err(|e| {
GarrisonError::Internal(loc!(
"oauth2-server-token-deserialize",
format!("TokenRecord deserialize failed: {e}"),
("arg0", &e.to_string())
))
})?;
if record.client_id != client.client_id {
return Err(GarrisonError::OAuth2(loc!(
"oauth2-refresh-token-client-mismatch",
"invalid_grant: refresh_token does not match client_id"
)));
}
let user_id = record.user_id;
let scopes = record.scopes.clone();
let username = record.username.clone();
let resp = match self
.issue_tokens(
&client.client_id,
user_id,
&scopes,
true, username.as_deref(),
)
.await
{
Ok(resp) => resp,
Err(e) => {
let remaining = (record.expires_at - Utc::now()).num_seconds();
if remaining > 0 {
if let Err(set_err) = self.dao.set(&key, &json, remaining as u64).await {
tracing::warn!(
error = %set_err,
"handle_refresh_token: failed to restore refresh token after issue failure"
);
}
}
return Err(e);
},
};
Ok(resp)
}
async fn handle_client_credentials(
&self,
client: &OAuth2Client,
req: &TokenRequest,
) -> GarrisonResult<TokenResponse> {
if !client.allows_grant_type(&GrantType::ClientCredentials) {
return Err(GarrisonError::OAuth2(loc!(
"oauth2-grant-not-allowed-client-credentials",
"unauthorized_client: client_credentials grant type not allowed for this client"
)));
}
let scopes: Vec<String> = req
.scope
.as_ref()
.map(|s| s.split_whitespace().map(|x| x.to_string()).collect())
.unwrap_or_default();
client.validate_scopes(&scopes)?;
self.issue_tokens(&client.client_id, None, &scopes, false, None)
.await
}
async fn handle_password(
&self,
client: &OAuth2Client,
req: &TokenRequest,
) -> GarrisonResult<TokenResponse> {
if !client.allows_grant_type(&GrantType::Password) {
return Err(GarrisonError::OAuth2(loc!(
"oauth2-grant-not-allowed-password",
"unauthorized_client: password grant type not allowed for this client"
)));
}
let verifier = self.password_verifier.as_ref().ok_or_else(|| {
GarrisonError::OAuth2(loc!(
"oauth2-password-verifier-not-configured",
"unauthorized_grant_type: PasswordVerifier not configured for password grant type"
))
})?;
let username = req.username.as_ref().ok_or_else(|| {
GarrisonError::OAuth2(loc!(
"oauth2-username-param-missing",
"invalid_request: missing username parameter"
))
})?;
let password = req.password.as_ref().ok_or_else(|| {
GarrisonError::OAuth2(loc!(
"oauth2-password-param-missing",
"invalid_request: missing password parameter"
))
})?;
if !self.token_rate_limiter.check_username(username).await {
return Err(GarrisonError::OAuth2(loc!(
"oauth2-rate-limited-user",
"rate_limited: user requests too frequent, please retry later"
)));
}
if !self.password_rate_limiter.check(username).await {
return Err(GarrisonError::OAuth2(loc!(
"oauth2-account-temp-locked",
"rate_limited: account temporarily locked, please retry later"
)));
}
let user_id = match verifier.verify(username, password).await? {
Some(uid) => uid,
None => {
self.password_rate_limiter.record_failure(username).await;
return Err(GarrisonError::OAuth2(loc!(
"oauth2-invalid-credentials",
"invalid_grant: invalid username or password"
)));
},
};
self.password_rate_limiter.reset(username).await;
let scopes: Vec<String> = req
.scope
.as_ref()
.map(|s| s.split_whitespace().map(|x| x.to_string()).collect())
.unwrap_or_default();
client.validate_scopes(&scopes)?;
self.issue_tokens(
&client.client_id,
Some(user_id),
&scopes,
true,
Some(username.as_str()),
)
.await
}
async fn issue_tokens(
&self,
client_id: &str,
user_id: Option<i64>,
scopes: &[String],
with_refresh: bool,
username: Option<&str>,
) -> GarrisonResult<TokenResponse> {
let access_token = generate_token();
let now = Utc::now();
let at_expires_at = now + Duration::seconds(ACCESS_TOKEN_TTL_SECONDS as i64);
let at_jti = uuid::Uuid::new_v4().to_string();
let at_record = TokenRecord {
token: access_token.clone(),
client_id: client_id.to_string(),
user_id,
scopes: scopes.to_vec(),
token_type: TokenType::Access.to_string(),
expires_at: at_expires_at,
issued_at: now,
jti: Some(at_jti),
username: username.map(|s| s.to_string()),
};
let at_key = DaoKeyPrefix::OAuth2AccessToken.build_key(&access_token);
let at_json = serde_json::to_string(&at_record).map_err(|e| {
GarrisonError::Internal(loc!(
"oauth2-server-token-serialize",
format!("TokenRecord serialize failed: {e}"),
("arg0", &e.to_string())
))
})?;
self.dao
.set(&at_key, &at_json, ACCESS_TOKEN_TTL_SECONDS)
.await?;
let refresh_token = if with_refresh {
#[cfg(feature = "db-sqlite")]
{
if let Some(rotation) = &self.refresh_rotation {
let login_id = user_id.unwrap_or(0);
let rt = rotation
.issue(
client_id,
user_id,
scopes,
username,
login_id,
0, REFRESH_TOKEN_TTL_SECONDS as i64,
)
.await?;
Some(rt)
} else {
self.issue_refresh_via_dao(client_id, user_id, scopes, username, now)
.await?
}
}
#[cfg(not(feature = "db-sqlite"))]
{
self.issue_refresh_via_dao(client_id, user_id, scopes, username, now)
.await?
}
} else {
None
};
let scope_str = if scopes.is_empty() {
None
} else {
Some(scopes.join(" "))
};
Ok(TokenResponse {
access_token,
token_type: TokenType::Bearer.to_string(),
expires_in: ACCESS_TOKEN_TTL_SECONDS,
refresh_token,
scope: scope_str,
})
}
async fn issue_refresh_via_dao(
&self,
client_id: &str,
user_id: Option<i64>,
scopes: &[String],
username: Option<&str>,
now: DateTime<Utc>,
) -> GarrisonResult<Option<String>> {
let rt = generate_token();
let rt_expires_at = now + Duration::seconds(REFRESH_TOKEN_TTL_SECONDS as i64);
let rt_jti = uuid::Uuid::new_v4().to_string();
let rt_record = TokenRecord {
token: rt.clone(),
client_id: client_id.to_string(),
user_id,
scopes: scopes.to_vec(),
token_type: TokenType::Refresh.to_string(),
expires_at: rt_expires_at,
issued_at: now,
jti: Some(rt_jti),
username: username.map(|s| s.to_string()),
};
let rt_key = oauth2_refresh_token_key(&rt);
let rt_json = serde_json::to_string(&rt_record).map_err(|e| {
GarrisonError::Internal(loc!(
"oauth2-server-token-serialize",
format!("TokenRecord serialize failed: {e}"),
("arg0", &e.to_string())
))
})?;
self.dao
.set(&rt_key, &rt_json, REFRESH_TOKEN_TTL_SECONDS)
.await?;
Ok(Some(rt))
}
pub async fn get_access_token_record(
&self,
token: &str,
) -> GarrisonResult<Option<TokenRecord>> {
let key = DaoKeyPrefix::OAuth2AccessToken.build_key(token);
let json = self.dao.get(&key).await?;
match json {
Some(json) => {
let record: TokenRecord = serde_json::from_str(&json).map_err(|e| {
GarrisonError::Internal(loc!(
"oauth2-server-token-deserialize",
format!("TokenRecord deserialize failed: {e}"),
("arg0", &e.to_string())
))
})?;
Ok(Some(record))
},
None => Ok(None),
}
}
pub async fn get_refresh_token_record(
&self,
token: &str,
) -> GarrisonResult<Option<TokenRecord>> {
#[cfg(feature = "db-sqlite")]
{
if let Some(rotation) = &self.refresh_rotation {
let record = match rotation.validate(token).await? {
Some(r) => r,
None => return Ok(None),
};
let expires_at =
DateTime::<Utc>::from_timestamp(record.expires_at, 0).ok_or_else(|| {
GarrisonError::Internal("refresh-token-expires-at-invalid".into())
})?;
let issued_at =
DateTime::<Utc>::from_timestamp(record.created_at, 0).unwrap_or(expires_at);
return Ok(Some(TokenRecord {
token: token.to_string(),
client_id: record.client_id.unwrap_or_default(),
user_id: record.user_id.or(Some(record.login_id)),
scopes: record
.scopes
.as_ref()
.map(|s| s.split_whitespace().map(|x| x.to_string()).collect())
.unwrap_or_default(),
token_type: TokenType::Refresh.to_string(),
expires_at,
issued_at,
jti: Some(record.token_hash),
username: record.username,
}));
}
}
let key = oauth2_refresh_token_key(token);
let json = self.dao.get(&key).await?;
match json {
Some(json) => {
let record: TokenRecord = serde_json::from_str(&json).map_err(|e| {
GarrisonError::Internal(loc!(
"oauth2-server-token-deserialize",
format!("TokenRecord deserialize failed: {e}"),
("arg0", &e.to_string())
))
})?;
Ok(Some(record))
},
None => Ok(None),
}
}
pub async fn revoke_token(&self, token: &str) -> GarrisonResult<()> {
let at_key = DaoKeyPrefix::OAuth2AccessToken.build_key(token);
self.dao.delete(&at_key).await?;
let rt_key = oauth2_refresh_token_key(token);
self.dao.delete(&rt_key).await?;
#[cfg(feature = "db-sqlite")]
if let Some(rotation) = &self.refresh_rotation {
use sha2::{Digest, Sha256};
let mut hasher = Sha256::new();
hasher.update(token.as_bytes());
let token_hash: String = hasher
.finalize()
.iter()
.map(|b| format!("{:02x}", b))
.collect();
rotation.revoke_chain(&token_hash).await?;
}
Ok(())
}
}
fn generate_token() -> String {
let mut bytes = [0u8; 32];
getrandom::fill(&mut bytes).expect("OS CSPRNG 不可用");
URL_SAFE_NO_PAD.encode(bytes)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::dao::InMemoryDao;
use crate::oauth2_server::authorize::AuthorizeHandler;
use crate::oauth2_server::client::DaoOAuth2ClientStore;
struct TestPasswordVerifier;
#[async_trait]
impl PasswordVerifier for TestPasswordVerifier {
async fn verify(&self, username: &str, password: &str) -> GarrisonResult<Option<i64>> {
if username == "alice" && password == "wonderland" {
Ok(Some(5001))
} else {
Ok(None)
}
}
}
fn make_handler() -> (TokenHandler, Arc<InMemoryDao>) {
make_handler_with_limiters(
Arc::new(PasswordRateLimiter::new(1000, 300)),
Arc::new(TokenRateLimiter::with_limits(100_000, 60, 100_000, 60)),
)
}
fn make_handler_with_limiters(
password_rate_limiter: Arc<PasswordRateLimiter>,
token_rate_limiter: Arc<TokenRateLimiter>,
) -> (TokenHandler, Arc<InMemoryDao>) {
let dao = Arc::new(InMemoryDao::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 handler = TokenHandler::new(
store,
dao.clone(),
authorize_handler,
password_rate_limiter,
token_rate_limiter,
)
.with_password_verifier(Arc::new(TestPasswordVerifier));
(handler, dao)
}
fn make_full_client(id: &str) -> OAuth2Client {
OAuth2Client::new(
id,
"secret-123",
vec!["https://app.example.com/cb".into()],
vec![
GrantType::AuthorizationCode,
GrantType::RefreshToken,
GrantType::ClientCredentials,
GrantType::Password,
],
vec!["read".into(), "write".into()],
)
.unwrap()
}
async fn get_auth_code(handler: &TokenHandler, client_id: &str, verifier: &str) -> String {
let challenge = crate::oauth2_server::authorize::generate_code_challenge(verifier);
let req = crate::oauth2_server::authorize::AuthorizeRequest {
response_type: "code".into(),
client_id: client_id.into(),
redirect_uri: "https://app.example.com/cb".into(),
scope: Some("read".into()),
state: Some("xyz".into()),
code_challenge: challenge,
code_challenge_method: "S256".into(),
prompt: None,
};
let resp = handler
.authorize_handler
.authorize(&req, Some(1001))
.await
.unwrap();
match resp {
crate::oauth2_server::authorize::AuthorizeResponse::Redirect { location } => location
.split("code=")
.nth(1)
.unwrap()
.split('&')
.next()
.unwrap()
.to_string(),
_ => panic!("期望 Redirect"),
}
}
#[tokio::test]
async fn handle_invalid_client_id() {
let (handler, _) = make_handler();
let req = TokenRequest {
grant_type: "client_credentials".into(),
client_id: "no-such".into(),
client_secret: "secret".into(),
code: None,
redirect_uri: None,
code_verifier: None,
refresh_token: None,
scope: None,
username: None,
password: None,
};
let err = handler.handle(&req).await.unwrap_err();
assert!(err.to_string().contains("invalid_client"));
}
#[tokio::test]
async fn handle_invalid_client_secret() {
let (handler, _) = make_handler();
handler
.store
.create(make_full_client("c-secret"))
.await
.unwrap();
let req = TokenRequest {
grant_type: "client_credentials".into(),
client_id: "c-secret".into(),
client_secret: "wrong".into(),
code: None,
redirect_uri: None,
code_verifier: None,
refresh_token: None,
scope: None,
username: None,
password: None,
};
let err = handler.handle(&req).await.unwrap_err();
assert!(err.to_string().contains("invalid_client"));
}
#[test]
fn parse_basic_auth_decodes_valid_header() {
let header = "Basic Y2lkOnNlY3JldA==";
let result = parse_basic_auth(header);
assert_eq!(result, Some(("cid".to_string(), "secret".to_string())));
}
#[test]
fn parse_basic_auth_rejects_non_basic() {
assert!(parse_basic_auth("Bearer token123").is_none());
assert!(parse_basic_auth("").is_none());
}
#[test]
fn parse_basic_auth_rejects_invalid_base64() {
assert!(parse_basic_auth("Basic !!!not-base64!!!").is_none());
}
#[test]
fn parse_basic_auth_rejects_no_colon() {
assert!(parse_basic_auth("Basic bm9zZXBhcmF0b3I=").is_none());
}
#[test]
fn parse_basic_auth_handles_empty_client_id() {
let result = parse_basic_auth("Basic OnNlY3JldA==");
assert_eq!(result, Some(("".to_string(), "secret".to_string())));
}
#[test]
fn parse_basic_auth_handles_empty_client_secret() {
let result = parse_basic_auth("Basic Y2lkOg==");
assert_eq!(result, Some(("cid".to_string(), "".to_string())));
}
#[test]
fn parse_basic_auth_handles_colon_in_secret() {
let result = parse_basic_auth("Basic Y2lkOnNlYzpyZXQ=");
assert_eq!(result, Some(("cid".to_string(), "sec:ret".to_string())));
}
#[test]
fn parse_basic_auth_handles_special_chars() {
use base64::engine::general_purpose::STANDARD;
use base64::Engine;
let encoded = STANDARD.encode("user@domain:p@ss!word");
let header = format!("Basic {}", encoded);
let result = parse_basic_auth(&header);
assert_eq!(
result,
Some(("user@domain".to_string(), "p@ss!word".to_string()))
);
}
#[test]
fn parse_basic_auth_handles_basic_prefix_only() {
assert!(parse_basic_auth("Basic ").is_none());
}
#[test]
fn parse_basic_auth_case_sensitive_prefix() {
use base64::engine::general_purpose::STANDARD;
use base64::Engine;
let encoded = STANDARD.encode("cid:secret");
assert!(parse_basic_auth(&format!("basic {}", encoded)).is_none());
assert!(parse_basic_auth(&format!("BASIC {}", encoded)).is_none());
}
#[test]
fn parse_basic_auth_rejects_bearer_prefix() {
assert!(parse_basic_auth("Bearer Y2lkOnNlY3JldA==").is_none());
}
#[tokio::test]
async fn handle_with_authorization_uses_basic_auth() {
let (handler, _) = make_handler();
handler
.store
.create(make_full_client("basic-auth-cid"))
.await
.unwrap();
let credentials = STANDARD.encode("basic-auth-cid:secret-123");
let auth_header = format!("Basic {}", credentials);
let req = TokenRequest {
grant_type: "client_credentials".into(),
client_id: "".into(), client_secret: "".into(),
code: None,
redirect_uri: None,
code_verifier: None,
refresh_token: None,
scope: None,
username: None,
password: None,
};
let resp = handler
.handle_with_authorization(&req, Some(&auth_header))
.await
.expect("Basic Auth 认证应成功");
assert_eq!(resp.token_type, "Bearer");
assert_eq!(resp.expires_in, 3600);
}
#[tokio::test]
async fn handle_with_authorization_basic_auth_overrides_body() {
let (handler, _) = make_handler();
handler
.store
.create(make_full_client("override-cid"))
.await
.unwrap();
let credentials = STANDARD.encode("override-cid:secret-123");
let auth_header = format!("Basic {}", credentials);
let req = TokenRequest {
grant_type: "client_credentials".into(),
client_id: "override-cid".into(),
client_secret: "WRONG-SECRET".into(), code: None,
redirect_uri: None,
code_verifier: None,
refresh_token: None,
scope: None,
username: None,
password: None,
};
let resp = handler
.handle_with_authorization(&req, Some(&auth_header))
.await
.expect("Basic Auth 应优先,body 错误凭证被忽略");
assert_eq!(resp.token_type, "Bearer");
}
#[tokio::test]
async fn handle_with_authorization_falls_back_to_body() {
let (handler, _) = make_handler();
handler
.store
.create(make_full_client("fallback-cid"))
.await
.unwrap();
let req = TokenRequest {
grant_type: "client_credentials".into(),
client_id: "fallback-cid".into(),
client_secret: "secret-123".into(),
code: None,
redirect_uri: None,
code_verifier: None,
refresh_token: None,
scope: None,
username: None,
password: None,
};
let resp = handler
.handle_with_authorization(&req, None)
.await
.expect("body 参数认证应成功");
assert_eq!(resp.token_type, "Bearer");
}
#[tokio::test]
async fn handle_with_authorization_basic_auth_wrong_secret() {
let (handler, _) = make_handler();
handler
.store
.create(make_full_client("wrong-secret-cid"))
.await
.unwrap();
let credentials = STANDARD.encode("wrong-secret-cid:WRONG");
let auth_header = format!("Basic {}", credentials);
let req = TokenRequest {
grant_type: "client_credentials".into(),
client_id: "".into(),
client_secret: "".into(),
code: None,
redirect_uri: None,
code_verifier: None,
refresh_token: None,
scope: None,
username: None,
password: None,
};
let err = handler
.handle_with_authorization(&req, Some(&auth_header))
.await
.unwrap_err();
assert!(err.to_string().contains("invalid_client"));
}
#[tokio::test]
async fn handle_with_authorization_no_credentials_returns_error() {
let (handler, _) = make_handler();
let req = TokenRequest {
grant_type: "client_credentials".into(),
client_id: "".into(),
client_secret: "".into(),
code: None,
redirect_uri: None,
code_verifier: None,
refresh_token: None,
scope: None,
username: None,
password: None,
};
let err = handler
.handle_with_authorization(&req, None)
.await
.unwrap_err();
assert!(
err.to_string().contains("invalid_client"),
"无凭证应返回 invalid_client,实际: {}",
err
);
}
#[tokio::test]
async fn handle_unsupported_grant_type() {
let (handler, _) = make_handler();
handler
.store
.create(make_full_client("c-gt"))
.await
.unwrap();
let req = TokenRequest {
grant_type: "implicit".into(),
client_id: "c-gt".into(),
client_secret: "secret-123".into(),
code: None,
redirect_uri: None,
code_verifier: None,
refresh_token: None,
scope: None,
username: None,
password: None,
};
let err = handler.handle(&req).await.unwrap_err();
assert!(err.to_string().contains("unsupported_grant_type"));
}
#[tokio::test]
async fn handle_authorization_code_success() {
let (handler, _) = make_handler();
handler
.store
.create(make_full_client("ac-001"))
.await
.unwrap();
let verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
let code = get_auth_code(&handler, "ac-001", verifier).await;
let req = TokenRequest {
grant_type: "authorization_code".into(),
client_id: "ac-001".into(),
client_secret: "secret-123".into(),
code: Some(code),
redirect_uri: Some("https://app.example.com/cb".into()),
code_verifier: Some(verifier.into()),
refresh_token: None,
scope: None,
username: None,
password: None,
};
let resp = handler.handle(&req).await.expect("签发 token");
assert_eq!(resp.token_type, "Bearer");
assert_eq!(resp.expires_in, 3600);
assert!(!resp.access_token.is_empty());
assert!(resp.refresh_token.is_some());
}
#[tokio::test]
async fn handle_authorization_code_pkce_mismatch() {
let (handler, _) = make_handler();
handler
.store
.create(make_full_client("ac-002"))
.await
.unwrap();
let verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
let code = get_auth_code(&handler, "ac-002", verifier).await;
let req = TokenRequest {
grant_type: "authorization_code".into(),
client_id: "ac-002".into(),
client_secret: "secret-123".into(),
code: Some(code),
redirect_uri: Some("https://app.example.com/cb".into()),
code_verifier: Some("wrong-verifier-wrong-verifier-wrong-verifier-wrong".into()),
refresh_token: None,
scope: None,
username: None,
password: None,
};
let err = handler.handle(&req).await.unwrap_err();
assert!(err.to_string().contains("PKCE"));
}
#[tokio::test]
async fn handle_authorization_code_already_used() {
let (handler, _) = make_handler();
handler
.store
.create(make_full_client("ac-003"))
.await
.unwrap();
let verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
let code = get_auth_code(&handler, "ac-003", verifier).await;
let req = TokenRequest {
grant_type: "authorization_code".into(),
client_id: "ac-003".into(),
client_secret: "secret-123".into(),
code: Some(code.clone()),
redirect_uri: Some("https://app.example.com/cb".into()),
code_verifier: Some(verifier.into()),
refresh_token: None,
scope: None,
username: None,
password: None,
};
handler.handle(&req).await.expect("首次签发");
let err = handler.handle(&req).await.unwrap_err();
assert!(err.to_string().contains("invalid_grant"));
}
#[tokio::test]
async fn handle_refresh_token_success() {
let (handler, _) = make_handler();
handler
.store
.create(make_full_client("rt-001"))
.await
.unwrap();
let verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
let code = get_auth_code(&handler, "rt-001", verifier).await;
let req = TokenRequest {
grant_type: "authorization_code".into(),
client_id: "rt-001".into(),
client_secret: "secret-123".into(),
code: Some(code),
redirect_uri: Some("https://app.example.com/cb".into()),
code_verifier: Some(verifier.into()),
refresh_token: None,
scope: None,
username: None,
password: None,
};
let first_resp = handler.handle(&req).await.unwrap();
let refresh_token = first_resp.refresh_token.clone().unwrap();
let refresh_req = TokenRequest {
grant_type: "refresh_token".into(),
client_id: "rt-001".into(),
client_secret: "secret-123".into(),
code: None,
redirect_uri: None,
code_verifier: None,
refresh_token: Some(refresh_token),
scope: None,
username: None,
password: None,
};
let resp = handler.handle(&refresh_req).await.expect("刷新 token");
assert_eq!(resp.token_type, "Bearer");
assert_eq!(resp.expires_in, 3600);
assert!(
resp.refresh_token.is_some(),
"VULN-0009: 刷新应轮换返回新 refresh_token"
);
assert_ne!(
resp.refresh_token.as_ref().unwrap(),
first_resp.refresh_token.as_ref().unwrap(),
"VULN-0009: 新 refresh_token 应与旧的不同(轮换)"
);
}
#[tokio::test]
async fn handle_refresh_token_invalid() {
let (handler, _) = make_handler();
handler
.store
.create(make_full_client("rt-002"))
.await
.unwrap();
let req = TokenRequest {
grant_type: "refresh_token".into(),
client_id: "rt-002".into(),
client_secret: "secret-123".into(),
code: None,
redirect_uri: None,
code_verifier: None,
refresh_token: Some("invalid-token".into()),
scope: None,
username: None,
password: None,
};
let err = handler.handle(&req).await.unwrap_err();
assert!(err.to_string().contains("invalid_grant"));
}
#[tokio::test]
async fn handle_refresh_token_rotation_deletes_old_token() {
let (handler, _) = make_handler();
handler
.store
.create(make_full_client("rt-rot-001"))
.await
.unwrap();
let verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
let code = get_auth_code(&handler, "rt-rot-001", verifier).await;
let issue_req = TokenRequest {
grant_type: "authorization_code".into(),
client_id: "rt-rot-001".into(),
client_secret: "secret-123".into(),
code: Some(code),
redirect_uri: Some("https://app.example.com/cb".into()),
code_verifier: Some(verifier.into()),
refresh_token: None,
scope: None,
username: None,
password: None,
};
let issue_resp = handler.handle(&issue_req).await.unwrap();
let old_token = issue_resp.refresh_token.unwrap();
let refresh_req = TokenRequest {
grant_type: "refresh_token".into(),
client_id: "rt-rot-001".into(),
client_secret: "secret-123".into(),
code: None,
redirect_uri: None,
code_verifier: None,
refresh_token: Some(old_token.clone()),
scope: None,
username: None,
password: None,
};
let refresh_resp = handler
.handle(&refresh_req)
.await
.expect("第一次刷新应成功");
let new_token = refresh_resp.refresh_token.unwrap();
assert_ne!(&new_token, &old_token, "新 refresh_token 应与旧的不同");
let err = handler.handle(&refresh_req).await.unwrap_err();
assert!(
err.to_string().contains("invalid_grant"),
"VULN-0009: 重用已删除的旧 refresh_token 应返回 invalid_grant,实际: {}",
err
);
}
#[tokio::test(flavor = "multi_thread")]
async fn handle_refresh_token_concurrent_only_one_wins() {
let (handler, _) = make_handler();
handler
.store
.create(make_full_client("rt-conc-001"))
.await
.unwrap();
let verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
let code = get_auth_code(&handler, "rt-conc-001", verifier).await;
let issue_req = TokenRequest {
grant_type: "authorization_code".into(),
client_id: "rt-conc-001".into(),
client_secret: "secret-123".into(),
code: Some(code),
redirect_uri: Some("https://app.example.com/cb".into()),
code_verifier: Some(verifier.into()),
refresh_token: None,
scope: None,
username: None,
password: None,
};
let issue_resp = handler.handle(&issue_req).await.unwrap();
let old_token = issue_resp.refresh_token.expect("应有 refresh_token");
let handler = Arc::new(handler);
let mut handles = Vec::new();
for _ in 0..16 {
let h = handler.clone();
let t = old_token.clone();
handles.push(tokio::spawn(async move {
let req = TokenRequest {
grant_type: "refresh_token".into(),
client_id: "rt-conc-001".into(),
client_secret: "secret-123".into(),
code: None,
redirect_uri: None,
code_verifier: None,
refresh_token: Some(t),
scope: None,
username: None,
password: None,
};
h.handle(&req).await
}));
}
let mut wins = 0usize;
for h in handles {
if h.await.unwrap().is_ok() {
wins += 1;
}
}
assert_eq!(
wins, 1,
"并发刷新同一 refresh_token 仅一个应成功(防双花),实际 {}",
wins
);
}
#[tokio::test]
async fn handle_client_credentials_success() {
let (handler, _) = make_handler();
handler
.store
.create(make_full_client("cc-001"))
.await
.unwrap();
let req = TokenRequest {
grant_type: "client_credentials".into(),
client_id: "cc-001".into(),
client_secret: "secret-123".into(),
code: None,
redirect_uri: None,
code_verifier: None,
refresh_token: None,
scope: Some("read".into()),
username: None,
password: None,
};
let resp = handler.handle(&req).await.expect("签发 token");
assert_eq!(resp.token_type, "Bearer");
assert_eq!(resp.expires_in, 3600);
assert!(
resp.refresh_token.is_none(),
"client_credentials 不应返回 refresh_token"
);
assert_eq!(resp.scope.as_deref(), Some("read"));
}
#[tokio::test]
async fn handle_client_credentials_grant_not_allowed() {
let (handler, _) = make_handler();
let client = OAuth2Client::new(
"cc-only-auth",
"secret-123",
vec!["https://app.example.com/cb".into()],
vec![GrantType::AuthorizationCode],
vec![],
)
.unwrap();
handler.store.create(client).await.unwrap();
let req = TokenRequest {
grant_type: "client_credentials".into(),
client_id: "cc-only-auth".into(),
client_secret: "secret-123".into(),
code: None,
redirect_uri: None,
code_verifier: None,
refresh_token: None,
scope: None,
username: None,
password: None,
};
let err = handler.handle(&req).await.unwrap_err();
assert!(err.to_string().contains("unauthorized_client"));
}
#[tokio::test]
async fn handle_password_success() {
let (handler, _) = make_handler();
handler
.store
.create(make_full_client("pw-001"))
.await
.unwrap();
let req = TokenRequest {
grant_type: "password".into(),
client_id: "pw-001".into(),
client_secret: "secret-123".into(),
code: None,
redirect_uri: None,
code_verifier: None,
refresh_token: None,
scope: Some("read".into()),
username: Some("alice".into()),
password: Some("wonderland".into()),
};
let resp = handler.handle(&req).await.expect("签发 token");
assert_eq!(resp.token_type, "Bearer");
assert!(resp.refresh_token.is_some());
assert_eq!(resp.scope.as_deref(), Some("read"));
}
#[tokio::test]
async fn handle_password_wrong_credentials() {
let (handler, _) = make_handler();
handler
.store
.create(make_full_client("pw-002"))
.await
.unwrap();
let req = TokenRequest {
grant_type: "password".into(),
client_id: "pw-002".into(),
client_secret: "secret-123".into(),
code: None,
redirect_uri: None,
code_verifier: None,
refresh_token: None,
scope: None,
username: Some("alice".into()),
password: Some("wrong-password".into()),
};
let err = handler.handle(&req).await.unwrap_err();
assert!(err.to_string().contains("invalid_grant"));
}
#[tokio::test]
async fn handle_password_rate_limited_after_max_attempts() {
let (handler, _) = make_handler_with_limiters(
Arc::new(PasswordRateLimiter::new(3, 300)),
Arc::new(TokenRateLimiter::with_limits(100_000, 60, 100_000, 60)),
);
handler
.store
.create(make_full_client("pw-rl-001"))
.await
.unwrap();
let wrong_req = TokenRequest {
grant_type: "password".into(),
client_id: "pw-rl-001".into(),
client_secret: "secret-123".into(),
code: None,
redirect_uri: None,
code_verifier: None,
refresh_token: None,
scope: None,
username: Some("alice".into()),
password: Some("wrong".into()),
};
for i in 0..3 {
let err = handler.handle(&wrong_req).await.unwrap_err();
assert!(
err.to_string().contains("invalid_grant"),
"第 {} 次失败应为 invalid_grant,实际: {}",
i + 1,
err
);
}
let err = handler.handle(&wrong_req).await.unwrap_err();
assert!(
err.to_string().contains("rate_limited"),
"第 4 次尝试应为 rate_limited,实际: {}",
err
);
}
#[tokio::test]
async fn handle_password_rate_limit_resets_on_success() {
let (handler, _) = make_handler_with_limiters(
Arc::new(PasswordRateLimiter::new(3, 300)),
Arc::new(TokenRateLimiter::with_limits(100_000, 60, 100_000, 60)),
);
handler
.store
.create(make_full_client("pw-rl-002"))
.await
.unwrap();
let wrong_req = TokenRequest {
grant_type: "password".into(),
client_id: "pw-rl-002".into(),
client_secret: "secret-123".into(),
code: None,
redirect_uri: None,
code_verifier: None,
refresh_token: None,
scope: None,
username: Some("alice".into()),
password: Some("wrong".into()),
};
let right_req = TokenRequest {
grant_type: "password".into(),
client_id: "pw-rl-002".into(),
client_secret: "secret-123".into(),
code: None,
redirect_uri: None,
code_verifier: None,
refresh_token: None,
scope: None,
username: Some("alice".into()),
password: Some("wonderland".into()),
};
for _ in 0..2 {
let _ = handler.handle(&wrong_req).await.unwrap_err();
}
let resp = handler.handle(&right_req).await.expect("成功登录");
assert_eq!(resp.token_type, "Bearer");
for i in 0..3 {
let err = handler.handle(&wrong_req).await.unwrap_err();
assert!(
err.to_string().contains("invalid_grant"),
"重置后第 {} 次失败应为 invalid_grant,实际: {}",
i + 1,
err
);
}
let err = handler.handle(&wrong_req).await.unwrap_err();
assert!(
err.to_string().contains("rate_limited"),
"重置后第 4 次尝试应为 rate_limited,实际: {}",
err
);
}
#[tokio::test]
async fn password_rate_limiter_record_failure_increments_count() {
let limiter = PasswordRateLimiter::new(5, 300);
limiter.record_failure("alice").await;
assert!(
limiter.check("alice").await,
"count=1 < max_attempts=5,应允许"
);
limiter.record_failure("alice").await;
limiter.record_failure("alice").await;
assert!(
limiter.check("alice").await,
"count=3 < max_attempts=5,应允许"
);
assert_eq!(limiter.entry_count().await, 1, "应仅 1 个 entry");
}
#[tokio::test]
async fn password_rate_limiter_check_returns_false_at_threshold() {
let limiter = PasswordRateLimiter::new(3, 300);
limiter.record_failure("bob").await;
limiter.record_failure("bob").await;
limiter.record_failure("bob").await;
assert!(
!limiter.check("bob").await,
"count=3 = max_attempts=3,应锁定(check 返回 false)"
);
}
#[tokio::test]
async fn password_rate_limiter_check_passes_for_new_user() {
let limiter = PasswordRateLimiter::new(3, 300);
assert!(
limiter.check("new-user").await,
"未失败的 username 应允许尝试(check 返回 true)"
);
assert_eq!(limiter.entry_count().await, 0, "无失败记录时 entry_count=0");
}
#[tokio::test]
async fn password_rate_limiter_reset_clears_counter() {
let limiter = PasswordRateLimiter::new(3, 300);
limiter.record_failure("carol").await;
limiter.record_failure("carol").await;
assert_eq!(limiter.entry_count().await, 1, "失败 2 次后应有 1 个 entry");
limiter.reset("carol").await;
assert_eq!(limiter.entry_count().await, 0, "reset 后应无 entry");
limiter.record_failure("carol").await;
assert!(
limiter.check("carol").await,
"reset 后重新计数,count=1 < max_attempts=3,应允许"
);
}
#[tokio::test]
async fn password_rate_limiter_users_are_independent() {
let limiter = PasswordRateLimiter::new(2, 300);
limiter.record_failure("alice").await;
limiter.record_failure("alice").await;
assert!(!limiter.check("alice").await, "alice 应被锁定");
assert!(limiter.check("bob").await, "bob 应允许(独立计数器)");
assert_eq!(limiter.entry_count().await, 1, "应仅 alice 1 个 entry");
}
#[tokio::test]
async fn password_rate_limiter_max_attempts_zero_clamps_to_one() {
let limiter = PasswordRateLimiter::new(0, 300);
limiter.record_failure("dave").await;
assert!(
!limiter.check("dave").await,
"max_attempts=0 被 clamp 到 1,首次失败后应锁定"
);
}
#[tokio::test]
async fn handle_client_credentials_scope_not_allowed() {
let (handler, _) = make_handler();
handler
.store
.create(make_full_client("cc-scope-001"))
.await
.unwrap();
let req = TokenRequest {
grant_type: "client_credentials".into(),
client_id: "cc-scope-001".into(),
client_secret: "secret-123".into(),
code: None,
redirect_uri: None,
code_verifier: None,
refresh_token: None,
scope: Some("admin".into()),
username: None,
password: None,
};
let err = handler.handle(&req).await.unwrap_err();
assert!(
err.to_string().contains(&crate::i18n::translate_detail(
"oauth2-server-client-invalid-scope",
&[("arg0", "admin")],
)),
"期望 invalid-scope 错误,实际: {}",
err
);
}
#[tokio::test]
async fn handle_client_credentials_partial_scope_not_allowed() {
let (handler, _) = make_handler();
handler
.store
.create(make_full_client("cc-scope-002"))
.await
.unwrap();
let req = TokenRequest {
grant_type: "client_credentials".into(),
client_id: "cc-scope-002".into(),
client_secret: "secret-123".into(),
code: None,
redirect_uri: None,
code_verifier: None,
refresh_token: None,
scope: Some("read admin".into()),
username: None,
password: None,
};
let err = handler.handle(&req).await.unwrap_err();
assert!(err.to_string().contains(&crate::i18n::translate_detail(
"oauth2-server-client-invalid-scope",
&[("arg0", "admin")],
)));
}
#[tokio::test]
async fn handle_password_scope_not_allowed() {
let (handler, _) = make_handler();
handler
.store
.create(make_full_client("pw-scope-001"))
.await
.unwrap();
let req = TokenRequest {
grant_type: "password".into(),
client_id: "pw-scope-001".into(),
client_secret: "secret-123".into(),
code: None,
redirect_uri: None,
code_verifier: None,
refresh_token: None,
scope: Some("admin".into()),
username: Some("alice".into()),
password: Some("wonderland".into()),
};
let err = handler.handle(&req).await.unwrap_err();
assert!(
err.to_string().contains(&crate::i18n::translate_detail(
"oauth2-server-client-invalid-scope",
&[("arg0", "admin")],
)),
"期望 invalid-scope 错误,实际: {}",
err
);
}
#[tokio::test]
async fn handle_client_credentials_empty_allowed_scopes_fail_closed() {
let (handler, _) = make_handler();
let client = OAuth2Client::new(
"cc-empty-scopes",
"secret-123",
vec!["https://app.example.com/cb".into()],
vec![GrantType::ClientCredentials],
vec![],
)
.unwrap();
handler.store.create(client).await.unwrap();
let req = TokenRequest {
grant_type: "client_credentials".into(),
client_id: "cc-empty-scopes".into(),
client_secret: "secret-123".into(),
code: None,
redirect_uri: None,
code_verifier: None,
refresh_token: None,
scope: Some("any-scope".into()),
username: None,
password: None,
};
let err = handler.handle(&req).await.unwrap_err();
assert!(
err.to_string().contains(&crate::i18n::translate_detail(
"oauth2-server-client-invalid-scope",
&[("arg0", "any-scope")],
)),
"空 allowed_scopes 应拒绝任意 scope(fail-closed),实际: {}",
err
);
}
#[tokio::test]
async fn handle_client_credentials_wildcard_scope_allows_any() {
let (handler, _) = make_handler();
let client = OAuth2Client::new(
"cc-wildcard-scopes",
"secret-123",
vec!["https://app.example.com/cb".into()],
vec![GrantType::ClientCredentials],
vec!["*".into()],
)
.unwrap();
handler.store.create(client).await.unwrap();
let req = TokenRequest {
grant_type: "client_credentials".into(),
client_id: "cc-wildcard-scopes".into(),
client_secret: "secret-123".into(),
code: None,
redirect_uri: None,
code_verifier: None,
refresh_token: None,
scope: Some("any-scope".into()),
username: None,
password: None,
};
let resp = handler
.handle(&req)
.await
.expect("通配 allowed_scopes 应允许任意 scope");
assert_eq!(resp.scope.as_deref(), Some("any-scope"));
}
#[tokio::test]
async fn get_access_token_record_after_issue() {
let (handler, _) = make_handler();
handler
.store
.create(make_full_client("rec-001"))
.await
.unwrap();
let req = TokenRequest {
grant_type: "client_credentials".into(),
client_id: "rec-001".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,
};
let resp = handler.handle(&req).await.unwrap();
let record = handler
.get_access_token_record(&resp.access_token)
.await
.unwrap()
.expect("应存在");
assert_eq!(record.client_id, "rec-001");
assert!(record.user_id.is_none(), "client_credentials 无 user_id");
assert_eq!(record.scopes, vec!["read", "write"]);
assert_eq!(record.token_type, "access");
}
#[tokio::test]
async fn revoke_token_makes_it_inaccessible() {
let (handler, _) = make_handler();
handler
.store
.create(make_full_client("rev-001"))
.await
.unwrap();
let req = TokenRequest {
grant_type: "client_credentials".into(),
client_id: "rev-001".into(),
client_secret: "secret-123".into(),
code: None,
redirect_uri: None,
code_verifier: None,
refresh_token: None,
scope: None,
username: None,
password: None,
};
let resp = handler.handle(&req).await.unwrap();
assert!(handler
.get_access_token_record(&resp.access_token)
.await
.unwrap()
.is_some());
handler.revoke_token(&resp.access_token).await.unwrap();
assert!(handler
.get_access_token_record(&resp.access_token)
.await
.unwrap()
.is_none());
}
#[test]
fn generate_token_produces_unique() {
let t1 = generate_token();
let t2 = generate_token();
assert_ne!(t1, t2);
assert!(t1.len() >= 43);
}
#[test]
fn token_rate_limiter_new_uses_defaults() {
let limiter = TokenRateLimiter::new();
assert_eq!(limiter.client_max, 10);
assert_eq!(limiter.client_window_secs, 1);
assert_eq!(limiter.username_max, 5);
assert_eq!(limiter.username_window_secs, 60);
}
#[test]
fn token_rate_limiter_default_equals_new() {
let limiter = TokenRateLimiter::default();
assert_eq!(limiter.client_max, 10);
assert_eq!(limiter.username_max, 5);
}
#[test]
fn token_rate_limiter_with_limits_zero_clamps_to_one() {
let limiter = TokenRateLimiter::with_limits(0, 0, 0, 0);
assert_eq!(limiter.client_max, 1);
assert_eq!(limiter.client_window_secs, 1);
assert_eq!(limiter.username_max, 1);
assert_eq!(limiter.username_window_secs, 1);
}
#[tokio::test]
async fn password_rate_limiter_check_fails_closed_on_dao_error() {
let dao = Arc::new(InMemoryDao::new());
dao.set("rate_limit:pw:alice", "not-a-number", 60)
.await
.unwrap();
let limiter = PasswordRateLimiter {
limiter: GarrisonDaoDistributedLimiter::new(dao.clone()),
dao,
max_attempts: 5,
window_seconds: 60,
};
assert!(
!limiter.check("alice").await,
"DAO 故障时应拒绝本次密码校验(fail-closed,防绕过撞库锁定)"
);
}
#[tokio::test]
async fn token_rate_limiter_dao_error_applies_different_fail_strategies() {
let dao = Arc::new(InMemoryDao::new());
dao.set("rate_limit:token:user:bob", "corrupt", 60)
.await
.unwrap();
dao.set("rate_limit:token:client:c1", "corrupt", 60)
.await
.unwrap();
let limiter = TokenRateLimiter {
limiter: GarrisonDaoDistributedLimiter::new(dao.clone()),
client_max: 10,
client_window_secs: 1,
username_max: 5,
username_window_secs: 60,
};
assert!(
!limiter.check_username("bob").await,
"username 维度应 fail-closed(撞库防护不允许故障放行)"
);
assert!(
limiter.check_client("c1").await,
"client QPS 维度应保持 fail-open(可用性优先)"
);
}
#[tokio::test]
async fn token_rate_limiter_check_client_allows_within_limit() {
let limiter = TokenRateLimiter::with_limits(3, 60, 100, 60);
for i in 0..3 {
assert!(
limiter.check_client("client-A").await,
"第 {} 次应允许",
i + 1
);
}
assert!(
!limiter.check_client("client-A").await,
"第 4 次应拒绝(超 client_max=3)"
);
}
#[tokio::test]
async fn token_rate_limiter_check_client_isolates_clients() {
let limiter = TokenRateLimiter::with_limits(2, 60, 100, 60);
assert!(limiter.check_client("client-A").await);
assert!(limiter.check_client("client-A").await);
assert!(!limiter.check_client("client-A").await, "client-A 达上限");
assert!(
limiter.check_client("client-B").await,
"client-B 应允许(独立计数器)"
);
}
#[tokio::test]
async fn token_rate_limiter_check_username_allows_within_limit() {
let limiter = TokenRateLimiter::with_limits(100, 60, 3, 60);
for i in 0..3 {
assert!(
limiter.check_username("alice").await,
"第 {} 次应允许",
i + 1
);
}
assert!(
!limiter.check_username("alice").await,
"第 4 次应拒绝(超 username_max=3)"
);
}
#[tokio::test]
async fn token_rate_limiter_check_username_isolates_users() {
let limiter = TokenRateLimiter::with_limits(100, 60, 2, 60);
assert!(limiter.check_username("alice").await);
assert!(limiter.check_username("alice").await);
assert!(!limiter.check_username("alice").await, "alice 达上限");
assert!(
limiter.check_username("bob").await,
"bob 应允许(独立计数器)"
);
}
#[tokio::test]
async fn handle_with_authorization_rate_limited_after_client_threshold() {
let (handler, _) = make_handler_with_limiters(
Arc::new(PasswordRateLimiter::new(1000, 300)),
Arc::new(TokenRateLimiter::with_limits(2, 60, 100, 60)),
);
handler
.store
.create(make_full_client("rl-cid"))
.await
.unwrap();
let req = TokenRequest {
grant_type: "client_credentials".into(),
client_id: "rl-cid".into(),
client_secret: "secret-123".into(),
code: None,
redirect_uri: None,
code_verifier: None,
refresh_token: None,
scope: None,
username: None,
password: None,
};
for i in 0..2 {
let resp = handler.handle(&req).await;
assert!(resp.is_ok(), "第 {} 次应成功,实际: {:?}", i + 1, resp);
}
let err = handler.handle(&req).await.unwrap_err();
assert!(
err.to_string().contains("rate_limited"),
"第 3 次应被限速,实际: {}",
err
);
}
#[tokio::test]
async fn handle_with_authorization_rate_limits_by_basic_auth_client_id() {
let (handler, _) = make_handler_with_limiters(
Arc::new(PasswordRateLimiter::new(1000, 300)),
Arc::new(TokenRateLimiter::with_limits(1, 60, 100, 60)),
);
handler
.store
.create(make_full_client("ba-rl"))
.await
.unwrap();
let credentials = STANDARD.encode("ba-rl:secret-123");
let auth_header = format!("Basic {}", credentials);
let req = TokenRequest {
grant_type: "client_credentials".into(),
client_id: "".into(), client_secret: "".into(),
code: None,
redirect_uri: None,
code_verifier: None,
refresh_token: None,
scope: None,
username: None,
password: None,
};
let _ = handler
.handle_with_authorization(&req, Some(&auth_header))
.await
.expect("第 1 次应成功");
let err = handler
.handle_with_authorization(&req, Some(&auth_header))
.await
.unwrap_err();
assert!(
err.to_string().contains("rate_limited"),
"第 2 次应被限速(Basic Auth client_id),实际: {}",
err
);
}
#[tokio::test]
async fn handle_password_rate_limited_after_username_threshold() {
let (handler, _) = make_handler_with_limiters(
Arc::new(PasswordRateLimiter::new(1000, 300)),
Arc::new(TokenRateLimiter::with_limits(100, 60, 2, 60)),
);
handler
.store
.create(make_full_client("pw-url-001"))
.await
.unwrap();
let req = TokenRequest {
grant_type: "password".into(),
client_id: "pw-url-001".into(),
client_secret: "secret-123".into(),
code: None,
redirect_uri: None,
code_verifier: None,
refresh_token: None,
scope: None,
username: Some("alice".into()),
password: Some("wonderland".into()),
};
for i in 0..2 {
let resp = handler.handle(&req).await;
assert!(resp.is_ok(), "第 {} 次应成功,实际: {:?}", i + 1, resp);
}
let err = handler.handle(&req).await.unwrap_err();
assert!(
err.to_string().contains("rate_limited"),
"第 3 次应被 per-username 限速,实际: {}",
err
);
}
}
#[cfg(all(test, feature = "db-sqlite"))]
mod refresh_rotation_tests {
use super::*;
use crate::dao::{init_dbnexus, GarrisonMigration};
use crate::oauth2_server::authorize::AuthorizeHandler;
use crate::oauth2_server::client::{DaoOAuth2ClientStore, GrantType, OAuth2Client};
use crate::protocol::jwt::refresh::RefreshTokenRotation;
use crate::protocol::jwt::JwtHandler;
use dbnexus::DbPool;
use std::path::PathBuf;
use std::sync::{Arc, RwLock};
fn project_migrations_dir() -> PathBuf {
let manifest_dir = env!("CARGO_MANIFEST_DIR");
PathBuf::from(manifest_dir)
.join("migrations")
.join("sqlite")
}
async fn setup_db() -> DbPool {
let pool = init_dbnexus("sqlite::memory:")
.await
.expect("init_dbnexus 应成功");
let migration = GarrisonMigration::with_base_dir(pool.clone(), project_migrations_dir());
migration.migrate_core().await.expect("migrate_core 应成功");
pool
}
struct TestPasswordVerifier;
#[async_trait]
impl PasswordVerifier for TestPasswordVerifier {
async fn verify(&self, username: &str, password: &str) -> GarrisonResult<Option<i64>> {
if username == "alice" && password == "wonderland" {
Ok(Some(5001))
} else {
Ok(None)
}
}
}
async fn make_handler_with_rotation() -> TokenHandler {
let pool = setup_db().await;
let dao = Arc::new(crate::dao::InMemoryDao::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 jwt_handler = Arc::new(JwtHandler::new("test_secret_that_is_at_least_32_bytes"));
let rotation = Arc::new(RefreshTokenRotation::new(
pool,
jwt_handler,
Arc::new(RwLock::new(1)),
));
TokenHandler::new(
store,
dao,
authorize_handler,
Arc::new(PasswordRateLimiter::new(1000, 300)),
Arc::new(TokenRateLimiter::with_limits(100_000, 60, 100_000, 60)),
)
.with_password_verifier(Arc::new(TestPasswordVerifier))
.with_refresh_rotation(rotation)
}
fn make_handler_without_rotation() -> TokenHandler {
let dao = Arc::new(crate::dao::InMemoryDao::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(),
));
TokenHandler::new(
store,
dao,
authorize_handler,
Arc::new(PasswordRateLimiter::new(1000, 300)),
Arc::new(TokenRateLimiter::with_limits(100_000, 60, 100_000, 60)),
)
.with_password_verifier(Arc::new(TestPasswordVerifier))
}
fn make_full_client(id: &str) -> OAuth2Client {
OAuth2Client::new(
id,
"secret-123",
vec!["https://app.example.com/cb".into()],
vec![
GrantType::AuthorizationCode,
GrantType::RefreshToken,
GrantType::ClientCredentials,
GrantType::Password,
],
vec!["read".into(), "write".into()],
)
.unwrap()
}
async fn get_auth_code(handler: &TokenHandler, client_id: &str, verifier: &str) -> String {
let challenge = crate::oauth2_server::authorize::generate_code_challenge(verifier);
let req = crate::oauth2_server::authorize::AuthorizeRequest {
response_type: "code".into(),
client_id: client_id.into(),
redirect_uri: "https://app.example.com/cb".into(),
scope: Some("read".into()),
state: Some("xyz".into()),
code_challenge: challenge,
code_challenge_method: "S256".into(),
prompt: None,
};
let resp = handler
.authorize_handler
.authorize(&req, Some(1001))
.await
.unwrap();
match resp {
crate::oauth2_server::authorize::AuthorizeResponse::Redirect { location } => location
.split("code=")
.nth(1)
.unwrap()
.split('&')
.next()
.unwrap()
.to_string(),
_ => panic!("期望 Redirect"),
}
}
#[tokio::test(flavor = "multi_thread")]
async fn token_handler_with_refresh_rotation() {
let handler = make_handler_with_rotation().await;
assert!(
handler.refresh_rotation.is_some(),
"注入后 refresh_rotation 应为 Some"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn issue_tokens_with_rotation_uses_issue_method() {
let handler = make_handler_with_rotation().await;
let client = make_full_client("rot-auth-001");
handler
.store
.create(client.clone())
.await
.expect("create client 应成功");
let verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
let code = get_auth_code(&handler, "rot-auth-001", verifier).await;
let req = TokenRequest {
grant_type: "authorization_code".into(),
client_id: "rot-auth-001".into(),
client_secret: "secret-123".into(),
code: Some(code),
redirect_uri: Some("https://app.example.com/cb".into()),
code_verifier: Some(verifier.into()),
refresh_token: None,
scope: None,
username: None,
password: None,
};
let resp = handler.handle(&req).await.expect("token 签发应成功");
assert!(resp.refresh_token.is_some(), "应返回 refresh_token");
let rotation = handler.refresh_rotation.as_ref().unwrap();
let record = rotation
.validate(resp.refresh_token.as_ref().unwrap())
.await
.expect("validate 应成功");
assert!(record.is_some(), "refresh_token 应在 refresh_tokens 表中");
let record = record.unwrap();
assert_eq!(record.client_id, Some("rot-auth-001".to_string()));
}
#[tokio::test(flavor = "multi_thread")]
async fn handle_refresh_token_with_rotation_rotates() {
let handler = make_handler_with_rotation().await;
let client = make_full_client("rot-refresh-001");
handler.store.create(client.clone()).await.unwrap();
let verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
let code = get_auth_code(&handler, "rot-refresh-001", verifier).await;
let issue_req = TokenRequest {
grant_type: "authorization_code".into(),
client_id: "rot-refresh-001".into(),
client_secret: "secret-123".into(),
code: Some(code),
redirect_uri: Some("https://app.example.com/cb".into()),
code_verifier: Some(verifier.into()),
refresh_token: None,
scope: None,
username: None,
password: None,
};
let issue_resp = handler.handle(&issue_req).await.unwrap();
let old_refresh = issue_resp.refresh_token.expect("应有 refresh_token");
let refresh_req = TokenRequest {
grant_type: "refresh_token".into(),
client_id: "rot-refresh-001".into(),
client_secret: "secret-123".into(),
code: None,
redirect_uri: None,
code_verifier: None,
refresh_token: Some(old_refresh.clone()),
scope: None,
username: None,
password: None,
};
let refresh_resp = handler.handle(&refresh_req).await.expect("refresh 应成功");
assert!(
refresh_resp.refresh_token.is_some(),
"轮换后应返回新 refresh_token"
);
assert_ne!(
refresh_resp.refresh_token.as_ref().unwrap(),
&old_refresh,
"新 refresh_token 应与旧的不同(轮换)"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn handle_refresh_token_reuse_detection() {
let handler = make_handler_with_rotation().await;
let client = make_full_client("rot-reuse-001");
handler.store.create(client.clone()).await.unwrap();
let verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
let code = get_auth_code(&handler, "rot-reuse-001", verifier).await;
let issue_req = TokenRequest {
grant_type: "authorization_code".into(),
client_id: "rot-reuse-001".into(),
client_secret: "secret-123".into(),
code: Some(code),
redirect_uri: Some("https://app.example.com/cb".into()),
code_verifier: Some(verifier.into()),
refresh_token: None,
scope: None,
username: None,
password: None,
};
let issue_resp = handler.handle(&issue_req).await.unwrap();
let old_refresh = issue_resp.refresh_token.expect("应有 refresh_token");
let refresh_req = TokenRequest {
grant_type: "refresh_token".into(),
client_id: "rot-reuse-001".into(),
client_secret: "secret-123".into(),
code: None,
redirect_uri: None,
code_verifier: None,
refresh_token: Some(old_refresh.clone()),
scope: None,
username: None,
password: None,
};
let _first = handler
.handle(&refresh_req)
.await
.expect("第一次 refresh 应成功");
let result = handler.handle(&refresh_req).await;
assert!(
matches!(&result, Err(GarrisonError::TokenRevoked(_))),
"重用已消费的 refresh token 应返回 TokenRevoked,实际: {:?}",
result
);
}
#[tokio::test(flavor = "multi_thread")]
async fn revoke_token_revokes_rotation_refresh_token() {
let handler = make_handler_with_rotation().await;
let client = make_full_client("rot-revoke-001");
handler.store.create(client.clone()).await.unwrap();
let verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
let code = get_auth_code(&handler, "rot-revoke-001", verifier).await;
let issue_req = TokenRequest {
grant_type: "authorization_code".into(),
client_id: "rot-revoke-001".into(),
client_secret: "secret-123".into(),
code: Some(code),
redirect_uri: Some("https://app.example.com/cb".into()),
code_verifier: Some(verifier.into()),
refresh_token: None,
scope: None,
username: None,
password: None,
};
let issue_resp = handler.handle(&issue_req).await.unwrap();
let refresh_token = issue_resp.refresh_token.expect("应有 refresh_token");
let rotation = handler.refresh_rotation.as_ref().unwrap();
assert!(rotation.validate(&refresh_token).await.unwrap().is_some());
handler.revoke_token(&refresh_token).await.unwrap();
assert!(
rotation.validate(&refresh_token).await.unwrap().is_none(),
"revoke_token 应撤销 rotation 路径签发的 refresh token"
);
let refresh_req = TokenRequest {
grant_type: "refresh_token".into(),
client_id: "rot-revoke-001".into(),
client_secret: "secret-123".into(),
code: None,
redirect_uri: None,
code_verifier: None,
refresh_token: Some(refresh_token),
scope: None,
username: None,
password: None,
};
let err = handler.handle(&refresh_req).await.unwrap_err();
assert!(
err.to_string().contains("invalid_grant") || err.to_string().contains("revoke"),
"已撤销的 refresh token 不得再刷新,实际: {}",
err
);
}
#[tokio::test(flavor = "multi_thread")]
async fn handle_refresh_token_without_rotation_fallback() {
let handler = make_handler_without_rotation();
let client = make_full_client("rot-fallback-001");
handler.store.create(client.clone()).await.unwrap();
let verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
let code = get_auth_code(&handler, "rot-fallback-001", verifier).await;
let issue_req = TokenRequest {
grant_type: "authorization_code".into(),
client_id: "rot-fallback-001".into(),
client_secret: "secret-123".into(),
code: Some(code),
redirect_uri: Some("https://app.example.com/cb".into()),
code_verifier: Some(verifier.into()),
refresh_token: None,
scope: None,
username: None,
password: None,
};
let issue_resp = handler.handle(&issue_req).await.unwrap();
let old_refresh = issue_resp.refresh_token.expect("应有 refresh_token");
let refresh_req = TokenRequest {
grant_type: "refresh_token".into(),
client_id: "rot-fallback-001".into(),
client_secret: "secret-123".into(),
code: None,
redirect_uri: None,
code_verifier: None,
refresh_token: Some(old_refresh.clone()),
scope: None,
username: None,
password: None,
};
let refresh_resp = handler.handle(&refresh_req).await.expect("refresh 应成功");
assert!(
refresh_resp.refresh_token.is_some(),
"VULN-0009: Fallback 路径应轮换返回新 refresh_token"
);
assert_ne!(
refresh_resp.refresh_token.as_ref().unwrap(),
&old_refresh,
"VULN-0009: 新 refresh_token 应与旧的不同"
);
let reuse_err = handler.handle(&refresh_req).await.unwrap_err();
assert!(
reuse_err.to_string().contains("invalid_grant"),
"VULN-0009: 重用旧 refresh_token 应返回 invalid_grant,实际: {}",
reuse_err
);
}
#[tokio::test(flavor = "multi_thread")]
async fn oauth2_full_flow_with_refresh_rotation() {
let handler = make_handler_with_rotation().await;
let client = make_full_client("rot-e2e-001");
handler.store.create(client.clone()).await.unwrap();
let verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
let code = get_auth_code(&handler, "rot-e2e-001", verifier).await;
let issue_req = TokenRequest {
grant_type: "authorization_code".into(),
client_id: "rot-e2e-001".into(),
client_secret: "secret-123".into(),
code: Some(code),
redirect_uri: Some("https://app.example.com/cb".into()),
code_verifier: Some(verifier.into()),
refresh_token: None,
scope: None,
username: None,
password: None,
};
let issue_resp = handler.handle(&issue_req).await.expect("签发 token");
let token1 = issue_resp.refresh_token.expect("应有 refresh_token");
let refresh_req_1 = TokenRequest {
grant_type: "refresh_token".into(),
client_id: "rot-e2e-001".into(),
client_secret: "secret-123".into(),
code: None,
redirect_uri: None,
code_verifier: None,
refresh_token: Some(token1.clone()),
scope: None,
username: None,
password: None,
};
let resp1 = handler
.handle(&refresh_req_1)
.await
.expect("第一次 refresh");
let token2 = resp1.refresh_token.expect("应返回新 refresh_token");
assert_ne!(&token2, &token1, "token2 应与 token1 不同");
let refresh_req_2 = TokenRequest {
grant_type: "refresh_token".into(),
client_id: "rot-e2e-001".into(),
client_secret: "secret-123".into(),
code: None,
redirect_uri: None,
code_verifier: None,
refresh_token: Some(token2.clone()),
scope: None,
username: None,
password: None,
};
let resp2 = handler
.handle(&refresh_req_2)
.await
.expect("第二次 refresh");
let token3 = resp2.refresh_token.expect("应返回新 refresh_token");
assert_ne!(&token3, &token2, "token3 应与 token2 不同");
let reuse_result = handler.handle(&refresh_req_1).await;
assert!(
matches!(&reuse_result, Err(GarrisonError::TokenRevoked(_))),
"重用 token1 应返回 TokenRevoked,实际: {:?}",
reuse_result
);
let rotation = handler.refresh_rotation.as_ref().unwrap();
let token1_record = rotation.validate(&token1).await.expect("validate token1");
assert!(
token1_record.is_none(),
"token1 应已 revoked(validate 返回 None)"
);
let token2_record = rotation.validate(&token2).await.expect("validate token2");
assert!(
token2_record.is_none(),
"token2 应已 revoked(链式撤销子代,validate 返回 None)"
);
let token3_record = rotation.validate(&token3).await.expect("validate token3");
assert!(
token3_record.is_none(),
"token3 应已 revoked(链式撤销孙代,validate 返回 None)"
);
}
#[derive(Clone)]
struct LogCapture(Arc<std::sync::Mutex<Vec<String>>>);
impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for LogCapture {
type Writer = LogCaptureWriter;
fn make_writer(&'a self) -> Self::Writer {
LogCaptureWriter(self.0.clone())
}
}
struct LogCaptureWriter(Arc<std::sync::Mutex<Vec<String>>>);
impl std::io::Write for LogCaptureWriter {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.0
.lock()
.expect("日志缓冲锁应可用")
.push(String::from_utf8_lossy(buf).to_string());
Ok(buf.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
#[test]
fn degraded_refresh_emits_structured_warning() {
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
let logs = LogCapture(Arc::new(std::sync::Mutex::new(Vec::new())));
let subscriber = tracing_subscriber::registry().with(
tracing_subscriber::fmt::layer()
.with_ansi(false)
.with_writer(logs.clone()),
);
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.expect("runtime 构建应成功");
let _guard = subscriber.set_default();
let logs_value = rt.block_on(async {
let handler = make_handler_without_rotation();
assert!(
!handler.has_refresh_rotation(),
"未注入 rotation 时探针应为 false"
);
let handler = handler.with_password_verifier(Arc::new(TestPasswordVerifier));
let client = make_full_client("rot-degraded-warn-001");
handler.store.create(client).await.unwrap();
let issue_req = TokenRequest {
grant_type: "password".into(),
client_id: "rot-degraded-warn-001".into(),
client_secret: "secret-123".into(),
code: None,
redirect_uri: None,
code_verifier: None,
refresh_token: None,
scope: None,
username: Some("alice".into()),
password: Some("wonderland".into()),
};
let issue_resp = handler
.handle(&issue_req)
.await
.expect("password 签发应成功");
let old_refresh = issue_resp.refresh_token.expect("应有 refresh_token");
let refresh_req = TokenRequest {
grant_type: "refresh_token".into(),
client_id: "rot-degraded-warn-001".into(),
client_secret: "secret-123".into(),
code: None,
redirect_uri: None,
code_verifier: None,
refresh_token: Some(old_refresh),
scope: None,
username: None,
password: None,
};
handler
.handle(&refresh_req)
.await
.expect("退化路径 refresh 应成功(行为降级非功能损坏)");
logs.0.lock().expect("日志缓冲锁应可用").clone()
});
let degraded_warn =
crate::i18n::translate_detail("logs-oauth2-refresh-rotation-not-configured", &[]);
let degraded_warns: Vec<&String> = logs_value
.iter()
.filter(|l| l.contains(°raded_warn))
.collect();
assert_eq!(
degraded_warns.len(),
1,
"单次降级刷新应恰好输出一条退化 warn,日志: {:?}",
logs_value
);
}
#[test]
fn rotation_injected_refresh_emits_no_degraded_warning() {
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
let logs = LogCapture(Arc::new(std::sync::Mutex::new(Vec::new())));
let subscriber = tracing_subscriber::registry().with(
tracing_subscriber::fmt::layer()
.with_ansi(false)
.with_writer(logs.clone()),
);
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.expect("runtime 构建应成功");
let _guard = subscriber.set_default();
let logs_value = rt.block_on(async {
let handler = make_handler_with_rotation().await;
assert!(
handler.has_refresh_rotation(),
"注入 rotation 后探针应为 true"
);
let handler = handler.with_password_verifier(Arc::new(TestPasswordVerifier));
let client = make_full_client("rot-warn-clean-001");
handler.store.create(client).await.unwrap();
let issue_req = TokenRequest {
grant_type: "password".into(),
client_id: "rot-warn-clean-001".into(),
client_secret: "secret-123".into(),
code: None,
redirect_uri: None,
code_verifier: None,
refresh_token: None,
scope: None,
username: Some("alice".into()),
password: Some("wonderland".into()),
};
let issue_resp = handler
.handle(&issue_req)
.await
.expect("password 签发应成功");
let old_refresh = issue_resp.refresh_token.expect("应有 refresh_token");
let refresh_req = TokenRequest {
grant_type: "refresh_token".into(),
client_id: "rot-warn-clean-001".into(),
client_secret: "secret-123".into(),
code: None,
redirect_uri: None,
code_verifier: None,
refresh_token: Some(old_refresh),
scope: None,
username: None,
password: None,
};
handler
.handle(&refresh_req)
.await
.expect("统一路径 refresh 应成功");
logs.0.lock().expect("日志缓冲锁应可用").clone()
});
let degraded_warn =
crate::i18n::translate_detail("logs-oauth2-refresh-rotation-not-configured", &[]);
assert!(
!logs_value.iter().any(|l| l.contains(°raded_warn)),
"注入 rotation 后不得输出退化 warn,日志: {:?}",
logs_value
);
}
}