use crate::constants::DaoKeyPrefix;
use crate::error::{GarrisonError, GarrisonResult};
use async_trait::async_trait;
use chrono::Utc;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SamlAssertion {
#[serde(default)]
pub id: String,
pub issuer: String,
pub subject: String,
pub audience: String,
pub not_on_or_after: String,
pub attributes: Vec<(String, String)>,
#[serde(skip_serializing, skip_deserializing, default)]
pub raw_xml: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SamlResponse {
pub destination: String,
pub issuer: String,
pub assertion: Option<SamlAssertion>,
pub status_code: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SamlRequest {
pub id: String,
pub issue_instant: String,
pub destination: String,
pub issuer: String,
pub assertion_consumer_service_url: String,
}
#[async_trait]
pub trait SamlProvider: Send + Sync {
async fn build_authn_request(
&self,
sp_entity_id: &str,
acs_url: &str,
idp_sso_endpoint: &str,
) -> GarrisonResult<SamlRequest>;
async fn parse_response(&self, response_xml: &str) -> GarrisonResult<SamlResponse>;
async fn validate_assertion(&self, assertion: &SamlAssertion) -> GarrisonResult<bool>;
}
pub struct DefaultSamlProvider {
expected_destination: Option<String>,
expected_audience: Option<String>,
}
impl DefaultSamlProvider {
pub fn new() -> GarrisonResult<Self> {
Ok(Self {
expected_destination: None,
expected_audience: None,
})
}
pub fn with_expected_destination(mut self, destination: String) -> Self {
self.expected_destination = Some(destination);
self
}
pub fn with_expected_audience(mut self, audience: String) -> Self {
self.expected_audience = Some(audience);
self
}
}
impl Default for DefaultSamlProvider {
fn default() -> Self {
Self::new().expect("DefaultSamlProvider::new 不应失败")
}
}
#[async_trait]
impl SamlProvider for DefaultSamlProvider {
async fn build_authn_request(
&self,
sp_entity_id: &str,
acs_url: &str,
idp_sso_endpoint: &str,
) -> GarrisonResult<SamlRequest> {
Ok(SamlRequest {
id: Uuid::new_v4().to_string(),
issue_instant: Utc::now().to_rfc3339(),
destination: idp_sso_endpoint.to_string(),
issuer: sp_entity_id.to_string(),
assertion_consumer_service_url: acs_url.to_string(),
})
}
async fn parse_response(&self, response_xml: &str) -> GarrisonResult<SamlResponse> {
let mut response = parse_saml_response_xml(response_xml)?;
validate_destination(&response.destination, self.expected_destination.as_deref())?;
if let Some(ref assertion) = response.assertion {
validate_audience(&assertion.audience, self.expected_audience.as_deref())?;
}
if let Some(ref assertion) = response.assertion {
match self.validate_assertion(assertion).await {
Ok(true) => {},
Ok(false) => {
tracing::warn!("SAML Assertion signature verification failed, stripped");
response.assertion = None;
},
Err(GarrisonError::NotImplemented(_)) => {
tracing::warn!("SAML signature verification not implemented, Assertion stripped (fail-closed)");
response.assertion = None;
},
Err(e) => return Err(e),
}
}
Ok(response)
}
async fn validate_assertion(&self, _assertion: &SamlAssertion) -> GarrisonResult<bool> {
Err(GarrisonError::NotImplemented(
"sso-saml-signature-not-implemented".to_string(),
))
}
}
fn validate_destination(actual: &str, expected: Option<&str>) -> GarrisonResult<()> {
match expected {
Some(exp) if !exp.is_empty() => {
if actual != exp {
return Err(GarrisonError::InvalidParam(format!(
"sso-saml-destination-mismatch::expected={}::actual={}",
exp, actual
)));
}
Ok(())
},
_ => {
if !actual.is_empty() {
tracing::warn!(
actual = %actual,
"SAML Destination 未配置验证(expected_destination=None),存在重定向攻击风险"
);
}
Ok(())
},
}
}
fn validate_audience(actual: &str, expected: Option<&str>) -> GarrisonResult<()> {
match expected {
Some(exp) if !exp.is_empty() => {
if actual != exp {
return Err(GarrisonError::InvalidParam(format!(
"sso-saml-audience-mismatch::expected={}::actual={}",
exp, actual
)));
}
Ok(())
},
_ => {
if !actual.is_empty() {
tracing::warn!(
actual = %actual,
"SAML Audience 未配置验证(expected_audience=None),存在跨 SP 重放风险"
);
}
Ok(())
},
}
}
fn parse_saml_response_xml(xml: &str) -> GarrisonResult<SamlResponse> {
use quick_xml::events::Event;
use quick_xml::reader::Reader;
let mut reader = Reader::from_str(xml);
reader.config_mut().trim_text(true);
let mut buf = Vec::new();
let mut destination = String::new();
let mut issuer = String::new();
let mut status_code = String::new();
let mut assertion: Option<SamlAssertion> = None;
let mut in_assertion = false;
let mut in_issuer = false;
let mut in_subject = false;
let mut in_audience = false;
let mut in_attribute = false;
let mut current_attr_name = String::new();
let mut assertion_issuer = String::new();
let mut assertion_subject = String::new();
let mut assertion_audience = String::new();
let mut assertion_not_on_or_after = String::new();
let mut assertion_id = String::new();
let mut assertion_attributes: Vec<(String, String)> = Vec::new();
let mut current_text = String::new();
let mut assertion_start_pos: Option<u64> = None;
let mut assertion_raw_xml: Option<String> = None;
loop {
let pos_before = reader.buffer_position();
match reader.read_event_into(&mut buf) {
Err(e) => {
return Err(GarrisonError::Internal(format!(
"sso-saml-xml-parse::{}",
e
)))
},
Ok(Event::Eof) => break,
Ok(Event::Start(e)) => {
if !check_saml_namespace(e.name().as_ref()) {
continue;
}
let local_name = extract_local_name(e.name().as_ref());
match local_name.as_str() {
"Response" => {
for attr in e.attributes().flatten() {
if attr.key.as_ref() == b"Destination" {
destination = attr_value_to_string(&attr.value);
}
}
},
"Assertion" => {
in_assertion = true;
assertion_start_pos = Some(pos_before);
assertion_issuer.clear();
assertion_subject.clear();
assertion_audience.clear();
assertion_not_on_or_after.clear();
assertion_id.clear();
assertion_attributes.clear();
for attr in e.attributes().flatten() {
if attr.key.as_ref() == b"ID" {
assertion_id = attr_value_to_string(&attr.value);
}
}
},
"Issuer" => {
in_issuer = true;
current_text.clear();
},
"Subject" => in_subject = true,
"Audience" => {
in_audience = true;
current_text.clear();
},
"Attribute" => {
in_attribute = true;
current_attr_name.clear();
current_text.clear();
for attr in e.attributes().flatten() {
if attr.key.as_ref() == b"Name" {
current_attr_name = attr_value_to_string(&attr.value);
}
}
},
"SubjectConfirmationData" => {
for attr in e.attributes().flatten() {
if attr.key.as_ref() == b"NotOnOrAfter" {
assertion_not_on_or_after = attr_value_to_string(&attr.value);
}
}
},
_ => {},
}
},
Ok(Event::Empty(e)) => {
if !check_saml_namespace(e.name().as_ref()) {
continue;
}
let local_name = extract_local_name(e.name().as_ref());
match local_name.as_str() {
"StatusCode" => {
for attr in e.attributes().flatten() {
if attr.key.as_ref() == b"Value" {
status_code = attr_value_to_string(&attr.value);
}
}
},
"SubjectConfirmationData" => {
for attr in e.attributes().flatten() {
if attr.key.as_ref() == b"NotOnOrAfter" {
assertion_not_on_or_after = attr_value_to_string(&attr.value);
}
}
},
"AttributeValue" if in_attribute => {
if assertion_attributes
.iter()
.any(|(n, _)| n == ¤t_attr_name)
{
tracing::warn!(
attr_name = %current_attr_name,
"SAML Assertion 包含重复属性名,可能为属性污染攻击"
);
}
assertion_attributes.push((current_attr_name.clone(), String::new()));
},
_ => {},
}
},
Ok(Event::End(e)) => {
let local_name = extract_local_name(e.name().as_ref());
match local_name.as_str() {
"Assertion" => {
if in_assertion {
let pos_after = reader.buffer_position();
if let Some(start) = assertion_start_pos {
let start_usize = start as usize;
let pos_after_usize = pos_after as usize;
if pos_after_usize >= start_usize && pos_after_usize <= xml.len() {
assertion_raw_xml =
Some(xml[start_usize..pos_after_usize].to_string());
}
}
assertion = Some(SamlAssertion {
id: assertion_id.clone(),
issuer: assertion_issuer.clone(),
subject: assertion_subject.clone(),
audience: assertion_audience.clone(),
not_on_or_after: assertion_not_on_or_after.clone(),
attributes: assertion_attributes.clone(),
raw_xml: assertion_raw_xml.clone(),
});
in_assertion = false;
}
},
"Issuer" => {
if in_issuer {
if in_assertion {
assertion_issuer = current_text.clone();
} else {
issuer = current_text.clone();
}
in_issuer = false;
current_text.clear();
}
},
"Subject" => in_subject = false,
"Audience" => {
if in_audience {
assertion_audience = current_text.clone();
in_audience = false;
current_text.clear();
}
},
"Attribute" => {
if in_attribute {
if assertion_attributes
.iter()
.any(|(n, _)| n == ¤t_attr_name)
{
tracing::warn!(
attr_name = %current_attr_name,
"SAML Assertion 包含重复属性名,可能为属性污染攻击"
);
}
assertion_attributes
.push((current_attr_name.clone(), current_text.clone()));
in_attribute = false;
current_text.clear();
}
},
"NameID" => {
if in_subject {
assertion_subject = current_text.clone();
current_text.clear();
}
},
"AttributeValue" => {
},
_ => {},
}
},
Ok(Event::Text(e)) => {
let text = String::from_utf8_lossy(e.as_ref());
current_text.push_str(&text);
},
_ => {},
}
buf.clear();
}
if let Some(ref assertion) = assertion {
if !assertion.not_on_or_after.is_empty() {
let expiry =
chrono::DateTime::parse_from_rfc3339(&assertion.not_on_or_after).map_err(|e| {
GarrisonError::InvalidToken(format!("sso-saml-not-on-or-after-parse::{}", e))
})?;
if Utc::now().timestamp() >= expiry.timestamp() {
return Err(GarrisonError::InvalidToken(format!(
"sso-saml-assertion-expired::{}",
assertion.not_on_or_after
)));
}
}
}
Ok(SamlResponse {
destination,
issuer,
assertion,
status_code,
})
}
pub async fn check_assertion_replay(
assertion_id: &str,
not_on_or_after: &str,
dao: &dyn crate::dao::GarrisonDao,
) -> GarrisonResult<bool> {
if assertion_id.is_empty() {
return Ok(true);
}
let key = format!("{}consumed:{}", DaoKeyPrefix::Saml, assertion_id);
let existing = dao.get_and_delete(&key).await?;
if existing.is_some() {
return Ok(false);
}
let ttl = if not_on_or_after.is_empty() {
300
} else {
let expiry = chrono::DateTime::parse_from_rfc3339(not_on_or_after).map_err(|e| {
GarrisonError::InvalidToken(format!("sso-saml-not-on-or-after-parse::{}", e))
})?;
let remaining = expiry.timestamp().saturating_sub(Utc::now().timestamp());
if remaining > 0 {
remaining as u64
} else {
300
}
};
dao.set(&key, "1", ttl).await?;
Ok(true)
}
fn extract_local_name(qualified: &[u8]) -> String {
let full = String::from_utf8_lossy(qualified);
match full.rsplit_once(':') {
Some((_, local)) => local.to_string(),
None => full.to_string(),
}
}
fn check_saml_namespace(qualified: &[u8]) -> bool {
let full = String::from_utf8_lossy(qualified);
match full.rsplit_once(':') {
Some((prefix, _)) => {
let valid = matches!(prefix, "saml" | "samlp" | "ds");
if !valid {
tracing::warn!(
qualified = %full,
"SAML XML 元素使用非标准命名空间前缀,可能为命名空间混淆攻击"
);
}
valid
},
None => true,
}
}
fn attr_value_to_string(value: &[u8]) -> String {
String::from_utf8_lossy(value).to_string()
}
#[cfg(feature = "secure-saml")]
const SIG_ALG_RSA_SHA256: &str = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";
#[cfg(feature = "secure-saml")]
const SIG_ALG_ECDSA_SHA256: &str = "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha256";
#[cfg(feature = "secure-saml")]
const SIG_ALG_RSA_1_5: &str = "http://www.w3.org/2000/09/xmldsig#rsa-1_5";
#[cfg(all(feature = "secure-saml", test))]
fn is_signature_algorithm_allowed(algorithm: &str) -> bool {
matches!(algorithm, SIG_ALG_RSA_SHA256 | SIG_ALG_ECDSA_SHA256)
}
#[cfg(feature = "secure-saml")]
fn extract_signature_method_algorithm(signature_xml: &str) -> Option<String> {
let method_start = signature_xml.find("<")?;
let rest = &signature_xml[method_start..];
let method_idx = rest.find("SignatureMethod")?;
let after_method = &rest[method_idx..];
let alg_key = after_method.find("Algorithm=\"")?;
let alg_value_start = alg_key + "Algorithm=\"".len();
let after_alg = &after_method[alg_value_start..];
let alg_end = after_alg.find('"')?;
Some(after_alg[..alg_end].to_string())
}
#[cfg(feature = "secure-saml")]
fn extract_signature_value(signature_xml: &str) -> Option<String> {
let start_tag_options = ["<ds:SignatureValue>", "<SignatureValue>"];
let end_tag_options = ["</ds:SignatureValue>", "</SignatureValue>"];
for (start_tag, end_tag) in start_tag_options.iter().zip(end_tag_options.iter()) {
if let Some(start_idx) = signature_xml.find(start_tag) {
let content_start = start_idx + start_tag.len();
if let Some(end_idx) = signature_xml[content_start..].find(end_tag) {
let value = &signature_xml[content_start..content_start + end_idx];
return Some(value.trim().to_string());
}
}
}
None
}
#[cfg(feature = "secure-saml")]
fn extract_signed_info_xml(assertion_xml: &str) -> Option<String> {
let start_tag_options = ["<ds:SignedInfo>", "<SignedInfo>"];
let end_tag_options = ["</ds:SignedInfo>", "</SignedInfo>"];
for (start_tag, end_tag) in start_tag_options.iter().zip(end_tag_options.iter()) {
if let Some(start_idx) = assertion_xml.find(start_tag) {
if let Some(end_idx) = assertion_xml[start_idx..].find(end_tag) {
let end_pos = start_idx + end_idx + end_tag.len();
return Some(assertion_xml[start_idx..end_pos].to_string());
}
}
}
None
}
#[cfg(feature = "secure-saml")]
fn extract_signature_xml(assertion_xml: &str) -> Option<String> {
let start_tag_options = [
"<ds:Signature>",
"<ds:Signature ",
"<Signature>",
"<Signature ",
];
let end_tag_options = ["</ds:Signature>", "</Signature>"];
for start_tag in start_tag_options {
if let Some(start_idx) = assertion_xml.find(start_tag) {
for end_tag in end_tag_options {
if let Some(end_idx) = assertion_xml[start_idx..].find(end_tag) {
let end_pos = start_idx + end_idx + end_tag.len();
return Some(assertion_xml[start_idx..end_pos].to_string());
}
}
}
}
None
}
#[cfg(feature = "secure-saml")]
fn verify_saml_signature(assertion_xml: &str, idp_public_key_pem: &str) -> GarrisonResult<bool> {
use rsa::pkcs1::DecodeRsaPublicKey;
use rsa::pkcs8::DecodePublicKey;
let signature_xml = match extract_signature_xml(assertion_xml) {
Some(xml) => xml,
None => {
tracing::warn!(
"SAML Assertion missing <ds:Signature> element, signature verification failed"
);
return Ok(false);
},
};
let algorithm = extract_signature_method_algorithm(&signature_xml);
match algorithm.as_deref() {
Some(SIG_ALG_RSA_SHA256) => {}, Some(SIG_ALG_ECDSA_SHA256) => {
tracing::warn!(
algorithm = %SIG_ALG_ECDSA_SHA256,
"SAML 签名算法 ecdsa-sha256 在白名单内但当前实现不支持验证(待引入 ECDSA 库)"
);
return Ok(false);
},
Some(alg) if alg == SIG_ALG_RSA_1_5 => {
tracing::warn!(
algorithm = %alg,
"SAML 签名算法 rsa-1_5 被拒绝(弱算法,Bleichenbacher 攻击风险)"
);
return Ok(false);
},
Some(alg) => {
tracing::warn!(
algorithm = %alg,
"SAML 签名算法不在白名单内(仅允许 rsa-sha256 / ecdsa-sha256)"
);
return Ok(false);
},
None => {
tracing::warn!("SAML <ds:Signature> missing <ds:SignatureMethod Algorithm=...>");
return Ok(false);
},
}
let signature_value_b64 = match extract_signature_value(&signature_xml) {
Some(v) => v,
None => {
tracing::warn!("SAML <ds:Signature> missing <ds:SignatureValue>");
return Ok(false);
},
};
use base64::Engine as _;
let signature_value = base64::engine::general_purpose::STANDARD
.decode(&signature_value_b64)
.map_err(|e| {
GarrisonError::InvalidParam(format!("sso-saml-signature-value-decode::{}", e))
})?;
let signed_info_xml = match extract_signed_info_xml(assertion_xml) {
Some(xml) => xml,
None => {
tracing::warn!("SAML Assertion missing <ds:SignedInfo>");
return Ok(false);
},
};
use rsa::pkcs1v15::{Signature, VerifyingKey};
use rsa::sha2::Sha256;
use rsa::signature::Verifier;
let public_key = match rsa::RsaPublicKey::from_public_key_pem(idp_public_key_pem) {
Ok(k) => k,
Err(e1) => match rsa::RsaPublicKey::from_pkcs1_pem(idp_public_key_pem) {
Ok(k) => k,
Err(e2) => {
return Err(GarrisonError::InvalidParam(format!(
"sso-saml-idp-public-key-parse-failed::pkcs8_err={}::pkcs1_err={}",
e1, e2
)));
},
},
};
use std::convert::TryFrom;
let signature = Signature::try_from(signature_value.as_slice()).map_err(|e| {
GarrisonError::InvalidParam(format!("sso-saml-signature-bytes-decode::{}", e))
})?;
let verifying_key = VerifyingKey::<Sha256>::new(public_key);
match verifying_key.verify(signed_info_xml.as_bytes(), &signature) {
Ok(()) => Ok(true),
Err(_) => {
tracing::warn!(
"SAML signature verification failed: signature value does not match SignedInfo"
);
Ok(false)
},
}
}
#[cfg(feature = "secure-saml")]
pub struct XmlSecSamlProvider {
idp_public_key_pem: String,
expected_destination: Option<String>,
expected_audience: Option<String>,
}
#[cfg(feature = "secure-saml")]
impl XmlSecSamlProvider {
pub fn new(idp_public_key_pem: String) -> GarrisonResult<Self> {
let _ = parse_rsa_public_key(&idp_public_key_pem)?;
Ok(Self {
idp_public_key_pem,
expected_destination: None,
expected_audience: None,
})
}
pub fn with_expected_destination(mut self, destination: String) -> Self {
self.expected_destination = Some(destination);
self
}
pub fn with_expected_audience(mut self, audience: String) -> Self {
self.expected_audience = Some(audience);
self
}
}
#[cfg(feature = "secure-saml")]
fn parse_rsa_public_key(pem: &str) -> GarrisonResult<rsa::RsaPublicKey> {
use rsa::pkcs1::DecodeRsaPublicKey;
use rsa::pkcs8::DecodePublicKey;
match rsa::RsaPublicKey::from_public_key_pem(pem) {
Ok(k) => Ok(k),
Err(e1) => match rsa::RsaPublicKey::from_pkcs1_pem(pem) {
Ok(k) => Ok(k),
Err(e2) => Err(GarrisonError::InvalidParam(format!(
"sso-saml-idp-public-key-parse-failed::pkcs8_err={}::pkcs1_err={}",
e1, e2
))),
},
}
}
#[cfg(feature = "secure-saml")]
#[async_trait]
impl SamlProvider for XmlSecSamlProvider {
async fn build_authn_request(
&self,
sp_entity_id: &str,
acs_url: &str,
idp_sso_endpoint: &str,
) -> GarrisonResult<SamlRequest> {
Ok(SamlRequest {
id: Uuid::new_v4().to_string(),
issue_instant: Utc::now().to_rfc3339(),
destination: idp_sso_endpoint.to_string(),
issuer: sp_entity_id.to_string(),
assertion_consumer_service_url: acs_url.to_string(),
})
}
async fn parse_response(&self, response_xml: &str) -> GarrisonResult<SamlResponse> {
let mut response = parse_saml_response_xml(response_xml)?;
validate_destination(&response.destination, self.expected_destination.as_deref())?;
if let Some(ref assertion) = response.assertion {
validate_audience(&assertion.audience, self.expected_audience.as_deref())?;
}
if let Some(ref assertion) = response.assertion {
match self.validate_assertion(assertion).await {
Ok(true) => {},
Ok(false) => {
tracing::warn!("SAML Assertion signature verification failed, stripped");
response.assertion = None;
},
Err(e) => return Err(e),
}
}
Ok(response)
}
async fn validate_assertion(&self, assertion: &SamlAssertion) -> GarrisonResult<bool> {
let raw_xml = assertion.raw_xml.as_ref().ok_or_else(|| {
GarrisonError::InvalidParam(
"sso-saml-missing-raw-xml-for-signature-verification".to_string(),
)
})?;
verify_saml_signature(raw_xml, &self.idp_public_key_pem)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn saml_assertion_serde_roundtrip() {
let assertion = SamlAssertion {
id: "assertion-001".to_string(),
issuer: "https://idp.example.com".to_string(),
subject: "user@example.com".to_string(),
audience: "https://sp.example.com".to_string(),
not_on_or_after: "2026-07-10T12:00:00Z".to_string(),
attributes: vec![("email".to_string(), "user@example.com".to_string())],
raw_xml: None,
};
let json = serde_json::to_string(&assertion).unwrap();
let deserialized: SamlAssertion = serde_json::from_str(&json).unwrap();
assert_eq!(deserialized.id, assertion.id);
assert_eq!(deserialized.issuer, assertion.issuer);
assert_eq!(deserialized.subject, assertion.subject);
assert_eq!(deserialized.audience, assertion.audience);
assert_eq!(deserialized.not_on_or_after, assertion.not_on_or_after);
assert_eq!(deserialized.attributes.len(), 1);
assert_eq!(deserialized.attributes[0].0, "email");
assert_eq!(deserialized.attributes[0].1, "user@example.com");
assert!(deserialized.raw_xml.is_none());
}
#[test]
fn saml_response_serde_roundtrip() {
let response = SamlResponse {
destination: "https://sp.example.com/acs".to_string(),
issuer: "https://idp.example.com".to_string(),
assertion: None,
status_code: "urn:oasis:names:tc:SAML:2.0:status:Success".to_string(),
};
let json = serde_json::to_string(&response).unwrap();
let deserialized: SamlResponse = serde_json::from_str(&json).unwrap();
assert_eq!(deserialized.destination, response.destination);
assert_eq!(deserialized.issuer, response.issuer);
assert!(deserialized.assertion.is_none());
assert_eq!(deserialized.status_code, response.status_code);
}
#[test]
fn saml_request_serde_roundtrip() {
let request = SamlRequest {
id: "id-12345".to_string(),
issue_instant: "2026-07-10T12:00:00Z".to_string(),
destination: "https://idp.example.com/sso".to_string(),
issuer: "https://sp.example.com".to_string(),
assertion_consumer_service_url: "https://sp.example.com/acs".to_string(),
};
let json = serde_json::to_string(&request).unwrap();
let deserialized: SamlRequest = serde_json::from_str(&json).unwrap();
assert_eq!(deserialized.id, request.id);
assert_eq!(deserialized.issue_instant, request.issue_instant);
assert_eq!(deserialized.destination, request.destination);
assert_eq!(deserialized.issuer, request.issuer);
assert_eq!(
deserialized.assertion_consumer_service_url,
request.assertion_consumer_service_url
);
}
#[test]
fn saml_assertion_implements_clone_debug() {
let assertion = SamlAssertion {
id: "assertion-002".to_string(),
issuer: "idp".to_string(),
subject: "user".to_string(),
audience: "sp".to_string(),
not_on_or_after: "2026-07-10T12:00:00Z".to_string(),
attributes: vec![],
raw_xml: None,
};
let cloned = assertion.clone();
assert_eq!(cloned.issuer, assertion.issuer);
let debug_str = format!("{:?}", assertion);
assert!(debug_str.contains("SamlAssertion"));
}
#[test]
fn default_saml_provider_new_returns_ok() {
let provider = DefaultSamlProvider::new();
assert!(provider.is_ok());
}
#[test]
fn default_saml_provider_implements_saml_provider() {
fn assert_saml_provider<T: SamlProvider>(_provider: &T) {}
let provider = DefaultSamlProvider::new().unwrap();
assert_saml_provider(&provider);
}
#[tokio::test]
async fn build_authn_request_returns_valid_request() {
let provider = DefaultSamlProvider::new().unwrap();
let request = provider
.build_authn_request(
"https://sp.example.com",
"https://sp.example.com/acs",
"https://idp.example.com/sso",
)
.await
.unwrap();
assert_eq!(request.issuer, "https://sp.example.com");
assert_eq!(
request.assertion_consumer_service_url,
"https://sp.example.com/acs"
);
assert_eq!(request.destination, "https://idp.example.com/sso");
assert!(!request.id.is_empty());
assert!(!request.issue_instant.is_empty());
}
#[tokio::test]
async fn build_authn_request_generates_unique_ids() {
let provider = DefaultSamlProvider::new().unwrap();
let r1 = provider
.build_authn_request("sp1", "https://sp1.example.com/acs", "https://idp/sso")
.await
.unwrap();
let r2 = provider
.build_authn_request("sp1", "https://sp1.example.com/acs", "https://idp/sso")
.await
.unwrap();
assert_ne!(r1.id, r2.id);
}
#[tokio::test]
async fn parse_response_success() {
let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<samlp:Response xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
Destination="https://sp.example.com/acs">
<saml:Issuer>https://idp.example.com</saml:Issuer>
<samlp:Status>
<samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/>
</samlp:Status>
<saml:Assertion ID="assertion-123">
<saml:Issuer>https://idp.example.com</saml:Issuer>
<saml:Subject>
<saml:NameID>user@example.com</saml:NameID>
</saml:Subject>
<saml:Conditions>
<saml:AudienceRestriction>
<saml:Audience>https://sp.example.com</saml:Audience>
</saml:AudienceRestriction>
</saml:Conditions>
<saml:AttributeStatement>
<saml:Attribute Name="email">
<saml:AttributeValue>user@example.com</saml:AttributeValue>
</saml:Attribute>
</saml:AttributeStatement>
</saml:Assertion>
</samlp:Response>"#;
let provider = DefaultSamlProvider::new().unwrap();
let response = provider.parse_response(xml).await.unwrap();
assert_eq!(response.destination, "https://sp.example.com/acs");
assert_eq!(response.issuer, "https://idp.example.com");
assert_eq!(
response.status_code,
"urn:oasis:names:tc:SAML:2.0:status:Success"
);
assert!(
response.assertion.is_none(),
"C-1: validate_assertion 未实现时应剥离 Assertion(fail-closed)"
);
}
#[tokio::test]
async fn parse_response_without_assertion() {
let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<samlp:Response xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
Destination="https://sp.example.com/acs">
<saml:Issuer>https://idp.example.com</saml:Issuer>
<samlp:Status>
<samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Requester"/>
</samlp:Status>
</samlp:Response>"#;
let provider = DefaultSamlProvider::new().unwrap();
let response = provider.parse_response(xml).await.unwrap();
assert_eq!(response.destination, "https://sp.example.com/acs");
assert_eq!(response.issuer, "https://idp.example.com");
assert_eq!(
response.status_code,
"urn:oasis:names:tc:SAML:2.0:status:Requester"
);
assert!(response.assertion.is_none());
}
#[tokio::test]
async fn parse_response_non_saml_xml_returns_empty_fields() {
let provider = DefaultSamlProvider::new().unwrap();
let response = provider
.parse_response("not a saml response")
.await
.unwrap();
assert!(response.destination.is_empty());
assert!(response.issuer.is_empty());
assert!(response.status_code.is_empty());
assert!(response.assertion.is_none());
}
#[tokio::test]
async fn parse_response_rejects_expired_assertion() {
let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<samlp:Response xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
Destination="https://sp.example.com/acs">
<saml:Issuer>https://idp.example.com</saml:Issuer>
<samlp:Status>
<samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/>
</samlp:Status>
<saml:Assertion>
<saml:Issuer>https://idp.example.com</saml:Issuer>
<saml:Subject>
<saml:NameID>user@example.com</saml:NameID>
<saml:SubjectConfirmation>
<saml:SubjectConfirmationData NotOnOrAfter="2020-01-01T00:00:00Z"/>
</saml:SubjectConfirmation>
</saml:Subject>
</saml:Assertion>
</samlp:Response>"#;
let provider = DefaultSamlProvider::new().unwrap();
let result = provider.parse_response(xml).await;
assert!(
matches!(result, Err(GarrisonError::InvalidToken(_))),
"过期 Assertion 应返回 InvalidToken,实际: {:?}",
result
);
}
#[tokio::test]
async fn parse_response_accepts_valid_assertion() {
let future = Utc::now().timestamp() + 3600;
let future_str = chrono::DateTime::from_timestamp(future, 0)
.unwrap()
.to_rfc3339();
let xml = format!(
r#"<?xml version="1.0" encoding="UTF-8"?>
<samlp:Response xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
Destination="https://sp.example.com/acs">
<saml:Issuer>https://idp.example.com</saml:Issuer>
<samlp:Status>
<samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/>
</samlp:Status>
<saml:Assertion>
<saml:Issuer>https://idp.example.com</saml:Issuer>
<saml:Subject>
<saml:NameID>user@example.com</saml:NameID>
<saml:SubjectConfirmation>
<saml:SubjectConfirmationData NotOnOrAfter="{}"/>
</saml:SubjectConfirmation>
</saml:Subject>
</saml:Assertion>
</samlp:Response>"#,
future_str
);
let provider = DefaultSamlProvider::new().unwrap();
let response = provider.parse_response(&xml).await.unwrap();
assert_eq!(
response.status_code,
"urn:oasis:names:tc:SAML:2.0:status:Success"
);
}
#[tokio::test]
async fn validate_assertion_returns_not_implemented() {
let provider = DefaultSamlProvider::new().unwrap();
let assertion = SamlAssertion {
id: "assertion-003".to_string(),
issuer: "https://idp.example.com".to_string(),
subject: "user@example.com".to_string(),
audience: "https://sp.example.com".to_string(),
not_on_or_after: "2026-07-10T12:00:00Z".to_string(),
attributes: vec![],
raw_xml: None,
};
let result = provider.validate_assertion(&assertion).await;
assert!(result.is_err());
match result.err() {
Some(GarrisonError::NotImplemented(_)) => {},
other => panic!("期望 NotImplemented 错误,实际: {:?}", other),
}
}
#[tokio::test]
async fn check_assertion_replay_rejects_replay() {
let dao = crate::dao::tests::MockDao::new();
let future = Utc::now().timestamp() + 3600;
let future_str = chrono::DateTime::from_timestamp(future, 0)
.unwrap()
.to_rfc3339();
let first = check_assertion_replay("assertion-replay-001", &future_str, &dao)
.await
.expect("首次 check 不应报错");
assert!(first, "首次消费应通过");
let second = check_assertion_replay("assertion-replay-001", &future_str, &dao)
.await
.expect("二次 check 不应报错");
assert!(
!second,
"同一 Assertion ID 二次消费应被拒绝(C-3 重放防护)"
);
}
#[tokio::test]
async fn check_assertion_replay_isolates_by_id() {
let dao = crate::dao::tests::MockDao::new();
let future = Utc::now().timestamp() + 3600;
let future_str = chrono::DateTime::from_timestamp(future, 0)
.unwrap()
.to_rfc3339();
let a = check_assertion_replay("assertion-A", &future_str, &dao)
.await
.unwrap();
assert!(a, "assertion-A 首次应通过");
let b = check_assertion_replay("assertion-B", &future_str, &dao)
.await
.unwrap();
assert!(b, "assertion-B 首次应通过(不同 ID 隔离)");
}
#[tokio::test]
async fn check_assertion_replay_empty_id_passes() {
let dao = crate::dao::tests::MockDao::new();
let result = check_assertion_replay("", "", &dao)
.await
.expect("空 ID 不应报错");
assert!(result, "空 Assertion ID 应放行(无法做重放检查)");
}
#[test]
fn extract_local_name_strips_namespace() {
assert_eq!(extract_local_name(b"samlp:Response"), "Response");
assert_eq!(extract_local_name(b"saml:Issuer"), "Issuer");
assert_eq!(extract_local_name(b"Assertion"), "Assertion");
}
#[test]
fn check_saml_namespace_accepts_valid_prefixes() {
assert!(check_saml_namespace(b"samlp:Response"));
assert!(check_saml_namespace(b"saml:Assertion"));
assert!(check_saml_namespace(b"saml:Issuer"));
assert!(check_saml_namespace(b"ds:Signature"));
assert!(check_saml_namespace(b"Response")); assert!(check_saml_namespace(b"Assertion")); }
#[test]
fn check_saml_namespace_rejects_invalid_prefixes() {
assert!(!check_saml_namespace(b"evil:Assertion"));
assert!(!check_saml_namespace(b"foo:Response"));
assert!(!check_saml_namespace(b"xs:Issuer"));
assert!(!check_saml_namespace(b"attack:Attribute"));
}
#[tokio::test]
async fn parse_saml_response_skips_invalid_namespace_assertion() {
let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<Response>
<evil:Assertion xmlns:evil="http://evil.example.com">
<Issuer>https://idp.example.com</Issuer>
<Subject>user@example.com</Subject>
<Audience>https://sp.example.com</Audience>
<SubjectConfirmationData NotOnOrAfter="2099-12-31T23:59:59Z"/>
</evil:Assertion>
</Response>"#;
let result = parse_saml_response_xml(xml).expect("解析不应报错");
assert!(
result.assertion.is_none(),
"非标准命名空间的 Assertion 应被跳过"
);
}
#[tokio::test]
async fn parse_saml_response_with_duplicate_attributes_preserves_both() {
let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<Response>
<Assertion ID="attr-dup-001">
<Issuer>https://idp.example.com</Issuer>
<Subject>user@example.com</Subject>
<Audience>https://sp.example.com</Audience>
<SubjectConfirmationData NotOnOrAfter="2099-12-31T23:59:59Z"/>
<AttributeStatement>
<Attribute Name="role">
<AttributeValue>user</AttributeValue>
</Attribute>
<Attribute Name="role">
<AttributeValue>admin</AttributeValue>
</Attribute>
</AttributeStatement>
</Assertion>
</Response>"#;
let result = parse_saml_response_xml(xml).expect("解析不应报错");
let assertion = result
.assertion
.expect("parse_saml_response_xml 应返回 Assertion(剥离由 parse_response 负责)");
let roles: Vec<&str> = assertion
.attributes
.iter()
.filter(|(name, _)| name == "role")
.map(|(_, value)| value.as_str())
.collect();
assert_eq!(
roles.len(),
2,
"重复属性名应保留两个值(供消费方决策),实际: {:?}",
roles
);
assert!(roles.contains(&"user"));
assert!(roles.contains(&"admin"));
}
#[tokio::test]
async fn parse_response_destination_match_passes() {
let future = Utc::now().timestamp() + 3600;
let future_str = chrono::DateTime::from_timestamp(future, 0)
.unwrap()
.to_rfc3339();
let xml = format!(
r#"<?xml version="1.0" encoding="UTF-8"?>
<samlp:Response xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
Destination="https://sp.example.com/acs">
<saml:Issuer>https://idp.example.com</saml:Issuer>
<samlp:Status>
<samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/>
</samlp:Status>
<saml:Assertion>
<saml:Issuer>https://idp.example.com</saml:Issuer>
<saml:Subject>
<saml:NameID>user@example.com</saml:NameID>
<saml:SubjectConfirmation>
<saml:SubjectConfirmationData NotOnOrAfter="{}"/>
</saml:SubjectConfirmation>
</saml:Subject>
<saml:Conditions>
<saml:AudienceRestriction>
<saml:Audience>https://sp.example.com</saml:Audience>
</saml:AudienceRestriction>
</saml:Conditions>
</saml:Assertion>
</samlp:Response>"#,
future_str
);
let provider = DefaultSamlProvider::new()
.unwrap()
.with_expected_destination("https://sp.example.com/acs".to_string())
.with_expected_audience("https://sp.example.com".to_string());
let response = provider.parse_response(&xml).await.unwrap();
assert_eq!(response.destination, "https://sp.example.com/acs");
}
#[tokio::test]
async fn parse_response_destination_mismatch_returns_error() {
let future = Utc::now().timestamp() + 3600;
let future_str = chrono::DateTime::from_timestamp(future, 0)
.unwrap()
.to_rfc3339();
let xml = format!(
r#"<?xml version="1.0" encoding="UTF-8"?>
<samlp:Response xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
Destination="https://evil.example.com/acs">
<saml:Issuer>https://idp.example.com</saml:Issuer>
<samlp:Status>
<samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/>
</samlp:Status>
<saml:Assertion>
<saml:Issuer>https://idp.example.com</saml:Issuer>
<saml:Subject><saml:NameID>user@example.com</saml:NameID>
<saml:SubjectConfirmation>
<saml:SubjectConfirmationData NotOnOrAfter="{}"/>
</saml:SubjectConfirmation>
</saml:Subject>
</saml:Assertion>
</samlp:Response>"#,
future_str
);
let provider = DefaultSamlProvider::new()
.unwrap()
.with_expected_destination("https://sp.example.com/acs".to_string());
let result = provider.parse_response(&xml).await;
assert!(
matches!(result, Err(GarrisonError::InvalidParam(_))),
"Destination 不匹配应返回 InvalidParam(fail-loud),实际: {:?}",
result
);
}
#[tokio::test]
async fn parse_response_audience_mismatch_returns_error() {
let future = Utc::now().timestamp() + 3600;
let future_str = chrono::DateTime::from_timestamp(future, 0)
.unwrap()
.to_rfc3339();
let xml = format!(
r#"<?xml version="1.0" encoding="UTF-8"?>
<samlp:Response xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
Destination="https://sp.example.com/acs">
<saml:Issuer>https://idp.example.com</saml:Issuer>
<samlp:Status>
<samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/>
</samlp:Status>
<saml:Assertion>
<saml:Issuer>https://idp.example.com</saml:Issuer>
<saml:Subject>
<saml:NameID>user@example.com</saml:NameID>
<saml:SubjectConfirmation>
<saml:SubjectConfirmationData NotOnOrAfter="{}"/>
</saml:SubjectConfirmation>
</saml:Subject>
<saml:Conditions>
<saml:AudienceRestriction>
<saml:Audience>https://evil.example.com</saml:Audience>
</saml:AudienceRestriction>
</saml:Conditions>
</saml:Assertion>
</samlp:Response>"#,
future_str
);
let provider = DefaultSamlProvider::new()
.unwrap()
.with_expected_audience("https://sp.example.com".to_string());
let result = provider.parse_response(&xml).await;
assert!(
matches!(result, Err(GarrisonError::InvalidParam(_))),
"Audience 不匹配应返回 InvalidParam(fail-loud),实际: {:?}",
result
);
}
#[test]
fn validate_destination_audience_unit_tests() {
assert!(validate_destination("https://sp/acs", Some("https://sp/acs")).is_ok());
assert!(matches!(
validate_destination("https://evil/acs", Some("https://sp/acs")),
Err(GarrisonError::InvalidParam(_))
));
assert!(validate_destination("https://sp/acs", None).is_ok());
assert!(validate_destination("https://sp/acs", Some("")).is_ok());
assert!(validate_audience("https://sp", Some("https://sp")).is_ok());
assert!(matches!(
validate_audience("https://evil", Some("https://sp")),
Err(GarrisonError::InvalidParam(_))
));
assert!(validate_audience("https://sp", None).is_ok());
}
#[cfg(feature = "secure-saml")]
mod signature_tests {
use super::*;
#[test]
fn signature_algorithm_whitelist_allows_strong_algorithms() {
assert!(
is_signature_algorithm_allowed(SIG_ALG_RSA_SHA256),
"rsa-sha256 应在白名单内"
);
assert!(
is_signature_algorithm_allowed(SIG_ALG_ECDSA_SHA256),
"ecdsa-sha256 应在白名单内"
);
}
#[test]
fn signature_algorithm_whitelist_rejects_weak_and_unknown_algorithms() {
assert!(
!is_signature_algorithm_allowed(SIG_ALG_RSA_1_5),
"rsa-1_5 应被拒绝(Bleichenbacher 攻击风险)"
);
assert!(
!is_signature_algorithm_allowed("http://www.w3.org/2000/09/xmldsig#dsa-sha1"),
"dsa-sha1 应被拒绝(未在白名单)"
);
assert!(
!is_signature_algorithm_allowed("unknown-algorithm"),
"未知算法应被拒绝"
);
assert!(!is_signature_algorithm_allowed(""), "空字符串应被拒绝");
}
fn build_test_signed_assertion() -> (String, String) {
use base64::Engine as _;
use rsa::pkcs1v15::SigningKey;
use rsa::pkcs8::EncodePublicKey;
use rsa::sha2::Sha256;
use rsa::signature::{SignatureEncoding, Signer};
use rsa::RsaPrivateKey;
let mut rng = rand::rngs::OsRng;
let private_key =
RsaPrivateKey::new(&mut rng, 2048).expect("RSA 2048 密钥生成不应失败");
let public_key_pem = private_key
.to_public_key()
.to_public_key_pem(rsa::pkcs8::LineEnding::LF)
.expect("PEM 编码不应失败");
let signed_info = r#"<ds:SignedInfo><ds:SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"></ds:SignatureMethod></ds:SignedInfo>"#;
let signing_key = SigningKey::<Sha256>::new(private_key);
let signature = signing_key.sign(signed_info.as_bytes());
let signature_b64 =
base64::engine::general_purpose::STANDARD.encode(signature.to_bytes());
let xml = format!(
r#"<Assertion><ds:Signature>{}<ds:SignatureValue>{}</ds:SignatureValue></ds:Signature></Assertion>"#,
signed_info, signature_b64
);
(xml, public_key_pem)
}
#[test]
fn verify_saml_signature_accepts_valid_signature() {
let (xml, public_key_pem) = build_test_signed_assertion();
let result = verify_saml_signature(&xml, &public_key_pem);
assert!(
result.is_ok(),
"verify_saml_signature 不应报错: {:?}",
result
);
assert!(result.unwrap(), "合法 RSA-SHA256 签名应验证通过");
}
#[test]
fn verify_saml_signature_rejects_wrong_public_key() {
use rsa::pkcs8::EncodePublicKey;
let (xml, _original_public_pem) = build_test_signed_assertion();
let mut rng = rand::rngs::OsRng;
let other_key =
rsa::RsaPrivateKey::new(&mut rng, 2048).expect("RSA 2048 密钥生成不应失败");
let other_public_pem = other_key
.to_public_key()
.to_public_key_pem(rsa::pkcs8::LineEnding::LF)
.expect("PEM 编码不应失败");
let result = verify_saml_signature(&xml, &other_public_pem);
assert!(
result.is_ok(),
"verify_saml_signature 不应报错: {:?}",
result
);
assert!(!result.unwrap(), "用错误公钥验证应返回 false(签名不匹配)");
}
#[test]
fn verify_saml_signature_rejects_tampered_signed_info() {
let (xml, public_key_pem) = build_test_signed_assertion();
let tampered_xml =
xml.replacen("<ds:SignedInfo>", "<ds:SignedInfo><!-- tampered -->", 1);
let result = verify_saml_signature(&tampered_xml, &public_key_pem);
assert!(
result.is_ok(),
"verify_saml_signature 不应报错: {:?}",
result
);
assert!(!result.unwrap(), "篡改 SignedInfo 后签名验证应失败");
}
#[test]
fn verify_saml_signature_rejects_missing_signature() {
let xml = r#"<Assertion><Issuer>https://idp.example.com</Issuer></Assertion>"#;
let (_signed_xml, public_key_pem) = build_test_signed_assertion();
let result = verify_saml_signature(xml, &public_key_pem);
assert!(
result.is_ok(),
"verify_saml_signature 不应报错: {:?}",
result
);
assert!(!result.unwrap(), "缺少 <ds:Signature> 应返回 false");
}
#[test]
fn verify_saml_signature_rejects_rsa_1_5_algorithm() {
let xml = format!(
r#"<Assertion><ds:Signature><ds:SignedInfo><ds:SignatureMethod Algorithm="{}"></ds:SignatureMethod></ds:SignedInfo><ds:SignatureValue>dGVzdA==</ds:SignatureValue></ds:Signature></Assertion>"#,
SIG_ALG_RSA_1_5
);
let (_signed_xml, public_key_pem) = build_test_signed_assertion();
let result = verify_saml_signature(&xml, &public_key_pem);
assert!(
result.is_ok(),
"verify_saml_signature 不应报错: {:?}",
result
);
assert!(
!result.unwrap(),
"rsa-1_5 算法应被白名单拒绝(Bleichenbacher 攻击风险)"
);
}
#[test]
fn verify_saml_signature_rejects_invalid_public_key_pem() {
let (xml, _public_key_pem) = build_test_signed_assertion();
let invalid_pem = "-----BEGIN INVALID-----\nnot a real key\n-----END INVALID-----";
let result = verify_saml_signature(&xml, invalid_pem);
assert!(
result.is_err(),
"非法公钥 PEM 应返回 Err(fail-loud),实际: {:?}",
result
);
assert!(
matches!(result, Err(GarrisonError::InvalidParam(_))),
"应为 InvalidParam 错误"
);
}
}
#[tokio::test]
async fn check_assertion_replay_concurrent_atomic_get_and_delete() {
let dao = std::sync::Arc::new(crate::dao::tests::MockDao::new());
let future = Utc::now().timestamp() + 3600;
let future_str = chrono::DateTime::from_timestamp(future, 0)
.unwrap()
.to_rfc3339();
let assertion_id = "assertion-toctou-concurrent-001".to_string();
let mut handles = Vec::new();
for _ in 0..10 {
let dao_clone = dao.clone();
let id = assertion_id.clone();
let ttl = future_str.clone();
handles.push(tokio::spawn(async move {
check_assertion_replay(&id, &ttl, &*dao_clone).await
}));
}
let mut success_count = 0usize;
let mut failure_count = 0usize;
for handle in handles {
let result = handle.await.expect("并发任务不应 panic");
match result {
Ok(true) => success_count += 1,
Ok(false) => failure_count += 1,
Err(e) => panic!("check_assertion_replay 不应报错: {:?}", e),
}
}
assert!(
success_count >= 1,
"至少一个任务应成功消费,实际成功: {}",
success_count
);
assert!(
failure_count >= 1,
"至少一个任务应被拒绝(get_and_delete 原子性),实际拒绝: {}",
failure_count
);
assert_eq!(
success_count + failure_count,
10,
"所有 10 个任务都应正常完成"
);
}
#[tokio::test]
async fn check_assertion_replay_serial_replay_protection() {
let dao = crate::dao::tests::MockDao::new();
let future = Utc::now().timestamp() + 3600;
let future_str = chrono::DateTime::from_timestamp(future, 0)
.unwrap()
.to_rfc3339();
let first = check_assertion_replay("assertion-serial-001", &future_str, &dao)
.await
.expect("首次 check 不应报错");
assert!(first, "首次消费应通过");
let second = check_assertion_replay("assertion-serial-001", &future_str, &dao)
.await
.expect("二次 check 不应报错");
assert!(
!second,
"同一 Assertion ID 二次消费应被拒绝(vuln-0003 重放防护)"
);
}
}