use super::{PasswordPolicyRule, PolicyContext, PolicyError};
use crate::account::credential::PasswordVerifier;
use crate::loc;
pub struct LengthRule {
min: u32,
max: u32,
}
impl LengthRule {
pub fn new(min: u32, max: u32) -> Self {
Self { min, max }
}
}
impl PasswordPolicyRule for LengthRule {
fn name(&self) -> &'static str {
"length"
}
fn validate(&self, _ctx: &PolicyContext, password: &str) -> Result<(), PolicyError> {
let len = password.chars().count() as u32;
if len < self.min {
return Err(PolicyError::new(
"length",
loc!("policy-length-too-short", ""),
));
}
if len > self.max {
return Err(PolicyError::new(
"length",
loc!("policy-length-too-long", ""),
));
}
Ok(())
}
}
const MAX_HISTORY_COUNT: u32 = 24;
pub struct HistoryRule {
count: u32,
}
impl HistoryRule {
pub fn new(count: u32) -> Self {
Self {
count: count.min(MAX_HISTORY_COUNT),
}
}
}
impl PasswordPolicyRule for HistoryRule {
fn name(&self) -> &'static str {
"history"
}
fn validate(&self, ctx: &PolicyContext, password: &str) -> Result<(), PolicyError> {
if ctx.password_history.is_empty() || self.count == 0 {
return Ok(());
}
let start = ctx
.password_history
.len()
.saturating_sub(self.count as usize);
for hash in &ctx.password_history[start..] {
match PasswordVerifier::verify(password, hash) {
Ok(true) => {
return Err(PolicyError::new(
"history",
loc!("policy-history-duplicate", ""),
));
},
Ok(false) => {},
Err(e) => {
tracing::warn!(
rule = "history",
error = %e,
"password history hash verify failed, skipping entry (fail-open)"
);
},
}
}
Ok(())
}
}
pub struct BlacklistRule {
passwords: Vec<String>,
}
impl BlacklistRule {
pub fn new(passwords: Vec<String>) -> Self {
Self { passwords }
}
}
impl PasswordPolicyRule for BlacklistRule {
fn name(&self) -> &'static str {
"blacklist"
}
fn validate(&self, _ctx: &PolicyContext, password: &str) -> Result<(), PolicyError> {
if self.passwords.iter().any(|p| p == password) {
return Err(PolicyError::new(
"blacklist",
loc!("policy-blacklist-match", ""),
));
}
Ok(())
}
}
pub struct NotUsernameRule;
impl NotUsernameRule {
pub fn new() -> Self {
Self
}
}
impl Default for NotUsernameRule {
fn default() -> Self {
Self::new()
}
}
impl PasswordPolicyRule for NotUsernameRule {
fn name(&self) -> &'static str {
"not_username"
}
fn validate(&self, ctx: &PolicyContext, password: &str) -> Result<(), PolicyError> {
let Some(username) = &ctx.username else {
return Ok(());
};
if username.is_empty() {
return Ok(());
}
let password_lower = password.to_lowercase();
let username_lower = username.to_lowercase();
if password_lower.contains(&username_lower) {
return Err(PolicyError::new(
"not_username",
loc!("policy-contains-username", ""),
));
}
Ok(())
}
}
pub struct NotCommonPasswordRule {
common_list: Vec<String>,
}
impl NotCommonPasswordRule {
pub fn new(common_list: Vec<String>) -> Self {
Self { common_list }
}
}
impl PasswordPolicyRule for NotCommonPasswordRule {
fn name(&self) -> &'static str {
"not_common_password"
}
fn validate(&self, _ctx: &PolicyContext, password: &str) -> Result<(), PolicyError> {
if self.common_list.iter().any(|p| p == password) {
return Err(PolicyError::new(
"not_common_password",
loc!("policy-common-password", ""),
));
}
Ok(())
}
}
pub struct MaxAgeRule {
days: u32,
}
impl MaxAgeRule {
pub fn new(days: u32) -> Self {
Self { days }
}
}
impl PasswordPolicyRule for MaxAgeRule {
fn name(&self) -> &'static str {
"max_age"
}
fn validate(&self, ctx: &PolicyContext, _password: &str) -> Result<(), PolicyError> {
let Some(created_at) = ctx.password_created_at else {
return Ok(());
};
let now = chrono::Utc::now().timestamp();
let max_age_secs = self.days as i64 * 86_400;
if now - created_at > max_age_secs {
return Err(PolicyError::new(
"max_age",
loc!("policy-max-age-expired", ""),
));
}
Ok(())
}
}
pub struct DictionaryRule {
dictionary: Vec<String>,
}
impl DictionaryRule {
pub fn new(dictionary: Vec<String>) -> Self {
Self { dictionary }
}
}
impl PasswordPolicyRule for DictionaryRule {
fn name(&self) -> &'static str {
"dictionary"
}
fn validate(&self, _ctx: &PolicyContext, password: &str) -> Result<(), PolicyError> {
if self.dictionary.iter().any(|w| w == password) {
return Err(PolicyError::new(
"dictionary",
loc!("policy-dictionary-word", ""),
));
}
Ok(())
}
}
pub struct NotEmailRule;
impl NotEmailRule {
pub fn new() -> Self {
Self
}
}
impl Default for NotEmailRule {
fn default() -> Self {
Self::new()
}
}
impl PasswordPolicyRule for NotEmailRule {
fn name(&self) -> &'static str {
"not_email"
}
fn validate(&self, ctx: &PolicyContext, password: &str) -> Result<(), PolicyError> {
let Some(email) = &ctx.email else {
return Ok(());
};
let local_part = match email.split_once('@') {
Some((local, _)) => local,
None => return Ok(()), };
if local_part.is_empty() {
return Ok(());
}
let password_lower = password.to_lowercase();
let local_lower = local_part.to_lowercase();
if password_lower.contains(&local_lower) {
return Err(PolicyError::new(
"not_email",
loc!("policy-contains-email-prefix", ""),
));
}
Ok(())
}
}
pub struct RegexRule {
pattern: regex::Regex,
error_msg: String,
}
impl RegexRule {
pub fn new(pattern: regex::Regex, error_msg: String) -> Self {
Self { pattern, error_msg }
}
}
impl PasswordPolicyRule for RegexRule {
fn name(&self) -> &'static str {
"regex"
}
fn validate(&self, _ctx: &PolicyContext, password: &str) -> Result<(), PolicyError> {
if self.pattern.is_match(password) {
return Err(PolicyError::new("regex", self.error_msg.clone()));
}
Ok(())
}
}
pub struct NistComplianceRule {
min_length: u32,
}
impl NistComplianceRule {
pub fn new(min_length: u32) -> Self {
Self { min_length }
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct HibpVerdict {
pub pwned: bool,
pub count: u64,
pub service_available: bool,
}
impl NistComplianceRule {
#[cfg(feature = "policy-hibp")]
const HIBP_URL: &'static str = "https://api.pwnedpasswords.com/range";
#[cfg(feature = "policy-hibp")]
const DEFAULT_HIBP_THRESHOLD: u64 = 1;
#[cfg(feature = "policy-hibp")]
const HIBP_TIMEOUT_SECS: u64 = 3;
#[cfg(feature = "policy-hibp")]
pub async fn check_hibp(&self, password: &str) -> Result<HibpVerdict, PolicyError> {
self.check_hibp_with_base(password, Self::HIBP_URL).await
}
#[cfg(feature = "policy-hibp")]
pub async fn check_hibp_with_base(
&self,
password: &str,
base_url: &str,
) -> Result<HibpVerdict, PolicyError> {
use sha1::{Digest, Sha1};
let digest = Sha1::digest(password.as_bytes());
let hex_digest: String = digest.iter().map(|b| format!("{b:02x}")).collect();
let prefix = &hex_digest[..5];
let suffix = &hex_digest[5..];
let url = format!("{base_url}/{prefix}");
let client = reqwest::Client::builder()
.timeout(std::time::Duration::from_secs(Self::HIBP_TIMEOUT_SECS))
.build()
.map_err(|e| {
tracing::warn!("hibp-client-build-failed::{}", e);
PolicyError::new("hibp", format!("hibp-client-build-failed::{e}"))
})?;
let resp = match client.get(&url).send().await {
Ok(r) if r.status().is_success() => r,
Ok(r) => {
tracing::warn!("hibp-http-status::{url}::{}", r.status());
return Ok(HibpVerdict {
pwned: false,
count: 0,
service_available: false,
});
},
Err(e) => {
tracing::warn!("hibp-request-failed::{url}::{e}");
return Ok(HibpVerdict {
pwned: false,
count: 0,
service_available: false,
});
},
};
let body = match resp.text().await {
Ok(b) => b,
Err(e) => {
tracing::warn!("hibp-body-read-failed::{e}");
return Ok(HibpVerdict {
pwned: false,
count: 0,
service_available: false,
});
},
};
let suffix_lower = suffix.to_lowercase();
let mut total: u64 = 0;
for line in body.lines() {
if let Some((hit, count_str)) = line.split_once(':') {
if hit.trim().to_lowercase() == suffix_lower {
if let Ok(c) = count_str.trim().parse::<u64>() {
total = total.saturating_add(c);
}
}
}
}
Ok(HibpVerdict {
pwned: total >= Self::DEFAULT_HIBP_THRESHOLD,
count: total,
service_available: true,
})
}
#[cfg(not(feature = "policy-hibp"))]
pub async fn check_hibp(&self, _password: &str) -> Result<HibpVerdict, PolicyError> {
Err(PolicyError::new(
"hibp",
loc!("policy-hibp-requires-feature", ""),
))
}
}
impl PasswordPolicyRule for NistComplianceRule {
fn name(&self) -> &'static str {
"nist_compliance"
}
fn validate(&self, _ctx: &PolicyContext, password: &str) -> Result<(), PolicyError> {
let len = password.chars().count() as u32;
if len < self.min_length {
return Err(PolicyError::new(
"nist_compliance",
format!("policy-nist-length-too-short::{}::{}", len, self.min_length),
));
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::account::credential::Argon2Hasher;
use crate::account::credential::PasswordHasher;
fn make_ctx(username: Option<&str>, history: Vec<&str>) -> PolicyContext {
PolicyContext {
user_id: "test-user".to_string(),
tenant_id: None,
username: username.map(|s| s.to_string()),
email: None,
password_history: history.into_iter().map(|s| s.to_string()).collect(),
password_created_at: None,
}
}
#[test]
fn length_rule_passes_within_range() {
let rule = LengthRule::new(8, 128);
let ctx = make_ctx(None, vec![]);
assert!(rule.validate(&ctx, "password").is_ok());
}
#[test]
fn length_rule_fails_too_short() {
let rule = LengthRule::new(8, 128);
let ctx = make_ctx(None, vec![]);
let result = rule.validate(&ctx, "short");
assert!(result.is_err());
let err = result.unwrap_err();
assert_eq!(err.rule_name, "length");
}
#[test]
fn length_rule_fails_too_long() {
let rule = LengthRule::new(8, 10);
let ctx = make_ctx(None, vec![]);
let result = rule.validate(&ctx, "this_is_too_long");
assert!(result.is_err());
assert_eq!(result.unwrap_err().rule_name, "length");
}
#[test]
fn length_rule_boundary_min_and_max_pass() {
let rule = LengthRule::new(4, 8);
let ctx = make_ctx(None, vec![]);
assert!(rule.validate(&ctx, "abcd").is_ok(), "== min 应通过");
assert!(rule.validate(&ctx, "abcdefgh").is_ok(), "== max 应通过");
}
#[test]
fn length_rule_name_returns_length() {
let rule = LengthRule::new(8, 128);
assert_eq!(rule.name(), "length");
}
#[test]
fn history_rule_passes_no_match() {
let hasher = Argon2Hasher::default();
let hash = hasher.hash("old-password").unwrap();
let rule = HistoryRule::new(3);
let ctx = make_ctx(None, vec![&hash]);
assert!(rule.validate(&ctx, "new-password").is_ok());
}
#[test]
fn history_rule_fails_matches_recent() {
let hasher = Argon2Hasher::default();
let hash = hasher.hash("same-password").unwrap();
let rule = HistoryRule::new(3);
let ctx = make_ctx(None, vec![&hash]);
let result = rule.validate(&ctx, "same-password");
assert!(result.is_err());
assert_eq!(result.unwrap_err().rule_name, "history");
}
#[test]
fn history_rule_passes_empty_history() {
let rule = HistoryRule::new(3);
let ctx = make_ctx(None, vec![]);
assert!(rule.validate(&ctx, "any").is_ok());
}
#[test]
fn history_rule_passes_history_shorter_than_count() {
let hasher = Argon2Hasher::default();
let h1 = hasher.hash("pw1").unwrap();
let rule = HistoryRule::new(5);
let ctx = make_ctx(None, vec![&h1]);
assert!(rule.validate(&ctx, "pw2").is_ok());
}
#[test]
fn history_rule_only_checks_recent_count() {
let hasher = Argon2Hasher::default();
let h1 = hasher.hash("very-old").unwrap();
let h2 = hasher.hash("recent").unwrap();
let rule = HistoryRule::new(1);
let ctx = make_ctx(None, vec![&h1, &h2]);
assert!(
rule.validate(&ctx, "very-old").is_ok(),
"very-old 不在最近 1 条中,应通过"
);
assert!(
rule.validate(&ctx, "recent").is_err(),
"recent 在最近 1 条中,应失败"
);
}
#[test]
fn history_rule_count_zero_always_passes() {
let hasher = Argon2Hasher::default();
let hash = hasher.hash("same").unwrap();
let rule = HistoryRule::new(0);
let ctx = make_ctx(None, vec![&hash]);
assert!(rule.validate(&ctx, "same").is_ok());
}
#[test]
fn history_rule_count_clamped_to_max() {
let clamped = HistoryRule::new(10_000);
assert_eq!(
clamped.count, MAX_HISTORY_COUNT,
"count 超上限应被钳制到 MAX_HISTORY_COUNT"
);
assert_eq!(HistoryRule::new(5).count, 5);
assert_eq!(HistoryRule::new(MAX_HISTORY_COUNT).count, MAX_HISTORY_COUNT);
}
#[test]
fn history_rule_name_returns_history() {
let rule = HistoryRule::new(3);
assert_eq!(rule.name(), "history");
}
#[test]
fn blacklist_rule_passes_not_in_list() {
let rule = BlacklistRule::new(vec!["password".into(), "123456".into()]);
let ctx = make_ctx(None, vec![]);
assert!(rule.validate(&ctx, "secure-pw").is_ok());
}
#[test]
fn blacklist_rule_fails_in_list() {
let rule = BlacklistRule::new(vec!["password".into(), "123456".into()]);
let ctx = make_ctx(None, vec![]);
let result = rule.validate(&ctx, "password");
assert!(result.is_err());
assert_eq!(result.unwrap_err().rule_name, "blacklist");
}
#[test]
fn blacklist_rule_passes_empty_list() {
let rule = BlacklistRule::new(vec![]);
let ctx = make_ctx(None, vec![]);
assert!(rule.validate(&ctx, "anything").is_ok());
}
#[test]
fn blacklist_rule_exact_match_not_substring() {
let rule = BlacklistRule::new(vec!["pass".into()]);
let ctx = make_ctx(None, vec![]);
assert!(rule.validate(&ctx, "password").is_ok());
}
#[test]
fn blacklist_rule_name_returns_blacklist() {
let rule = BlacklistRule::new(vec![]);
assert_eq!(rule.name(), "blacklist");
}
#[test]
fn not_username_rule_passes_no_username() {
let rule = NotUsernameRule::new();
let ctx = make_ctx(None, vec![]);
assert!(rule.validate(&ctx, "anything").is_ok());
}
#[test]
fn not_username_rule_passes_does_not_contain() {
let rule = NotUsernameRule::new();
let ctx = make_ctx(Some("alice"), vec![]);
assert!(rule.validate(&ctx, "secure-pw").is_ok());
}
#[test]
fn not_username_rule_fails_contains_username() {
let rule = NotUsernameRule::new();
let ctx = make_ctx(Some("alice"), vec![]);
let result = rule.validate(&ctx, "alice123");
assert!(result.is_err());
assert_eq!(result.unwrap_err().rule_name, "not_username");
}
#[test]
fn not_username_rule_case_insensitive() {
let rule = NotUsernameRule::new();
let ctx = make_ctx(Some("Alice"), vec![]);
assert!(
rule.validate(&ctx, "ALICE123").is_err(),
"大写密码包含小写用户名应失败"
);
assert!(
rule.validate(&ctx, "alice123").is_err(),
"小写密码包含大写用户名应失败"
);
}
#[test]
fn not_username_rule_name_returns_not_username() {
let rule = NotUsernameRule::new();
assert_eq!(rule.name(), "not_username");
}
#[test]
fn not_common_password_rule_passes_not_in_list() {
let rule = NotCommonPasswordRule::new(vec!["123456".into(), "password".into()]);
let ctx = make_ctx(None, vec![]);
assert!(rule.validate(&ctx, "secure-pw").is_ok());
}
#[test]
fn not_common_password_rule_fails_in_list() {
let rule = NotCommonPasswordRule::new(vec!["123456".into(), "password".into()]);
let ctx = make_ctx(None, vec![]);
let result = rule.validate(&ctx, "123456");
assert!(result.is_err());
assert_eq!(result.unwrap_err().rule_name, "not_common_password");
}
#[test]
fn not_common_password_rule_passes_empty_list() {
let rule = NotCommonPasswordRule::new(vec![]);
let ctx = make_ctx(None, vec![]);
assert!(rule.validate(&ctx, "anything").is_ok());
}
#[test]
fn not_common_password_rule_exact_match_not_substring() {
let rule = NotCommonPasswordRule::new(vec!["pass".into()]);
let ctx = make_ctx(None, vec![]);
assert!(rule.validate(&ctx, "password").is_ok());
}
#[test]
fn not_common_password_rule_name_returns_not_common_password() {
let rule = NotCommonPasswordRule::new(vec![]);
assert_eq!(rule.name(), "not_common_password");
}
#[test]
fn max_age_rule_no_created_at_passes() {
let rule = MaxAgeRule::new(90);
let mut ctx = make_ctx(None, vec![]);
ctx.password_created_at = None;
assert!(rule.validate(&ctx, "any-password").is_ok());
}
#[test]
fn max_age_rule_password_not_expired_passes() {
let rule = MaxAgeRule::new(90);
let mut ctx = make_ctx(None, vec![]);
ctx.password_created_at = Some(chrono::Utc::now().timestamp() - 30 * 86_400);
assert!(rule.validate(&ctx, "any-password").is_ok());
}
#[test]
fn max_age_rule_password_expired_fails() {
let rule = MaxAgeRule::new(90);
let mut ctx = make_ctx(None, vec![]);
ctx.password_created_at = Some(chrono::Utc::now().timestamp() - 100 * 86_400);
let result = rule.validate(&ctx, "any-password");
assert!(result.is_err());
assert_eq!(result.unwrap_err().rule_name, "max_age");
}
#[test]
fn max_age_rule_boundary_exactly_expired_fails() {
let rule = MaxAgeRule::new(90);
let mut ctx = make_ctx(None, vec![]);
ctx.password_created_at = Some(chrono::Utc::now().timestamp() - 90 * 86_400 - 1);
let result = rule.validate(&ctx, "any-password");
assert!(result.is_err());
}
#[test]
fn max_age_rule_boundary_exactly_not_expired_passes() {
let rule = MaxAgeRule::new(90);
let mut ctx = make_ctx(None, vec![]);
ctx.password_created_at = Some(chrono::Utc::now().timestamp() - 90 * 86_400);
assert!(rule.validate(&ctx, "any-password").is_ok());
}
#[test]
fn max_age_rule_name_returns_max_age() {
let rule = MaxAgeRule::new(90);
assert_eq!(rule.name(), "max_age");
}
#[test]
fn dictionary_rule_passes_not_in_dictionary() {
let rule = DictionaryRule::new(vec!["hello".into(), "world".into()]);
let ctx = make_ctx(None, vec![]);
assert!(rule.validate(&ctx, "secure-pw").is_ok());
}
#[test]
fn dictionary_rule_fails_in_dictionary() {
let rule = DictionaryRule::new(vec!["hello".into(), "world".into()]);
let ctx = make_ctx(None, vec![]);
let result = rule.validate(&ctx, "hello");
assert!(result.is_err());
assert_eq!(result.unwrap_err().rule_name, "dictionary");
}
#[test]
fn dictionary_rule_passes_empty_dictionary() {
let rule = DictionaryRule::new(vec![]);
let ctx = make_ctx(None, vec![]);
assert!(rule.validate(&ctx, "anything").is_ok());
}
#[test]
fn dictionary_rule_exact_match_not_substring() {
let rule = DictionaryRule::new(vec!["hello".into()]);
let ctx = make_ctx(None, vec![]);
assert!(rule.validate(&ctx, "helloworld").is_ok());
}
#[test]
fn dictionary_rule_name_returns_dictionary() {
let rule = DictionaryRule::new(vec![]);
assert_eq!(rule.name(), "dictionary");
}
#[test]
fn not_email_rule_passes_no_email() {
let rule = NotEmailRule::new();
let ctx = make_ctx(None, vec![]);
assert!(rule.validate(&ctx, "anything").is_ok());
}
#[test]
fn not_email_rule_passes_does_not_contain() {
let rule = NotEmailRule::new();
let ctx = PolicyContext {
user_id: "test-user".to_string(),
tenant_id: None,
username: None,
email: Some("alice@example.com".to_string()),
password_history: vec![],
password_created_at: None,
};
assert!(rule.validate(&ctx, "secure-pw").is_ok());
}
#[test]
fn not_email_rule_fails_contains_email_prefix() {
let rule = NotEmailRule::new();
let ctx = PolicyContext {
user_id: "test-user".to_string(),
tenant_id: None,
username: None,
email: Some("alice@example.com".to_string()),
password_history: vec![],
password_created_at: None,
};
let result = rule.validate(&ctx, "alice123");
assert!(result.is_err());
assert_eq!(result.unwrap_err().rule_name, "not_email");
}
#[test]
fn not_email_rule_case_insensitive() {
let rule = NotEmailRule::new();
let ctx = PolicyContext {
user_id: "test-user".to_string(),
tenant_id: None,
username: None,
email: Some("Alice@example.com".to_string()),
password_history: vec![],
password_created_at: None,
};
assert!(
rule.validate(&ctx, "ALICE123").is_err(),
"大写密码包含小写邮箱前缀应失败"
);
}
#[test]
fn not_email_rule_no_at_sign_passes() {
let rule = NotEmailRule::new();
let ctx = PolicyContext {
user_id: "test-user".to_string(),
tenant_id: None,
username: None,
email: Some("alice".to_string()),
password_history: vec![],
password_created_at: None,
};
assert!(rule.validate(&ctx, "alice123").is_ok());
}
#[test]
fn not_email_rule_name_returns_not_email() {
let rule = NotEmailRule::new();
assert_eq!(rule.name(), "not_email");
}
#[test]
fn regex_rule_passes_no_match() {
let rule = RegexRule::new(
regex::Regex::new(r"\s").unwrap(),
"密码不能包含空格".to_string(),
);
let ctx = make_ctx(None, vec![]);
assert!(rule.validate(&ctx, "no_spaces").is_ok());
}
#[test]
fn regex_rule_fails_match() {
let rule = RegexRule::new(
regex::Regex::new(r"\s").unwrap(),
"密码不能包含空格".to_string(),
);
let ctx = make_ctx(None, vec![]);
let result = rule.validate(&ctx, "has space");
assert!(result.is_err());
assert_eq!(result.unwrap_err().rule_name, "regex");
}
#[test]
fn regex_rule_error_msg_in_error() {
let rule = RegexRule::new(
regex::Regex::new(r"[0-9]").unwrap(),
"密码不能包含数字".to_string(),
);
let ctx = make_ctx(None, vec![]);
let err = rule.validate(&ctx, "abc1").unwrap_err();
assert_eq!(err.message, "密码不能包含数字");
}
#[test]
fn regex_rule_name_returns_regex() {
let rule = RegexRule::new(regex::Regex::new(r".").unwrap(), "test".to_string());
assert_eq!(rule.name(), "regex");
}
#[test]
fn all_rules_usable_as_dyn_trait_object() {
let rules: Vec<Box<dyn PasswordPolicyRule>> = vec![
Box::new(LengthRule::new(8, 128)),
Box::new(HistoryRule::new(3)),
Box::new(BlacklistRule::new(vec![])),
Box::new(NotUsernameRule::new()),
Box::new(NotCommonPasswordRule::new(vec![])),
Box::new(MaxAgeRule::new(90)),
Box::new(DictionaryRule::new(vec![])),
Box::new(NotEmailRule::new()),
Box::new(RegexRule::new(
regex::Regex::new(r".").unwrap(),
"test".to_string(),
)),
];
assert_eq!(rules.len(), 9);
assert_eq!(rules[0].name(), "length");
assert_eq!(rules[1].name(), "history");
assert_eq!(rules[2].name(), "blacklist");
assert_eq!(rules[3].name(), "not_username");
assert_eq!(rules[4].name(), "not_common_password");
assert_eq!(rules[5].name(), "max_age");
assert_eq!(rules[6].name(), "dictionary");
assert_eq!(rules[7].name(), "not_email");
assert_eq!(rules[8].name(), "regex");
}
}
#[cfg(all(test, feature = "policy-hibp"))]
mod hibp_tests {
use super::*;
use sha1::{Digest, Sha1};
use wiremock::matchers::{method, path_regex};
use wiremock::{Mock, MockServer, ResponseTemplate};
fn sha1_hex(pw: &str) -> String {
Sha1::digest(pw.as_bytes())
.iter()
.map(|b| format!("{b:02x}"))
.collect()
}
#[tokio::test]
async fn hibp_hit_reports_pwned() {
let server = MockServer::start().await;
let hex = sha1_hex(&format!("{}_{}", "i_am_leaked", 2024));
let suffix = &hex[5..];
Mock::given(method("GET"))
.and(path_regex(r"/range/[0-9a-f]{5}".to_string()))
.respond_with(
ResponseTemplate::new(200).set_body_string(format!("{suffix}:217\nAABBCCDD:1\n")),
)
.mount(&server)
.await;
let rule = NistComplianceRule::new(8);
let verdict = rule
.check_hibp_with_base(
&format!("{}_{}", "i_am_leaked", 2024),
&format!("{}/range", server.uri()),
)
.await
.unwrap();
assert!(verdict.pwned, "命中应判定已泄露");
assert_eq!(verdict.count, 217);
assert!(verdict.service_available);
}
#[tokio::test]
async fn hibp_miss_reports_clean() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path_regex(r"/range/[0-9a-f]{5}".to_string()))
.respond_with(
ResponseTemplate::new(200)
.set_body_string(format!("{}{}:1\n", "F".repeat(6), "0".repeat(34))),
)
.mount(&server)
.await;
let rule = NistComplianceRule::new(8);
let verdict = rule
.check_hibp_with_base(
&format!("{}_{}", "totally_clean_password", "xyz"),
&format!("{}/range", server.uri()),
)
.await
.unwrap();
assert!(!verdict.pwned);
assert_eq!(verdict.count, 0);
assert!(verdict.service_available);
}
#[tokio::test]
async fn hibp_server_error_fails_open() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path_regex(r"/range/[0-9a-f]{5}".to_string()))
.respond_with(ResponseTemplate::new(500))
.mount(&server)
.await;
let rule = NistComplianceRule::new(8);
let verdict = rule
.check_hibp_with_base(
&format!("{}_pw", "whatever"),
&format!("{}/range", server.uri()),
)
.await
.unwrap();
assert!(!verdict.pwned);
assert!(!verdict.service_available);
}
#[tokio::test]
async fn hibp_malformed_response_fails_open() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path_regex(r"/range/[0-9a-f]{5}".to_string()))
.respond_with(ResponseTemplate::new(200).set_body_string("<html>error</html>"))
.mount(&server)
.await;
let rule = NistComplianceRule::new(8);
let verdict = rule
.check_hibp_with_base(
&format!("{}_pw", "malformed_response"),
&format!("{}/range", server.uri()),
)
.await
.unwrap();
assert!(!verdict.pwned);
assert!(verdict.service_available); }
#[tokio::test]
async fn hibp_unreachable_fails_open() {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
drop(listener);
let rule = NistComplianceRule::new(8);
let verdict = rule
.check_hibp_with_base(&format!("{}_pw", "unreachable"), &format!("http://{addr}"))
.await
.unwrap();
assert!(!verdict.pwned);
assert!(!verdict.service_available);
}
}
#[cfg(test)]
mod nist_rule_tests {
use super::*;
fn ctx() -> PolicyContext {
PolicyContext {
user_id: "test-user".to_string(),
tenant_id: None,
username: None,
email: None,
password_history: Vec::new(),
password_created_at: None,
}
}
#[test]
fn nist_rule_counts_chars_not_bytes() {
let rule = NistComplianceRule::new(8);
assert_eq!(rule.name(), "nist_compliance");
assert!(
rule.validate(&ctx(), "密码密码密码密码").is_ok(),
"8 个多字节字符应满足 min_length=8(chars 计数)"
);
}
#[test]
fn nist_rule_rejects_too_short_with_lengths() {
let rule = NistComplianceRule::new(12);
let err = rule
.validate(&ctx(), "short")
.expect_err("不足 12 字符必须拒绝");
assert_eq!(err.rule_name, "nist_compliance");
assert!(
err.message.contains("policy-nist-length-too-short::5::12"),
"错误应携带实际长度 5 与下限 12,实际: {}",
err.message
);
}
}