use super::{PasswordPolicyRule, PolicyContext, PolicyError};
use crate::account::credential::PasswordVerifier;
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.len() as u32;
if len < self.min {
return Err(PolicyError::new(
"length",
format!("密码长度 {} 小于最小要求 {}", len, self.min),
));
}
if len > self.max {
return Err(PolicyError::new(
"length",
format!("密码长度 {} 超过最大限制 {}", len, self.max),
));
}
Ok(())
}
}
#[deprecated(note = "NIST SP 800-63B 不推荐强制复杂度,使用 NistComplianceRule")]
pub struct ComplexityRule {
upper: u32,
lower: u32,
digit: u32,
special: u32,
}
#[allow(deprecated)]
impl ComplexityRule {
pub fn new(upper: u32, lower: u32, digit: u32, special: u32) -> Self {
Self {
upper,
lower,
digit,
special,
}
}
}
#[allow(deprecated)]
impl PasswordPolicyRule for ComplexityRule {
fn name(&self) -> &'static str {
"complexity"
}
fn validate(&self, _ctx: &PolicyContext, password: &str) -> Result<(), PolicyError> {
let mut upper_count = 0u32;
let mut lower_count = 0u32;
let mut digit_count = 0u32;
let mut special_count = 0u32;
for c in password.chars() {
if c.is_uppercase() {
upper_count += 1;
} else if c.is_lowercase() {
lower_count += 1;
} else if c.is_ascii_digit() {
digit_count += 1;
} else {
special_count += 1;
}
}
if upper_count < self.upper {
return Err(PolicyError::new(
"complexity",
format!("大写字母 {} 个,少于要求的 {} 个", upper_count, self.upper),
));
}
if lower_count < self.lower {
return Err(PolicyError::new(
"complexity",
format!("小写字母 {} 个,少于要求的 {} 个", lower_count, self.lower),
));
}
if digit_count < self.digit {
return Err(PolicyError::new(
"complexity",
format!("数字 {} 个,少于要求的 {} 个", digit_count, self.digit),
));
}
if special_count < self.special {
return Err(PolicyError::new(
"complexity",
format!(
"特殊字符 {} 个,少于要求的 {} 个",
special_count, self.special
),
));
}
Ok(())
}
}
pub struct HistoryRule {
count: u32,
}
impl HistoryRule {
pub fn new(count: u32) -> Self {
Self { 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..] {
if let Ok(true) = PasswordVerifier::verify(password, hash) {
return Err(PolicyError::new("history", "密码与历史密码重复"));
}
}
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", "密码在黑名单中"));
}
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", "密码包含用户名"));
}
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", "密码为常见密码"));
}
Ok(())
}
}
pub struct MaxAgeRule;
impl MaxAgeRule {
pub fn new(_days: u32) -> Self {
Self
}
}
impl PasswordPolicyRule for MaxAgeRule {
fn name(&self) -> &'static str {
"max_age"
}
fn validate(&self, _ctx: &PolicyContext, _password: &str) -> Result<(), PolicyError> {
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", "密码为字典单词"));
}
Ok(())
}
}
#[deprecated(note = "NIST SP 800-63B 不推荐强制复杂度,使用 NistComplianceRule")]
pub struct NotRepeatCharRule {
max_consecutive: u32,
}
#[allow(deprecated)]
impl NotRepeatCharRule {
pub fn new(max_consecutive: u32) -> Self {
Self { max_consecutive }
}
}
#[allow(deprecated)]
impl PasswordPolicyRule for NotRepeatCharRule {
fn name(&self) -> &'static str {
"not_repeat_char"
}
fn validate(&self, _ctx: &PolicyContext, password: &str) -> Result<(), PolicyError> {
let chars: Vec<char> = password.chars().collect();
if chars.len() <= 1 {
return Ok(());
}
let max_allowed = self.max_consecutive as usize;
let mut current_run = 1usize;
for i in 1..chars.len() {
if chars[i] == chars[i - 1] {
current_run += 1;
if current_run > max_allowed {
return Err(PolicyError::new(
"not_repeat_char",
format!(
"密码包含 {} 个连续相同字符 '{}',超过最大允许 {}",
current_run, chars[i], max_allowed
),
));
}
} else {
current_run = 1;
}
}
Ok(())
}
}
#[deprecated(note = "NIST SP 800-63B 不推荐强制复杂度,使用 NistComplianceRule")]
pub struct NotSequenceRule {
max_sequence: u32,
}
#[allow(deprecated)]
impl NotSequenceRule {
pub fn new(max_sequence: u32) -> Self {
Self { max_sequence }
}
}
#[allow(deprecated)]
impl PasswordPolicyRule for NotSequenceRule {
fn name(&self) -> &'static str {
"not_sequence"
}
fn validate(&self, _ctx: &PolicyContext, password: &str) -> Result<(), PolicyError> {
let chars: Vec<char> = password.chars().collect();
if chars.len() <= 1 {
return Ok(());
}
let max_seq = self.max_sequence as usize;
let mut max_found = 1usize;
let mut current_len = 1usize;
let mut direction = 0i32;
for i in 1..chars.len() {
let diff = chars[i] as i32 - chars[i - 1] as i32;
let new_direction = if diff == 1 {
1
} else if diff == -1 {
-1
} else {
0
};
if new_direction != 0 && new_direction == direction {
current_len += 1;
} else if new_direction != 0 {
current_len = 2;
direction = new_direction;
} else {
current_len = 1;
direction = 0;
}
if current_len > max_found {
max_found = current_len;
}
}
if max_found > max_seq {
return Err(PolicyError::new(
"not_sequence",
format!(
"密码包含长度 {} 的连续序列,超过最大允许 {}",
max_found, max_seq
),
));
}
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", "密码包含邮箱前缀"));
}
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 }
}
pub fn check_hibp(&self, _password: &str) -> Result<(), PolicyError> {
Ok(())
}
}
impl PasswordPolicyRule for NistComplianceRule {
fn name(&self) -> &'static str {
"nist_compliance"
}
fn validate(&self, _ctx: &PolicyContext, password: &str) -> Result<(), PolicyError> {
let len = password.len() as u32;
if len < self.min_length {
return Err(PolicyError::new(
"nist_compliance",
format!(
"密码长度 {} 小于 NIST SP 800-63B 最小要求 {}",
len, self.min_length
),
));
}
Ok(())
}
}
#[cfg(test)]
#[allow(deprecated)]
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(),
}
}
#[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 complexity_rule_passes_all_met() {
let rule = ComplexityRule::new(1, 1, 1, 1);
let ctx = make_ctx(None, vec![]);
assert!(rule.validate(&ctx, "Aa1!").is_ok());
}
#[test]
fn complexity_rule_fails_missing_upper() {
let rule = ComplexityRule::new(1, 1, 1, 1);
let ctx = make_ctx(None, vec![]);
let result = rule.validate(&ctx, "aa1!");
assert!(result.is_err());
assert_eq!(result.unwrap_err().rule_name, "complexity");
}
#[test]
fn complexity_rule_fails_missing_digit() {
let rule = ComplexityRule::new(1, 1, 1, 1);
let ctx = make_ctx(None, vec![]);
assert!(rule.validate(&ctx, "Aa!b").is_err());
}
#[test]
fn complexity_rule_boundary_exact_counts() {
let rule = ComplexityRule::new(2, 2, 2, 2);
let ctx = make_ctx(None, vec![]);
assert!(rule.validate(&ctx, "AAaa11!!").is_ok());
}
#[test]
fn complexity_rule_name_returns_complexity() {
let rule = ComplexityRule::new(1, 1, 1, 1);
assert_eq!(rule.name(), "complexity");
}
#[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_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_stub_always_passes() {
let rule = MaxAgeRule::new(90);
let ctx = make_ctx(None, vec![]);
assert!(rule.validate(&ctx, "any-password").is_ok());
}
#[test]
fn max_age_rule_stub_passes_empty_password() {
let rule = MaxAgeRule::new(30);
let ctx = make_ctx(None, vec![]);
assert!(rule.validate(&ctx, "").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_repeat_char_rule_passes_no_repeats() {
let rule = NotRepeatCharRule::new(2);
let ctx = make_ctx(None, vec![]);
assert!(rule.validate(&ctx, "abac").is_ok());
}
#[test]
fn not_repeat_char_rule_fails_consecutive_repeats() {
let rule = NotRepeatCharRule::new(2);
let ctx = make_ctx(None, vec![]);
let result = rule.validate(&ctx, "aaa");
assert!(result.is_err());
assert_eq!(result.unwrap_err().rule_name, "not_repeat_char");
}
#[test]
fn not_repeat_char_rule_boundary_exact_max() {
let rule = NotRepeatCharRule::new(2);
let ctx = make_ctx(None, vec![]);
assert!(
rule.validate(&ctx, "aa").is_ok(),
"2 个连续(== max)应通过"
);
}
#[test]
fn not_repeat_char_rule_max_one_fails_pair() {
let rule = NotRepeatCharRule::new(1);
let ctx = make_ctx(None, vec![]);
assert!(rule.validate(&ctx, "aa").is_err());
assert!(rule.validate(&ctx, "ab").is_ok());
}
#[test]
fn not_repeat_char_rule_name_returns_not_repeat_char() {
let rule = NotRepeatCharRule::new(2);
assert_eq!(rule.name(), "not_repeat_char");
}
#[test]
fn not_sequence_rule_passes_no_sequence() {
let rule = NotSequenceRule::new(3);
let ctx = make_ctx(None, vec![]);
assert!(rule.validate(&ctx, "a1b2").is_ok());
}
#[test]
fn not_sequence_rule_fails_forward_sequence() {
let rule = NotSequenceRule::new(3);
let ctx = make_ctx(None, vec![]);
let result = rule.validate(&ctx, "abcd");
assert!(result.is_err());
assert_eq!(result.unwrap_err().rule_name, "not_sequence");
}
#[test]
fn not_sequence_rule_fails_reverse_sequence() {
let rule = NotSequenceRule::new(2);
let ctx = make_ctx(None, vec![]);
assert!(rule.validate(&ctx, "321").is_err());
}
#[test]
fn not_sequence_rule_boundary_exact_max() {
let rule = NotSequenceRule::new(3);
let ctx = make_ctx(None, vec![]);
assert!(rule.validate(&ctx, "abc").is_ok(), "长度 3 == max,应通过");
}
#[test]
fn not_sequence_rule_fails_alpha_reverse() {
let rule = NotSequenceRule::new(2);
let ctx = make_ctx(None, vec![]);
assert!(rule.validate(&ctx, "zyx").is_err());
}
#[test]
fn not_sequence_rule_name_returns_not_sequence() {
let rule = NotSequenceRule::new(3);
assert_eq!(rule.name(), "not_sequence");
}
#[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![],
};
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![],
};
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![],
};
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![],
};
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(ComplexityRule::new(1, 1, 1, 1)),
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(NotRepeatCharRule::new(2)),
Box::new(NotSequenceRule::new(3)),
Box::new(NotEmailRule::new()),
Box::new(RegexRule::new(
regex::Regex::new(r".").unwrap(),
"test".to_string(),
)),
];
assert_eq!(rules.len(), 12);
assert_eq!(rules[0].name(), "length");
assert_eq!(rules[1].name(), "complexity");
assert_eq!(rules[2].name(), "history");
assert_eq!(rules[3].name(), "blacklist");
assert_eq!(rules[4].name(), "not_username");
assert_eq!(rules[5].name(), "not_common_password");
assert_eq!(rules[6].name(), "max_age");
assert_eq!(rules[7].name(), "dictionary");
assert_eq!(rules[8].name(), "not_repeat_char");
assert_eq!(rules[9].name(), "not_sequence");
assert_eq!(rules[10].name(), "not_email");
assert_eq!(rules[11].name(), "regex");
}
}