use crate::i18n::translate_detail;
use unicode_security::confusable_detection::skeleton;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConfusableWarning {
pub position: usize,
pub char: char,
pub confusable_with: char,
pub suggestion: String,
}
pub fn check_confusable(s: &str) -> Vec<ConfusableWarning> {
let mut warnings = Vec::new();
for (byte_pos, c) in s.char_indices() {
let skel: String = skeleton(&c.to_string()).collect();
let mut skel_chars = skel.chars();
if let Some(skel_char) = skel_chars.next() {
if skel_char != c && skel_chars.next().is_none() {
let suggestion = translate_detail(
"confusable-suggestion",
&[
("arg0", skel_char.to_string().as_str()),
("arg1", c.to_string().as_str()),
],
);
warnings.push(ConfusableWarning {
position: byte_pos,
char: c,
confusable_with: skel_char,
suggestion,
});
}
}
}
warnings
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn check_confusable_returns_empty_for_pure_ascii() {
let warnings = check_confusable("user:read");
assert!(
warnings.is_empty(),
"纯 ASCII 字符串不应有可疑字符: {:?}",
warnings
);
}
#[test]
fn check_confusable_returns_warning_for_homoglyph() {
let input = "a\u{0430}";
let warnings = check_confusable(input);
assert!(!warnings.is_empty(), "应检测到 Cyrillic 'а' 可疑字符");
let cyrillic_warning = warnings
.iter()
.find(|w| w.char == '\u{0430}')
.expect("应包含 Cyrillic 'а' (U+0430) 的警告");
assert_eq!(
cyrillic_warning.confusable_with, 'a',
"Cyrillic 'а' 应混淆为 Latin 'a'"
);
}
#[test]
fn check_confusable_returns_warning_for_mixed_script() {
let input = "\u{0430}dmin";
let warnings = check_confusable(input);
assert!(!warnings.is_empty(), "混合字符串应检测到可疑字符");
let first = &warnings[0];
assert_eq!(first.char, '\u{0430}', "首字符应为 Cyrillic 'а'");
assert_eq!(first.confusable_with, 'a', "应混淆为 Latin 'a'");
assert_eq!(first.position, 0, "首字符字节位置应为 0");
}
#[test]
fn check_confusable_returns_empty_for_empty_string() {
let warnings = check_confusable("");
assert!(warnings.is_empty(), "空字符串不应有可疑字符");
}
#[test]
fn check_confusable_returns_multiple_warnings_for_multiple_homoglyphs() {
let input = "\u{0430}d\u{043E}min";
let warnings = check_confusable(input);
assert!(
warnings.len() >= 2,
"应至少有 2 个警告(Cyrillic 'а' 与 Cyrillic 'о'),实际: {}",
warnings.len()
);
let chars: Vec<char> = warnings.iter().map(|w| w.char).collect();
assert!(chars.contains(&'\u{0430}'), "应检测到 Cyrillic 'а'");
assert!(chars.contains(&'\u{043E}'), "应检测到 Cyrillic 'о'");
}
#[test]
fn check_confusable_detects_mixed_digits() {
let input = "v\u{0661}";
let warnings = check_confusable(input);
assert!(!warnings.is_empty(), "应检测到 Arabic-Indic '١' 可疑数字");
let digit_warning = warnings
.iter()
.find(|w| w.char == '\u{0661}')
.expect("应包含 Arabic-Indic '١' (U+0661) 的警告");
assert_eq!(
digit_warning.confusable_with, 'l',
"Arabic-Indic '١' 的 skeleton 应为 'l'"
);
}
}