use subtle::ConstantTimeEq;
pub fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
let len_eq = (a.len() as u64).ct_eq(&(b.len() as u64));
let max_len = a.len().max(b.len());
let mut byte_eq = subtle::Choice::from(1u8);
for i in 0..max_len {
let x = a.get(i).copied().unwrap_or(0);
let y = b.get(i).copied().unwrap_or(0);
byte_eq &= x.ct_eq(&y);
}
(len_eq & byte_eq).unwrap_u8() == 1
}
#[cfg(test)]
fn strip_rust_comment(line: &str) -> &str {
let trimmed = line.trim_start();
if trimmed.starts_with("//") {
""
} else {
line
}
}
#[cfg(test)]
fn collect_rs_sources(dir: &std::path::Path, src_root: &str) -> Vec<(String, String)> {
let mut out = Vec::new();
let Ok(read_dir) = std::fs::read_dir(dir) else {
return out;
};
for entry in read_dir.flatten() {
let path = entry.path();
if path.is_dir() {
out.extend(collect_rs_sources(&path, src_root));
} else if path.extension().and_then(|e| e.to_str()) == Some("rs") {
if let Ok(source) = std::fs::read_to_string(&path) {
let rel = path
.strip_prefix(src_root)
.unwrap_or(&path)
.to_string_lossy()
.replace('\\', "/");
out.push((rel, source));
}
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn equal_slices_return_true() {
assert!(constant_time_eq(b"hello", b"hello"));
assert!(constant_time_eq(b"", b""));
assert!(constant_time_eq(&[0u8; 32], &[0u8; 32]));
}
#[test]
fn different_slices_return_false() {
assert!(!constant_time_eq(b"hello", b"world"));
assert!(!constant_time_eq(b"hello", b"hellp"));
}
#[test]
fn different_lengths_return_false() {
assert!(!constant_time_eq(b"abc", b"abcd"));
assert!(!constant_time_eq(b"abcd", b"abc"));
assert!(!constant_time_eq(b"", b"a"));
}
#[test]
fn long_inputs_no_panic() {
let a = vec![0u8; 1024];
let b = vec![0u8; 1024];
assert!(constant_time_eq(&a, &b));
let mut c = b.clone();
c[1023] = 1;
assert!(!constant_time_eq(&a, &c));
}
#[test]
fn acc_adr0003_single_implementation_no_local_duplicates() {
let manifest_dir = env!("CARGO_MANIFEST_DIR");
let src_root = format!("{manifest_dir}/src");
let mut violations = Vec::new();
for (rel, source) in collect_rs_sources(std::path::Path::new(&src_root), &src_root) {
if rel == "secure/ct_eq.rs" {
continue;
}
for (idx, line) in source.lines().enumerate() {
let code = strip_rust_comment(line);
if code.contains("fn constant_time_eq(") {
violations.push(format!(
"src/{rel}:{}: 本地 constant_time_eq 第二实现(ADR-0003 决策 2 要求统一走 secure::ct_eq)",
idx + 1
));
}
}
}
assert!(
violations.is_empty(),
"ADR-0003 守卫:发现本地常量时间比较第二实现:\n{}",
violations.join("\n")
);
}
#[test]
fn acc_adr0003_sensitive_paths_depend_on_secure_ct_eq() {
let manifest = include_str!("../../Cargo.toml");
const SENSITIVE_FEATURES: &[&str] = &[
"protocol-apikey",
"audit-log",
"oauth2-server",
"protocol-httpdigest",
"secure-simple-token",
"secure-sign",
"web-csrf",
"email-verification",
"sms-rate-limit",
];
for feature in SENSITIVE_FEATURES {
let decl = format!("{feature} = [");
assert!(
manifest.contains(&decl),
"ADR-0003 守卫:feature '{feature}' 未在 Cargo.toml 声明"
);
let line = manifest
.lines()
.find(|l| l.starts_with(&decl))
.unwrap_or_else(|| panic!("feature '{feature}' 声明行缺失"));
assert!(
line.contains("secure-ct-eq"),
"ADR-0003 决策 2 守卫:feature '{feature}' 必须依赖 secure-ct-eq,实际: {line}"
);
}
const ALLOWED_SUBTLE_DIRECT: &[&str] = &[
"secure/ct_eq.rs",
"protocol/sso/saml.rs",
"protocol/oauth2/oidc.rs",
"protocol/qrlogin/service.rs",
];
let manifest_dir = env!("CARGO_MANIFEST_DIR");
let src_root = format!("{manifest_dir}/src");
let mut violations = Vec::new();
for (rel, source) in collect_rs_sources(std::path::Path::new(&src_root), &src_root) {
for (idx, line) in source.lines().enumerate() {
let code = strip_rust_comment(line);
if code.contains("subtle::ConstantTimeEq") || code.contains("subtle::Choice") {
let allowed = ALLOWED_SUBTLE_DIRECT.contains(&rel.as_str());
if !allowed {
violations.push(format!(
"src/{rel}:{}: 敏感路径 subtle 直连(ADR-0003 决策 2 要求走 secure::ct_eq): {}",
idx + 1,
code.trim()
));
}
}
}
}
assert!(
violations.is_empty(),
"ADR-0003 守卫:发现敏感路径 subtle 直连:\n{}",
violations.join("\n")
);
}
#[test]
fn matches_slice_equality_matrix() {
let samples: [&[u8]; 10] = [
b"", b"a", b"ab", b"abc", b"abcd", b"xyz", b"123456", b"12345", b"654321", b"abcdef",
];
for a in samples {
for b in samples {
assert_eq!(
constant_time_eq(a, b),
a == b,
"constant_time_eq({:?}, {:?}) 应与切片相等语义一致",
String::from_utf8_lossy(a),
String::from_utf8_lossy(b)
);
}
}
}
#[test]
fn matches_str_equality_matrix() {
let samples = [
"", "1", "12", "123456", "12345", "654321", "000000", "abcdef",
];
for a in samples {
for b in samples {
assert_eq!(
constant_time_eq(a.as_bytes(), b.as_bytes()),
a == b,
"constant_time_eq({a:?}, {b:?}) 应与 str 相等语义一致"
);
}
}
}
}