use super::current_token;
use super::GarrisonLogicDefault;
#[cfg(feature = "protocol-jwt")]
use crate::config::GarrisonConfig;
#[cfg(feature = "mfa-recovery")]
use crate::constants::DaoKeyPrefix;
#[cfg(feature = "protocol-jwt")]
use crate::context::{build_set_cookie_value, CookieType};
use crate::dao::GarrisonDao;
use crate::error::{GarrisonError, GarrisonResult};
use crate::stp::session::SessionLogic;
use async_trait::async_trait;
#[cfg(feature = "mfa-recovery")]
use std::sync::Arc;
#[async_trait]
pub trait MfaLogic: SessionLogic {
async fn check_session_precondition(&self) -> GarrisonResult<()> {
if current_token().is_ok() && !self.check_login().await? {
return Err(GarrisonError::Session(
"stp-secondary-check-not-login::".to_string(),
));
}
Ok(())
}
async fn check_safe(&self) -> GarrisonResult<()> {
self.check_session_precondition().await?;
self.check_mfa_chain(None).await?;
if !self.is_safe("default").await? {
return Err(Self::not_safe("SAFE_EXPIRED"));
}
Ok(())
}
async fn check_mfa_chain(&self, _client_id: Option<&str>) -> GarrisonResult<()> {
Ok(())
}
async fn check_disable(&self) -> GarrisonResult<()> {
self.check_session_precondition().await?;
Ok(())
}
async fn open_safe(&self, _service: &str, _duration_secs: u64) -> GarrisonResult<()> {
Ok(())
}
async fn is_safe(&self, _service: &str) -> GarrisonResult<bool> {
Ok(true)
}
async fn close_safe(&self, _service: &str) -> GarrisonResult<()> {
Ok(())
}
fn disable_service(
service: &str,
until: Option<chrono::DateTime<chrono::Utc>>,
) -> GarrisonError {
GarrisonError::DisableService {
service: service.to_string(),
until,
}
}
fn not_safe(reason: &str) -> GarrisonError {
GarrisonError::NotSafe {
reason: reason.to_string(),
}
}
}
pub const KNOWN_CHAIN_FACTORS: &[&str] = &["otp", "webauthn"];
pub fn validate_mfa_chains(
global_chain: &[String],
per_client_chains: &std::collections::HashMap<String, Vec<String>>,
) -> GarrisonResult<()> {
for factor in global_chain {
if !KNOWN_CHAIN_FACTORS.contains(&factor.as_str()) {
return Err(GarrisonError::Config(format!(
"config-mfa-chain-factor-unknown::{factor}"
)));
}
}
for chains in per_client_chains.values() {
for factor in chains {
if !KNOWN_CHAIN_FACTORS.contains(&factor.as_str()) {
return Err(GarrisonError::Config(format!(
"config-mfa-chain-factor-unknown::{factor}"
)));
}
}
}
Ok(())
}
pub fn chain_factor_amr(factor: &str) -> Option<&'static str> {
match factor {
"otp" => Some("otp"),
"webauthn" => Some("webauthn"),
_ => None,
}
}
pub fn first_unmet_chain_factor(
decision: &MfaChainDecision,
ledger: &[AmrEntry],
) -> Option<String> {
let MfaChainDecision::Require(factors) = decision else {
return None;
};
factors
.iter()
.find(|f| match chain_factor_amr(f) {
Some(amr) => !ledger.iter().any(|e| e.method == amr),
None => true,
})
.cloned()
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MfaChainDecision {
None,
Require(Vec<String>),
}
pub fn resolve_mfa_chain(
per_client: Option<&Vec<String>>,
global_chain: &[String],
) -> MfaChainDecision {
match per_client {
None => {
if global_chain.is_empty() {
MfaChainDecision::None
} else {
MfaChainDecision::Require(global_chain.to_vec())
}
},
Some(chain) if chain.is_empty() => MfaChainDecision::None,
Some(chain) => MfaChainDecision::Require(chain.clone()),
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MfaFreshness {
pub max_age_secs: i64,
pub min_aal: u8,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FreshnessInput {
pub auth_time: Option<i64>,
pub ledger_max_aal: u8,
pub now: i64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FreshnessVerdict {
Fresh,
Stale,
}
pub fn assert_freshness(input: &FreshnessInput, threshold: &MfaFreshness) -> FreshnessVerdict {
let Some(auth_time) = input.auth_time else {
return FreshnessVerdict::Stale;
};
if input.now - auth_time > threshold.max_age_secs {
return FreshnessVerdict::Stale;
}
if input.ledger_max_aal < threshold.min_aal {
return FreshnessVerdict::Stale;
}
FreshnessVerdict::Fresh
}
pub fn stepup_required(
input: &FreshnessInput,
threshold: &MfaFreshness,
remember_cookie_valid: bool,
) -> bool {
!remember_cookie_valid && assert_freshness(input, threshold) == FreshnessVerdict::Stale
}
#[derive(Debug, Clone)]
pub struct RequiredActionContext {
pub login_id: String,
pub auth_time: Option<i64>,
pub ledger_max_aal: u8,
pub now: i64,
}
impl RequiredActionContext {
pub fn freshness_input(&self) -> FreshnessInput {
FreshnessInput {
auth_time: self.auth_time,
ledger_max_aal: self.ledger_max_aal,
now: self.now,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RequiredActionChallenge {
pub action: String,
pub payload: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ProcessOutcome {
Verified {
method: &'static str,
aal: u8,
},
Rejected,
}
#[async_trait]
pub trait RequiredActionProvider: Send + Sync {
fn action_id(&self) -> &'static str;
async fn evaluate(
&self,
ctx: &RequiredActionContext,
threshold: &MfaFreshness,
) -> GarrisonResult<bool>;
async fn challenge(
&self,
ctx: &RequiredActionContext,
) -> GarrisonResult<RequiredActionChallenge>;
async fn process(
&self,
ctx: &RequiredActionContext,
response: &str,
dao: &dyn GarrisonDao,
) -> GarrisonResult<ProcessOutcome>;
}
pub async fn complete_required_action(
session: &crate::session::GarrisonSession,
token: &str,
outcome: &ProcessOutcome,
completed_at: i64,
) -> GarrisonResult<()> {
let ProcessOutcome::Verified { method, aal } = outcome else {
return Ok(());
};
session
.append_amr_entry(token, method, *aal, completed_at)
.await
}
pub const AMR_METHODS: &[&str] = &["pwd", "otp", "webauthn"];
pub const PRIMARY_FACTOR_AMR: &str = "pwd";
pub const PRIMARY_FACTOR_AAL: u8 = 1;
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct AmrEntry {
pub method: String,
pub aal: u8,
pub completed_at: i64,
}
impl AmrEntry {
pub fn new(method: impl Into<String>, aal: u8, completed_at: i64) -> GarrisonResult<Self> {
let method = method.into();
if !AMR_METHODS.contains(&method.as_str()) {
return Err(GarrisonError::InvalidParam(format!(
"mfa-amr-method-unknown::{method}::allowed={:?}",
AMR_METHODS
)));
}
if !(1..=3).contains(&aal) {
return Err(GarrisonError::InvalidParam(format!(
"mfa-aal-out-of-range::{aal}::allowed=1..=3"
)));
}
Ok(Self {
method,
aal,
completed_at,
})
}
}
pub fn primary_issuance_claims(now: i64) -> (Vec<String>, Option<i64>) {
(vec![PRIMARY_FACTOR_AMR.to_string()], Some(now))
}
pub fn amr_claim(entries: &[AmrEntry]) -> Vec<String> {
let mut seen = std::collections::HashSet::new();
entries
.iter()
.filter(|e| seen.insert(e.method.as_str()))
.map(|e| e.method.clone())
.collect()
}
pub fn ledger_max_aal(entries: &[AmrEntry]) -> u8 {
entries.iter().map(|e| e.aal).max().unwrap_or(0)
}
#[cfg(feature = "secure-totp")]
pub struct TotpRequiredActionProvider {
secret_base32: String,
}
#[cfg(feature = "secure-totp")]
impl TotpRequiredActionProvider {
pub fn new(secret_base32: impl Into<String>) -> Self {
Self {
secret_base32: secret_base32.into(),
}
}
pub fn generate_current_code(&self, now: i64) -> GarrisonResult<String> {
self.handler()?.generate(now)
}
fn handler(&self) -> GarrisonResult<crate::secure::totp::TotpHandler> {
let secret = crate::secure::totp::TotpHandler::secret_from_base32(&self.secret_base32)?;
crate::secure::totp::TotpHandler::new(secret, 30, 6)
}
}
#[cfg(feature = "secure-totp")]
#[async_trait]
impl RequiredActionProvider for TotpRequiredActionProvider {
fn action_id(&self) -> &'static str {
"otp"
}
async fn evaluate(
&self,
ctx: &RequiredActionContext,
threshold: &MfaFreshness,
) -> GarrisonResult<bool> {
Ok(assert_freshness(&ctx.freshness_input(), threshold) == FreshnessVerdict::Stale)
}
async fn challenge(
&self,
_ctx: &RequiredActionContext,
) -> GarrisonResult<RequiredActionChallenge> {
Ok(RequiredActionChallenge {
action: self.action_id().to_string(),
payload: "totp:enter-code".to_string(),
})
}
async fn process(
&self,
ctx: &RequiredActionContext,
response: &str,
dao: &dyn GarrisonDao,
) -> GarrisonResult<ProcessOutcome> {
let handler = self.handler()?;
let ok = handler
.validate_and_consume(&ctx.login_id, response, ctx.now, dao)
.await?;
if ok {
Ok(ProcessOutcome::Verified {
method: "otp",
aal: 2,
})
} else {
Ok(ProcessOutcome::Rejected)
}
}
}
#[cfg(feature = "protocol-webauthn")]
pub struct WebauthnRequiredActionProvider;
#[cfg(feature = "protocol-webauthn")]
#[async_trait]
impl RequiredActionProvider for WebauthnRequiredActionProvider {
fn action_id(&self) -> &'static str {
"webauthn"
}
async fn evaluate(
&self,
ctx: &RequiredActionContext,
threshold: &MfaFreshness,
) -> GarrisonResult<bool> {
Ok(assert_freshness(&ctx.freshness_input(), threshold) == FreshnessVerdict::Stale)
}
async fn challenge(
&self,
_ctx: &RequiredActionContext,
) -> GarrisonResult<RequiredActionChallenge> {
Ok(RequiredActionChallenge {
action: self.action_id().to_string(),
payload: "webauthn:use-passkey".to_string(),
})
}
async fn process(
&self,
ctx: &RequiredActionContext,
response: &str,
_dao: &dyn GarrisonDao,
) -> GarrisonResult<ProcessOutcome> {
let verifier = webauthn_factor::webauthn_factor().ok_or_else(|| {
GarrisonError::Config("mfa-webauthn-factor-not-registered::".to_string())
})?;
let assertion: webauthn_rs::prelude::PublicKeyCredential = serde_json::from_str(response)
.map_err(|e| {
GarrisonError::InvalidParam(format!("mfa-webauthn-assertion-parse::{e}"))
})?;
let auth = verifier.verify_second_factor(&assertion).await?;
if auth.user_id != ctx.login_id {
return Err(GarrisonError::InvalidParam(format!(
"mfa-webauthn-subject-mismatch::{}::{}",
auth.user_id, ctx.login_id
)));
}
Ok(ProcessOutcome::Verified {
method: "webauthn",
aal: 2,
})
}
}
#[cfg(feature = "protocol-webauthn")]
#[cfg(test)]
mod webauthn_provider_tests {
use super::*;
#[tokio::test(flavor = "multi_thread")]
#[serial_test::serial]
async fn process_without_registered_verifier_fails_closed() {
webauthn_factor::reset_webauthn_factor_for_tests();
let provider = WebauthnRequiredActionProvider;
let ctx = RequiredActionContext {
login_id: "user-wn-provider".to_string(),
auth_time: None,
ledger_max_aal: 1,
now: 1_700_000_000,
};
let result = provider
.process(&ctx, "{}", &crate::dao::InMemoryDao::new())
.await;
assert!(
matches!(result, Err(GarrisonError::Config(ref m)) if m.contains("not-registered")),
"未注册校验函数应 fail-closed,实际: {result:?}"
);
}
#[cfg(all(test, feature = "db-sqlite"))]
#[tokio::test(flavor = "multi_thread")]
#[serial_test::serial]
async fn process_with_real_assertion_completes_full_flow() {
use crate::dao::repository::WebauthnCredentialRepository;
use crate::protocol::webauthn::tests::{
domain_to_credential, seed_authentication, service_with_bound_vector_credential,
test_config, AUTH_VECTOR_JSON,
};
use std::sync::Arc;
webauthn_factor::reset_webauthn_factor_for_tests();
let (service, repo, store, bound) =
service_with_bound_vector_credential(test_config()).await;
webauthn_factor::register_webauthn_factor(Arc::new(
webauthn_factor::WebauthnFactorVerifier::new(Arc::new(service)),
))
.expect("首次注册 factor 应成功");
let stored_cred = repo
.find_by_credential_id(0, &bound.credential_id)
.await
.expect("查询应成功")
.expect("凭据应存在");
let domain =
crate::protocol::webauthn::credential::WebauthnCredential::from_row(stored_cred)
.expect("行重建应成功");
seed_authentication(&store, 0, "user-1", domain_to_credential(&domain)).await;
let provider = WebauthnRequiredActionProvider;
let ctx = RequiredActionContext {
login_id: "user-1".to_string(),
auth_time: None,
ledger_max_aal: 1,
now: 1_700_000_000,
};
let outcome = provider
.process(&ctx, AUTH_VECTOR_JSON, &crate::dao::InMemoryDao::new())
.await
.expect("真实 assertion 应穿透 process 全流程");
assert_eq!(
outcome,
ProcessOutcome::Verified {
method: "webauthn",
aal: 2
},
"真实 assertion 应产出 Verified{{webauthn, aal:2}},实际: {outcome:?}"
);
}
}
#[cfg(feature = "mfa-recovery")]
#[cfg(feature = "mfa-recovery")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RecoveryVerify {
Valid,
Invalid,
Locked,
}
#[cfg(feature = "mfa-recovery")]
pub struct RecoveryCodeManager {
dao: Arc<dyn GarrisonDao>,
misuse_tolerance: u32,
}
#[cfg(feature = "mfa-recovery")]
impl RecoveryCodeManager {
const KEY_PREFIX: &'static str = "recovery:";
const MISUSE_SUFFIX: &'static str = "misuse:";
pub fn new(dao: Arc<dyn GarrisonDao>, misuse_tolerance: u32) -> Self {
Self {
dao,
misuse_tolerance,
}
}
fn code_key(&self, login_id: &str, code: &str) -> String {
let code_hash = Self::code_hash(code);
format!(
"{}{}{}:{}:{}",
DaoKeyPrefix::Mfa.as_str(),
Self::KEY_PREFIX,
login_id.len(),
login_id,
code_hash
)
}
fn code_hash(code: &str) -> String {
use sha2::{Digest, Sha256};
let mut hasher = Sha256::new();
hasher.update(code.as_bytes());
let result = hasher.finalize();
use std::fmt::Write as _;
let mut hex = String::with_capacity(result.len() * 2);
for b in result {
let _ = write!(hex, "{b:02x}");
}
hex
}
fn misuse_key(&self, login_id: &str) -> String {
format!(
"{}{}{}{}",
DaoKeyPrefix::Mfa.as_str(),
Self::KEY_PREFIX,
Self::MISUSE_SUFFIX,
login_id
)
}
pub async fn generate(&self, login_id: &str, count: usize) -> GarrisonResult<Vec<String>> {
const MAX_BATCH: usize = 64;
if count == 0 || count > MAX_BATCH {
return Err(GarrisonError::InvalidParam(format!(
"mfa-recovery-batch-size-invalid::{count}::allowed=1..={MAX_BATCH}"
)));
}
let mut codes = Vec::with_capacity(count);
for _ in 0..count {
let hex = uuid::Uuid::new_v4().simple().to_string();
let code = format!("{}-{}", &hex[..5], &hex[5..10]);
self.dao
.set(&self.code_key(login_id, &code), "unused", 0)
.await?;
codes.push(code);
}
Ok(codes)
}
async fn misuse_count(&self, login_id: &str) -> GarrisonResult<u64> {
match self.dao.get(&self.misuse_key(login_id)).await? {
Some(v) => v
.parse::<u64>()
.map_err(|e| GarrisonError::Internal(format!("mfa-recovery-misuse-parse::{}", e))),
None => Ok(0),
}
}
pub async fn verify(&self, login_id: &str, code: &str) -> GarrisonResult<RecoveryVerify> {
if self.misuse_count(login_id).await? > self.misuse_tolerance as u64 {
return Ok(RecoveryVerify::Locked);
}
match self.dao.get(&self.code_key(login_id, code)).await? {
Some(state) if state == "unused" => Ok(RecoveryVerify::Valid),
Some(_) => Ok(RecoveryVerify::Invalid),
None => {
const MISUSE_LOCK_TTL_SECS: u64 = 24 * 60 * 60;
let count = self
.dao
.incr(&self.misuse_key(login_id), MISUSE_LOCK_TTL_SECS)
.await?;
if count > self.misuse_tolerance as u64 {
Ok(RecoveryVerify::Locked)
} else {
Ok(RecoveryVerify::Invalid)
}
},
}
}
pub async fn consume(&self, login_id: &str, code: &str) -> GarrisonResult<bool> {
if self.misuse_count(login_id).await? > self.misuse_tolerance as u64 {
return Err(GarrisonError::NotSafe {
reason: "MFA_RECOVERY_LOCKED".to_string(),
});
}
self.dao
.compare_and_swap(&self.code_key(login_id, code), Some("unused"), "used", 0)
.await
}
pub async fn unconsumed_count(&self, login_id: &str) -> GarrisonResult<usize> {
let pattern = format!(
"{}{}{}:{}:*",
DaoKeyPrefix::Mfa.as_str(),
Self::KEY_PREFIX,
login_id.len(),
login_id
);
let misuse_prefix = self.misuse_key(login_id);
let mut count = 0;
for key in self.dao.keys(&pattern).await? {
if key.starts_with(&misuse_prefix) {
continue;
}
count += 1;
}
Ok(count)
}
}
#[cfg(feature = "protocol-jwt")]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct MfaRememberClaims {
pub stage: String,
pub login_id: String,
pub credential_id: String,
pub exp: i64,
}
#[cfg(feature = "protocol-jwt")]
pub const MFA_REMEMBER_COOKIE_NAME: &str = "mfa_remember";
#[cfg(feature = "protocol-jwt")]
fn mfa_remember_subkey(secret: &str) -> Vec<u8> {
use hkdf::Hkdf;
let hk = Hkdf::<sha2::Sha256>::new(None, secret.as_bytes());
let mut okm = [0u8; 32];
hk.expand(b"garrison:mfa-remember-cookie:v1" as &[u8], &mut okm)
.unwrap_or_else(|e| {
panic!(
"{}: {e}",
crate::i18n::translate_detail("mfa-hkdf-okm-len-static", &[],)
)
});
okm.to_vec()
}
#[cfg(feature = "protocol-jwt")]
pub fn issue_mfa_remember_cookie(
secret: &str,
config: &GarrisonConfig,
stage: &str,
login_id: &str,
credential_id: &str,
ttl_secs: i64,
) -> GarrisonResult<String> {
if secret.len() < 32 {
return Err(GarrisonError::Config(format!(
"mfa-remember-secret-too-short::{}::min=32",
secret.len()
)));
}
let signing_key = mfa_remember_subkey(secret);
let now = chrono::Utc::now().timestamp();
let claims = MfaRememberClaims {
stage: stage.to_string(),
login_id: login_id.to_string(),
credential_id: credential_id.to_string(),
exp: now.checked_add(ttl_secs).ok_or_else(|| {
GarrisonError::InvalidParam(format!("mfa-remember-ttl-overflow::{ttl_secs}"))
})?,
};
let jwt = jsonwebtoken::encode(
&jsonwebtoken::Header::new(jsonwebtoken::Algorithm::HS256),
&claims,
&jsonwebtoken::EncodingKey::from_secret(&signing_key),
)
.map_err(|e| GarrisonError::Internal(format!("mfa-remember-sign::{}", e)))?;
let cookie = CookieType {
max_age: Some(ttl_secs),
..CookieType::session(MFA_REMEMBER_COOKIE_NAME, config)?
};
build_set_cookie_value(&cookie, &jwt, config.cookie_secure)
}
#[cfg(feature = "protocol-jwt")]
pub fn verify_mfa_remember_cookie(
secret: &str,
jwt: &str,
stage: &str,
login_id: &str,
credential_id: &str,
now: i64,
) -> bool {
if secret.is_empty() {
return false;
}
let signing_key = mfa_remember_subkey(secret);
let mut validation = jsonwebtoken::Validation::new(jsonwebtoken::Algorithm::HS256);
validation.leeway = 0;
let Ok(data) = jsonwebtoken::decode::<MfaRememberClaims>(
jwt,
&jsonwebtoken::DecodingKey::from_secret(&signing_key),
&validation,
) else {
return false;
};
data.claims.stage == stage
&& data.claims.login_id == login_id
&& data.claims.credential_id == credential_id
&& data.claims.exp > now
}
#[async_trait]
impl MfaLogic for GarrisonLogicDefault {
async fn check_safe(&self) -> GarrisonResult<()> {
self.check_session_precondition().await?;
self.check_mfa_chain(None).await?;
if !self.is_safe("default").await? {
return Err(Self::not_safe("SAFE_EXPIRED"));
}
Ok(())
}
async fn check_mfa_chain(&self, client_id: Option<&str>) -> GarrisonResult<()> {
let decision = crate::stp::mfa::resolve_mfa_chain(
client_id.and_then(|id| self.config.mfa.per_client_chains.get(id)),
&self.config.mfa.global_chain,
);
if matches!(decision, crate::stp::mfa::MfaChainDecision::None) {
return Ok(());
}
let not_enrolled = || GarrisonError::NotSafe {
reason: "MFA_CHAIN_INCOMPLETE::no-active-session".to_string(),
};
let token = current_token().map_err(|_| not_enrolled())?;
let ts = self
.session
.get_token_session(&token)
.await?
.ok_or_else(not_enrolled)?;
match crate::stp::mfa::first_unmet_chain_factor(&decision, &ts.amr_ledger) {
None => Ok(()),
Some(factor) => Err(GarrisonError::NotSafe {
reason: format!("MFA_CHAIN_INCOMPLETE::{factor}"),
}),
}
}
async fn check_disable(&self) -> GarrisonResult<()> {
self.check_session_precondition().await?;
let token = match current_token() {
Ok(t) => t,
Err(_) => {
tracing::warn!(
reason = "no_current_token",
"check_disable skipped: no current token (not logged in)"
);
return Ok(());
},
};
let ts = match self.session.get_token_session(&token).await? {
Some(ts) => ts,
None => {
return Err(GarrisonError::Session(
"stp-check-disable-token-session-not-found::".to_string(),
));
},
};
if self
.disable_repository
.is_disable(&ts.login_id, "default")
.await?
{
let until = self
.disable_repository
.get_disable_time(&ts.login_id, "default")
.await?;
return Err(Self::disable_service("default", until));
}
Ok(())
}
}
#[cfg(feature = "protocol-webauthn")]
pub mod webauthn_factor {
use super::*;
use crate::protocol::webauthn::service::WebauthnService;
use std::sync::{Arc, RwLock};
static WEBAUTHN_FACTOR: RwLock<Option<Arc<WebauthnFactorVerifier>>> = RwLock::new(None);
pub struct WebauthnFactorVerifier {
service: Arc<WebauthnService>,
}
impl WebauthnFactorVerifier {
pub fn new(service: Arc<WebauthnService>) -> Self {
Self { service }
}
pub async fn verify_second_factor(
&self,
assertion: &webauthn_rs::prelude::PublicKeyCredential,
) -> GarrisonResult<crate::protocol::webauthn::service::WebauthnAuthentication> {
self.service
.finish_authentication(assertion)
.await
.map_err(GarrisonError::from)
}
pub fn service(&self) -> &Arc<WebauthnService> {
&self.service
}
}
pub fn register_webauthn_factor(verifier: Arc<WebauthnFactorVerifier>) -> GarrisonResult<()> {
let mut guard = WEBAUTHN_FACTOR.write().unwrap_or_else(|e| {
panic!(
"{}: {e}",
crate::i18n::translate_detail("mfa-webauthn-factor-registry-lock-poisoned", &[],)
)
});
if guard.is_some() {
return Err(GarrisonError::Config(
"mfa-webauthn-factor-already-registered::".to_string(),
));
}
*guard = Some(verifier);
Ok(())
}
pub fn webauthn_factor() -> Option<Arc<WebauthnFactorVerifier>> {
WEBAUTHN_FACTOR
.read()
.unwrap_or_else(|e| {
panic!(
"{}: {e}",
crate::i18n::translate_detail(
"mfa-webauthn-factor-registry-lock-poisoned",
&[],
)
)
})
.clone()
}
#[cfg(test)]
pub fn reset_webauthn_factor_for_tests() {
*WEBAUTHN_FACTOR
.write()
.expect("mfa webauthn factor 注册表锁不应中毒") = None;
}
#[cfg(all(test, feature = "db-sqlite"))]
mod tests {
use super::*;
use crate::dao::InMemoryDao;
use crate::protocol::webauthn::WebauthnConfig;
#[tokio::test(flavor = "multi_thread")]
#[serial_test::serial]
async fn register_then_get_and_duplicate_rejected() {
let pool = crate::dao::init_dbnexus("sqlite::memory:")
.await
.expect("init_dbnexus 应成功");
let service = Arc::new(WebauthnService::new(
Arc::new(InMemoryDao::new()),
Arc::new(
crate::dao::repository::sqlite::DbnexusWebauthnCredentialRepository::new(pool),
),
WebauthnConfig {
issuer: "https://auth.example.com".to_string(),
challenge_ttl_secs: 120,
passwordless: crate::protocol::webauthn::FactorPolicy { enabled: false },
second_factor: crate::protocol::webauthn::FactorPolicy { enabled: true },
},
));
let verifier = Arc::new(WebauthnFactorVerifier::new(service));
reset_webauthn_factor_for_tests();
register_webauthn_factor(verifier.clone()).expect("首次注册应成功");
let got = webauthn_factor();
assert!(got.is_some(), "注册后应可取回 factor");
let dup = register_webauthn_factor(verifier);
assert!(
matches!(dup, Err(GarrisonError::Config(_))),
"重复注册应显性拒绝,实际: {dup:?}"
);
if let Err(GarrisonError::Config(m)) = &dup {
assert!(
m.contains("already-registered"),
"重复注册错误应含 already-registered 指引,实际: {m}"
);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::GarrisonConfig;
use crate::error::GarrisonResult;
use crate::stp::core::GarrisonCore;
use crate::stp::session::SessionLogic;
use crate::stp::LoginParams;
use std::sync::Arc;
struct MockMfa {
config: Arc<GarrisonConfig>,
}
impl GarrisonCore for MockMfa {
fn config(&self) -> Arc<GarrisonConfig> {
Arc::clone(&self.config)
}
}
#[async_trait]
impl SessionLogic for MockMfa {
async fn login(
&self,
_login_id: &str,
_params: &crate::stp::LoginParams,
) -> GarrisonResult<String> {
Ok("mock-token".to_string())
}
async fn login_with_token(&self, _login_id: &str, _token: &str) -> GarrisonResult<()> {
Ok(())
}
async fn logout(&self) -> GarrisonResult<()> {
Ok(())
}
async fn logout_by_login_id(&self, _login_id: &str) -> GarrisonResult<()> {
Ok(())
}
async fn kickout(&self, _login_id: &str) -> GarrisonResult<()> {
Ok(())
}
async fn kickout_by_token(&self, _token: &str) -> GarrisonResult<()> {
Ok(())
}
async fn revoke_token(&self, _token: &str) -> GarrisonResult<()> {
Ok(())
}
async fn check_login(&self) -> GarrisonResult<bool> {
Ok(true)
}
async fn get_login_id(&self) -> GarrisonResult<Option<String>> {
Ok(Some("42".to_string()))
}
}
#[async_trait]
impl MfaLogic for MockMfa {}
#[tokio::test]
async fn check_safe_default_ok() {
let mock = MockMfa {
config: Arc::new(GarrisonConfig::default()),
};
mock.check_safe().await.unwrap();
}
#[tokio::test]
async fn check_disable_default_ok() {
let mock = MockMfa {
config: Arc::new(GarrisonConfig::default()),
};
mock.check_disable().await.unwrap();
}
#[test]
fn disable_service_constructs_correct_error() {
let err = MockMfa::disable_service("default", None);
match err {
GarrisonError::DisableService { service, until } => {
assert_eq!(service, "default");
assert!(until.is_none(), "until=None 表示永久封禁");
},
other => panic!("期望 DisableService 变体,实际: {:?}", other),
}
}
#[test]
fn disable_service_with_until_timestamp() {
let until = chrono::DateTime::parse_from_rfc3339("2026-12-31T23:59:59Z")
.unwrap()
.with_timezone(&chrono::Utc);
let err = MockMfa::disable_service("oidc", Some(until));
match err {
GarrisonError::DisableService { service, until: u } => {
assert_eq!(service, "oidc");
assert!(u.is_some(), "until 应为 Some");
assert_eq!(u.unwrap().to_rfc3339(), "2026-12-31T23:59:59+00:00");
},
other => panic!("期望 DisableService 变体,实际: {:?}", other),
}
}
#[test]
fn not_safe_constructs_correct_error() {
let err = MockMfa::not_safe("MFA_TOTP_REQUIRED");
match err {
GarrisonError::NotSafe { reason } => {
assert_eq!(reason, "MFA_TOTP_REQUIRED");
},
other => panic!("期望 NotSafe 变体,实际: {:?}", other),
}
}
#[test]
fn not_safe_display_includes_reason() {
let err = MockMfa::not_safe("WEBAUTHN_REQUIRED");
let display = err.to_string();
assert!(
display.contains("WEBAUTHN_REQUIRED"),
"Display 应包含 reason,实际: {}",
display
);
assert!(
display.contains("authentication required") || display.contains("二次认证"),
"Display 应包含认证描述,实际: {}",
display
);
}
#[tokio::test]
async fn open_safe_default_returns_ok() {
let mock = MockMfa {
config: Arc::new(GarrisonConfig::default()),
};
mock.open_safe("default", 3600).await.unwrap();
}
#[tokio::test]
async fn close_safe_default_returns_ok() {
let mock = MockMfa {
config: Arc::new(GarrisonConfig::default()),
};
mock.close_safe("default").await.unwrap();
}
#[tokio::test]
async fn t025_check_safe_default_without_safe_auth() {
let mock = MockMfa {
config: Arc::new(GarrisonConfig::default()),
};
mock.check_safe().await.unwrap();
}
#[tokio::test]
async fn t025_check_safe_default_uses_is_safe_default() {
let mock = MockMfa {
config: Arc::new(GarrisonConfig::default()),
};
assert!(
mock.is_safe("default").await.unwrap(),
"is_safe 默认应返回 Ok(true)"
);
assert!(mock.check_safe().await.is_ok(), "check_safe 应返回 Ok(())");
}
struct MockMfaSafe {
config: Arc<GarrisonConfig>,
safe_result: GarrisonResult<bool>,
}
impl GarrisonCore for MockMfaSafe {
fn config(&self) -> Arc<GarrisonConfig> {
Arc::clone(&self.config)
}
}
#[async_trait]
impl SessionLogic for MockMfaSafe {
async fn login(
&self,
_login_id: &str,
_params: &crate::stp::LoginParams,
) -> GarrisonResult<String> {
Ok("mock-token".to_string())
}
async fn login_with_token(&self, _login_id: &str, _token: &str) -> GarrisonResult<()> {
Ok(())
}
async fn logout(&self) -> GarrisonResult<()> {
Ok(())
}
async fn logout_by_login_id(&self, _login_id: &str) -> GarrisonResult<()> {
Ok(())
}
async fn kickout(&self, _login_id: &str) -> GarrisonResult<()> {
Ok(())
}
async fn kickout_by_token(&self, _token: &str) -> GarrisonResult<()> {
Ok(())
}
async fn revoke_token(&self, _token: &str) -> GarrisonResult<()> {
Ok(())
}
async fn check_login(&self) -> GarrisonResult<bool> {
Ok(true)
}
async fn get_login_id(&self) -> GarrisonResult<Option<String>> {
Ok(Some("42".to_string()))
}
}
#[async_trait]
impl MfaLogic for MockMfaSafe {
async fn is_safe(&self, _service: &str) -> GarrisonResult<bool> {
match &self.safe_result {
Ok(b) => Ok(*b),
Err(GarrisonError::Dao(s)) => Err(GarrisonError::Dao(s.clone())),
Err(GarrisonError::Internal(s)) => Err(GarrisonError::Internal(s.clone())),
Err(e) => panic!("MockMfaSafe 不支持此错误变体: {:?}", e),
}
}
}
#[tokio::test]
async fn check_safe_is_safe_false_returns_not_safe() {
let mock = MockMfaSafe {
config: Arc::new(GarrisonConfig::default()),
safe_result: Ok(false),
};
let result = mock.check_safe().await;
match result {
Err(GarrisonError::NotSafe { reason }) => {
assert_eq!(
reason, "SAFE_EXPIRED",
"is_safe=false 时 check_safe 应返回 NotSafe(reason=\"SAFE_EXPIRED\")"
);
},
other => panic!(
"is_safe=false 时 check_safe 应返回 Err(NotSafe),实际: {:?}",
other
),
}
}
#[tokio::test]
async fn check_safe_is_safe_true_returns_ok() {
let mock = MockMfaSafe {
config: Arc::new(GarrisonConfig::default()),
safe_result: Ok(true),
};
mock.check_safe().await.unwrap();
}
#[tokio::test]
async fn check_safe_is_safe_error_propagates() {
let mock = MockMfaSafe {
config: Arc::new(GarrisonConfig::default()),
safe_result: Err(GarrisonError::Dao("数据源连接失败".to_string())),
};
let result = mock.check_safe().await;
assert!(
matches!(result, Err(GarrisonError::Dao(ref s)) if s.contains("数据源连接失败")),
"is_safe 返回 Dao 错误时应透传,实际: {:?}",
result
);
}
#[tokio::test]
async fn check_safe_is_safe_internal_error_propagates() {
let mock = MockMfaSafe {
config: Arc::new(GarrisonConfig::default()),
safe_result: Err(GarrisonError::Internal("内部错误".to_string())),
};
let result = mock.check_safe().await;
assert!(
matches!(result, Err(GarrisonError::Internal(ref s)) if s.contains("内部错误")),
"is_safe 返回 Internal 错误时应透传,实际: {:?}",
result
);
}
struct MockMfaSession {
config: Arc<GarrisonConfig>,
logged_in: bool,
}
impl GarrisonCore for MockMfaSession {
fn config(&self) -> Arc<GarrisonConfig> {
Arc::clone(&self.config)
}
}
#[async_trait]
impl SessionLogic for MockMfaSession {
async fn login(
&self,
_login_id: &str,
_params: &crate::stp::LoginParams,
) -> GarrisonResult<String> {
Ok("mock-token".to_string())
}
async fn login_with_token(&self, _login_id: &str, _token: &str) -> GarrisonResult<()> {
Ok(())
}
async fn logout(&self) -> GarrisonResult<()> {
Ok(())
}
async fn logout_by_login_id(&self, _login_id: &str) -> GarrisonResult<()> {
Ok(())
}
async fn kickout(&self, _login_id: &str) -> GarrisonResult<()> {
Ok(())
}
async fn kickout_by_token(&self, _token: &str) -> GarrisonResult<()> {
Ok(())
}
async fn revoke_token(&self, _token: &str) -> GarrisonResult<()> {
Ok(())
}
async fn check_login(&self) -> GarrisonResult<bool> {
Ok(self.logged_in)
}
async fn get_login_id(&self) -> GarrisonResult<Option<String>> {
Ok(Some("42".to_string()))
}
}
#[async_trait]
impl MfaLogic for MockMfaSession {}
#[tokio::test]
async fn t_sec_check_safe_trait_default_rejects_invalid_session() {
let mock = MockMfaSession {
config: Arc::new(GarrisonConfig::default()),
logged_in: false,
};
let result = crate::stp::with_current_token("forged-token".to_string(), async {
mock.check_safe().await
})
.await;
assert!(
matches!(result, Err(GarrisonError::Session(_))),
"无效会话的 check_safe 应返回 Err(Session),实际: {:?}",
result
);
}
#[tokio::test]
async fn t_sec_check_disable_trait_default_rejects_invalid_session() {
let mock = MockMfaSession {
config: Arc::new(GarrisonConfig::default()),
logged_in: false,
};
let result = crate::stp::with_current_token("forged-token".to_string(), async {
mock.check_disable().await
})
.await;
assert!(
matches!(result, Err(GarrisonError::Session(_))),
"无效会话的 check_disable 应返回 Err(Session),实际: {:?}",
result
);
}
#[tokio::test]
async fn t_sec_check_safe_trait_default_valid_session_passes() {
let mock = MockMfaSession {
config: Arc::new(GarrisonConfig::default()),
logged_in: true,
};
let result = crate::stp::with_current_token("valid-token".to_string(), async {
mock.check_safe().await
})
.await;
assert!(
result.is_ok(),
"有效会话的 check_safe 应保持 Ok(()),实际: {:?}",
result
);
}
#[tokio::test]
async fn t_sec_check_safe_trait_default_without_token_context_keeps_pass() {
let mock = MockMfaSession {
config: Arc::new(GarrisonConfig::default()),
logged_in: false,
};
mock.check_safe().await.unwrap();
}
#[test]
fn disable_service_display_includes_service() {
let err = MockMfa::disable_service("payment", None);
let display = err.to_string();
assert!(
display.contains("payment"),
"Display 应包含 service 名称,实际: {}",
display
);
}
#[tokio::test]
async fn mock_mfa_session_logic_all_methods() {
let mock = MockMfa {
config: Arc::new(GarrisonConfig::default()),
};
let _ = mock.config();
let params = LoginParams::default();
let _ = mock.login("u1", ¶ms).await.unwrap();
let _ = mock.login_with_token("u1", "tok").await;
let _ = mock.logout().await;
let _ = mock.logout_by_login_id("u1").await;
let _ = mock.kickout("u1").await;
let _ = mock.kickout_by_token("tok").await;
let _ = mock.revoke_token("tok").await;
let _ = mock.check_login().await.unwrap();
let _ = mock.get_login_id().await.unwrap();
}
#[test]
fn resolve_mfa_chain_none_inherits_global() {
let global = vec!["otp".to_string()];
assert_eq!(
resolve_mfa_chain(None, &global),
MfaChainDecision::Require(vec!["otp".to_string()])
);
}
#[test]
fn resolve_mfa_chain_none_empty_global_is_none() {
assert_eq!(resolve_mfa_chain(None, &[]), MfaChainDecision::None);
}
#[test]
fn resolve_mfa_chain_empty_set_disables() {
let global = vec!["otp".to_string()];
let empty = Vec::new();
assert_eq!(
resolve_mfa_chain(Some(&empty), &global),
MfaChainDecision::None,
"Some(空集) 应显式禁用(压过全局默认)"
);
}
#[test]
fn resolve_mfa_chain_non_empty_overrides_global() {
let global = vec!["otp".to_string()];
let own = vec!["webauthn".to_string()];
assert_eq!(
resolve_mfa_chain(Some(&own), &global),
MfaChainDecision::Require(vec!["webauthn".to_string()])
);
}
#[test]
fn validate_mfa_chains_rejects_unknown_factor() {
let mut per_client = std::collections::HashMap::new();
per_client.insert("c1".to_string(), vec!["otp".to_string()]);
assert!(validate_mfa_chains(&["webauthn".to_string()], &per_client).is_ok());
assert!(validate_mfa_chains(&["sms".to_string()], &per_client).is_err());
per_client.insert("c2".to_string(), vec!["pwd".to_string()]);
let result = validate_mfa_chains(&[], &per_client);
assert!(
matches!(result, Err(GarrisonError::Config(ref m)) if m.contains("pwd")),
"pwd 不入 chain 词汇表(主因子),实际: {:?}",
result
);
}
#[test]
fn amr_entry_new_accepts_known_method_and_valid_aal() {
for method in AMR_METHODS {
let entry = AmrEntry::new(*method, 2, 1_700_000_000).unwrap();
assert_eq!(entry.method, *method);
assert_eq!(entry.aal, 2);
assert_eq!(entry.completed_at, 1_700_000_000);
}
}
#[test]
fn amr_entry_new_rejects_unknown_method() {
for method in ["sms", "", "PWD", "push"] {
let result = AmrEntry::new(method, 2, 0);
assert!(
matches!(result, Err(GarrisonError::InvalidParam(ref m)) if m.contains("amr-method")),
"method={:?} 应被拒绝,实际: {:?}",
method,
result.map(|_| ())
);
}
}
#[test]
fn amr_entry_new_rejects_out_of_range_aal() {
for aal in [0u8, 4] {
let result = AmrEntry::new("otp", aal, 0);
assert!(
matches!(result, Err(GarrisonError::InvalidParam(ref m)) if m.contains("aal")),
"aal={} 应被拒绝,实际: {:?}",
aal,
result.map(|_| ())
);
}
}
#[test]
fn amr_claim_preserves_order_and_dedups() {
let entries = vec![
AmrEntry::new("pwd", 1, 1).unwrap(),
AmrEntry::new("otp", 2, 2).unwrap(),
AmrEntry::new("webauthn", 2, 3).unwrap(),
AmrEntry::new("otp", 2, 4).unwrap(),
];
assert_eq!(
amr_claim(&entries),
vec!["pwd".to_string(), "otp".to_string(), "webauthn".to_string()]
);
}
#[test]
fn amr_claim_empty_ledger_maps_to_empty_array() {
assert!(amr_claim(&[]).is_empty());
}
#[test]
fn ledger_max_aal_takes_maximum() {
assert_eq!(ledger_max_aal(&[]), 0);
let entries = vec![
AmrEntry::new("pwd", 1, 1).unwrap(),
AmrEntry::new("otp", 2, 2).unwrap(),
];
assert_eq!(ledger_max_aal(&entries), 2);
}
#[cfg(feature = "protocol-jwt")]
#[tokio::test]
async fn login_jwt_token_carries_primary_amr_and_auth_time() {
use crate::dao::tests::MockDao;
use crate::dao::GarrisonDao;
use crate::session::GarrisonSession;
use crate::strategy::GarrisonPermissionStrategy;
struct NoopFirewall;
#[async_trait::async_trait]
impl GarrisonPermissionStrategy for NoopFirewall {
async fn get_permission_list(&self, _login_id: &str) -> GarrisonResult<Vec<String>> {
Ok(vec![])
}
async fn get_role_list(&self, _login_id: &str) -> GarrisonResult<Vec<String>> {
Ok(vec![])
}
async fn check_permission(
&self,
_login_id: &str,
_permission: &str,
) -> GarrisonResult<bool> {
Ok(true)
}
async fn check_role(&self, _login_id: &str, _role: &str) -> GarrisonResult<bool> {
Ok(true)
}
async fn check_role_any(
&self,
_login_id: &str,
_roles: &[&str],
) -> GarrisonResult<bool> {
Ok(true)
}
async fn check_role_all(
&self,
_login_id: &str,
_roles: &[&str],
) -> GarrisonResult<bool> {
Ok(true)
}
async fn check_permission_in_tenant(
&self,
_tenant_id: i64,
_login_id: &str,
_permission: &str,
) -> GarrisonResult<bool> {
Ok(true)
}
async fn check_role_in_tenant(
&self,
_tenant_id: i64,
_login_id: &str,
_role: &str,
) -> GarrisonResult<bool> {
Ok(true)
}
#[cfg(any(
feature = "sms-rate-limit",
feature = "firewall-ratelimit",
feature = "firewall-bruteforce",
feature = "firewall-ddos",
feature = "firewall",
feature = "oauth2-server"
))]
async fn check_login_hooks(
&self,
_login_id: &str,
_ctx: &crate::strategy::hooks::LoginContext,
) -> GarrisonResult<()> {
Ok(())
}
}
let dao = Arc::new(MockDao::new());
let session = Arc::new(GarrisonSession::new(
dao.clone() as Arc<dyn GarrisonDao>,
3600,
86400,
0,
));
let mut config = GarrisonConfig::default_config();
config.throw_on_not_login = false;
config.token_style = "jwt".to_string();
config.jwt_secret = "0123456789abcdef0123456789abcdef".to_string().into();
let firewall: Arc<dyn GarrisonPermissionStrategy> = Arc::new(NoopFirewall);
let logic = GarrisonLogicDefault::new(
session,
Arc::new(config),
firewall,
Arc::new(crate::account::disable::DefaultDisableRepository::new(
dao.clone() as Arc<dyn GarrisonDao>,
)),
);
let token = logic
.login("user-mfa-1", &LoginParams::default())
.await
.unwrap();
let handler = crate::protocol::jwt::JwtHandler::new("0123456789abcdef0123456789abcdef");
let claims = crate::protocol::jwt::tests::verify_ok(&handler, &token);
assert_eq!(
claims.amr,
Some(vec![PRIMARY_FACTOR_AMR.to_string()]),
"主登录签发的 amr 应为 [\"pwd\"]"
);
let now = chrono::Utc::now().timestamp();
assert!(
claims.auth_time.is_some_and(|t| (now - t).abs() <= 5),
"auth_time 应等于签发时刻(±5s),实际: {:?}",
claims.auth_time
);
}
#[tokio::test]
async fn mock_mfa_safe_session_logic_all_methods() {
let mock = MockMfaSafe {
config: Arc::new(GarrisonConfig::default()),
safe_result: Ok(true),
};
let _ = mock.config();
let params = LoginParams::default();
let _ = mock.login("u1", ¶ms).await.unwrap();
let _ = mock.login_with_token("u1", "tok").await;
let _ = mock.logout().await;
let _ = mock.logout_by_login_id("u1").await;
let _ = mock.kickout("u1").await;
let _ = mock.kickout_by_token("tok").await;
let _ = mock.revoke_token("tok").await;
let _ = mock.check_login().await.unwrap();
let _ = mock.get_login_id().await.unwrap();
}
mod t019_disable_integration {
use super::*;
use crate::account::disable::{DefaultDisableRepository, DisableRepository};
use crate::config::GarrisonConfig;
use crate::dao::tests::MockDao;
use crate::dao::GarrisonDao;
use crate::session::GarrisonSession;
use crate::stp::with_current_token;
use crate::stp::LoginParams;
use crate::strategy::GarrisonPermissionStrategy;
use async_trait::async_trait;
use chrono::Utc;
use std::sync::Arc;
struct MockFirewall;
#[async_trait]
impl GarrisonPermissionStrategy for MockFirewall {
async fn get_permission_list(&self, _login_id: &str) -> GarrisonResult<Vec<String>> {
Ok(vec![])
}
async fn get_role_list(&self, _login_id: &str) -> GarrisonResult<Vec<String>> {
Ok(vec![])
}
async fn check_permission(
&self,
_login_id: &str,
_permission: &str,
) -> GarrisonResult<bool> {
Ok(true)
}
async fn check_role(&self, _login_id: &str, _role: &str) -> GarrisonResult<bool> {
Ok(true)
}
async fn check_role_any(
&self,
_login_id: &str,
_roles: &[&str],
) -> GarrisonResult<bool> {
Ok(true)
}
async fn check_role_all(
&self,
_login_id: &str,
_roles: &[&str],
) -> GarrisonResult<bool> {
Ok(true)
}
async fn check_permission_in_tenant(
&self,
_tenant_id: i64,
_login_id: &str,
_permission: &str,
) -> GarrisonResult<bool> {
Ok(true)
}
async fn check_role_in_tenant(
&self,
_tenant_id: i64,
_login_id: &str,
_role: &str,
) -> GarrisonResult<bool> {
Ok(true)
}
#[cfg(any(
feature = "sms-rate-limit",
feature = "firewall-ratelimit",
feature = "firewall-bruteforce",
feature = "firewall-ddos",
feature = "firewall",
feature = "oauth2-server"
))]
async fn check_login_hooks(
&self,
_login_id: &str,
_ctx: &crate::strategy::hooks::LoginContext,
) -> GarrisonResult<()> {
Ok(())
}
}
fn make_logic_with_repo() -> (
GarrisonLogicDefault,
Arc<DefaultDisableRepository>,
Arc<MockDao>,
) {
let dao = Arc::new(MockDao::new());
let session = Arc::new(GarrisonSession::new(
dao.clone() as Arc<dyn GarrisonDao>,
3600,
86400,
0,
));
let mut config = GarrisonConfig::default_config();
config.throw_on_not_login = false;
config.token_style = "uuid".to_string();
let firewall: Arc<dyn GarrisonPermissionStrategy> = Arc::new(MockFirewall);
let repo = Arc::new(DefaultDisableRepository::new(
dao.clone() as Arc<dyn GarrisonDao>
));
let logic = GarrisonLogicDefault::new(
session,
Arc::new(config),
firewall,
repo.clone() as Arc<dyn DisableRepository>,
);
(logic, repo, dao)
}
#[tokio::test]
async fn test_check_disable_not_disabled_returns_ok() {
let (logic, _repo, _dao) = make_logic_with_repo();
let token = logic.login("1001", &LoginParams::default()).await.unwrap();
let result = with_current_token(token, async { logic.check_disable().await }).await;
assert!(
result.is_ok(),
"未封禁时 check_disable 应返回 Ok,实际: {:?}",
result
);
}
#[tokio::test]
async fn test_check_disable_disabled_returns_error() {
let (logic, repo, _dao) = make_logic_with_repo();
let token = logic.login("1001", &LoginParams::default()).await.unwrap();
let until = Utc::now() + chrono::Duration::seconds(3600);
repo.disable("1001", "default", Some(until), 0, 3600)
.await
.unwrap();
let result = with_current_token(token, async { logic.check_disable().await }).await;
match result {
Err(GarrisonError::DisableService { service, .. }) => {
assert_eq!(
service, "default",
"DisableService 错误的 service 字段应为 'default'"
);
},
other => panic!(
"已封禁时 check_disable 应返回 Err(DisableService),实际: {:?}",
other
),
}
}
#[tokio::test]
async fn test_check_disable_permanent_ban_until_none() {
let (logic, repo, _dao) = make_logic_with_repo();
let token = logic.login("1002", &LoginParams::default()).await.unwrap();
repo.disable("1002", "default", None, 0, 0).await.unwrap();
let result = with_current_token(token, async { logic.check_disable().await }).await;
match result {
Err(GarrisonError::DisableService { service, until }) => {
assert_eq!(service, "default");
assert!(
until.is_none(),
"永久封禁 until 应为 None,实际: {:?}",
until
);
},
other => panic!(
"永久封禁应返回 Err(DisableService {{ until: None }}),实际: {:?}",
other
),
}
}
#[tokio::test]
async fn test_check_disable_timed_ban_until_some() {
let (logic, repo, _dao) = make_logic_with_repo();
let token = logic.login("1003", &LoginParams::default()).await.unwrap();
let until = Utc::now() + chrono::Duration::seconds(7200);
repo.disable("1003", "default", Some(until), 0, 7200)
.await
.unwrap();
let result = with_current_token(token, async { logic.check_disable().await }).await;
match result {
Err(GarrisonError::DisableService { service, until: u }) => {
assert_eq!(service, "default");
assert!(u.is_some(), "定时封禁 until 应为 Some");
assert_eq!(
u.unwrap(),
until,
"定时封禁 until 应精确匹配 disable 时设置的值"
);
},
other => panic!(
"定时封禁应返回 Err(DisableService {{ until: Some(_) }}),实际: {:?}",
other
),
}
}
#[tokio::test]
async fn test_check_disable_no_token_returns_ok() {
let (logic, _repo, _dao) = make_logic_with_repo();
let result = logic.check_disable().await;
assert!(
result.is_ok(),
"未登录(无 current_token)时 check_disable 应返回 Ok,实际: {:?}",
result
);
}
#[tokio::test]
async fn test_check_disable_token_session_not_found_fails_closed() {
let (logic, _repo, _dao) = make_logic_with_repo();
let result = with_current_token("nonexistent-token-xyz".to_string(), async {
logic.check_disable().await
})
.await;
assert!(
matches!(result, Err(GarrisonError::Session(_))),
"token 对应的 TokenSession 不存在时 check_disable 应返回 Err(Session),实际: {:?}",
result
);
}
#[tokio::test]
async fn mock_firewall_all_methods() {
let fw = MockFirewall;
let _ = fw.get_permission_list("u1").await.unwrap();
let _ = fw.get_role_list("u1").await.unwrap();
let _ = fw.check_permission("u1", "user:read").await.unwrap();
let _ = fw.check_role("u1", "admin").await.unwrap();
let _ = fw.check_role_any("u1", &["admin", "user"]).await.unwrap();
let _ = fw.check_role_all("u1", &["admin", "user"]).await.unwrap();
}
}
mod t_sec_session_precondition {
use super::*;
use crate::account::disable::DefaultDisableRepository;
use crate::dao::tests::MockDao;
use crate::dao::GarrisonDao;
use crate::session::GarrisonSession;
use crate::stp::with_current_token;
use crate::stp::LoginParams;
use crate::strategy::GarrisonPermissionStrategy;
use async_trait::async_trait;
use std::sync::Arc;
struct MockFirewall;
#[async_trait]
impl GarrisonPermissionStrategy for MockFirewall {
async fn get_permission_list(&self, _login_id: &str) -> GarrisonResult<Vec<String>> {
Ok(vec![])
}
async fn get_role_list(&self, _login_id: &str) -> GarrisonResult<Vec<String>> {
Ok(vec![])
}
async fn check_permission(
&self,
_login_id: &str,
_permission: &str,
) -> GarrisonResult<bool> {
Ok(true)
}
async fn check_role(&self, _login_id: &str, _role: &str) -> GarrisonResult<bool> {
Ok(true)
}
async fn check_role_any(
&self,
_login_id: &str,
_roles: &[&str],
) -> GarrisonResult<bool> {
Ok(true)
}
async fn check_role_all(
&self,
_login_id: &str,
_roles: &[&str],
) -> GarrisonResult<bool> {
Ok(true)
}
async fn check_permission_in_tenant(
&self,
_tenant_id: i64,
_login_id: &str,
_permission: &str,
) -> GarrisonResult<bool> {
Ok(true)
}
async fn check_role_in_tenant(
&self,
_tenant_id: i64,
_login_id: &str,
_role: &str,
) -> GarrisonResult<bool> {
Ok(true)
}
#[cfg(any(
feature = "sms-rate-limit",
feature = "firewall-ratelimit",
feature = "firewall-bruteforce",
feature = "firewall-ddos",
feature = "firewall",
feature = "oauth2-server"
))]
async fn check_login_hooks(
&self,
_login_id: &str,
_ctx: &crate::strategy::hooks::LoginContext,
) -> GarrisonResult<()> {
Ok(())
}
}
fn make_logic() -> GarrisonLogicDefault {
let dao = Arc::new(MockDao::new());
let session = Arc::new(GarrisonSession::new(
dao.clone() as Arc<dyn GarrisonDao>,
3600,
86400,
0,
));
let mut config = GarrisonConfig::default_config();
config.throw_on_not_login = false;
config.token_style = "uuid".to_string();
let firewall: Arc<dyn GarrisonPermissionStrategy> = Arc::new(MockFirewall);
GarrisonLogicDefault::new(
session,
Arc::new(config),
firewall,
Arc::new(DefaultDisableRepository::new(dao)),
)
}
#[tokio::test]
async fn check_safe_rejects_forged_token() {
let logic = make_logic();
let result =
with_current_token("00000000-0000-0000-0000-000000000000".to_string(), async {
logic.check_safe().await
})
.await;
assert!(
matches!(result, Err(GarrisonError::Session(_))),
"伪造 token 的 check_safe 应返回 Err(Session),实际: {:?}",
result
);
}
#[tokio::test]
async fn check_safe_rejects_kicked_out_token() {
let logic = make_logic();
let token = logic
.login("sec-safe-kick", &LoginParams::default())
.await
.unwrap();
logic.kickout("sec-safe-kick").await.unwrap();
let result = with_current_token(token, async { logic.check_safe().await }).await;
assert!(
matches!(result, Err(GarrisonError::Session(_))),
"kickout 后旧 token 的 check_safe 应返回 Err(Session),实际: {:?}",
result
);
}
#[tokio::test]
async fn check_safe_valid_token_behavior_preserved() {
let logic = make_logic();
let token = logic
.login("sec-safe-valid", &LoginParams::default())
.await
.unwrap();
let result = with_current_token(token, async { logic.check_safe().await }).await;
#[cfg(feature = "security-extra")]
assert!(
matches!(result, Err(GarrisonError::NotSafe { .. })),
"security-extra 下有效 token 未 open_safe 应为 NotSafe,实际: {:?}",
result
);
#[cfg(not(feature = "security-extra"))]
assert!(
result.is_ok(),
"无 security-extra 时有效 token 的 check_safe 应保持 Ok,实际: {:?}",
result
);
}
#[tokio::test]
async fn check_disable_rejects_forged_token() {
let logic = make_logic();
let result =
with_current_token("00000000-0000-0000-0000-000000000000".to_string(), async {
logic.check_disable().await
})
.await;
assert!(
matches!(result, Err(GarrisonError::Session(_))),
"伪造 token 的 check_disable 应返回 Err(Session),实际: {:?}",
result
);
}
#[tokio::test]
async fn check_disable_rejects_kicked_out_token() {
let logic = make_logic();
let token = logic
.login("sec-disable-kick", &LoginParams::default())
.await
.unwrap();
logic.kickout("sec-disable-kick").await.unwrap();
let result = with_current_token(token, async { logic.check_disable().await }).await;
assert!(
matches!(result, Err(GarrisonError::Session(_))),
"kickout 后旧 token 的 check_disable 应返回 Err(Session),实际: {:?}",
result
);
}
#[tokio::test]
async fn check_disable_valid_token_unbanned_still_ok() {
let logic = make_logic();
let token = logic
.login("sec-disable-valid", &LoginParams::default())
.await
.unwrap();
let result = with_current_token(token, async { logic.check_disable().await }).await;
assert!(
result.is_ok(),
"有效 token 未封禁时 check_disable 应保持 Ok,实际: {:?}",
result
);
}
}
#[cfg(feature = "security-extra")]
mod t025_check_safe_integration {
use super::*;
use crate::config::GarrisonConfig;
use crate::dao::tests::MockDao;
use crate::dao::GarrisonDao;
use crate::error::GarrisonError;
use crate::session::GarrisonSession;
use crate::stp::session::SessionLogic;
use crate::stp::with_current_token;
use crate::stp::LoginParams;
use crate::strategy::GarrisonPermissionStrategy;
use async_trait::async_trait;
use std::sync::Arc;
struct MockFirewall;
#[async_trait]
impl GarrisonPermissionStrategy for MockFirewall {
async fn get_permission_list(&self, _login_id: &str) -> GarrisonResult<Vec<String>> {
Ok(vec![])
}
async fn get_role_list(&self, _login_id: &str) -> GarrisonResult<Vec<String>> {
Ok(vec![])
}
async fn check_permission(
&self,
_login_id: &str,
_permission: &str,
) -> GarrisonResult<bool> {
Ok(true)
}
async fn check_role(&self, _login_id: &str, _role: &str) -> GarrisonResult<bool> {
Ok(true)
}
async fn check_role_any(
&self,
_login_id: &str,
_roles: &[&str],
) -> GarrisonResult<bool> {
Ok(true)
}
async fn check_role_all(
&self,
_login_id: &str,
_roles: &[&str],
) -> GarrisonResult<bool> {
Ok(true)
}
async fn check_permission_in_tenant(
&self,
_tenant_id: i64,
_login_id: &str,
_permission: &str,
) -> GarrisonResult<bool> {
Ok(true)
}
async fn check_role_in_tenant(
&self,
_tenant_id: i64,
_login_id: &str,
_role: &str,
) -> GarrisonResult<bool> {
Ok(true)
}
#[cfg(any(
feature = "sms-rate-limit",
feature = "firewall-ratelimit",
feature = "firewall-bruteforce",
feature = "firewall-ddos",
feature = "firewall",
feature = "oauth2-server"
))]
async fn check_login_hooks(
&self,
_login_id: &str,
_ctx: &crate::strategy::hooks::LoginContext,
) -> GarrisonResult<()> {
Ok(())
}
}
fn make_logic() -> (GarrisonLogicDefault, Arc<MockDao>) {
let dao = Arc::new(MockDao::new());
let session = Arc::new(GarrisonSession::new(
dao.clone() as Arc<dyn GarrisonDao>,
3600,
86400,
0,
));
let mut config = GarrisonConfig::default_config();
config.throw_on_not_login = false;
config.token_style = "uuid".to_string();
let firewall: Arc<dyn GarrisonPermissionStrategy> = Arc::new(MockFirewall);
let logic = GarrisonLogicDefault::new(
session,
Arc::new(config),
firewall,
Arc::new(crate::account::disable::DefaultDisableRepository::new(
dao.clone(),
)),
);
(logic, dao)
}
#[tokio::test]
async fn t025_check_safe_passes_after_open_safe() {
let (logic, _dao) = make_logic();
let token = logic
.login("user-4001", &LoginParams::default())
.await
.unwrap();
let result = with_current_token(token.clone(), async {
logic.open_safe("default", 3600).await.unwrap();
logic.check_safe().await
})
.await;
assert!(
result.is_ok(),
"open_safe 后 check_safe 应返回 Ok(()),实际: {:?}",
result
);
}
#[tokio::test]
async fn t025_check_safe_fails_without_open_safe() {
let (logic, _dao) = make_logic();
let token = logic
.login("user-4002", &LoginParams::default())
.await
.unwrap();
let result =
with_current_token(token.clone(), async { logic.check_safe().await }).await;
match result {
Err(GarrisonError::NotSafe { reason }) => {
assert_eq!(
reason, "SAFE_EXPIRED",
"未 open_safe 时 check_safe 应返回 NotSafe(reason=\"SAFE_EXPIRED\")"
);
},
other => panic!(
"未 open_safe 时 check_safe 应返回 Err(NotSafe {{ reason: \"SAFE_EXPIRED\" }}),实际: {:?}",
other
),
}
}
#[tokio::test]
async fn t025_check_safe_fails_after_expiry() {
let (logic, _dao) = make_logic();
let token = logic
.login("user-4003", &LoginParams::default())
.await
.unwrap();
let result = with_current_token(token.clone(), async {
logic.open_safe("default", 0).await.unwrap();
logic.check_safe().await
})
.await;
match result {
Err(GarrisonError::NotSafe { reason }) => {
assert_eq!(
reason, "SAFE_EXPIRED",
"过期后 check_safe 应返回 NotSafe(reason=\"SAFE_EXPIRED\")"
);
},
other => panic!(
"过期后 check_safe 应返回 Err(NotSafe {{ reason: \"SAFE_EXPIRED\" }}),实际: {:?}",
other
),
}
}
#[tokio::test]
async fn t025_check_safe_fails_after_close_safe() {
let (logic, _dao) = make_logic();
let token = logic
.login("user-4004", &LoginParams::default())
.await
.unwrap();
let result = with_current_token(token.clone(), async {
logic.open_safe("default", 3600).await.unwrap();
logic.close_safe("default").await.unwrap();
logic.check_safe().await
})
.await;
match result {
Err(GarrisonError::NotSafe { reason }) => {
assert_eq!(
reason, "SAFE_EXPIRED",
"close_safe 后 check_safe 应返回 NotSafe(reason=\"SAFE_EXPIRED\")"
);
},
other => panic!(
"close_safe 后 check_safe 应返回 Err(NotSafe {{ reason: \"SAFE_EXPIRED\" }}),实际: {:?}",
other
),
}
}
}
use crate::stp::mfa::{
assert_freshness, stepup_required, FreshnessInput, FreshnessVerdict, MfaFreshness,
};
#[cfg(feature = "secure-totp")]
use crate::stp::mfa::{ProcessOutcome, RequiredActionContext};
#[test]
fn freshness_fresh_within_window_and_aal() {
let threshold = MfaFreshness {
max_age_secs: 300,
min_aal: 1,
};
let input = FreshnessInput {
auth_time: Some(1_000),
ledger_max_aal: 1,
now: 1_000 + 299,
};
assert_eq!(
assert_freshness(&input, &threshold),
FreshnessVerdict::Fresh
);
assert!(
!stepup_required(&input, &threshold, false),
"新鲜会话不应触发 step-up"
);
}
#[test]
fn freshness_stale_after_window() {
let threshold = MfaFreshness {
max_age_secs: 300,
min_aal: 1,
};
let input = FreshnessInput {
auth_time: Some(1_000),
ledger_max_aal: 2,
now: 1_000 + 301,
};
assert_eq!(
assert_freshness(&input, &threshold),
FreshnessVerdict::Stale
);
assert!(stepup_required(&input, &threshold, false));
}
#[test]
fn freshness_stale_when_aal_below_threshold() {
let threshold = MfaFreshness {
max_age_secs: 300,
min_aal: 2,
};
let input = FreshnessInput {
auth_time: Some(1_000),
ledger_max_aal: 1,
now: 1_005,
};
assert_eq!(
assert_freshness(&input, &threshold),
FreshnessVerdict::Stale
);
}
#[test]
fn freshness_stale_without_auth_time() {
let threshold = MfaFreshness {
max_age_secs: 300,
min_aal: 1,
};
let input = FreshnessInput {
auth_time: None,
ledger_max_aal: 2,
now: 1_000,
};
assert_eq!(
assert_freshness(&input, &threshold),
FreshnessVerdict::Stale
);
}
#[test]
fn valid_remember_cookie_skips_challenge() {
let threshold = MfaFreshness {
max_age_secs: 300,
min_aal: 1,
};
let stale = FreshnessInput {
auth_time: Some(1_000),
ledger_max_aal: 2,
now: 1_000 + 301,
};
assert!(stepup_required(&stale, &threshold, false));
assert!(
!stepup_required(&stale, &threshold, true),
"有效 remember cookie 应跳过重复 challenge"
);
}
#[cfg(feature = "secure-totp")]
#[tokio::test]
async fn totp_provider_process_upgrades_ledger() {
use crate::dao::tests::MockDao;
use crate::dao::GarrisonDao;
use crate::session::token_key;
use crate::session::GarrisonSession;
use crate::session::TokenSession;
use crate::stp::mfa::{complete_required_action, TotpRequiredActionProvider};
use std::sync::Arc;
let dao = Arc::new(MockDao::new());
let session = GarrisonSession::new(dao.clone() as Arc<dyn GarrisonDao>, 3600, 86400, 0);
session.create("user-ta", "TOK").await.unwrap();
let key = token_key("TOK");
let raw = dao.get(&key).await.unwrap().unwrap();
let mut ts: TokenSession = serde_json::from_str(&raw).unwrap();
ts.auth_time = Some(chrono::Utc::now().timestamp() - 3600);
dao.set(&key, &serde_json::to_string(&ts).unwrap(), 3600)
.await
.unwrap();
let now = chrono::Utc::now().timestamp();
let ctx = RequiredActionContext {
login_id: "user-ta".to_string(),
auth_time: ts.auth_time,
ledger_max_aal: 1,
now,
};
let threshold = MfaFreshness {
max_age_secs: 300,
min_aal: 2,
};
let provider = TotpRequiredActionProvider::new("GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ");
assert!(
provider.evaluate(&ctx, &threshold).await.unwrap(),
"过期会话应触发 Required Action"
);
let challenge = provider.challenge(&ctx).await.unwrap();
assert_eq!(challenge.action, "otp");
assert!(!challenge.payload.is_empty());
let code = provider.generate_current_code(now).unwrap();
let outcome = provider.process(&ctx, &code, dao.as_ref()).await.unwrap();
match outcome {
ProcessOutcome::Verified { method, aal } => {
assert_eq!(method, "otp");
assert_eq!(aal, 2);
},
other => panic!("正确验证码应 Verified,实际: {:?}", other),
}
complete_required_action(&session, "TOK", &outcome, now)
.await
.unwrap();
let upgraded = session.get_token_session("TOK").await.unwrap().unwrap();
assert_eq!(upgraded.amr_ledger.len(), 2);
assert_eq!(upgraded.amr_ledger[1].method, "otp");
assert_eq!(upgraded.amr_ledger[1].aal, 2);
assert_eq!(
crate::stp::mfa::ledger_max_aal(&upgraded.amr_ledger),
2,
"process 验证成功后账本最高 AAL 应升级"
);
}
#[cfg(feature = "secure-totp")]
#[tokio::test]
async fn totp_provider_process_wrong_code_rejected() {
use crate::dao::tests::MockDao;
use crate::dao::GarrisonDao;
use crate::session::GarrisonSession;
use crate::stp::mfa::TotpRequiredActionProvider;
use std::sync::Arc;
let dao = Arc::new(MockDao::new());
let session = GarrisonSession::new(dao.clone() as Arc<dyn GarrisonDao>, 3600, 86400, 0);
session.create("user-tb", "TOK2").await.unwrap();
let provider = TotpRequiredActionProvider::new("GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ");
let ctx = RequiredActionContext {
login_id: "user-tb".to_string(),
auth_time: Some(chrono::Utc::now().timestamp() - 3600),
ledger_max_aal: 1,
now: chrono::Utc::now().timestamp(),
};
let outcome = provider
.process(&ctx, "000000", dao.as_ref())
.await
.unwrap();
assert!(
matches!(outcome, ProcessOutcome::Rejected),
"错误验证码应 Rejected,实际: {:?}",
outcome
);
let ts = session.get_token_session("TOK2").await.unwrap().unwrap();
assert_eq!(ts.amr_ledger.len(), 1, "Rejected 不得升级账本");
}
#[cfg(feature = "secure-totp")]
#[tokio::test]
async fn totp_provider_evaluate_fresh_session_skips() {
use crate::stp::mfa::TotpRequiredActionProvider;
let now = chrono::Utc::now().timestamp();
let ctx = RequiredActionContext {
login_id: "user-tc".to_string(),
auth_time: Some(now),
ledger_max_aal: 2,
now,
};
let threshold = MfaFreshness {
max_age_secs: 300,
min_aal: 1,
};
let provider = TotpRequiredActionProvider::new("GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ");
assert!(
!provider.evaluate(&ctx, &threshold).await.unwrap(),
"新鲜会话不应触发 Required Action"
);
}
#[cfg(feature = "mfa-recovery")]
use crate::dao::tests::MockDao;
#[cfg(feature = "mfa-recovery")]
use crate::stp::mfa::{RecoveryCodeManager, RecoveryVerify};
#[cfg(feature = "mfa-recovery")]
#[tokio::test]
async fn recovery_generate_batch_unique_codes() {
let dao = Arc::new(MockDao::new());
let mgr = RecoveryCodeManager::new(dao, 0);
let codes = mgr.generate("user-rc", 10).await.unwrap();
assert_eq!(codes.len(), 10);
assert!(codes.iter().all(|c| !c.is_empty()));
let unique: std::collections::HashSet<&String> = codes.iter().collect();
assert_eq!(unique.len(), 10, "同批次码不得重复");
}
#[cfg(feature = "mfa-recovery")]
#[tokio::test]
async fn recovery_used_code_rejected() {
let dao = Arc::new(MockDao::new());
let mgr = RecoveryCodeManager::new(dao, 0);
let codes = mgr.generate("user-rc2", 1).await.unwrap();
let code = codes[0].clone();
assert_eq!(
mgr.verify("user-rc2", &code).await.unwrap(),
RecoveryVerify::Valid
);
assert!(
mgr.consume("user-rc2", &code).await.unwrap(),
"首次 consume 应成功"
);
assert_eq!(
mgr.verify("user-rc2", &code).await.unwrap(),
RecoveryVerify::Invalid,
"已用码 verify 应拒绝"
);
assert!(
!mgr.consume("user-rc2", &code).await.unwrap(),
"已用码二次消费应失败"
);
}
#[cfg(feature = "mfa-recovery")]
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn recovery_concurrent_consume_only_one_succeeds() {
let dao = Arc::new(MockDao::new());
let mgr = Arc::new(RecoveryCodeManager::new(dao, 0));
let codes = mgr.generate("user-rc3", 1).await.unwrap();
let code = codes[0].clone();
let m1 = Arc::clone(&mgr);
let m2 = Arc::clone(&mgr);
let c1 = code.clone();
let c2 = code.clone();
let (r1, r2) = tokio::join!(
async move { m1.consume("user-rc3", &c1).await },
async move { m2.consume("user-rc3", &c2).await },
);
let successes = [r1.unwrap(), r2.unwrap()]
.into_iter()
.filter(|ok| *ok)
.count();
assert_eq!(successes, 1, "并发消费同一恢复码应恰好一个成功");
}
#[cfg(feature = "mfa-recovery")]
#[tokio::test]
async fn recovery_misuse_over_tolerance_locks() {
let dao = Arc::new(MockDao::new());
let mgr = RecoveryCodeManager::new(dao, 0);
let codes = mgr.generate("user-rc4", 1).await.unwrap();
assert_eq!(
mgr.verify("user-rc4", "wrong-code").await.unwrap(),
RecoveryVerify::Locked,
"tolerance=0 时首次误用即锁定"
);
assert!(
mgr.consume("user-rc4", &codes[0]).await.is_err(),
"锁定状态下 consume 应返回错误"
);
}
#[cfg(feature = "mfa-recovery")]
#[tokio::test]
async fn recovery_misuse_within_tolerance_excused() {
let dao = Arc::new(MockDao::new());
let mgr = RecoveryCodeManager::new(dao, 2);
let codes = mgr.generate("user-rc5", 1).await.unwrap();
assert_eq!(
mgr.verify("user-rc5", "bad-1").await.unwrap(),
RecoveryVerify::Invalid
);
assert_eq!(
mgr.verify("user-rc5", "bad-2").await.unwrap(),
RecoveryVerify::Invalid
);
assert_eq!(
mgr.verify("user-rc5", "bad-3").await.unwrap(),
RecoveryVerify::Locked,
"第三次误用(超过 tolerance=2)应锁定"
);
assert!(
mgr.consume("user-rc5", &codes[0]).await.is_err(),
"锁定后正确码也不得消费"
);
}
#[cfg(feature = "protocol-jwt")]
#[test]
fn mfa_remember_cookie_roundtrip_and_buildpoint_attributes() {
let config = GarrisonConfig::default_config();
let secret = "0123456789abcdef0123456789abcdef";
let set_cookie =
issue_mfa_remember_cookie(secret, &config, "login", "user-rc", "cred-1", 3600).unwrap();
let expected_name = CookieType::session(MFA_REMEMBER_COOKIE_NAME, &config)
.unwrap()
.resolved_name(config.cookie_secure);
assert!(
set_cookie.starts_with(&format!("{expected_name}=")),
"cookie 名应与构建点 resolved_name 一致,实际: {}",
set_cookie
);
assert!(
set_cookie.contains("HttpOnly"),
"HttpOnly 恒定,实际: {}",
set_cookie
);
assert!(set_cookie.contains("SameSite="), "实际: {}", set_cookie);
assert!(set_cookie.contains("Path=/"), "实际: {}", set_cookie);
assert!(set_cookie.contains("Max-Age=3600"), "实际: {}", set_cookie);
let jwt = set_cookie
.split(';')
.next()
.unwrap()
.split_once('=')
.unwrap()
.1;
let now = chrono::Utc::now().timestamp();
assert!(
verify_mfa_remember_cookie(secret, jwt, "login", "user-rc", "cred-1", now),
"有效 cookie 应通过校验(跳过重复 challenge)"
);
}
#[cfg(feature = "protocol-jwt")]
#[test]
fn mfa_remember_cookie_not_portable_across_credentials() {
let config = GarrisonConfig::default_config();
let secret = "0123456789abcdef0123456789abcdef";
let set_cookie =
issue_mfa_remember_cookie(secret, &config, "login", "user-rc", "cred-1", 3600).unwrap();
let jwt = set_cookie
.split(';')
.next()
.unwrap()
.split_once('=')
.unwrap()
.1;
let now = chrono::Utc::now().timestamp();
assert!(
!verify_mfa_remember_cookie(secret, jwt, "login", "user-rc", "cred-2", now),
"跨 credential 的 cookie 不得通用"
);
assert!(
!verify_mfa_remember_cookie(secret, jwt, "other-stage", "user-rc", "cred-1", now),
"跨 stage 的 cookie 不得通用"
);
}
#[cfg(feature = "protocol-jwt")]
#[test]
fn mfa_remember_cookie_not_portable_across_subjects() {
let config = GarrisonConfig::default_config();
let secret = "0123456789abcdef0123456789abcdef";
let set_cookie =
issue_mfa_remember_cookie(secret, &config, "login", "user-a", "cred-1", 3600).unwrap();
let jwt = set_cookie
.split(';')
.next()
.unwrap()
.split_once('=')
.unwrap()
.1;
let now = chrono::Utc::now().timestamp();
assert!(
!verify_mfa_remember_cookie(secret, jwt, "login", "user-b", "cred-1", now),
"跨主体的 cookie 不得通用"
);
}
#[cfg(feature = "protocol-jwt")]
#[test]
fn mfa_remember_cookie_expired_is_invalid() {
let secret = "0123456789abcdef0123456789abcdef";
let claims = MfaRememberClaims {
stage: "login".to_string(),
login_id: "user-rc".to_string(),
credential_id: "cred-1".to_string(),
exp: chrono::Utc::now().timestamp() - 10,
};
let jwt = jsonwebtoken::encode(
&jsonwebtoken::Header::new(jsonwebtoken::Algorithm::HS256),
&claims,
&jsonwebtoken::EncodingKey::from_secret(secret.as_bytes()),
)
.unwrap();
assert!(
!verify_mfa_remember_cookie(
secret,
&jwt,
"login",
"user-rc",
"cred-1",
chrono::Utc::now().timestamp()
),
"过期 cookie 应失效"
);
}
#[cfg(feature = "protocol-jwt")]
#[test]
fn mfa_remember_cookie_rejects_tamper_and_short_secret() {
let config = GarrisonConfig::default_config();
let secret = "0123456789abcdef0123456789abcdef";
let set_cookie =
issue_mfa_remember_cookie(secret, &config, "login", "user-rc", "cred-1", 3600).unwrap();
let jwt = set_cookie
.split(';')
.next()
.unwrap()
.split_once('=')
.unwrap()
.1;
let now = chrono::Utc::now().timestamp();
assert!(!verify_mfa_remember_cookie(
"ffffffffffffffffffffffffffffffff",
jwt,
"login",
"user-rc",
"cred-1",
now
));
let result =
issue_mfa_remember_cookie("short", &config, "login", "user-rc", "cred-1", 3600);
assert!(
matches!(result, Err(GarrisonError::Config(ref m)) if m.contains("mfa-remember-secret-too-short")),
"短密钥应 fail-fast,实际: {:?}",
result.map(|_| ())
);
}
#[cfg(feature = "protocol-jwt")]
#[test]
fn mfa_remember_cookie_none_downgrades_via_buildpoint() {
let mut config = GarrisonConfig::default_config();
config.cookie_same_site = "None".to_string();
config.cookie_secure = false;
let set_cookie = issue_mfa_remember_cookie(
"0123456789abcdef0123456789abcdef",
&config,
"login",
"user-rc",
"c",
60,
)
.unwrap();
assert!(
set_cookie.contains("SameSite=Lax"),
"非 Secure 上下文应降级 Lax,实际: {}",
set_cookie
);
assert!(!set_cookie.contains("SameSite=None"));
}
use crate::stp::mfa::{chain_factor_amr, first_unmet_chain_factor};
#[test]
fn chain_factor_amr_maps_vocabulary() {
assert_eq!(chain_factor_amr("otp"), Some("otp"));
assert_eq!(chain_factor_amr("webauthn"), Some("webauthn"));
assert_eq!(chain_factor_amr("sms"), None);
}
#[test]
fn first_unmet_chain_factor_finds_gap() {
use crate::stp::mfa::MfaChainDecision;
let ledger = vec![AmrEntry::new("pwd", 1, 1).unwrap()];
let decision = MfaChainDecision::Require(vec!["otp".to_string()]);
assert_eq!(
first_unmet_chain_factor(&decision, &ledger),
Some("otp".to_string())
);
let full = vec![
AmrEntry::new("pwd", 1, 1).unwrap(),
AmrEntry::new("otp", 2, 2).unwrap(),
];
assert_eq!(first_unmet_chain_factor(&decision, &full), None);
assert_eq!(
first_unmet_chain_factor(&MfaChainDecision::None, &ledger),
None
);
}
async fn logged_in_logic(config: GarrisonConfig) -> (GarrisonLogicDefault, String) {
use crate::account::disable::DefaultDisableRepository;
use crate::dao::tests::MockDao;
use crate::dao::GarrisonDao;
use crate::session::GarrisonSession;
use crate::strategy::GarrisonPermissionStrategy;
struct NoopFirewall;
#[async_trait::async_trait]
impl GarrisonPermissionStrategy for NoopFirewall {
async fn get_permission_list(&self, _login_id: &str) -> GarrisonResult<Vec<String>> {
Ok(vec![])
}
async fn get_role_list(&self, _login_id: &str) -> GarrisonResult<Vec<String>> {
Ok(vec![])
}
async fn check_permission(
&self,
_login_id: &str,
_permission: &str,
) -> GarrisonResult<bool> {
Ok(true)
}
async fn check_role(&self, _login_id: &str, _role: &str) -> GarrisonResult<bool> {
Ok(true)
}
async fn check_role_any(
&self,
_login_id: &str,
_roles: &[&str],
) -> GarrisonResult<bool> {
Ok(true)
}
async fn check_role_all(
&self,
_login_id: &str,
_roles: &[&str],
) -> GarrisonResult<bool> {
Ok(true)
}
async fn check_permission_in_tenant(
&self,
_tenant_id: i64,
_login_id: &str,
_permission: &str,
) -> GarrisonResult<bool> {
Ok(true)
}
async fn check_role_in_tenant(
&self,
_tenant_id: i64,
_login_id: &str,
_role: &str,
) -> GarrisonResult<bool> {
Ok(true)
}
#[cfg(any(
feature = "sms-rate-limit",
feature = "firewall-ratelimit",
feature = "firewall-bruteforce",
feature = "firewall-ddos",
feature = "firewall",
feature = "oauth2-server"
))]
async fn check_login_hooks(
&self,
_login_id: &str,
_ctx: &crate::strategy::hooks::LoginContext,
) -> GarrisonResult<()> {
Ok(())
}
}
let dao = Arc::new(MockDao::new());
let session = Arc::new(GarrisonSession::new(
dao.clone() as Arc<dyn GarrisonDao>,
3600,
86400,
0,
));
let mut config = config;
config.throw_on_not_login = false;
let firewall: Arc<dyn GarrisonPermissionStrategy> = Arc::new(NoopFirewall);
let logic = GarrisonLogicDefault::new(
session,
Arc::new(config),
firewall,
Arc::new(DefaultDisableRepository::new(dao as Arc<dyn GarrisonDao>)),
);
let token = logic
.login("chain-user", &LoginParams::default())
.await
.unwrap();
(logic, token)
}
#[tokio::test]
async fn check_mfa_chain_enforces_global_chain() {
let mut config = GarrisonConfig::default_config();
config.mfa.global_chain = vec!["otp".to_string()];
let (logic, token) = logged_in_logic(config).await;
use crate::stp::with_current_token;
let result =
with_current_token(token.clone(), async { logic.check_mfa_chain(None).await }).await;
match &result {
Err(GarrisonError::NotSafe { reason }) => assert_eq!(
reason, "MFA_CHAIN_INCOMPLETE::otp",
"缺 otp 时应报告具体缺失因子"
),
other => panic!("账本未覆盖强制链应 Err,实际 ok={:?}", other.is_ok()),
}
logic
.session
.append_amr_entry(&token, "otp", 2, chrono::Utc::now().timestamp())
.await
.unwrap();
let result = with_current_token(token, async { logic.check_mfa_chain(None).await }).await;
assert!(
result.is_ok(),
"补齐后链校验应通过,实际: {:?}",
result.err()
);
}
#[tokio::test]
async fn check_mfa_chain_per_client_tri_state() {
use crate::stp::with_current_token;
let mut config = GarrisonConfig::default_config();
config.mfa.global_chain = vec!["otp".to_string()];
config
.mfa
.per_client_chains
.insert("acme".to_string(), vec![]);
let (logic, token) = logged_in_logic(config).await;
let ok =
with_current_token(token, async { logic.check_mfa_chain(Some("acme")).await }).await;
assert!(
ok.is_ok(),
"显式禁用的 client 不应强制,实际: {:?}",
ok.err()
);
let mut config = GarrisonConfig::default_config();
config.mfa.global_chain = vec![];
config
.mfa
.per_client_chains
.insert("web".to_string(), vec!["otp".to_string()]);
let (logic, token) = logged_in_logic(config).await;
let result =
with_current_token(token, async { logic.check_mfa_chain(Some("web")).await }).await;
assert!(
matches!(&result, Err(GarrisonError::NotSafe { reason }) if reason == "MFA_CHAIN_INCOMPLETE::otp"),
"per-client 强制集应生效,实际: {:?}",
result.map(|_| ())
);
}
#[cfg(feature = "security-extra")]
#[tokio::test]
async fn check_safe_enforces_chain_before_safe_service() {
use crate::stp::with_current_token;
let mut config = GarrisonConfig::default_config();
config.mfa.global_chain = vec!["otp".to_string()];
let (logic, token) = logged_in_logic(config).await;
let result = with_current_token(token, async { logic.check_safe().await }).await;
match &result {
Err(GarrisonError::NotSafe { reason }) => assert!(
reason.starts_with("MFA_CHAIN_INCOMPLETE"),
"链校验应先于 safe-service 检查,实际: {}",
reason
),
other => panic!("链未满足时 check_safe 应 Err,实际 ok={:?}", other.is_ok()),
}
}
}