use super::FirewallContext;
use crate::error::{GarrisonError, GarrisonResult};
impl FirewallContext {
pub fn new(ip: impl Into<String>) -> Self {
let ip = ip.into();
debug_assert!(
ip.parse::<std::net::IpAddr>().is_ok(),
"FirewallContext::new received malformed IP: {:?} (use try_new to validate)",
ip
);
Self {
ip,
login_id: None,
tenant_id: None,
}
}
pub fn try_new(ip: impl Into<String>) -> GarrisonResult<Self> {
let ip = ip.into();
if let Err(e) = ip.parse::<std::net::IpAddr>() {
return Err(GarrisonError::InvalidParam(format!(
"firewall-context-invalid-ip::{}::{}",
ip, e
)));
}
Ok(Self {
ip,
login_id: None,
tenant_id: None,
})
}
pub fn with_login_id(mut self, login_id: impl Into<String>) -> Self {
self.login_id = Some(login_id.into());
self
}
pub fn with_tenant_id(mut self, tenant_id: i64) -> Self {
self.tenant_id = Some(tenant_id);
self
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn try_new_accepts_valid_ips() {
assert!(FirewallContext::try_new("192.168.1.1").is_ok());
assert!(FirewallContext::try_new("::1").is_ok());
assert!(FirewallContext::try_new("2001:db8::1").is_ok());
}
#[test]
fn try_new_rejects_malformed_ips() {
assert!(FirewallContext::try_new("").is_err());
assert!(FirewallContext::try_new("not-an-ip").is_err());
assert!(FirewallContext::try_new("[::1]").is_err());
assert!(FirewallContext::try_new("0.0.0.0/0").is_err());
let err = FirewallContext::try_new("%31%2e%31").unwrap_err();
assert!(
matches!(&err, GarrisonError::InvalidParam(msg) if msg.contains("invalid-ip")),
"畸形 IP 应返回 InvalidParam,实际: {:?}",
err
);
}
#[test]
fn try_new_matches_new_for_valid_ip() {
let a = FirewallContext::try_new("10.0.0.1").unwrap();
let b = FirewallContext::new("10.0.0.1");
assert_eq!(a.ip, b.ip);
assert_eq!(a.login_id, b.login_id);
assert_eq!(a.tenant_id, b.tenant_id);
let c = FirewallContext::try_new("10.0.0.2")
.unwrap()
.with_login_id("1001")
.with_tenant_id(7);
assert_eq!(c.ip, "10.0.0.2");
assert_eq!(c.login_id.as_deref(), Some("1001"));
assert_eq!(c.tenant_id, Some(7));
}
}