use super::algorithm::hex_encode;
use super::auth::current_unix_seconds;
use super::*;
use crate::secure::ct_eq::constant_time_eq;
use base64::{engine::general_purpose::STANDARD, Engine};
use std::sync::Arc;
use uuid::Uuid;
#[test]
fn algorithm_from_str_md5() {
assert_eq!(
"MD5".parse::<DigestAlgorithm>().unwrap(),
DigestAlgorithm::Md5
);
assert_eq!(
"md5".parse::<DigestAlgorithm>().unwrap(),
DigestAlgorithm::Md5
);
}
#[test]
fn algorithm_from_str_sha256() {
assert_eq!(
"SHA256".parse::<DigestAlgorithm>().unwrap(),
DigestAlgorithm::Sha256
);
assert_eq!(
"sha256".parse::<DigestAlgorithm>().unwrap(),
DigestAlgorithm::Sha256
);
}
#[test]
fn algorithm_from_str_unknown_errors() {
assert!("SHA512".parse::<DigestAlgorithm>().is_err());
assert!("".parse::<DigestAlgorithm>().is_err());
}
#[test]
fn algorithm_default_is_sha256() {
assert_eq!(DigestAlgorithm::default(), DigestAlgorithm::Sha256);
}
#[test]
fn new_constructs_instance() {
let auth = HttpDigestAuth::new("test@realm", "MD5").unwrap();
let challenge = auth.challenge();
assert!(challenge.starts_with("Digest "));
}
#[test]
fn new_rejects_unknown_algorithm() {
assert!(HttpDigestAuth::new("realm", "SHA512").is_err());
}
#[test]
fn challenge_contains_required_fields() {
let auth = HttpDigestAuth::new("test@realm", "MD5").unwrap();
let challenge = auth.challenge();
assert!(challenge.starts_with("Digest "));
assert!(challenge.contains(r#"realm="test@realm""#));
assert!(challenge.contains(r#"qop="auth,auth-int""#));
assert!(challenge.contains("algorithm=MD5"));
assert!(challenge.contains("nonce="));
}
#[test]
fn challenge_nonce_is_random() {
let auth = HttpDigestAuth::new("realm", "MD5").unwrap();
let c1 = auth.challenge();
let c2 = auth.challenge();
let n1 = extract_nonce(&c1).unwrap();
let n2 = extract_nonce(&c2).unwrap();
assert!(!n1.is_empty());
assert_ne!(n1, n2);
}
#[test]
fn challenge_sha256_algorithm() {
let auth = HttpDigestAuth::new("realm", "SHA256").unwrap();
let challenge = auth.challenge();
assert!(challenge.contains("algorithm=SHA256"));
}
#[test]
fn challenge_nonce_is_valid() {
let auth = HttpDigestAuth::new("realm", "SHA256").unwrap();
let challenge = auth.challenge();
let nonce = extract_nonce(&challenge).unwrap();
assert!(auth.is_nonce_valid(&nonce));
}
#[test]
fn with_nonce_ttl_sets_ttl() {
let auth = HttpDigestAuth::new("realm", "MD5")
.unwrap()
.with_nonce_ttl(60);
assert_eq!(auth.nonce_ttl(), 60);
}
#[test]
fn compute_ha1_known_md5_value() {
let auth = HttpDigestAuth::new("realm", "MD5").unwrap();
let ha1 = auth.compute_ha1("user", "pass");
let expected_input = "user:realm:pass";
let expected = md5::compute(expected_input.as_bytes());
let expected_hex: String = expected.0.iter().map(|b| format!("{:02x}", b)).collect();
assert_eq!(ha1, expected_hex);
}
#[test]
fn compute_ha1_sha256_returns_64_chars() {
let auth = HttpDigestAuth::new("realm", "SHA256").unwrap();
let ha1 = auth.compute_ha1("user", "pass");
assert_eq!(ha1.len(), 64);
}
fn make_valid_nonce() -> String {
let timestamp = current_unix_seconds();
let random = Uuid::new_v4().simple().to_string();
let raw = format!("{}:{}", timestamp, random);
STANDARD.encode(raw.as_bytes())
}
fn make_expired_nonce(ttl: u64) -> String {
let expired_timestamp = current_unix_seconds().saturating_sub(ttl + 10);
let random = Uuid::new_v4().simple().to_string();
let raw = format!("{}:{}", expired_timestamp, random);
STANDARD.encode(raw.as_bytes())
}
fn make_future_nonce() -> String {
let future_timestamp = current_unix_seconds() + 100;
let random = Uuid::new_v4().simple().to_string();
let raw = format!("{}:{}", future_timestamp, random);
STANDARD.encode(raw.as_bytes())
}
#[allow(clippy::too_many_arguments)]
fn build_md5_auth_header(
_auth: &HttpDigestAuth,
username: &str,
realm: &str,
nonce: &str,
nc: &str,
cnonce: &str,
method: &str,
uri: &str,
ha1: &str,
) -> String {
let ha2_input = format!("{}:{}", method, uri);
let ha2 = md5::compute(ha2_input.as_bytes());
let ha2_hex: String = ha2.0.iter().map(|b| format!("{:02x}", b)).collect();
let resp_input = format!("{}:{}:{}:{}:auth:{}", ha1, nonce, nc, cnonce, ha2_hex);
let resp = md5::compute(resp_input.as_bytes());
let resp_hex: String = resp.0.iter().map(|b| format!("{:02x}", b)).collect();
format!(
r#"Digest username="{}", realm="{}", nonce="{}", uri="{}", response="{}", qop=auth, nc={}, cnonce="{}""#,
username, realm, nonce, uri, resp_hex, nc, cnonce
)
}
#[allow(clippy::too_many_arguments)]
fn build_sha256_auth_header(
_auth: &HttpDigestAuth,
username: &str,
realm: &str,
nonce: &str,
nc: &str,
cnonce: &str,
method: &str,
uri: &str,
ha1: &str,
) -> String {
use sha2::Digest;
let ha2_input = format!("{}:{}", method, uri);
let mut h2 = sha2::Sha256::new();
h2.update(ha2_input.as_bytes());
let ha2_hex: String = h2.finalize().iter().map(|b| format!("{:02x}", b)).collect();
let resp_input = format!("{}:{}:{}:{}:auth:{}", ha1, nonce, nc, cnonce, ha2_hex);
let mut h = sha2::Sha256::new();
h.update(resp_input.as_bytes());
let resp_hex: String = h.finalize().iter().map(|b| format!("{:02x}", b)).collect();
format!(
r#"Digest username="{}", realm="{}", nonce="{}", uri="{}", response="{}", qop=auth, nc={}, cnonce="{}""#,
username, realm, nonce, uri, resp_hex, nc, cnonce
)
}
#[test]
fn validate_correct_password_succeeds() {
let auth = HttpDigestAuth::new("test@realm", "MD5").unwrap();
let ha1 = auth.compute_ha1("admin", "secret");
let nonce = make_valid_nonce();
let nc = "00000001";
let cnonce = "0a4f113c";
let method = "GET";
let uri = "/resource";
let header = build_md5_auth_header(
&auth,
"admin",
"test@realm",
&nonce,
nc,
cnonce,
method,
uri,
&ha1,
);
assert!(auth.validate(&header, method, uri, &ha1));
}
#[test]
fn validate_wrong_password_fails() {
let auth = HttpDigestAuth::new("test@realm", "MD5").unwrap();
let ha1_correct = auth.compute_ha1("admin", "secret");
let ha1_wrong = auth.compute_ha1("admin", "wrong");
let nonce = make_valid_nonce();
let nc = "00000001";
let cnonce = "0a4f113c";
let method = "GET";
let uri = "/resource";
let header = build_md5_auth_header(
&auth,
"admin",
"test@realm",
&nonce,
nc,
cnonce,
method,
uri,
&ha1_wrong,
);
assert!(!auth.validate(&header, method, uri, &ha1_correct));
}
#[test]
fn validate_wrong_method_fails() {
let auth = HttpDigestAuth::new("test@realm", "MD5").unwrap();
let ha1 = auth.compute_ha1("admin", "secret");
let nonce = make_valid_nonce();
let nc = "00000001";
let cnonce = "0a4f113c";
let method = "POST";
let uri = "/resource";
let header = build_md5_auth_header(
&auth,
"admin",
"test@realm",
&nonce,
nc,
cnonce,
method,
uri,
&ha1,
);
assert!(!auth.validate(&header, "GET", uri, &ha1));
}
#[test]
fn validate_expired_nonce_rejected() {
let auth = HttpDigestAuth::new("test@realm", "MD5").unwrap();
let ha1 = auth.compute_ha1("admin", "secret");
let nonce = make_expired_nonce(300);
let nc = "00000001";
let cnonce = "0a4f113c";
let method = "GET";
let uri = "/resource";
let header = build_md5_auth_header(
&auth,
"admin",
"test@realm",
&nonce,
nc,
cnonce,
method,
uri,
&ha1,
);
assert!(!auth.validate(&header, method, uri, &ha1));
}
#[test]
fn validate_future_nonce_rejected() {
let auth = HttpDigestAuth::new("test@realm", "MD5").unwrap();
let ha1 = auth.compute_ha1("admin", "secret");
let nonce = make_future_nonce();
let nc = "00000001";
let cnonce = "0a4f113c";
let method = "GET";
let uri = "/resource";
let header = build_md5_auth_header(
&auth,
"admin",
"test@realm",
&nonce,
nc,
cnonce,
method,
uri,
&ha1,
);
assert!(!auth.validate(&header, method, uri, &ha1));
}
#[test]
fn validate_malformed_nonce_rejected() {
let auth = HttpDigestAuth::new("test@realm", "MD5").unwrap();
let ha1 = auth.compute_ha1("admin", "secret");
let nonce = "abc123nonce";
let nc = "00000001";
let cnonce = "0a4f113c";
let method = "GET";
let uri = "/resource";
let header = build_md5_auth_header(
&auth,
"admin",
"test@realm",
nonce,
nc,
cnonce,
method,
uri,
&ha1,
);
assert!(!auth.validate(&header, method, uri, &ha1));
}
#[test]
fn validate_custom_ttl_works() {
let auth = HttpDigestAuth::new("test@realm", "MD5")
.unwrap()
.with_nonce_ttl(1);
let ha1 = auth.compute_ha1("admin", "secret");
let nonce = make_expired_nonce(1);
let nc = "00000001";
let cnonce = "0a4f113c";
let method = "GET";
let uri = "/resource";
let header = build_md5_auth_header(
&auth,
"admin",
"test@realm",
&nonce,
nc,
cnonce,
method,
uri,
&ha1,
);
assert!(!auth.validate(&header, method, uri, &ha1));
let valid_nonce = make_valid_nonce();
let valid_header = build_md5_auth_header(
&auth,
"admin",
"test@realm",
&valid_nonce,
nc,
cnonce,
method,
uri,
&ha1,
);
assert!(auth.validate(&valid_header, method, uri, &ha1));
}
#[test]
fn validate_auth_int_rejected_without_body() {
let auth = HttpDigestAuth::new("test@realm", "MD5").unwrap();
let ha1 = auth.compute_ha1("admin", "secret");
let nonce = make_valid_nonce();
let nc = "00000001";
let cnonce = "0a4f113c";
let method = "POST";
let uri = "/resource";
let empty_body_hash = auth.algorithm.hash(b"");
let ha2_input = format!("{}:{}:{}", method, uri, empty_body_hash);
let ha2 = md5::compute(ha2_input.as_bytes());
let ha2_hex: String = ha2.0.iter().map(|b| format!("{:02x}", b)).collect();
let resp_input = format!("{}:{}:{}:{}:auth-int:{}", ha1, nonce, nc, cnonce, ha2_hex);
let resp = md5::compute(resp_input.as_bytes());
let resp_hex: String = resp.0.iter().map(|b| format!("{:02x}", b)).collect();
let header = format!(
r#"Digest username="admin", realm="test@realm", nonce="{}", uri="{}", response="{}", qop=auth-int, nc={}, cnonce="{}""#,
nonce, uri, resp_hex, nc, cnonce
);
assert!(
!auth.validate(&header, method, uri, &ha1),
"auth-int 在 body 缺失时应被拒绝(即使按空 body 正确计算 response)"
);
assert!(
auth.validate_with_body(&header, method, uri, b"", &ha1),
"validate_with_body 携带(空)body 时应正常校验通过"
);
}
#[test]
fn validate_with_body_auth_int_md5_succeeds() {
let auth = HttpDigestAuth::new("test@realm", "MD5").unwrap();
let ha1 = auth.compute_ha1("admin", "secret");
let nonce = make_valid_nonce();
let nc = "00000001";
let cnonce = "0a4f113c";
let method = "POST";
let uri = "/resource";
let body = b"hello world";
let body_hash = auth.algorithm.hash(body);
let ha2_input = format!("{}:{}:{}", method, uri, body_hash);
let ha2 = md5::compute(ha2_input.as_bytes());
let ha2_hex: String = ha2.0.iter().map(|b| format!("{:02x}", b)).collect();
let resp_input = format!("{}:{}:{}:{}:auth-int:{}", ha1, nonce, nc, cnonce, ha2_hex);
let resp = md5::compute(resp_input.as_bytes());
let resp_hex: String = resp.0.iter().map(|b| format!("{:02x}", b)).collect();
let header = format!(
r#"Digest username="admin", realm="test@realm", nonce="{}", uri="{}", response="{}", qop=auth-int, nc={}, cnonce="{}""#,
nonce, uri, resp_hex, nc, cnonce
);
assert!(auth.validate_with_body(&header, method, uri, body, &ha1));
}
#[test]
fn validate_with_body_auth_int_sha256_succeeds() {
let auth = HttpDigestAuth::new("test@realm", "SHA256").unwrap();
let ha1 = auth.compute_ha1("admin", "secret");
let nonce = make_valid_nonce();
let nc = "00000001";
let cnonce = "0a4f113c";
let method = "POST";
let uri = "/resource";
let body = b"hello world";
use sha2::Digest;
let body_hash = {
let mut h = sha2::Sha256::new();
h.update(body);
h.finalize()
.iter()
.map(|b| format!("{:02x}", b))
.collect::<String>()
};
let ha2_input = format!("{}:{}:{}", method, uri, body_hash);
let mut h2 = sha2::Sha256::new();
h2.update(ha2_input.as_bytes());
let ha2_hex: String = h2.finalize().iter().map(|b| format!("{:02x}", b)).collect();
let resp_input = format!("{}:{}:{}:{}:auth-int:{}", ha1, nonce, nc, cnonce, ha2_hex);
let mut h = sha2::Sha256::new();
h.update(resp_input.as_bytes());
let resp_hex: String = h.finalize().iter().map(|b| format!("{:02x}", b)).collect();
let header = format!(
r#"Digest username="admin", realm="test@realm", nonce="{}", uri="{}", response="{}", qop=auth-int, nc={}, cnonce="{}""#,
nonce, uri, resp_hex, nc, cnonce
);
assert!(auth.validate_with_body(&header, method, uri, body, &ha1));
}
#[test]
fn validate_with_body_tampered_body_fails() {
let auth = HttpDigestAuth::new("test@realm", "MD5").unwrap();
let ha1 = auth.compute_ha1("admin", "secret");
let nonce = make_valid_nonce();
let nc = "00000001";
let cnonce = "0a4f113c";
let method = "POST";
let uri = "/resource";
let original_body = b"hello world";
let body_hash = auth.algorithm.hash(original_body);
let ha2_input = format!("{}:{}:{}", method, uri, body_hash);
let ha2 = md5::compute(ha2_input.as_bytes());
let ha2_hex: String = ha2.0.iter().map(|b| format!("{:02x}", b)).collect();
let resp_input = format!("{}:{}:{}:{}:auth-int:{}", ha1, nonce, nc, cnonce, ha2_hex);
let resp = md5::compute(resp_input.as_bytes());
let resp_hex: String = resp.0.iter().map(|b| format!("{:02x}", b)).collect();
let header = format!(
r#"Digest username="admin", realm="test@realm", nonce="{}", uri="{}", response="{}", qop=auth-int, nc={}, cnonce="{}""#,
nonce, uri, resp_hex, nc, cnonce
);
let tampered_body = b"tampered body";
assert!(!auth.validate_with_body(&header, method, uri, tampered_body, &ha1));
}
#[test]
fn validate_with_body_supports_auth_qop() {
let auth = HttpDigestAuth::new("test@realm", "MD5").unwrap();
let ha1 = auth.compute_ha1("admin", "secret");
let nonce = make_valid_nonce();
let nc = "00000001";
let cnonce = "0a4f113c";
let method = "GET";
let uri = "/resource";
let header = build_md5_auth_header(
&auth,
"admin",
"test@realm",
&nonce,
nc,
cnonce,
method,
uri,
&ha1,
);
assert!(auth.validate_with_body(&header, method, uri, b"any body", &ha1));
}
#[test]
fn validate_malformed_header_returns_false() {
let auth = HttpDigestAuth::new("realm", "MD5").unwrap();
let ha1 = "dummy";
assert!(!auth.validate("Basic abc123", "GET", "/resource", ha1));
assert!(!auth.validate("Digest username=\"admin\"", "GET", "/resource", ha1));
}
#[test]
fn validate_sha256_succeeds() {
let auth = HttpDigestAuth::new("test@realm", "SHA256").unwrap();
let ha1 = auth.compute_ha1("admin", "secret");
let nonce = make_valid_nonce();
let nc = "00000001";
let cnonce = "0a4f113c";
let method = "GET";
let uri = "/resource";
let header = build_sha256_auth_header(
&auth,
"admin",
"test@realm",
&nonce,
nc,
cnonce,
method,
uri,
&ha1,
);
assert!(auth.validate(&header, method, uri, &ha1));
}
#[test]
fn validate_header_without_whitespace_returns_false() {
let auth = HttpDigestAuth::new("realm", "MD5").unwrap();
assert!(!auth.validate("Digest", "GET", "/resource", "ha1"));
}
#[test]
fn validate_header_with_unknown_params_returns_false() {
let auth = HttpDigestAuth::new("realm", "MD5").unwrap();
let nonce = make_valid_nonce();
let header = format!(
r#"Digest username="admin", realm="realm", nonce="{}", uri="/r", response="r", qop=auth, nc=1, cnonce="c", custom_param="x""#,
nonce
);
assert!(!auth.validate(&header, "GET", "/r", "dummy_ha1"));
}
#[test]
fn validate_header_with_escaped_chars_returns_false() {
let auth = HttpDigestAuth::new("realm", "MD5").unwrap();
let nonce = make_valid_nonce();
let header = format!(
r#"Digest username="ad\"min", realm="realm", nonce="{}", uri="/r", response="r", qop=auth, nc=1, cnonce="c""#,
nonce
);
assert!(!auth.validate(&header, "GET", "/r", "dummy_ha1"));
}
#[test]
fn validate_header_with_key_without_equals_returns_false() {
let auth = HttpDigestAuth::new("realm", "MD5").unwrap();
let nonce = make_valid_nonce();
let header = format!(
r#"Digest username realm="realm", nonce="{}", uri="/r", response="r", qop=auth, nc=1, cnonce="c""#,
nonce
);
assert!(!auth.validate(&header, "GET", "/r", "dummy_ha1"));
}
#[test]
fn validate_header_without_qop_returns_false() {
let auth = HttpDigestAuth::new("realm", "MD5").unwrap();
let nonce = make_valid_nonce();
let header = format!(
r#"Digest username="admin", realm="realm", nonce="{}", uri="/r", response="r", nc=1, cnonce="c""#,
nonce
);
assert!(!auth.validate(&header, "GET", "/r", "dummy_ha1"));
}
#[test]
fn is_nonce_valid_empty_returns_false() {
let auth = HttpDigestAuth::new("realm", "MD5").unwrap();
assert!(!auth.is_nonce_valid(""));
}
#[test]
fn is_nonce_valid_plain_text_returns_false() {
let auth = HttpDigestAuth::new("realm", "MD5").unwrap();
assert!(!auth.is_nonce_valid("abc123nonce"));
}
#[test]
fn is_nonce_valid_no_colon_returns_false() {
let auth = HttpDigestAuth::new("realm", "MD5").unwrap();
let nonce = STANDARD.encode(b"12345");
assert!(!auth.is_nonce_valid(&nonce));
}
#[test]
fn is_nonce_valid_non_numeric_timestamp_returns_false() {
let auth = HttpDigestAuth::new("realm", "MD5").unwrap();
let raw = "abc:def";
let nonce = STANDARD.encode(raw.as_bytes());
assert!(!auth.is_nonce_valid(&nonce));
}
#[test]
fn constant_time_eq_different_lengths_returns_false() {
assert!(!constant_time_eq(b"abc", b"ab"));
assert!(!constant_time_eq(b"ab", b"abc"));
assert!(!constant_time_eq(b"", b"abc"));
assert!(!constant_time_eq(b"abc", b""));
}
#[test]
fn constant_time_eq_same_strings_returns_true() {
assert!(constant_time_eq(b"abc", b"abc"));
assert!(constant_time_eq(b"", b""));
}
#[test]
fn constant_time_eq_different_strings_returns_false() {
assert!(!constant_time_eq(b"abc", b"xyz"));
}
#[test]
fn validate_oversized_response_rejected() {
let auth = HttpDigestAuth::new("test@realm", "MD5").unwrap();
let ha1 = auth.compute_ha1("admin", "secret");
let nonce = make_valid_nonce();
let header = build_md5_auth_header(
&auth,
"admin",
"test@realm",
&nonce,
"00000001",
"0a4f113c",
"GET",
"/resource",
&ha1,
);
let resp_start = header.find("response=\"").unwrap() + "response=\"".len();
let resp_end = header[resp_start..].find('"').unwrap() + resp_start;
let oversized = format!(
"{}{}{}",
&header[..resp_start],
"a".repeat(4096),
&header[resp_end..]
);
assert!(
!auth.validate(&oversized, "GET", "/resource", &ha1),
"超长 response 应被拒绝"
);
let short = format!(
"{}{}{}",
&header[..resp_start],
"a".repeat(31),
&header[resp_end..]
);
assert!(
!auth.validate(&short, "GET", "/resource", &ha1),
"长度不足的 response 应被拒绝"
);
}
#[test]
fn is_nonce_valid_oversized_mac_returns_false() {
let auth = HttpDigestAuth::new("realm", "SHA256")
.unwrap()
.with_server_key(b"server-secret-key-material-with-enough-bytes-32");
let ts = current_unix_seconds();
let uuid = Uuid::new_v4().simple().to_string();
let oversized = format!("{}:{}:{}", ts, uuid, "a".repeat(4096));
let forged = STANDARD.encode(oversized.as_bytes());
assert!(!auth.is_nonce_valid(&forged), "超长 mac 段应被拒绝");
}
#[test]
fn hex_encode_empty_bytes() {
assert_eq!(hex_encode(&[]), "");
}
#[test]
fn hex_encode_known_bytes() {
assert_eq!(hex_encode(&[0x00, 0xff, 0x0a]), "00ff0a");
}
#[tokio::test(flavor = "multi_thread")]
async fn validate_nc_first_use_accepted_with_dao() {
let dao: Arc<dyn crate::dao::GarrisonDao> = Arc::new(crate::dao::InMemoryDao::new());
let auth = HttpDigestAuth::new("test@realm", "MD5")
.unwrap()
.with_dao(dao);
let ha1 = auth.compute_ha1("admin", "secret");
let nonce = make_valid_nonce();
let nc = "00000001";
let cnonce = "0a4f113c";
let method = "GET";
let uri = "/resource";
let header = build_md5_auth_header(
&auth,
"admin",
"test@realm",
&nonce,
nc,
cnonce,
method,
uri,
&ha1,
);
assert!(
auth.validate(&header, method, uri, &ha1),
"vuln-0008: 首次使用 nonce 应通过 nc 校验"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn validate_nc_replay_rejected_with_dao() {
let dao: Arc<dyn crate::dao::GarrisonDao> = Arc::new(crate::dao::InMemoryDao::new());
let auth = HttpDigestAuth::new("test@realm", "MD5")
.unwrap()
.with_dao(dao);
let ha1 = auth.compute_ha1("admin", "secret");
let nonce = make_valid_nonce();
let nc = "00000001";
let cnonce = "0a4f113c";
let method = "GET";
let uri = "/resource";
let header = build_md5_auth_header(
&auth,
"admin",
"test@realm",
&nonce,
nc,
cnonce,
method,
uri,
&ha1,
);
assert!(
auth.validate(&header, method, uri, &ha1),
"vuln-0008: 首次请求应通过"
);
assert!(
!auth.validate(&header, method, uri, &ha1),
"vuln-0008: 相同 nc 重放应被拒绝"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn validate_nc_decrease_rejected_with_dao() {
let dao: Arc<dyn crate::dao::GarrisonDao> = Arc::new(crate::dao::InMemoryDao::new());
let auth = HttpDigestAuth::new("test@realm", "MD5")
.unwrap()
.with_dao(dao);
let ha1 = auth.compute_ha1("admin", "secret");
let nonce = make_valid_nonce();
let cnonce = "0a4f113c";
let method = "GET";
let uri = "/resource";
let header1 = build_md5_auth_header(
&auth,
"admin",
"test@realm",
&nonce,
"00000003",
cnonce,
method,
uri,
&ha1,
);
assert!(
auth.validate(&header1, method, uri, &ha1),
"vuln-0008: nc=3 应通过"
);
let header2 = build_md5_auth_header(
&auth,
"admin",
"test@realm",
&nonce,
"00000002",
cnonce,
method,
uri,
&ha1,
);
assert!(
!auth.validate(&header2, method, uri, &ha1),
"vuln-0008: nc 回退(3→2)应被拒绝"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn validate_nc_increasing_accepted_with_dao() {
let dao: Arc<dyn crate::dao::GarrisonDao> = Arc::new(crate::dao::InMemoryDao::new());
let auth = HttpDigestAuth::new("test@realm", "MD5")
.unwrap()
.with_dao(dao);
let ha1 = auth.compute_ha1("admin", "secret");
let nonce = make_valid_nonce();
let cnonce = "0a4f113c";
let method = "GET";
let uri = "/resource";
for i in 1..=3u64 {
let nc = format!("{:08x}", i);
let header = build_md5_auth_header(
&auth,
"admin",
"test@realm",
&nonce,
&nc,
cnonce,
method,
uri,
&ha1,
);
assert!(
auth.validate(&header, method, uri, &ha1),
"vuln-0008: nc={} 应通过(单调递增)",
nc
);
}
}
#[tokio::test(flavor = "multi_thread")]
async fn validate_nc_skipped_without_dao() {
let auth = HttpDigestAuth::new("test@realm", "MD5").unwrap();
let ha1 = auth.compute_ha1("admin", "secret");
let nonce = make_valid_nonce();
let nc = "00000001";
let cnonce = "0a4f113c";
let method = "GET";
let uri = "/resource";
let header = build_md5_auth_header(
&auth,
"admin",
"test@realm",
&nonce,
nc,
cnonce,
method,
uri,
&ha1,
);
assert!(
auth.validate(&header, method, uri, &ha1),
"vuln-0008: 无 DAO 时首次请求应通过"
);
assert!(
auth.validate(&header, method, uri, &ha1),
"vuln-0008: 无 DAO 时相同 nc 重放仍通过(fail-open)"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn validate_nc_isolates_nonces_with_dao() {
let dao: Arc<dyn crate::dao::GarrisonDao> = Arc::new(crate::dao::InMemoryDao::new());
let auth = HttpDigestAuth::new("test@realm", "MD5")
.unwrap()
.with_dao(dao);
let ha1 = auth.compute_ha1("admin", "secret");
let cnonce = "0a4f113c";
let method = "GET";
let uri = "/resource";
let nc = "00000001";
let nonce_a = make_valid_nonce();
let header_a = build_md5_auth_header(
&auth,
"admin",
"test@realm",
&nonce_a,
nc,
cnonce,
method,
uri,
&ha1,
);
assert!(
auth.validate(&header_a, method, uri, &ha1),
"vuln-0008: nonce-A nc=1 应通过"
);
let nonce_b = make_valid_nonce();
let header_b = build_md5_auth_header(
&auth,
"admin",
"test@realm",
&nonce_b,
nc,
cnonce,
method,
uri,
&ha1,
);
assert!(
auth.validate(&header_b, method, uri, &ha1),
"vuln-0008: nonce-B nc=1 应通过(不同 nonce 独立计数)"
);
}
#[tokio::test]
async fn validate_nc_current_thread_runtime_fail_closed() {
let dao: Arc<dyn crate::dao::GarrisonDao> = Arc::new(crate::dao::InMemoryDao::new());
let auth = HttpDigestAuth::new("test@realm", "MD5")
.unwrap()
.with_dao(dao);
let ha1 = auth.compute_ha1("admin", "secret");
let nonce = make_valid_nonce();
let nc = "00000001";
let cnonce = "0a4f113c";
let method = "GET";
let uri = "/resource";
let header = build_md5_auth_header(
&auth,
"admin",
"test@realm",
&nonce,
nc,
cnonce,
method,
uri,
&ha1,
);
assert!(
!auth.validate(&header, method, uri, &ha1),
"vuln-0012: current_thread runtime 下 validate_nc 应 fail-closed,首次请求拒绝"
);
assert!(
!auth.validate(&header, method, uri, &ha1),
"vuln-0012: current_thread runtime 下相同 nc 重放仍拒绝(fail-closed)"
);
}
struct FailingDao;
#[async_trait::async_trait]
impl crate::dao::GarrisonDao for FailingDao {
async fn get(&self, key: &str) -> crate::error::GarrisonResult<Option<String>> {
Err(crate::error::GarrisonError::Dao(format!(
"vuln-0012-failing-dao-get::{}",
key
)))
}
async fn set(
&self,
key: &str,
_value: &str,
_ttl_seconds: u64,
) -> crate::error::GarrisonResult<()> {
Err(crate::error::GarrisonError::Dao(format!(
"vuln-0012-failing-dao-set::{}",
key
)))
}
async fn update(&self, key: &str, _value: &str) -> crate::error::GarrisonResult<()> {
Err(crate::error::GarrisonError::Dao(format!(
"vuln-0012-failing-dao-update::{}",
key
)))
}
async fn expire(&self, key: &str, _seconds: u64) -> crate::error::GarrisonResult<()> {
Err(crate::error::GarrisonError::Dao(format!(
"vuln-0012-failing-dao-expire::{}",
key
)))
}
async fn delete(&self, key: &str) -> crate::error::GarrisonResult<()> {
Err(crate::error::GarrisonError::Dao(format!(
"vuln-0012-failing-dao-delete::{}",
key
)))
}
crate::atomic_test_fallback!();
}
#[tokio::test(flavor = "multi_thread")]
async fn validate_nc_dao_error_fail_closed() {
{
use crate::dao::GarrisonDao;
let d = FailingDao;
let _ = d.set_if_absent("a", "v", 60).await;
let _ = d.get_and_delete("a").await;
let _ = d.incr("c", 60).await;
let _ = d.decr("c").await;
let _ = d.rename("a", "b").await;
let _ = d.compare_and_swap("b", None, "v", 60).await;
let _ = d.set_permanent("p", "v").await;
let _ = d.get_timeout("k").await;
let _ = d.get_with_ttl("k").await;
let _ = d.keys("*").await;
let _ = d.find_social_binding(0, "w", "o").await;
let _ = d.insert_social_binding(0, "u", "w", "o", None, 0).await;
let _ = d.compare_and_update_if_greater("k", 1, 60).await;
let _ = d.eval_lua("r", vec![], vec![]).await;
#[cfg(any(feature = "db-sqlite", feature = "db-postgres", feature = "db-mysql"))]
{
let _ = d.insert_credit_consumption(0, "r", 1, 1, 1, 0).await;
let _ = d.query_credit_consumption(0, 0, 0).await;
let _ = d.query_role_hierarchy_edges(0).await;
let _ = d.insert_role_hierarchy_edge(0, "c", "p").await;
let _ = d.delete_role_hierarchy_edge(0, "c", "p").await;
}
}
let dao: Arc<dyn crate::dao::GarrisonDao> = Arc::new(FailingDao);
let auth = HttpDigestAuth::new("test@realm", "MD5")
.unwrap()
.with_dao(dao);
let ha1 = auth.compute_ha1("admin", "secret");
let nonce = make_valid_nonce();
let nc = "00000001";
let cnonce = "0a4f113c";
let method = "GET";
let uri = "/resource";
let header = build_md5_auth_header(
&auth,
"admin",
"test@realm",
&nonce,
nc,
cnonce,
method,
uri,
&ha1,
);
assert!(
!auth.validate(&header, method, uri, &ha1),
"vuln-0012: DAO 错误时 validate_nc 应 fail-closed(拒绝请求)"
);
assert!(
!auth.validate(&header, method, uri, &ha1),
"vuln-0012: DAO 错误时相同 nc 重放仍拒绝(fail-closed)"
);
}
#[test]
fn validate_nc_no_runtime_fail_closed() {
let dao: Arc<dyn crate::dao::GarrisonDao> = Arc::new(crate::dao::InMemoryDao::new());
let auth = HttpDigestAuth::new("test@realm", "MD5")
.unwrap()
.with_dao(dao);
let ha1 = auth.compute_ha1("admin", "secret");
let nonce = make_valid_nonce();
let nc = "00000001";
let cnonce = "0a4f113c";
let method = "GET";
let uri = "/resource";
let header = build_md5_auth_header(
&auth,
"admin",
"test@realm",
&nonce,
nc,
cnonce,
method,
uri,
&ha1,
);
assert!(
!auth.validate(&header, method, uri, &ha1),
"vuln-0012: 无 tokio runtime 时 validate_nc 应 fail-closed,拒绝请求"
);
assert!(
!auth.validate(&header, method, uri, &ha1),
"vuln-0012: 无 tokio runtime 时相同 nc 重放仍拒绝(fail-closed)"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn validate_nc_malformed_hex_rejected() {
let dao: Arc<dyn crate::dao::GarrisonDao> = Arc::new(crate::dao::InMemoryDao::new());
let auth = HttpDigestAuth::new("test@realm", "MD5")
.unwrap()
.with_dao(dao);
let ha1 = auth.compute_ha1("admin", "secret");
let nonce = make_valid_nonce();
let nc = "gggggggg";
let cnonce = "0a4f113c";
let method = "GET";
let uri = "/resource";
let header = format!(
r#"Digest username="admin", realm="test@realm", nonce="{}", uri="{}", response="dummy", qop=auth, nc={}, cnonce="{}""#,
nonce, uri, nc, cnonce
);
assert!(
!auth.validate(&header, method, uri, &ha1),
"LOW-2: 非 hex 格式的 nc 应被拒绝(不是 fail-open)"
);
}
#[test]
fn validate_uri_mismatch_rejected() {
let auth = HttpDigestAuth::new("test@realm", "MD5").unwrap();
let ha1 = auth.compute_ha1("admin", "secret");
let nonce = make_valid_nonce();
let nc = "00000001";
let cnonce = "0a4f113c";
let method = "GET";
let header_uri = "/resource";
let actual_uri = "/other";
let header = build_md5_auth_header(
&auth,
"admin",
"test@realm",
&nonce,
nc,
cnonce,
method,
header_uri,
&ha1,
);
assert!(
!auth.validate(&header, method, actual_uri, &ha1),
"CRITICAL-5: 客户端 uri 与实际请求 URI 不匹配应被拒绝"
);
}
#[test]
fn signed_nonce_roundtrip_and_self_minted_rejected() {
let auth = HttpDigestAuth::new("realm", "SHA256")
.unwrap()
.with_server_key(b"server-secret-key-material-with-enough-bytes-32");
let nonce = extract_nonce(&auth.challenge()).unwrap();
assert!(auth.is_nonce_valid(&nonce), "签名 nonce 应有效");
let forged = STANDARD
.encode(format!("{}:{}", current_unix_seconds(), Uuid::new_v4().simple()).as_bytes());
assert!(!auth.is_nonce_valid(&forged), "无签名自铸 nonce 应被拒");
let ts = current_unix_seconds();
let uuid = Uuid::new_v4().simple().to_string();
let forged3 = STANDARD.encode(format!("{}:{}:deadbeef", ts, uuid).as_bytes());
assert!(
!auth.is_nonce_valid(&forged3),
"HMAC 错误的自铸 nonce 应被拒"
);
}
#[test]
fn validate_rejects_self_minted_nonce_with_server_key() {
let auth = HttpDigestAuth::new("test@realm", "MD5")
.unwrap()
.with_server_key(b"server-secret-key-material-with-enough-bytes-32");
let ha1 = auth.compute_ha1("admin", "secret");
let nonce = STANDARD
.encode(format!("{}:{}", current_unix_seconds(), Uuid::new_v4().simple()).as_bytes());
let nc = "00000001";
let cnonce = "0a4f113c";
let method = "GET";
let uri = "/resource";
let header = build_md5_auth_header(
&auth,
"admin",
"test@realm",
&nonce,
nc,
cnonce,
method,
uri,
&ha1,
);
assert!(
!auth.validate(&header, method, uri, &ha1),
"自铸 nonce 应被拒"
);
}
#[test]
fn validate_succeeds_with_signed_nonce() {
let auth = HttpDigestAuth::new("test@realm", "MD5")
.unwrap()
.with_server_key(b"server-secret-key-material-with-enough-bytes-32");
let ha1 = auth.compute_ha1("admin", "secret");
let nonce = extract_nonce(&auth.challenge()).unwrap();
let nc = "00000001";
let cnonce = "0a4f113c";
let method = "GET";
let uri = "/resource";
let header = build_md5_auth_header(
&auth,
"admin",
"test@realm",
&nonce,
nc,
cnonce,
method,
uri,
&ha1,
);
assert!(
auth.validate(&header, method, uri, &ha1),
"签名 nonce 应完成完整校验"
);
}
fn extract_nonce(challenge: &str) -> Option<String> {
let start = challenge.find("nonce=\"")? + "nonce=\"".len();
let end = challenge[start..].find('"')? + start;
Some(challenge[start..end].to_string())
}