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(
"core-token-parse-not-supported::UUID".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(
"core-token-parse-not-supported::random_64".to_string(),
))
}
}
#[cfg(feature = "secure-simple-token")]
impl SimpleTokenStyle {
fn compute_hmac(&self, login_id: &str, uuid_part: &str, exp: i64) -> GarrisonResult<String> {
use hmac::{Hmac, KeyInit, Mac};
use sha2::Sha256;
type HmacSha256 = Hmac<Sha256>;
let message = format!("{}|{}|{}", login_id, uuid_part, exp);
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")]
fn split_simple_token_parts(token: &str) -> Option<(&str, &str, i64, &str)> {
let (body, hmac_part) = token.rsplit_once('.')?;
let (left, exp_str) = body.rsplit_once('.')?;
let exp: i64 = exp_str.parse().ok()?;
let (login_id, uuid_part) = left.split_once('\x1f')?;
Some((login_id, uuid_part, exp, hmac_part))
}
#[cfg(feature = "secure-simple-token")]
impl Token for SimpleTokenStyle {
fn generate(&self, login_id: &str, timeout: i64) -> GarrisonResult<String> {
if self.secret.len() < 32 {
return Err(GarrisonError::Config(
"core-simple-secret-too-short::".to_string(),
));
}
if login_id.is_empty() {
return Err(GarrisonError::InvalidParam(
"core-simple-login-id-empty::".to_string(),
));
}
if login_id.contains('\x1f') {
return Err(GarrisonError::InvalidParam(
"core-simple-login-id-sep::".to_string(),
));
}
if timeout <= 0 {
return Err(GarrisonError::InvalidParam(format!(
"core-simple-timeout-invalid::{}",
timeout
)));
}
let uuid = Uuid::new_v4();
let uuid_str = uuid.to_string();
let exp = chrono::Utc::now().timestamp() + timeout;
let exp_str = exp.to_string();
let hmac = self.compute_hmac(login_id, &uuid_str, exp)?;
Ok(format!("{}\x1f{}.{}.{}", login_id, uuid_str, exp_str, hmac))
}
fn verify(&self, token: &str) -> GarrisonResult<Option<String>> {
if self.secret.len() < 32 {
return Ok(None);
}
let (login_id, uuid_part, exp, hmac_part) = match split_simple_token_parts(token) {
Some(parts) => parts,
None => return Ok(None),
};
if login_id.is_empty() {
return Ok(None);
}
if Uuid::parse_str(uuid_part).is_err() {
return Ok(None);
}
if exp != 0 && chrono::Utc::now().timestamp() >= exp {
return Ok(None);
}
let expected_hmac = match self.compute_hmac(login_id, uuid_part, exp) {
Ok(h) => h,
Err(_) => return Ok(None),
};
if crate::secure::ct_eq::constant_time_eq(expected_hmac.as_bytes(), hmac_part.as_bytes()) {
Ok(Some(login_id.to_string()))
} else {
Ok(None)
}
}
fn parse(&self, token: &str) -> GarrisonResult<TokenClaims> {
if self.secret.len() < 32 {
return Err(GarrisonError::Config(
"core-simple-secret-too-short::".to_string(),
));
}
let (login_id, uuid_part, exp, hmac_part) = split_simple_token_parts(token)
.ok_or_else(|| GarrisonError::Internal("core-simple-token-no-sep::".to_string()))?;
if login_id.is_empty() {
return Err(GarrisonError::InvalidToken(
"core-simple-token-login-id-empty::".to_string(),
));
}
if Uuid::parse_str(uuid_part).is_err() {
return Err(GarrisonError::Internal(
"core-simple-token-uuid-invalid::".to_string(),
));
}
if exp != 0 && chrono::Utc::now().timestamp() >= exp {
return Err(GarrisonError::ExpiredToken(
"core-simple-token-expired::".to_string(),
));
}
let expected_hmac = self.compute_hmac(login_id, uuid_part, exp)?;
if !crate::secure::ct_eq::constant_time_eq(expected_hmac.as_bytes(), hmac_part.as_bytes()) {
return Err(GarrisonError::InvalidToken(
"core-simple-token-hmac-failed::".to_string(),
));
}
Ok(TokenClaims {
login_id: login_id.to_string(),
expire_at: exp,
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(
"core-simple-requires-feature::".to_string(),
))
}
fn verify(&self, _token: &str) -> GarrisonResult<Option<String>> {
Ok(None)
}
fn parse(&self, _token: &str) -> GarrisonResult<TokenClaims> {
Err(GarrisonError::Config(
"core-simple-requires-feature::".to_string(),
))
}
}
#[cfg(feature = "protocol-jwt")]
impl JwtTokenStyle {
pub fn new(secret: &str) -> Self {
Self {
handler: crate::protocol::jwt::JwtHandler::new(secret),
}
}
pub fn from_algorithm_parts(
algorithm: &str,
secret: &str,
rsa_pem: Option<&str>,
ec_pem: Option<&str>,
ed_pem: Option<&str>,
) -> GarrisonResult<Self> {
Ok(Self {
handler: crate::protocol::jwt::JwtHandler::from_algorithm_parts(
algorithm, secret, rsa_pem, ec_pem, ed_pem,
)?,
})
}
}
#[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 generate_with_amr(
&self,
login_id: &str,
timeout: i64,
amr: &[String],
auth_time: Option<i64>,
) -> GarrisonResult<String> {
self.handler
.sign_with_amr(login_id, timeout, amr, auth_time)
}
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>> {
Self::new_with_jwt_keys(style, secret, None, None, None, None)
}
#[allow(clippy::new_ret_no_self)]
pub fn new_with_jwt_keys(
style: &str,
secret: &str,
jwt_algorithm: Option<&str>,
rsa_pem: Option<&str>,
ec_pem: Option<&str>,
ed_pem: Option<&str>,
) -> GarrisonResult<Box<dyn Token>> {
#[cfg(feature = "protocol-jwt")]
let jwt_algorithm = jwt_algorithm.unwrap_or("HS256");
#[cfg(not(feature = "protocol-jwt"))]
let _ = (jwt_algorithm, rsa_pem, ec_pem, ed_pem);
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::from_algorithm_parts(
jwt_algorithm,
secret,
rsa_pem,
ec_pem,
ed_pem,
)?)),
#[cfg(not(feature = "protocol-jwt"))]
"jwt" => {
let _ = secret; Err(GarrisonError::Config(
"config-unknown-token-style-jwt::".to_string(),
))
},
other => Err(GarrisonError::Config(format!(
"config-unknown-token-style::{}",
other
))),
}
}
}
#[cfg(all(test, feature = "secure-simple-token"))]
mod simple_token_impl_tests {
use super::*;
fn make_style() -> SimpleTokenStyle {
SimpleTokenStyle::new("test-hmac-secret-key-for-unit-tests-01".to_string())
}
#[test]
fn base64_url_no_pad_rfc4648_vectors() {
let cases: &[(&[u8], &str)] = &[
(b"", ""),
(b"f", "Zg"),
(b"fo", "Zm8"),
(b"foo", "Zm9v"),
(b"foob", "Zm9vYg"),
(b"fooba", "Zm9vYmE"),
(b"foobar", "Zm9vYmFy"),
];
for (input, expected) in cases {
assert_eq!(
&SimpleTokenStyle::base64_url_no_pad(input),
expected,
"input: {:?}",
input
);
}
}
#[test]
fn base64_url_no_pad_uses_url_safe_alphabet_no_padding() {
let encoded = SimpleTokenStyle::base64_url_no_pad(&[0xff; 6]);
assert_eq!(encoded, "________"); assert!(
!encoded.contains('+') && !encoded.contains('/') && !encoded.contains('='),
"URL-safe 输出不得含 '+', '/', '='"
);
}
#[test]
fn base64_url_no_pad_hmac_output_length() {
let encoded = SimpleTokenStyle::base64_url_no_pad(&[0x42; 32]);
assert_eq!(encoded.len(), 43, "32 字节输入应编码为 43 字符");
}
#[test]
fn simple_token_expiry_enforced() {
let style = make_style();
let uuid_str = Uuid::new_v4().to_string();
let past_exp = chrono::Utc::now().timestamp() - 100;
let hmac = style.compute_hmac("u1", &uuid_str, past_exp).unwrap();
let expired = format!("u1\x1f{}.{}.{}", uuid_str, past_exp, hmac);
assert_eq!(style.verify(&expired).unwrap(), None, "过期 token 应无效");
assert!(
matches!(style.parse(&expired), Err(GarrisonError::ExpiredToken(_))),
"过期 token parse 应返回 ExpiredToken,实际: {:?}",
style.parse(&expired)
);
let future_exp = chrono::Utc::now().timestamp() + 3600;
let hmac_future = style.compute_hmac("u1", &uuid_str, future_exp).unwrap();
let valid = format!("u1\x1f{}.{}.{}", uuid_str, future_exp, hmac_future);
assert_eq!(style.verify(&valid).unwrap(), Some("u1".to_string()));
let claims = style.parse(&valid).unwrap();
assert_eq!(claims.expire_at, future_exp);
let tampered = format!("u1\x1f{}.{}.{}", uuid_str, future_exp + 86_400, hmac_future);
assert_eq!(
style.verify(&tampered).unwrap(),
None,
"篡改 exp 后 HMAC 应失败"
);
}
#[test]
fn simple_token_tampered_hmac_rejected() {
let style = make_style();
let uuid_str = Uuid::new_v4().to_string();
let future_exp = chrono::Utc::now().timestamp() + 3600;
let hmac = style.compute_hmac("u1", &uuid_str, future_exp).unwrap();
let mut tampered_hmac = hmac.clone();
tampered_hmac.replace_range(0..1, if &hmac[0..1] == "A" { "B" } else { "A" });
let bad = format!("u1\x1f{}.{}.{}", uuid_str, future_exp, tampered_hmac);
assert_eq!(
style.verify(&bad).unwrap(),
None,
"篡改 HMAC 首字符后 token 应无效"
);
assert!(
matches!(style.parse(&bad), Err(GarrisonError::InvalidToken(_))),
"篡改 HMAC 后 parse 应返回 InvalidToken,实际: {:?}",
style.parse(&bad)
);
let mut last_flipped = hmac.clone();
let last = last_flipped.pop().unwrap();
last_flipped.push(if last == 'A' { 'B' } else { 'A' });
let bad_last = format!("u1\x1f{}.{}.{}", uuid_str, future_exp, last_flipped);
assert_eq!(style.verify(&bad_last).unwrap(), None);
let truncated = format!("u1\x1f{}.{}.{}", uuid_str, future_exp, &hmac[..42]);
assert_eq!(
style.verify(&truncated).unwrap(),
None,
"HMAC 段长度不符应无效"
);
let good = format!("u1\x1f{}.{}.{}", uuid_str, future_exp, hmac);
assert_eq!(style.verify(&good).unwrap(), Some("u1".to_string()));
}
}