use super::*;
use uuid::Uuid;
impl Token for UuidTokenStyle {
fn generate(&self, _login_id: &str, _timeout: i64) -> GarrisonResult<String> {
Ok(Uuid::new_v4().to_string())
}
fn verify(&self, _token: &str) -> GarrisonResult<Option<String>> {
Ok(None)
}
fn parse(&self, _token: &str) -> GarrisonResult<TokenClaims> {
Err(GarrisonError::Internal(
"UUID token 风格不支持 parse(无 payload)".to_string(),
))
}
}
impl Token for Random64TokenStyle {
fn generate(&self, _login_id: &str, _timeout: i64) -> GarrisonResult<String> {
let token = format!("{}{}", Uuid::new_v4().simple(), Uuid::new_v4().simple());
Ok(token)
}
fn verify(&self, _token: &str) -> GarrisonResult<Option<String>> {
Ok(None)
}
fn parse(&self, _token: &str) -> GarrisonResult<TokenClaims> {
Err(GarrisonError::Internal(
"random_64 token 风格不支持 parse(无 payload)".to_string(),
))
}
}
#[cfg(feature = "secure-simple-token")]
impl SimpleTokenStyle {
fn compute_hmac(&self, login_id: &str, uuid_part: &str) -> GarrisonResult<String> {
use hmac::{Hmac, KeyInit, Mac};
use sha2::Sha256;
type HmacSha256 = Hmac<Sha256>;
let message = format!("{}|{}", login_id, uuid_part);
let mut mac = HmacSha256::new_from_slice(self.secret.as_bytes())
.map_err(|e| GarrisonError::Config(format!("core-hmac-key-invalid::{}", e)))?;
mac.update(message.as_bytes());
Ok(Self::base64_url_no_pad(&mac.finalize().into_bytes()))
}
fn base64_url_no_pad(bytes: &[u8]) -> String {
const CHARS: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
let mut result = String::with_capacity((bytes.len() * 4).div_ceil(3));
for chunk in bytes.chunks(3) {
let b0 = chunk[0] as u32;
let b1 = chunk.get(1).copied().unwrap_or(0) as u32;
let b2 = chunk.get(2).copied().unwrap_or(0) as u32;
let n = (b0 << 16) | (b1 << 8) | b2;
result.push(CHARS[((n >> 18) & 0x3F) as usize] as char);
result.push(CHARS[((n >> 12) & 0x3F) as usize] as char);
if chunk.len() > 1 {
result.push(CHARS[((n >> 6) & 0x3F) as usize] as char);
}
if chunk.len() > 2 {
result.push(CHARS[(n & 0x3F) as usize] as char);
}
}
result
}
}
#[cfg(feature = "secure-simple-token")]
impl Token for SimpleTokenStyle {
fn generate(&self, login_id: &str, _timeout: i64) -> GarrisonResult<String> {
if self.secret.is_empty() {
return Err(GarrisonError::Config(
"SimpleTokenStyle secret 不能为空(A11 fail-closed)".to_string(),
));
}
let uuid = Uuid::new_v4();
let uuid_str = uuid.to_string();
let hmac = self.compute_hmac(login_id, &uuid_str)?;
Ok(format!("{}\x1f{}.{}", login_id, uuid_str, hmac))
}
fn verify(&self, token: &str) -> GarrisonResult<Option<String>> {
use subtle::ConstantTimeEq;
if self.secret.is_empty() {
return Ok(None);
}
let (body, hmac_part) = match token.rsplit_once('.') {
Some((b, h)) => (b, h),
None => return Ok(None), };
let (login_id, uuid_part) = match body.split_once('\x1f') {
Some((l, u)) => (l, u),
None => return Ok(None),
};
if Uuid::parse_str(uuid_part).is_err() {
return Ok(None);
}
let expected_hmac = match self.compute_hmac(login_id, uuid_part) {
Ok(h) => h,
Err(_) => return Ok(None),
};
let ct_result = expected_hmac.as_bytes().ct_eq(hmac_part.as_bytes());
if bool::from(ct_result) {
Ok(Some(login_id.to_string()))
} else {
Ok(None)
}
}
fn parse(&self, token: &str) -> GarrisonResult<TokenClaims> {
if self.secret.is_empty() {
return Err(GarrisonError::Config(
"SimpleTokenStyle secret 不能为空(A11 fail-closed)".to_string(),
));
}
let (body, hmac_part) = token.rsplit_once('.').ok_or_else(|| {
GarrisonError::Internal("core-simple-token-no-hmac-sep::".to_string())
})?;
let (id_str, uuid_part) = body
.split_once('\x1f')
.ok_or_else(|| GarrisonError::Internal("core-simple-token-no-sep::".to_string()))?;
if Uuid::parse_str(uuid_part).is_err() {
return Err(GarrisonError::Internal(
"Simple token 格式错误:UUID 部分无效".to_string(),
));
}
use subtle::ConstantTimeEq;
let expected_hmac = self.compute_hmac(id_str, uuid_part)?;
let ct_result = expected_hmac.as_bytes().ct_eq(hmac_part.as_bytes());
if !bool::from(ct_result) {
return Err(GarrisonError::InvalidToken(
"Simple token HMAC 校验失败".to_string(),
));
}
Ok(TokenClaims {
login_id: id_str.to_string(),
expire_at: 0,
device: None,
})
}
}
#[cfg(not(feature = "secure-simple-token"))]
impl Token for SimpleTokenStyle {
fn generate(&self, _login_id: &str, _timeout: i64) -> GarrisonResult<String> {
Err(GarrisonError::Config(
"SimpleTokenStyle 需启用 secure-simple-token feature(A11 安全修复)".to_string(),
))
}
fn verify(&self, _token: &str) -> GarrisonResult<Option<String>> {
Ok(None)
}
fn parse(&self, _token: &str) -> GarrisonResult<TokenClaims> {
Err(GarrisonError::Config(
"SimpleTokenStyle 需启用 secure-simple-token feature(A11 安全修复)".to_string(),
))
}
}
#[cfg(feature = "protocol-jwt")]
impl JwtTokenStyle {
pub fn new(secret: &str) -> Self {
Self {
handler: crate::protocol::jwt::JwtHandler::new(secret),
}
}
}
#[cfg(feature = "protocol-jwt")]
impl Token for JwtTokenStyle {
fn generate(&self, login_id: &str, timeout: i64) -> GarrisonResult<String> {
self.handler.sign(login_id, timeout)
}
fn verify(&self, token: &str) -> GarrisonResult<Option<String>> {
match self.handler.verify(token) {
Ok(claims) => Ok(Some(claims.login_id)),
Err(_) => Ok(None),
}
}
fn parse(&self, token: &str) -> GarrisonResult<TokenClaims> {
let claims = self.handler.verify(token)?;
Ok(TokenClaims {
login_id: claims.login_id,
expire_at: claims.exp,
device: claims.device.clone(),
})
}
}
impl TokenStyleFactory {
#[allow(clippy::new_ret_no_self)]
pub fn new(style: &str, secret: &str) -> GarrisonResult<Box<dyn Token>> {
match style {
"uuid" => Ok(Box::new(UuidTokenStyle)),
"random_64" => Ok(Box::new(Random64TokenStyle)),
"simple" => Ok(Box::new(SimpleTokenStyle::new(secret.to_string()))),
#[cfg(feature = "protocol-jwt")]
"jwt" => Ok(Box::new(JwtTokenStyle::new(secret))),
#[cfg(not(feature = "protocol-jwt"))]
"jwt" => {
let _ = secret; Err(GarrisonError::Config(
"unknown token_style: jwt(需启用 protocol-jwt feature)".to_string(),
))
},
other => Err(GarrisonError::Config(format!(
"unknown token_style: {}",
other
))),
}
}
}