#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct RefreshTokenRecord {
pub token_hash: String,
pub parent_token_hash: Option<String>,
pub login_id: i64,
pub tenant_id: i64,
pub key_version: u32,
pub expires_at: i64,
pub revoked: bool,
pub created_at: i64,
#[serde(default)]
pub rotated_at: Option<i64>,
#[serde(deserialize_with = "deserialize_required_option")]
pub client_id: Option<String>,
#[serde(deserialize_with = "deserialize_required_option")]
pub scopes: Option<String>,
#[serde(deserialize_with = "deserialize_required_option")]
pub username: Option<String>,
#[serde(deserialize_with = "deserialize_required_option")]
pub user_id: Option<i64>,
}
fn deserialize_required_option<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
where
D: serde::Deserializer<'de>,
T: serde::Deserialize<'de>,
{
use serde::Deserialize as _;
Option::<T>::deserialize(deserializer)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RefreshTokenReuseSubtype {
RecentPrev,
OrphanedBranch,
StaleLineage,
}
#[cfg(feature = "db-sqlite")]
mod service {
use super::{RefreshTokenRecord, RefreshTokenReuseSubtype};
use crate::config::RecentReuseBehaviour;
use crate::error::{GarrisonError, GarrisonResult};
use crate::protocol::jwt::JwtHandler;
use dbnexus::sea_orm::{ConnectionTrait, DatabaseConnection, DbBackend, Statement, Value};
use dbnexus::DbPool;
use sha2::{Digest, Sha256};
use std::collections::HashMap;
use std::sync::{Arc, Mutex, RwLock};
use std::time::Duration;
use uuid::Uuid;
const REUSE_LINEAGE_MAX_DEPTH: usize = 32;
const GRACE_RACE_POLL: Duration = Duration::from_millis(10);
const GRACE_RACE_DEADLINE: Duration = Duration::from_millis(250);
struct GraceEntry {
new_refresh: String,
login_id: String,
rotated_at: i64,
uses: u32,
}
pub struct RefreshTokenRotation {
pub pool: DbPool,
pub jwt_handler: Arc<JwtHandler>,
pub key_version: Arc<RwLock<u32>>,
pub reuse_behaviour: RecentReuseBehaviour,
pub grace_period_secs: i64,
pub grace_max_uses: u32,
grace_entries: Arc<Mutex<HashMap<String, GraceEntry>>>,
}
impl RefreshTokenRotation {
pub fn new(
pool: DbPool,
jwt_handler: Arc<JwtHandler>,
key_version: Arc<RwLock<u32>>,
) -> Self {
Self {
pool,
jwt_handler,
key_version,
reuse_behaviour: RecentReuseBehaviour::default(),
grace_period_secs: 0,
grace_max_uses: 1,
grace_entries: Arc::new(Mutex::new(HashMap::new())),
}
}
pub fn with_reuse_behaviour(mut self, behaviour: RecentReuseBehaviour) -> Self {
self.reuse_behaviour = behaviour;
self
}
pub fn with_grace_window(mut self, period_secs: i64, max_uses: u32) -> Self {
self.grace_period_secs = period_secs;
self.grace_max_uses = max_uses;
self
}
fn sha256_hex(s: &str) -> String {
let mut hasher = Sha256::new();
hasher.update(s.as_bytes());
let result = hasher.finalize();
result.iter().map(|b| format!("{:02x}", b)).collect()
}
fn now_unix() -> i64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs() as i64)
.unwrap_or(0)
}
pub async fn rotate(&self, old_token: &str) -> GarrisonResult<(String, String)> {
let old_hash = Self::sha256_hex(old_token);
if let Some(subtype) = self.detect_reuse(&old_hash).await? {
if let Some((new_refresh, login_id)) =
self.try_grace_redemption(&old_hash, subtype).await?
{
let new_access = self.jwt_handler.sign(&login_id, 3600)?;
return Ok((new_access, new_refresh));
}
return Err(self.dispose_reuse(&old_hash, subtype).await?);
}
let session = self
.pool
.get_session("admin")
.await
.map_err(|e| GarrisonError::Dao(format!("jwt-refresh-get-session::{}", e)))?;
let conn = session
.connection()
.map_err(|e| GarrisonError::Dao(format!("jwt-refresh-get-conn::{}", e)))?;
let claim_stmt = Statement::from_sql_and_values(
DbBackend::Sqlite,
"UPDATE refresh_tokens SET revoked = 1, rotated_at = ? \
WHERE token_hash = ? AND revoked = 0",
vec![
Value::BigInt(Some(Self::now_unix())),
Value::String(Some(old_hash.clone())),
],
);
let claimed = conn
.execute_raw(claim_stmt)
.await
.map_err(|e| GarrisonError::Dao(format!("jwt-refresh-claim::{}", e)))?;
if claimed.rows_affected() == 0 {
let rotated_at_in_window = if self.grace_period_secs > 0 {
matches!(
Self::fetch_rotated_at(conn, &old_hash).await?,
Some(t) if Self::now_unix() - t <= self.grace_period_secs
)
} else {
false
};
drop(session);
let graced = if rotated_at_in_window {
self.await_grace_redemption(&old_hash).await
} else {
None
};
if let Some((new_refresh, login_id)) = graced {
let new_access = self.jwt_handler.sign(&login_id, 3600)?;
return Ok((new_access, new_refresh));
}
return Err(GarrisonError::InvalidToken(
"jwt-refresh-token-consumed::".to_string(),
));
}
let select_stmt = Statement::from_sql_and_values(
DbBackend::Sqlite,
"SELECT login_id, tenant_id, client_id, scopes, username, user_id \
FROM refresh_tokens WHERE token_hash = ?",
vec![Value::String(Some(old_hash.clone()))],
);
let row = conn
.query_one_raw(select_stmt)
.await
.map_err(|e| GarrisonError::Dao(format!("jwt-refresh-query::{}", e)))?
.ok_or_else(|| {
GarrisonError::InvalidToken("jwt-refresh-token-consumed::".to_string())
})?;
let login_id: String = row
.try_get("", "login_id")
.map_err(|e| GarrisonError::Dao(format!("jwt-refresh-query::{}", e)))?;
let tenant_id: i64 = row
.try_get("", "tenant_id")
.map_err(|e| GarrisonError::Dao(format!("jwt-refresh-query::{}", e)))?;
let client_id: Option<String> = row.try_get("", "client_id").ok().flatten();
let scopes: Option<String> = row.try_get("", "scopes").ok().flatten();
let username: Option<String> = row.try_get("", "username").ok().flatten();
let user_id: Option<i64> = row.try_get("", "user_id").ok().flatten();
let new_refresh = Uuid::new_v4().to_string();
let new_access = self.jwt_handler.sign(&login_id, 3600)?;
let new_hash = Self::sha256_hex(&new_refresh);
let now = Self::now_unix();
let kv = *self
.key_version
.read()
.expect("key_version RwLock should not be poisoned");
let insert_stmt = Statement::from_sql_and_values(
DbBackend::Sqlite,
"INSERT INTO refresh_tokens \
(token_hash, parent_token_hash, login_id, tenant_id, key_version, \
expires_at, revoked, created_at, client_id, scopes, username, user_id) \
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
vec![
Value::String(Some(new_hash.clone())),
Value::String(Some(old_hash.clone())),
Value::String(Some(login_id.clone())),
Value::BigInt(Some(tenant_id)),
Value::BigInt(Some(kv as i64)),
Value::BigInt(Some(now + 86400 * 7)),
Value::BigInt(Some(0)),
Value::BigInt(Some(now)),
client_id
.clone()
.map(|s| Value::String(Some(s)))
.unwrap_or(Value::String(None)),
scopes
.clone()
.map(|s| Value::String(Some(s)))
.unwrap_or(Value::String(None)),
username
.clone()
.map(|s| Value::String(Some(s)))
.unwrap_or(Value::String(None)),
user_id
.map(|i| Value::BigInt(Some(i)))
.unwrap_or(Value::BigInt(None)),
],
);
if let Err(insert_err) = conn.execute_raw(insert_stmt).await {
return match Self::compensate_failed_rotation(conn, &old_hash).await {
Ok(()) => Err(GarrisonError::Dao(format!(
"jwt-refresh-insert-rolled-back::{}",
insert_err
))),
Err(compensate_err) => Err(GarrisonError::Dao(format!(
"jwt-refresh-insert-and-compensate-failed::insert={insert_err}::compensate={compensate_err}"
))),
};
}
self.record_grace_entry(&old_hash, &new_refresh, &login_id, now);
Ok((new_access, new_refresh))
}
async fn compensate_failed_rotation(
conn: &DatabaseConnection,
old_hash: &str,
) -> GarrisonResult<()> {
let delete_stmt = Statement::from_sql_and_values(
DbBackend::Sqlite,
"DELETE FROM refresh_tokens WHERE parent_token_hash = ?",
vec![Value::String(Some(old_hash.to_string()))],
);
conn.execute_raw(delete_stmt)
.await
.map_err(|e| GarrisonError::Dao(format!("jwt-refresh-compensate-delete::{}", e)))?;
let restore_stmt = Statement::from_sql_and_values(
DbBackend::Sqlite,
"UPDATE refresh_tokens SET revoked = 0, rotated_at = NULL \
WHERE token_hash = ?",
vec![Value::String(Some(old_hash.to_string()))],
);
conn.execute_raw(restore_stmt).await.map_err(|e| {
GarrisonError::Dao(format!("jwt-refresh-compensate-restore::{}", e))
})?;
Ok(())
}
pub async fn issue(
&self,
client_id: &str,
user_id: Option<i64>,
scopes: &[String],
username: Option<&str>,
login_id: i64,
tenant_id: i64,
ttl_seconds: i64,
) -> GarrisonResult<String> {
let refresh_token = Uuid::new_v4().to_string();
let token_hash = Self::sha256_hex(&refresh_token);
let now = Self::now_unix();
let kv = *self
.key_version
.read()
.expect("key_version RwLock should not be poisoned");
let scopes_str = if scopes.is_empty() {
None
} else {
Some(scopes.join(" "))
};
let session = self
.pool
.get_session("admin")
.await
.map_err(|e| GarrisonError::Dao(format!("jwt-refresh-get-session::{}", e)))?;
let conn = session
.connection()
.map_err(|e| GarrisonError::Dao(format!("jwt-refresh-get-conn::{}", e)))?;
let insert_stmt = Statement::from_sql_and_values(
DbBackend::Sqlite,
"INSERT INTO refresh_tokens \
(token_hash, parent_token_hash, login_id, tenant_id, key_version, \
expires_at, revoked, created_at, client_id, scopes, username, user_id) \
VALUES (?, NULL, ?, ?, ?, ?, 0, ?, ?, ?, ?, ?)",
vec![
Value::String(Some(token_hash)),
Value::BigInt(Some(login_id)),
Value::BigInt(Some(tenant_id)),
Value::BigInt(Some(kv as i64)),
Value::BigInt(Some(now + ttl_seconds)),
Value::BigInt(Some(now)),
Value::String(Some(client_id.to_string())),
scopes_str
.map(|s| Value::String(Some(s)))
.unwrap_or(Value::String(None)),
username
.map(|s| Value::String(Some(s.to_string())))
.unwrap_or(Value::String(None)),
user_id
.map(|i| Value::BigInt(Some(i)))
.unwrap_or(Value::BigInt(None)),
],
);
conn.execute_raw(insert_stmt)
.await
.map_err(|e| GarrisonError::Dao(format!("jwt-refresh-insert::{}", e)))?;
Ok(refresh_token)
}
pub async fn validate(&self, token: &str) -> GarrisonResult<Option<RefreshTokenRecord>> {
let token_hash = Self::sha256_hex(token);
let session = self
.pool
.get_session("admin")
.await
.map_err(|e| GarrisonError::Dao(format!("jwt-refresh-get-session::{}", e)))?;
let conn = session
.connection()
.map_err(|e| GarrisonError::Dao(format!("jwt-refresh-get-conn::{}", e)))?;
let stmt = Statement::from_sql_and_values(
DbBackend::Sqlite,
"SELECT token_hash, parent_token_hash, login_id, tenant_id, \
key_version, expires_at, revoked, created_at, rotated_at, \
client_id, scopes, username, user_id \
FROM refresh_tokens WHERE token_hash = ? AND revoked = 0",
vec![Value::String(Some(token_hash.clone()))],
);
let row = conn
.query_one_raw(stmt)
.await
.map_err(|e| GarrisonError::Dao(format!("jwt-refresh-query::{}", e)))?;
match row {
Some(row) => {
let login_id: String = row
.try_get("", "login_id")
.map_err(|e| GarrisonError::Dao(format!("jwt-refresh-query::{}", e)))?;
let tenant_id: i64 = row
.try_get("", "tenant_id")
.map_err(|e| GarrisonError::Dao(format!("jwt-refresh-query::{}", e)))?;
let key_version: i64 = row
.try_get("", "key_version")
.map_err(|e| GarrisonError::Dao(format!("jwt-refresh-query::{}", e)))?;
let expires_at: i64 = row
.try_get("", "expires_at")
.map_err(|e| GarrisonError::Dao(format!("jwt-refresh-query::{}", e)))?;
let revoked: i64 = row
.try_get("", "revoked")
.map_err(|e| GarrisonError::Dao(format!("jwt-refresh-query::{}", e)))?;
let created_at: i64 = row
.try_get("", "created_at")
.map_err(|e| GarrisonError::Dao(format!("jwt-refresh-query::{}", e)))?;
let rotated_at: Option<i64> = row.try_get("", "rotated_at").ok().flatten();
let parent_token_hash: Option<String> =
row.try_get("", "parent_token_hash").ok().flatten();
let client_id: Option<String> = row.try_get("", "client_id").ok().flatten();
let scopes: Option<String> = row.try_get("", "scopes").ok().flatten();
let username: Option<String> = row.try_get("", "username").ok().flatten();
let user_id: Option<i64> = row.try_get("", "user_id").ok().flatten();
let login_id_i64: i64 = login_id.parse().map_err(|e| {
GarrisonError::Dao(format!(
"jwt-refresh-login-id-parse-failed::{}::{}",
login_id, e
))
})?;
Ok(Some(RefreshTokenRecord {
token_hash,
parent_token_hash,
login_id: login_id_i64,
tenant_id,
key_version: key_version as u32,
expires_at,
revoked: revoked == 1,
created_at,
rotated_at,
client_id,
scopes,
username,
user_id,
}))
},
None => Ok(None),
}
}
async fn try_grace_redemption(
&self,
old_hash: &str,
subtype: RefreshTokenReuseSubtype,
) -> GarrisonResult<Option<(String, String)>> {
if self.grace_period_secs <= 0 {
return Ok(None);
}
if matches!(subtype, RefreshTokenReuseSubtype::OrphanedBranch) {
return Ok(None);
}
let session = self
.pool
.get_session("admin")
.await
.map_err(|e| GarrisonError::Dao(format!("jwt-refresh-get-session::{}", e)))?;
let conn = session
.connection()
.map_err(|e| GarrisonError::Dao(format!("jwt-refresh-get-conn::{}", e)))?;
let rotated_at = Self::fetch_rotated_at(conn, old_hash).await?;
let in_window =
matches!(rotated_at, Some(t) if Self::now_unix() - t <= self.grace_period_secs);
if !in_window {
return Ok(None);
}
let eligible = match subtype {
RefreshTokenReuseSubtype::RecentPrev => true,
RefreshTokenReuseSubtype::OrphanedBranch => false,
RefreshTokenReuseSubtype::StaleLineage => {
!Self::has_children(conn, old_hash).await?
},
};
if !eligible {
return Ok(None);
}
drop(session);
Ok(self.await_grace_redemption(old_hash).await)
}
async fn await_grace_redemption(&self, old_hash: &str) -> Option<(String, String)> {
let deadline = std::time::Instant::now() + GRACE_RACE_DEADLINE;
loop {
if let Some(redeemed) = self.redeem_grace_entry(old_hash) {
return Some(redeemed);
}
if std::time::Instant::now() >= deadline {
return None;
}
tokio::time::sleep(GRACE_RACE_POLL).await;
}
}
fn record_grace_entry(
&self,
old_hash: &str,
new_refresh: &str,
login_id: &str,
rotated_at: i64,
) {
if self.grace_period_secs <= 0 {
return;
}
let mut entries = self.grace_entries.lock().unwrap_or_else(|e| {
panic!(
"{}: {e}",
crate::i18n::translate_detail("jwt-refresh-grace-entries-lock-poisoned", &[],)
)
});
entries.retain(|_, entry| rotated_at - entry.rotated_at <= self.grace_period_secs);
entries.insert(
old_hash.to_string(),
GraceEntry {
new_refresh: new_refresh.to_string(),
login_id: login_id.to_string(),
rotated_at,
uses: 0,
},
);
}
fn redeem_grace_entry(&self, old_hash: &str) -> Option<(String, String)> {
if self.grace_period_secs <= 0 {
return None;
}
let now = Self::now_unix();
let mut entries = self.grace_entries.lock().unwrap_or_else(|e| {
panic!(
"{}: {e}",
crate::i18n::translate_detail("jwt-refresh-grace-entries-lock-poisoned", &[],)
)
});
let entry = entries.get_mut(old_hash)?;
if now - entry.rotated_at > self.grace_period_secs || entry.uses >= self.grace_max_uses
{
return None;
}
entry.uses += 1;
Some((entry.new_refresh.clone(), entry.login_id.clone()))
}
async fn fetch_rotated_at(
conn: &DatabaseConnection,
token_hash: &str,
) -> GarrisonResult<Option<i64>> {
let stmt = Statement::from_sql_and_values(
DbBackend::Sqlite,
"SELECT rotated_at FROM refresh_tokens WHERE token_hash = ?",
vec![Value::String(Some(token_hash.to_string()))],
);
let row = conn
.query_one_raw(stmt)
.await
.map_err(|e| GarrisonError::Dao(format!("jwt-refresh-query::{}", e)))?;
match row {
Some(row) => row
.try_get::<Option<i64>>("", "rotated_at")
.map_err(|e| GarrisonError::Dao(format!("jwt-refresh-query::{}", e))),
None => Ok(None),
}
}
async fn has_children(conn: &DatabaseConnection, token_hash: &str) -> GarrisonResult<bool> {
let stmt = Statement::from_sql_and_values(
DbBackend::Sqlite,
"SELECT COUNT(*) AS cnt FROM refresh_tokens WHERE parent_token_hash = ?",
vec![Value::String(Some(token_hash.to_string()))],
);
let row = conn
.query_one_raw(stmt)
.await
.map_err(|e| GarrisonError::Dao(format!("jwt-refresh-query::{}", e)))?
.ok_or_else(|| GarrisonError::Dao("jwt-refresh-count-empty::".to_string()))?;
let count: i64 = row
.try_get("", "cnt")
.map_err(|e| GarrisonError::Dao(format!("jwt-refresh-query::{}", e)))?;
Ok(count > 0)
}
async fn dispose_reuse(
&self,
old_hash: &str,
subtype: RefreshTokenReuseSubtype,
) -> GarrisonResult<GarrisonError> {
let theft = match subtype {
RefreshTokenReuseSubtype::StaleLineage => true,
RefreshTokenReuseSubtype::RecentPrev | RefreshTokenReuseSubtype::OrphanedBranch => {
matches!(self.reuse_behaviour, RecentReuseBehaviour::TheftDetected)
},
};
if theft {
self.revoke_chain(old_hash).await?;
return Ok(GarrisonError::TokenRevoked(
"refresh token reuse detected, chain revoked".to_string(),
));
}
Ok(GarrisonError::InvalidToken(
"jwt-refresh-reuse-rejected::unauthorised".to_string(),
))
}
pub async fn detect_reuse(
&self,
token_hash: &str,
) -> GarrisonResult<Option<RefreshTokenReuseSubtype>> {
let session = self
.pool
.get_session("admin")
.await
.map_err(|e| GarrisonError::Dao(format!("jwt-refresh-get-session::{}", e)))?;
let conn = session
.connection()
.map_err(|e| GarrisonError::Dao(format!("jwt-refresh-get-conn::{}", e)))?;
let revoked = match Self::fetch_revoked(conn, token_hash).await? {
Some(revoked) => revoked,
None => return Ok(None),
};
if revoked != 1 {
return Ok(None);
}
Ok(Some(Self::classify_lineage(conn, token_hash).await?))
}
async fn fetch_revoked(
conn: &dbnexus::sea_orm::DatabaseConnection,
token_hash: &str,
) -> GarrisonResult<Option<i64>> {
let stmt = Statement::from_sql_and_values(
DbBackend::Sqlite,
"SELECT revoked FROM refresh_tokens WHERE token_hash = ?",
vec![Value::String(Some(token_hash.to_string()))],
);
let row = conn
.query_one_raw(stmt)
.await
.map_err(|e| GarrisonError::Dao(format!("jwt-refresh-query::{}", e)))?;
match row {
Some(row) => row
.try_get::<i64>("", "revoked")
.map(Some)
.map_err(|e| GarrisonError::Dao(format!("jwt-refresh-query::{}", e))),
None => Ok(None),
}
}
async fn classify_lineage(
conn: &dbnexus::sea_orm::DatabaseConnection,
token_hash: &str,
) -> GarrisonResult<RefreshTokenReuseSubtype> {
let mut frontier = vec![token_hash.to_string()];
for hop in 1..=REUSE_LINEAGE_MAX_DEPTH {
let mut next = Vec::new();
for parent in &frontier {
let stmt = Statement::from_sql_and_values(
DbBackend::Sqlite,
"SELECT token_hash, revoked FROM refresh_tokens \
WHERE parent_token_hash = ?",
vec![Value::String(Some(parent.clone()))],
);
let rows = conn.query_all_raw(stmt).await.map_err(|e| {
GarrisonError::Dao(format!("jwt-refresh-select-child::{}", e))
})?;
for row in rows {
let child_hash: String = row
.try_get("", "token_hash")
.map_err(|e| GarrisonError::Dao(format!("jwt-refresh-query::{}", e)))?;
let child_revoked: i64 = row
.try_get("", "revoked")
.map_err(|e| GarrisonError::Dao(format!("jwt-refresh-query::{}", e)))?;
if child_revoked == 0 {
return Ok(if hop == 1 {
RefreshTokenReuseSubtype::RecentPrev
} else {
RefreshTokenReuseSubtype::OrphanedBranch
});
}
next.push(child_hash);
}
}
if next.is_empty() {
return Ok(RefreshTokenReuseSubtype::StaleLineage);
}
frontier = next;
}
Ok(RefreshTokenReuseSubtype::OrphanedBranch)
}
pub async fn revoke_chain(&self, token_hash: &str) -> GarrisonResult<()> {
let session = self
.pool
.get_session("admin")
.await
.map_err(|e| GarrisonError::Dao(format!("jwt-refresh-get-session::{}", e)))?;
let conn = session
.connection()
.map_err(|e| GarrisonError::Dao(format!("jwt-refresh-get-conn::{}", e)))?;
let mut stack = vec![token_hash.to_string()];
while let Some(hash) = stack.pop() {
let update_stmt = Statement::from_sql_and_values(
DbBackend::Sqlite,
"UPDATE refresh_tokens SET revoked = 1 WHERE token_hash = ?",
vec![Value::String(Some(hash.clone()))],
);
conn.execute_raw(update_stmt)
.await
.map_err(|e| GarrisonError::Dao(format!("jwt-refresh-update::{}", e)))?;
{
let mut entries = self.grace_entries.lock().unwrap_or_else(|e| {
panic!(
"{}: {e}",
crate::i18n::translate_detail(
"jwt-refresh-grace-entries-lock-poisoned",
&[],
)
)
});
entries.remove(&hash);
}
let select_stmt = Statement::from_sql_and_values(
DbBackend::Sqlite,
"SELECT token_hash FROM refresh_tokens WHERE parent_token_hash = ?",
vec![Value::String(Some(hash))],
);
let rows = conn
.query_all_raw(select_stmt)
.await
.map_err(|e| GarrisonError::Dao(format!("jwt-refresh-select-child::{}", e)))?;
for row in rows {
let child_hash: String = row
.try_get("", "token_hash")
.map_err(|e| GarrisonError::Dao(format!("jwt-refresh-query::{}", e)))?;
stack.push(child_hash);
}
}
Ok(())
}
pub async fn cleanup_expired(&self) -> GarrisonResult<usize> {
let session = self.pool.get_session("admin").await.map_err(|e| {
GarrisonError::Dao(format!("jwt-refresh-cleanup-get-session::{}", e))
})?;
let conn = session
.connection()
.map_err(|e| GarrisonError::Dao(format!("jwt-refresh-cleanup-get-conn::{}", e)))?;
let threshold = Self::now_unix() - 7 * 86400;
let stmt = Statement::from_sql_and_values(
DbBackend::Sqlite,
"DELETE FROM refresh_tokens WHERE revoked = 1 AND expires_at < ?",
vec![Value::BigInt(Some(threshold))],
);
let result = conn
.execute_raw(stmt)
.await
.map_err(|e| GarrisonError::Dao(format!("jwt-refresh-cleanup-delete::{}", e)))?;
Ok(result.rows_affected() as usize)
}
}
}
#[cfg(feature = "db-sqlite")]
pub use service::RefreshTokenRotation;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn refresh_token_record_constructs_with_hash_chain_fields() {
let record = RefreshTokenRecord {
token_hash: "abc".to_string(),
parent_token_hash: Some("def".to_string()),
login_id: 1,
tenant_id: 0,
key_version: 1,
expires_at: 9999,
revoked: false,
created_at: 0,
rotated_at: None,
client_id: None,
scopes: None,
username: None,
user_id: None,
};
assert_eq!(record.token_hash, "abc");
assert_eq!(record.parent_token_hash, Some("def".to_string()));
assert_eq!(record.login_id, 1);
assert_eq!(record.tenant_id, 0);
assert_eq!(record.key_version, 1);
assert_eq!(record.expires_at, 9999);
assert!(!record.revoked);
assert_eq!(record.created_at, 0);
assert_eq!(record.rotated_at, None);
assert_eq!(record.client_id, None);
assert_eq!(record.scopes, None);
assert_eq!(record.username, None);
assert_eq!(record.user_id, None);
}
#[test]
fn refresh_token_record_requires_oauth2_fields() {
let json = r#"{
"token_hash": "abc123",
"parent_token_hash": null,
"login_id": 42,
"tenant_id": 1,
"key_version": 2,
"expires_at": 1700000000,
"revoked": false,
"created_at": 1699000000
}"#;
let result = serde_json::from_str::<RefreshTokenRecord>(json);
assert!(
result.is_err(),
"缺失 OAuth2 扩展字段的 JSON 应反序列化失败,实际: {:?}",
result
);
}
#[test]
fn refresh_token_record_new_json_roundtrip() {
let record = RefreshTokenRecord {
token_hash: "new_hash".to_string(),
parent_token_hash: Some("old_hash".to_string()),
login_id: 100,
tenant_id: 5,
key_version: 3,
expires_at: 1800000000,
revoked: false,
created_at: 1700000000,
rotated_at: Some(1699999000),
client_id: Some("client_123".to_string()),
scopes: Some("read write admin".to_string()),
username: Some("alice".to_string()),
user_id: Some(42),
};
let json = serde_json::to_string(&record).expect("序列化应成功");
let deserialized: RefreshTokenRecord = serde_json::from_str(&json).expect("反序列化应成功");
assert_eq!(record, deserialized);
}
}
#[cfg(all(test, feature = "protocol-jwt", feature = "db-sqlite"))]
mod db_sqlite_tests {
use super::{RefreshTokenReuseSubtype, RefreshTokenRotation};
use crate::config::RecentReuseBehaviour;
use crate::dao::{init_dbnexus, GarrisonMigration};
use crate::error::GarrisonError;
use crate::protocol::jwt::JwtHandler;
use dbnexus::sea_orm::{ConnectionTrait, DbBackend, Statement, Value};
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());
let applied = migration.migrate_core().await.expect("migrate_core 应成功");
assert!(applied >= 1, "migrate_core 应至少执行 1 个文件");
pool
}
#[cfg(feature = "loom-test")]
async fn setup_shared_db(name: &str) -> DbPool {
let url = format!("sqlite:file:{name}?mode=memory&cache=shared");
let pool = init_dbnexus(&url).await.expect("init_dbnexus 应成功");
let migration = GarrisonMigration::with_base_dir(pool.clone(), project_migrations_dir());
let applied = migration.migrate_core().await.expect("migrate_core 应成功");
assert!(applied >= 1, "migrate_core 应至少执行 1 个文件");
pool
}
#[tokio::test(flavor = "multi_thread")]
async fn refresh_tokens_table_exists_after_migration() {
let pool = setup_db().await;
let session = pool.get_session("admin").await.unwrap();
let conn = session.connection().unwrap();
let stmt = Statement::from_sql_and_values(
DbBackend::Sqlite,
"SELECT name FROM sqlite_master WHERE type='table' AND name='refresh_tokens'",
vec![],
);
let rows = conn.query_all_raw(stmt).await.expect("query_all 应成功");
assert_eq!(
rows.len(),
1,
"refresh_tokens 表应存在(迁移后 sqlite_master 应有 1 行记录)"
);
}
fn sha256_hex(s: &str) -> String {
use sha2::{Digest, Sha256};
let mut hasher = Sha256::new();
hasher.update(s.as_bytes());
let result = hasher.finalize();
result.iter().map(|b| format!("{:02x}", b)).collect()
}
async fn insert_refresh_token(
pool: &DbPool,
token_hash: &str,
parent_token_hash: Option<&str>,
login_id: i64,
tenant_id: i64,
key_version: u32,
expires_at: i64,
revoked: i64,
) {
let session = pool.get_session("admin").await.unwrap();
let conn = session.connection().unwrap();
let stmt = Statement::from_sql_and_values(
DbBackend::Sqlite,
"INSERT INTO refresh_tokens (token_hash, parent_token_hash, login_id, tenant_id, key_version, expires_at, revoked, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
vec![
Value::String(Some(token_hash.to_string())),
Value::String(parent_token_hash.map(|s| s.to_string())),
Value::BigInt(Some(login_id)),
Value::BigInt(Some(tenant_id)),
Value::BigInt(Some(key_version as i64)),
Value::BigInt(Some(expires_at)),
Value::BigInt(Some(revoked)),
Value::BigInt(Some(0)),
],
);
conn.execute_raw(stmt).await.expect("INSERT 应成功");
}
async fn query_revoked(pool: &DbPool, token_hash: &str) -> i64 {
let session = pool.get_session("admin").await.unwrap();
let conn = session.connection().unwrap();
let stmt = Statement::from_sql_and_values(
DbBackend::Sqlite,
"SELECT revoked FROM refresh_tokens WHERE token_hash = ?",
vec![Value::String(Some(token_hash.to_string()))],
);
let row = conn
.query_one_raw(stmt)
.await
.unwrap()
.expect("record 应存在");
row.try_get::<i64>("", "revoked").unwrap()
}
async fn query_record(pool: &DbPool, token_hash: &str) -> (Option<String>, i64) {
let session = pool.get_session("admin").await.unwrap();
let conn = session.connection().unwrap();
let stmt = Statement::from_sql_and_values(
DbBackend::Sqlite,
"SELECT parent_token_hash, revoked FROM refresh_tokens WHERE token_hash = ?",
vec![Value::String(Some(token_hash.to_string()))],
);
let row = conn
.query_one_raw(stmt)
.await
.unwrap()
.expect("record 应存在");
let parent: Option<String> = row.try_get("", "parent_token_hash").ok();
let revoked: i64 = row.try_get("", "revoked").unwrap();
(parent, revoked)
}
#[tokio::test(flavor = "multi_thread")]
async fn rotate_inserts_new_token_and_marks_old_consumed() {
let pool = setup_db().await;
let old_token = "old_token_value";
let old_hash = sha256_hex(old_token);
insert_refresh_token(&pool, &old_hash, None, 1, 0, 1, 9999, 0).await;
let jwt_handler = Arc::new(JwtHandler::new("test_secret_that_is_at_least_32_bytes"));
let rotation =
RefreshTokenRotation::new(pool.clone(), jwt_handler, Arc::new(RwLock::new(1)));
let (new_access, new_refresh) = rotation.rotate(old_token).await.expect("rotate 应成功");
assert!(!new_access.is_empty(), "new_access 应非空");
assert!(!new_refresh.is_empty(), "new_refresh 应非空");
let old_revoked = query_revoked(&pool, &old_hash).await;
assert_eq!(old_revoked, 1, "old_token 应标记为 revoked");
let new_hash = sha256_hex(&new_refresh);
let (parent, revoked) = query_record(&pool, &new_hash).await;
assert_eq!(
parent,
Some(old_hash),
"new record 的 parent_token_hash 应等于 old_hash"
);
assert_eq!(revoked, 0, "new record 应未 revoked");
}
#[tokio::test(flavor = "multi_thread")]
async fn detect_reuse_returns_true_when_token_already_consumed() {
let pool = setup_db().await;
let old_token = "old_token_value";
let old_hash = sha256_hex(old_token);
insert_refresh_token(&pool, &old_hash, None, 1, 0, 1, 9999, 0).await;
let jwt_handler = Arc::new(JwtHandler::new("test_secret_that_is_at_least_32_bytes"));
let rotation =
RefreshTokenRotation::new(pool.clone(), jwt_handler, Arc::new(RwLock::new(1)));
let (_, new_refresh) = rotation.rotate(old_token).await.expect("rotate 应成功");
let reused = rotation
.detect_reuse(&old_hash)
.await
.expect("detect_reuse 应成功");
assert!(reused.is_some(), "已 revoked 的 token 应检测为 reuse");
let new_hash = sha256_hex(&new_refresh);
let new_reused = rotation
.detect_reuse(&new_hash)
.await
.expect("detect_reuse 应成功");
assert!(new_reused.is_none(), "未 revoked 的 token 不应检测为 reuse");
}
#[tokio::test(flavor = "multi_thread")]
async fn recent_prev_detected_when_parent_hash_matches() {
let pool = setup_db().await;
let jwt_handler = Arc::new(JwtHandler::new("test_secret_that_is_at_least_32_bytes"));
let rotation =
RefreshTokenRotation::new(pool.clone(), jwt_handler, Arc::new(RwLock::new(1)));
let t1 = rotation
.issue("client", Some(1), &[], None, 1, 0, 9999)
.await
.expect("issue 应成功");
let (_, _t2) = rotation.rotate(&t1).await.expect("rotate 应成功");
let t1_hash = sha256_hex(&t1);
let subtype = rotation
.detect_reuse(&t1_hash)
.await
.expect("detect_reuse 应成功");
assert_eq!(
subtype,
Some(RefreshTokenReuseSubtype::RecentPrev),
"命中存活链头的 parent_token_hash 应分类为 RecentPrev,实际: {subtype:?}"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn orphaned_branch_detected_when_ancestor_hash_matches() {
let pool = setup_db().await;
let jwt_handler = Arc::new(JwtHandler::new("test_secret_that_is_at_least_32_bytes"));
let rotation =
RefreshTokenRotation::new(pool.clone(), jwt_handler, Arc::new(RwLock::new(1)));
let t1 = rotation
.issue("client", Some(1), &[], None, 1, 0, 9999)
.await
.expect("issue 应成功");
let (_, t2) = rotation.rotate(&t1).await.expect("第一次 rotate 应成功");
let (_, _t3) = rotation.rotate(&t2).await.expect("第二次 rotate 应成功");
let t2_hash = sha256_hex(&t2);
let t2_subtype = rotation
.detect_reuse(&t2_hash)
.await
.expect("detect_reuse 应成功");
assert_eq!(
t2_subtype,
Some(RefreshTokenReuseSubtype::RecentPrev),
"1 跳祖先应分类为 RecentPrev,实际: {t2_subtype:?}"
);
let t1_hash = sha256_hex(&t1);
let t1_subtype = rotation
.detect_reuse(&t1_hash)
.await
.expect("detect_reuse 应成功");
assert_eq!(
t1_subtype,
Some(RefreshTokenReuseSubtype::OrphanedBranch),
">1 跳祖先应分类为 OrphanedBranch,实际: {t1_subtype:?}"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn stale_lineage_when_no_relation() {
let pool = setup_db().await;
let jwt_handler = Arc::new(JwtHandler::new("test_secret_that_is_at_least_32_bytes"));
let rotation =
RefreshTokenRotation::new(pool.clone(), jwt_handler, Arc::new(RwLock::new(1)));
let orphan_hash = sha256_hex("orphan_token_value");
insert_refresh_token(&pool, &orphan_hash, None, 1, 0, 1, 9999, 1).await;
let orphan_subtype = rotation
.detect_reuse(&orphan_hash)
.await
.expect("detect_reuse 应成功");
assert_eq!(
orphan_subtype,
Some(RefreshTokenReuseSubtype::StaleLineage),
"无子代的已消费 token 应分类为 StaleLineage,实际: {orphan_subtype:?}"
);
let t1 = rotation
.issue("client", Some(1), &[], None, 1, 0, 9999)
.await
.expect("issue 应成功");
let (_, _t2) = rotation.rotate(&t1).await.expect("rotate 应成功");
let t1_hash = sha256_hex(&t1);
rotation
.revoke_chain(&t1_hash)
.await
.expect("revoke_chain 应成功");
let revoked_subtype = rotation
.detect_reuse(&t1_hash)
.await
.expect("detect_reuse 应成功");
assert_eq!(
revoked_subtype,
Some(RefreshTokenReuseSubtype::StaleLineage),
"整链吊销后的再呈现应分类为 StaleLineage,实际: {revoked_subtype:?}"
);
let t3 = rotation
.issue("client", Some(1), &[], None, 1, 0, 9999)
.await
.expect("issue 应成功");
let live_subtype = rotation
.detect_reuse(&sha256_hex(&t3))
.await
.expect("detect_reuse 应成功");
assert_eq!(live_subtype, None, "存活 token 不应检出重用");
let unknown_subtype = rotation
.detect_reuse(&sha256_hex("never_issued_token"))
.await
.expect("detect_reuse 应成功");
assert_eq!(unknown_subtype, None, "未知 token 不应检出重用");
}
#[tokio::test(flavor = "multi_thread")]
async fn recent_prev_disposal_unauthorised_keeps_chain() {
let pool = setup_db().await;
let jwt_handler = Arc::new(JwtHandler::new("test_secret_that_is_at_least_32_bytes"));
let rotation =
RefreshTokenRotation::new(pool.clone(), jwt_handler, Arc::new(RwLock::new(1)))
.with_reuse_behaviour(RecentReuseBehaviour::Unauthorised);
let t1 = rotation
.issue("client", Some(1), &[], None, 1, 0, 9999)
.await
.expect("issue 应成功");
let (_, t2) = rotation.rotate(&t1).await.expect("rotate 应成功");
let t2_hash = sha256_hex(&t2);
let result = rotation.rotate(&t1).await;
assert!(
matches!(result, Err(GarrisonError::InvalidToken(ref msg)) if msg.contains("unauthorised")),
"Unauthorised 处置应返回 InvalidToken,实际: {:?}",
result
);
let t2_revoked = query_revoked(&pool, &t2_hash).await;
assert_eq!(t2_revoked, 0, "Unauthorised 处置不得吊销存活链头");
}
#[tokio::test(flavor = "multi_thread")]
async fn orphaned_branch_disposal_unauthorised_keeps_chain() {
let pool = setup_db().await;
let jwt_handler = Arc::new(JwtHandler::new("test_secret_that_is_at_least_32_bytes"));
let rotation =
RefreshTokenRotation::new(pool.clone(), jwt_handler, Arc::new(RwLock::new(1)))
.with_reuse_behaviour(RecentReuseBehaviour::Unauthorised);
let t1 = rotation
.issue("client", Some(1), &[], None, 1, 0, 9999)
.await
.expect("issue 应成功");
let (_, t2) = rotation.rotate(&t1).await.expect("第一次 rotate 应成功");
let (_, t3) = rotation.rotate(&t2).await.expect("第二次 rotate 应成功");
let t2_hash = sha256_hex(&t2);
let t3_hash = sha256_hex(&t3);
let result = rotation.rotate(&t1).await;
assert!(
matches!(result, Err(GarrisonError::InvalidToken(_))),
"OrphanedBranch 在 Unauthorised 下应返回 InvalidToken,实际: {:?}",
result
);
assert_eq!(
query_revoked(&pool, &t2_hash).await,
1,
"t2 应保持 rotate 时的已消费态"
);
assert_eq!(
query_revoked(&pool, &t3_hash).await,
0,
"存活链头不得被吊销"
);
}
async fn setup_single_connection_db() -> DbPool {
let config = dbnexus::DbConfig {
url: "sqlite::memory:".to_string(),
pool_config: dbnexus::PoolConfig {
max_connections: 1,
min_connections: 1,
acquire_timeout: 15_000,
..Default::default()
},
..Default::default()
};
let pool = dbnexus::DbPool::with_config(config)
.await
.expect("初始化单连接 dbnexus 池应成功");
let migration = GarrisonMigration::with_base_dir(pool.clone(), project_migrations_dir());
let applied = migration.migrate_core().await.expect("migrate_core 应成功");
assert!(applied >= 1, "migrate_core 应至少执行 1 个文件");
pool
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn grace_window_concurrent_double_refresh_returns_same_token() {
let pool = setup_single_connection_db().await;
let jwt_handler = Arc::new(JwtHandler::new("test_secret_that_is_at_least_32_bytes"));
let rotation = Arc::new(
RefreshTokenRotation::new(pool.clone(), jwt_handler, Arc::new(RwLock::new(1)))
.with_grace_window(60, 1),
);
let t1 = rotation
.issue("client", Some(1), &[], None, 1, 0, 9999)
.await
.expect("issue 应成功");
let t1_hash = sha256_hex(&t1);
let mut set = tokio::task::JoinSet::new();
for _ in 0..2 {
let rotation = rotation.clone();
let token = t1.clone();
set.spawn(async move { rotation.rotate(&token).await });
}
let mut refreshes = Vec::new();
while let Some(result) = set.join_next().await {
let (_, refresh) = result
.expect("并发 rotate task 不应 panic")
.expect("宽限窗口内并发双刷应成功");
refreshes.push(refresh);
}
assert_eq!(refreshes.len(), 2, "双方都应成功");
assert_eq!(
refreshes[0], refreshes[1],
"宽限窗口内并发双刷应得到同一新 token"
);
let session = pool.get_session("admin").await.unwrap();
let conn = session.connection().unwrap();
let stmt = Statement::from_sql_and_values(
DbBackend::Sqlite,
"SELECT COUNT(*) AS cnt FROM refresh_tokens WHERE parent_token_hash = ?",
vec![Value::String(Some(t1_hash))],
);
let row = conn.query_one_raw(stmt).await.unwrap().unwrap();
assert_eq!(
row.try_get::<i64>("", "cnt").unwrap(),
1,
"不应产生重复子代"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn grace_window_expired_old_token_follows_reuse_disposal() {
let pool = setup_db().await;
let jwt_handler = Arc::new(JwtHandler::new("test_secret_that_is_at_least_32_bytes"));
let rotation =
RefreshTokenRotation::new(pool.clone(), jwt_handler, Arc::new(RwLock::new(1)))
.with_grace_window(60, 1);
let t1 = rotation
.issue("client", Some(1), &[], None, 1, 0, 9999)
.await
.expect("issue 应成功");
let (_, t2) = rotation.rotate(&t1).await.expect("rotate 应成功");
let t2_hash = sha256_hex(&t2);
let session = pool.get_session("admin").await.unwrap();
let conn = session.connection().unwrap();
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.expect("系统时钟应晚于 UNIX_EPOCH")
.as_secs() as i64;
let backdate = now - 120;
let stmt = Statement::from_sql_and_values(
DbBackend::Sqlite,
"UPDATE refresh_tokens SET rotated_at = ? WHERE token_hash = ?",
vec![
Value::BigInt(Some(backdate)),
Value::String(Some(sha256_hex(&t1))),
],
);
conn.execute_raw(stmt).await.expect("backdate 应成功");
drop(session);
let result = rotation.rotate(&t1).await;
assert!(
matches!(result, Err(GarrisonError::TokenRevoked(_))),
"窗口外旧 token 应按盗用处置,实际: {:?}",
result
);
assert_eq!(query_revoked(&pool, &t2_hash).await, 1, "链应被吊销");
}
#[tokio::test(flavor = "multi_thread")]
async fn grace_window_exhausted_uses_follow_disposal() {
let pool = setup_db().await;
let jwt_handler = Arc::new(JwtHandler::new("test_secret_that_is_at_least_32_bytes"));
let rotation =
RefreshTokenRotation::new(pool.clone(), jwt_handler, Arc::new(RwLock::new(1)))
.with_grace_window(60, 1);
let t1 = rotation
.issue("client", Some(1), &[], None, 1, 0, 9999)
.await
.expect("issue 应成功");
let (_, t2) = rotation.rotate(&t1).await.expect("rotate 应成功");
let t2_hash = sha256_hex(&t2);
let (_, graced) = rotation.rotate(&t1).await.expect("预算内重放应兑现");
assert_eq!(graced, t2, "窗口内兑现应返回既有新 token");
let result = rotation.rotate(&t1).await;
assert!(
matches!(result, Err(GarrisonError::TokenRevoked(_))),
"预算耗尽后应按盗用处置,实际: {:?}",
result
);
assert_eq!(query_revoked(&pool, &t2_hash).await, 1, "链应被吊销");
}
#[tokio::test(flavor = "multi_thread")]
async fn grace_window_inflight_winner_deleted_child_redeems_same_token() {
let pool = setup_db().await;
let jwt_handler = Arc::new(JwtHandler::new("test_secret_that_is_at_least_32_bytes"));
let rotation = Arc::new(
RefreshTokenRotation::new(pool.clone(), jwt_handler, Arc::new(RwLock::new(1)))
.with_grace_window(60, 1),
);
let t1 = rotation
.issue("client", Some(1), &[], None, 1, 0, 9999)
.await
.expect("issue 应成功");
let t1_hash = sha256_hex(&t1);
let (_, t2) = rotation.rotate(&t1).await.expect("rotate 应成功");
let t2_hash = sha256_hex(&t2);
{
let session = pool.get_session("admin").await.unwrap();
let conn = session.connection().unwrap();
let stmt = Statement::from_sql_and_values(
DbBackend::Sqlite,
"DELETE FROM refresh_tokens WHERE token_hash = ?",
vec![Value::String(Some(t2_hash.clone()))],
);
conn.execute_raw(stmt).await.expect("删除子代应成功");
}
let (_, graced) = rotation.rotate(&t1).await.expect("在途竞态兑现应成功");
assert_eq!(
graced, t2,
"在途胜者窗口内的重放应兑现与胜者相同的既有新 token"
);
let session = pool.get_session("admin").await.unwrap();
let conn = session.connection().unwrap();
let stmt = Statement::from_sql_and_values(
DbBackend::Sqlite,
"SELECT COUNT(*) AS cnt FROM refresh_tokens WHERE parent_token_hash = ?",
vec![Value::String(Some(t1_hash))],
);
let row = conn.query_one_raw(stmt).await.unwrap().unwrap();
assert_eq!(row.try_get::<i64>("", "cnt").unwrap(), 0, "兑现不应重旋转");
}
#[tokio::test(flavor = "multi_thread")]
async fn grace_window_race_wait_timeout_follows_disposal() {
let pool = setup_db().await;
let jwt_handler = Arc::new(JwtHandler::new("test_secret_that_is_at_least_32_bytes"));
let rotation =
RefreshTokenRotation::new(pool.clone(), jwt_handler, Arc::new(RwLock::new(1)))
.with_grace_window(60, 1);
let old_token = "inflight-lost-grace-entry-token";
let old_hash = sha256_hex(old_token);
insert_refresh_token(&pool, &old_hash, None, 1, 1, 1, 9999, 1).await;
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs() as i64;
{
let session = pool.get_session("admin").await.unwrap();
let conn = session.connection().unwrap();
let stmt = Statement::from_sql_and_values(
DbBackend::Sqlite,
"UPDATE refresh_tokens SET rotated_at = ? WHERE token_hash = ?",
vec![
Value::BigInt(Some(now)),
Value::String(Some(old_hash.clone())),
],
);
conn.execute_raw(stmt)
.await
.expect("写入 rotated_at 应成功");
}
let result = rotation.rotate(old_token).await;
assert!(
matches!(result, Err(GarrisonError::TokenRevoked(_))),
"竞态等待超时后应按盗用处置,实际: {:?}",
result
);
assert_eq!(query_revoked(&pool, &old_hash).await, 1, "链应被吊销");
}
#[tokio::test(flavor = "multi_thread")]
async fn grace_disabled_by_default_keeps_theft_semantics() {
let pool = setup_db().await;
let jwt_handler = Arc::new(JwtHandler::new("test_secret_that_is_at_least_32_bytes"));
let rotation =
RefreshTokenRotation::new(pool.clone(), jwt_handler, Arc::new(RwLock::new(1)));
let t1 = rotation
.issue("client", Some(1), &[], None, 1, 0, 9999)
.await
.expect("issue 应成功");
let (_, t2) = rotation.rotate(&t1).await.expect("rotate 应成功");
let t2_hash = sha256_hex(&t2);
let result = rotation.rotate(&t1).await;
assert!(
matches!(result, Err(GarrisonError::TokenRevoked(_))),
"默认配置下窗口内重放应按盗用处置,实际: {:?}",
result
);
assert_eq!(query_revoked(&pool, &t2_hash).await, 1, "链应被吊销");
}
#[tokio::test(flavor = "multi_thread")]
async fn rotate_insert_failure_compensates_and_keeps_chain_usable() {
let pool = setup_db().await;
let jwt_handler = Arc::new(JwtHandler::new("test_secret_that_is_at_least_32_bytes"));
let rotation =
RefreshTokenRotation::new(pool.clone(), jwt_handler, Arc::new(RwLock::new(1)));
let t1 = rotation
.issue("client", Some(1), &[], None, 1, 0, 9999)
.await
.expect("issue 应成功");
let t1_hash = sha256_hex(&t1);
let trigger_sql = "CREATE TRIGGER fail_rotate_insert BEFORE INSERT ON refresh_tokens \
BEGIN SELECT RAISE(ABORT, 'injected insert failure'); END;";
let session = pool.get_session("admin").await.unwrap();
let conn = session.connection().unwrap();
conn.execute_raw(Statement::from_sql_and_values(
DbBackend::Sqlite,
trigger_sql,
vec![],
))
.await
.expect("创建注入触发器应成功");
drop(session);
let result = rotation.rotate(&t1).await;
assert!(
matches!(result, Err(GarrisonError::Dao(ref msg)) if msg.contains("rolled-back")),
"注入失败应返回标注 rolled-back 的 Dao 错误,实际: {:?}",
result
);
let session = pool.get_session("admin").await.unwrap();
let conn = session.connection().unwrap();
let children = conn
.query_one_raw(Statement::from_sql_and_values(
DbBackend::Sqlite,
"SELECT COUNT(*) AS cnt FROM refresh_tokens WHERE parent_token_hash = ?",
vec![Value::String(Some(t1_hash.clone()))],
))
.await
.expect("COUNT 应成功")
.expect("应有结果行");
assert_eq!(
children.try_get::<i64>("", "cnt").unwrap(),
0,
"补偿后不得残留半成品子代"
);
let restored = conn
.query_one_raw(Statement::from_sql_and_values(
DbBackend::Sqlite,
"SELECT revoked, rotated_at FROM refresh_tokens WHERE token_hash = ?",
vec![Value::String(Some(t1_hash.clone()))],
))
.await
.expect("查询应成功")
.expect("原 token 记录应存在");
assert_eq!(
restored.try_get::<i64>("", "revoked").unwrap(),
0,
"原 token 应恢复 revoked=0"
);
let rotated_at: Option<i64> = restored.try_get("", "rotated_at").unwrap();
assert_eq!(rotated_at, None, "原 token 的 rotated_at 应回退为 NULL");
drop(session);
let session = pool.get_session("admin").await.unwrap();
let conn = session.connection().unwrap();
conn.execute_raw(Statement::from_sql_and_values(
DbBackend::Sqlite,
"DROP TRIGGER fail_rotate_insert",
vec![],
))
.await
.expect("移除注入触发器应成功");
drop(session);
let (_, retried) = rotation.rotate(&t1).await.expect("补偿后原链应可再次轮换");
assert!(!retried.is_empty(), "重试轮换应产出新 token");
}
#[tokio::test(flavor = "multi_thread")]
async fn stale_lineage_disposal_overrides_unauthorised() {
let pool = setup_db().await;
let jwt_handler = Arc::new(JwtHandler::new("test_secret_that_is_at_least_32_bytes"));
let rotation =
RefreshTokenRotation::new(pool.clone(), jwt_handler, Arc::new(RwLock::new(1)))
.with_reuse_behaviour(RecentReuseBehaviour::Unauthorised);
let t1 = rotation
.issue("client", Some(1), &[], None, 1, 0, 9999)
.await
.expect("issue 应成功");
let (_, t2) = rotation.rotate(&t1).await.expect("rotate 应成功");
let t2_hash = sha256_hex(&t2);
rotation
.revoke_chain(&sha256_hex(&t1))
.await
.expect("revoke_chain 应成功");
let result = rotation.rotate(&t1).await;
assert!(
matches!(result, Err(GarrisonError::TokenRevoked(_))),
"StaleLineage 在 Unauthorised 下仍应返回 TokenRevoked,实际: {:?}",
result
);
assert_eq!(query_revoked(&pool, &t2_hash).await, 1, "链应保持吊销");
}
#[tokio::test(flavor = "multi_thread")]
async fn revoke_chain_revokes_all_parent_tokens() {
let pool = setup_db().await;
let t1_hash = sha256_hex("t1");
let t2_hash = sha256_hex("t2");
let t3_hash = sha256_hex("t3");
insert_refresh_token(&pool, &t1_hash, None, 1, 0, 1, 9999, 0).await;
insert_refresh_token(&pool, &t2_hash, Some(&t1_hash), 1, 0, 1, 9999, 0).await;
insert_refresh_token(&pool, &t3_hash, Some(&t2_hash), 1, 0, 1, 9999, 0).await;
let jwt_handler = Arc::new(JwtHandler::new("test_secret_that_is_at_least_32_bytes"));
let rotation =
RefreshTokenRotation::new(pool.clone(), jwt_handler, Arc::new(RwLock::new(1)));
rotation
.revoke_chain(&t1_hash)
.await
.expect("revoke_chain 应成功");
assert_eq!(query_revoked(&pool, &t1_hash).await, 1, "t1 应 revoked");
assert_eq!(
query_revoked(&pool, &t2_hash).await,
1,
"t2 应 revoked(子代)"
);
assert_eq!(
query_revoked(&pool, &t3_hash).await,
1,
"t3 应 revoked(孙代)"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn rotate_with_reuse_detection_revokes_chain() {
let pool = setup_db().await;
let t1_token = "t1_token_value";
let t1_hash = sha256_hex(t1_token);
insert_refresh_token(&pool, &t1_hash, None, 1, 0, 1, 9999, 0).await;
let jwt_handler = Arc::new(JwtHandler::new("test_secret_that_is_at_least_32_bytes"));
let rotation =
RefreshTokenRotation::new(pool.clone(), jwt_handler, Arc::new(RwLock::new(1)));
let (_, t2_refresh) = rotation
.rotate(t1_token)
.await
.expect("第一次 rotate 应成功");
let t2_hash = sha256_hex(&t2_refresh);
let result = rotation.rotate(t1_token).await;
assert!(
matches!(result, Err(GarrisonError::TokenRevoked(_))),
"重用已消费的 refresh token 应返回 TokenRevoked,实际: {:?}",
result
);
assert_eq!(
query_revoked(&pool, &t1_hash).await,
1,
"t1 应 revoked(重用检测后)"
);
assert_eq!(
query_revoked(&pool, &t2_hash).await,
1,
"t2 应 revoked(链被吊销)"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn issue_creates_record_with_correct_fields() {
let pool = setup_db().await;
let jwt_handler = Arc::new(JwtHandler::new("test_secret_that_is_at_least_32_bytes"));
let rotation =
RefreshTokenRotation::new(pool.clone(), jwt_handler, Arc::new(RwLock::new(2)));
let scopes = vec!["read".to_string(), "write".to_string()];
let refresh_token = rotation
.issue(
"client_abc",
Some(42),
&scopes,
Some("alice"),
42,
5,
86400 * 7,
)
.await
.expect("issue 应成功");
let record = rotation
.validate(&refresh_token)
.await
.expect("validate 应成功")
.expect("record 应存在");
assert_eq!(
record.parent_token_hash, None,
"首次签发 parent_token_hash 应为 None"
);
assert!(!record.revoked, "新签发的 token 应未 revoked");
assert_eq!(record.tenant_id, 5);
assert_eq!(record.key_version, 2);
assert_eq!(record.login_id, 42);
assert_eq!(record.client_id, Some("client_abc".to_string()));
assert_eq!(record.scopes, Some("read write".to_string()));
assert_eq!(record.username, Some("alice".to_string()));
assert_eq!(record.user_id, Some(42));
}
#[tokio::test(flavor = "multi_thread")]
async fn issue_with_empty_scopes_stores_none() {
let pool = setup_db().await;
let jwt_handler = Arc::new(JwtHandler::new("test_secret_that_is_at_least_32_bytes"));
let rotation =
RefreshTokenRotation::new(pool.clone(), jwt_handler, Arc::new(RwLock::new(1)));
let refresh_token = rotation
.issue(
"client_xyz",
None, &[], None,
0,
0,
3600,
)
.await
.expect("issue 应成功");
let record = rotation
.validate(&refresh_token)
.await
.expect("validate 应成功")
.expect("record 应存在");
assert_eq!(record.scopes, None, "空 scopes 列表应存储为 None");
assert_eq!(record.user_id, None, "client_credentials 无 user_id");
assert_eq!(record.username, None);
}
#[tokio::test(flavor = "multi_thread")]
async fn validate_returns_some_for_valid_token() {
let pool = setup_db().await;
let jwt_handler = Arc::new(JwtHandler::new("test_secret_that_is_at_least_32_bytes"));
let rotation =
RefreshTokenRotation::new(pool.clone(), jwt_handler, Arc::new(RwLock::new(1)));
let refresh_token = rotation
.issue("client_1", Some(1), &["read".to_string()], None, 1, 0, 3600)
.await
.expect("issue 应成功");
let result = rotation
.validate(&refresh_token)
.await
.expect("validate 应成功");
assert!(result.is_some(), "有效 token 应返回 Some");
}
#[tokio::test(flavor = "multi_thread")]
async fn validate_returns_none_for_revoked_token() {
let pool = setup_db().await;
let jwt_handler = Arc::new(JwtHandler::new("test_secret_that_is_at_least_32_bytes"));
let rotation =
RefreshTokenRotation::new(pool.clone(), jwt_handler, Arc::new(RwLock::new(1)));
let refresh_token = rotation
.issue("client_1", Some(1), &["read".to_string()], None, 1, 0, 3600)
.await
.expect("issue 应成功");
let _ = rotation
.rotate(&refresh_token)
.await
.expect("rotate 应成功");
let result = rotation
.validate(&refresh_token)
.await
.expect("validate 应成功");
assert!(result.is_none(), "已 revoked token 应返回 None");
}
#[tokio::test(flavor = "multi_thread")]
async fn validate_returns_none_for_nonexistent_token() {
let pool = setup_db().await;
let jwt_handler = Arc::new(JwtHandler::new("test_secret_that_is_at_least_32_bytes"));
let rotation =
RefreshTokenRotation::new(pool.clone(), jwt_handler, Arc::new(RwLock::new(1)));
let result = rotation
.validate("nonexistent_token_12345")
.await
.expect("validate 应成功");
assert!(result.is_none(), "不存在的 token 应返回 None");
}
#[tokio::test(flavor = "multi_thread")]
async fn rotate_inherits_oauth2_fields() {
let pool = setup_db().await;
let jwt_handler = Arc::new(JwtHandler::new("test_secret_that_is_at_least_32_bytes"));
let rotation =
RefreshTokenRotation::new(pool.clone(), jwt_handler, Arc::new(RwLock::new(1)));
let scopes = vec!["admin".to_string(), "read".to_string()];
let old_token = rotation
.issue(
"client_inherit",
Some(99),
&scopes,
Some("bob"),
99,
3,
86400,
)
.await
.expect("issue 应成功");
let old_hash = sha256_hex(&old_token);
let (_, new_refresh) = rotation.rotate(&old_token).await.expect("rotate 应成功");
let new_record = rotation
.validate(&new_refresh)
.await
.expect("validate 应成功")
.expect("新 token 应存在");
assert_eq!(new_record.client_id, Some("client_inherit".to_string()));
assert_eq!(new_record.scopes, Some("admin read".to_string()));
assert_eq!(new_record.username, Some("bob".to_string()));
assert_eq!(new_record.user_id, Some(99));
assert_eq!(
new_record.parent_token_hash,
Some(old_hash),
"新记录 parent_token_hash 应指向旧记录 token_hash"
);
let old_record = rotation
.validate(&old_token)
.await
.expect("validate 应成功");
assert!(old_record.is_none(), "旧 token 应已 revoked");
}
#[tokio::test(flavor = "multi_thread")]
async fn rotate_old_record_with_null_new_fields_inherits_none() {
let pool = setup_db().await;
let jwt_handler = Arc::new(JwtHandler::new("test_secret_that_is_at_least_32_bytes"));
let rotation =
RefreshTokenRotation::new(pool.clone(), jwt_handler, Arc::new(RwLock::new(1)));
let old_token = "rotation_source_token";
let old_hash = sha256_hex(old_token);
insert_refresh_token(&pool, &old_hash, None, 1, 0, 1, 9999, 0).await;
let (_, new_refresh) = rotation.rotate(old_token).await.expect("rotate 应成功");
let new_record = rotation
.validate(&new_refresh)
.await
.expect("validate 应成功")
.expect("新 token 应存在");
assert_eq!(
new_record.client_id, None,
"旧记录 client_id 为 NULL,新记录应继承 None"
);
assert_eq!(new_record.scopes, None);
assert_eq!(new_record.username, None);
assert_eq!(new_record.user_id, None);
}
async fn count_records(pool: &DbPool) -> usize {
let session = pool.get_session("admin").await.unwrap();
let conn = session.connection().unwrap();
let stmt = Statement::from_sql_and_values(
DbBackend::Sqlite,
"SELECT COUNT(*) AS cnt FROM refresh_tokens",
vec![],
);
let row = conn
.query_one_raw(stmt)
.await
.expect("COUNT 应成功")
.expect("应有结果");
row.try_get::<i64>("", "cnt").unwrap() as usize
}
#[tokio::test(flavor = "multi_thread")]
async fn cleanup_expired_deletes_only_revoked_and_expired() {
let pool = setup_db().await;
let jwt_handler = Arc::new(JwtHandler::new("test_secret_that_is_at_least_32_bytes"));
let rotation =
RefreshTokenRotation::new(pool.clone(), jwt_handler, Arc::new(RwLock::new(1)));
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs() as i64;
let seven_days_ago = now - 7 * 86400;
insert_refresh_token(
&pool,
"hash_revoked_expired",
None,
1,
0,
1,
seven_days_ago - 86400 * 23,
1,
)
.await;
insert_refresh_token(
&pool,
"hash_active_expired",
None,
2,
0,
1,
seven_days_ago - 86400 * 3,
0,
)
.await;
insert_refresh_token(
&pool,
"hash_revoked_within_grace",
None,
3,
0,
1,
seven_days_ago + 86400 * 4,
1,
)
.await;
insert_refresh_token(
&pool,
"hash_active_valid",
None,
4,
0,
1,
now + 86400 * 7,
0,
)
.await;
assert_eq!(count_records(&pool).await, 4, "cleanup 前应有 4 条记录");
let deleted = rotation
.cleanup_expired()
.await
.expect("cleanup_expired 应成功");
assert_eq!(
deleted, 1,
"应仅删除 1 条记录(revoked=1 且 expires_at 超过 grace period)"
);
let remaining = count_records(&pool).await;
assert_eq!(remaining, 3, "应剩余 3 条记录");
let session = pool.get_session("admin").await.unwrap();
let conn = session.connection().unwrap();
let stmt = Statement::from_sql_and_values(
DbBackend::Sqlite,
"SELECT token_hash FROM refresh_tokens ORDER BY token_hash",
vec![],
);
let rows = conn.query_all_raw(stmt).await.expect("SELECT 应成功");
let hashes: Vec<String> = rows
.iter()
.map(|r| r.try_get::<String>("", "token_hash").unwrap())
.collect();
assert!(
hashes.contains(&"hash_active_expired".to_string()),
"未撤销的过期记录应保留"
);
assert!(
hashes.contains(&"hash_revoked_within_grace".to_string()),
"grace period 内的撤销记录应保留"
);
assert!(
hashes.contains(&"hash_active_valid".to_string()),
"有效记录应保留"
);
assert!(
!hashes.contains(&"hash_revoked_expired".to_string()),
"已撤销且过期超过 grace period 的记录应被删除"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn cleanup_expired_returns_zero_when_nothing_to_clean() {
let pool = setup_db().await;
let jwt_handler = Arc::new(JwtHandler::new("test_secret_that_is_at_least_32_bytes"));
let rotation =
RefreshTokenRotation::new(pool.clone(), jwt_handler, Arc::new(RwLock::new(1)));
let deleted = rotation
.cleanup_expired()
.await
.expect("cleanup_expired 应成功");
assert_eq!(deleted, 0, "空表应返回 0");
}
#[cfg(feature = "loom-test")]
const RACE_ROUNDS: usize = 16;
#[cfg(feature = "loom-test")]
async fn race_rotate(
rotation: Arc<RefreshTokenRotation>,
token: &str,
racers: usize,
) -> Vec<crate::error::GarrisonResult<(String, String)>> {
let barrier = Arc::new(tokio::sync::Barrier::new(racers));
let mut handles = Vec::with_capacity(racers);
for _ in 0..racers {
let rotation = Arc::clone(&rotation);
let token = token.to_string();
let barrier = Arc::clone(&barrier);
handles.push(tokio::spawn(async move {
barrier.wait().await;
rotation.rotate(&token).await
}));
}
let mut results = Vec::with_capacity(racers);
for handle in handles {
results.push(handle.await.expect("轮换任务不应 panic"));
}
results
}
#[cfg(feature = "loom-test")]
async fn assert_race_outcome(
round: usize,
racers: usize,
rotation: &RefreshTokenRotation,
results: &[crate::error::GarrisonResult<(String, String)>],
) {
let successes = results.iter().filter(|result| result.is_ok()).count();
let error_shapes: Vec<String> = results
.iter()
.filter_map(|result| result.as_ref().err())
.map(|error| error.code().to_string())
.collect();
assert_eq!(
successes, 1,
"第 {round} 轮({racers} 方):同一 token 并发轮换必须恰一成功,\
实际 {successes} 个成功,错误分布: {error_shapes:?}"
);
let mut revocation_ran = false;
for error in results.iter().filter_map(|result| result.as_ref().err()) {
match error {
GarrisonError::InvalidToken(message) => assert!(
message.starts_with("jwt-refresh-token-consumed")
|| message.starts_with("jwt-refresh-reuse-rejected"),
"第 {round} 轮:落败方应返回已消费或重用拒绝错误,实际: {message}"
),
GarrisonError::TokenRevoked(_) => revocation_ran = true,
other => panic!("第 {round} 轮:落败方应为已消费或重用检测错误,实际: {other:?}"),
}
}
if revocation_ran {
return;
}
let (_, new_refresh) = results
.iter()
.find_map(|result| result.as_ref().ok())
.expect("应恰有一个成功结果");
let record = rotation
.validate(new_refresh)
.await
.expect("校验胜者 token 不应失败");
assert!(
record.is_some(),
"第 {round} 轮:落败方未触发链吊销,胜者新签发的 refresh token \
却不可验证——「恰一成功」不代表客户端仍持有可用会话"
);
}
#[cfg(feature = "loom-test")]
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn concurrent_rotate_same_token_exactly_one_succeeds() {
let name = format!("garrison_refresh_concurrent_{}_pair", std::process::id());
let pool = setup_shared_db(&name).await;
let jwt_handler = Arc::new(JwtHandler::new("test_secret_that_is_at_least_32_bytes"));
let rotation = Arc::new(RefreshTokenRotation::new(
pool.clone(),
jwt_handler,
Arc::new(RwLock::new(1)),
));
for round in 0..RACE_ROUNDS {
let token = rotation
.issue("client", Some(1), &[], None, 1, 0, 9999)
.await
.expect("issue 应成功");
let results = race_rotate(Arc::clone(&rotation), &token, 2).await;
assert_race_outcome(round, 2, &rotation, &results).await;
}
}
#[cfg(feature = "loom-test")]
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn concurrent_rotate_same_token_many_racers_exactly_one_succeeds() {
let name = format!("garrison_refresh_concurrent_{}_many", std::process::id());
let pool = setup_shared_db(&name).await;
let jwt_handler = Arc::new(JwtHandler::new("test_secret_that_is_at_least_32_bytes"));
let rotation = Arc::new(RefreshTokenRotation::new(
pool.clone(),
jwt_handler,
Arc::new(RwLock::new(1)),
));
for round in 0..RACE_ROUNDS {
let token = rotation
.issue("client", Some(1), &[], None, 1, 0, 9999)
.await
.expect("issue 应成功");
let results = race_rotate(Arc::clone(&rotation), &token, 4).await;
assert_race_outcome(round, 4, &rotation, &results).await;
}
}
#[cfg(feature = "loom-test")]
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn concurrent_rotate_unauthorised_policy_rejected_without_chain_revocation() {
let name = format!("garrison_refresh_concurrent_{}_unauth", std::process::id());
let pool = setup_shared_db(&name).await;
let jwt_handler = Arc::new(JwtHandler::new("test_secret_that_is_at_least_32_bytes"));
let rotation = Arc::new(
RefreshTokenRotation::new(pool.clone(), jwt_handler, Arc::new(RwLock::new(1)))
.with_reuse_behaviour(RecentReuseBehaviour::Unauthorised),
);
for round in 0..RACE_ROUNDS {
let token = rotation
.issue("client", Some(1), &[], None, 1, 0, 9999)
.await
.expect("issue 应成功");
let results = race_rotate(Arc::clone(&rotation), &token, 2).await;
assert_race_outcome(round, 2, &rotation, &results).await;
}
}
}