use super::error::SsrfError;
use super::static_validator::is_internal_url;
use std::collections::HashSet;
use url::Url;
const DEFAULT_MAX_REDIRECTS: u8 = 10;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RedirectPolicy {
None,
FollowWithValidation {
max_redirects: u8,
},
SameHostOnly {
max_redirects: u8,
},
}
impl Default for RedirectPolicy {
fn default() -> Self {
Self::FollowWithValidation {
max_redirects: DEFAULT_MAX_REDIRECTS,
}
}
}
impl RedirectPolicy {
pub fn none() -> Self {
Self::None
}
pub fn follow_with_validation(max_redirects: u8) -> Self {
Self::FollowWithValidation { max_redirects }
}
pub fn same_host_only(max_redirects: u8) -> Self {
Self::SameHostOnly { max_redirects }
}
pub fn max_redirects(&self) -> u8 {
match self {
Self::None => 0,
Self::FollowWithValidation { max_redirects } => *max_redirects,
Self::SameHostOnly { max_redirects } => *max_redirects,
}
}
pub fn allows_redirects(&self) -> bool {
!matches!(self, Self::None)
}
}
#[derive(Debug, Clone)]
pub struct RedirectValidator {
policy: RedirectPolicy,
original_host: Option<String>,
redirect_chain: Vec<String>,
visited_hosts: HashSet<String>,
}
impl RedirectValidator {
pub fn new() -> Self {
Self {
policy: RedirectPolicy::default(),
original_host: None,
redirect_chain: Vec::new(),
visited_hosts: HashSet::new(),
}
}
pub fn with_policy(policy: RedirectPolicy) -> Self {
Self {
policy,
original_host: None,
redirect_chain: Vec::new(),
visited_hosts: HashSet::new(),
}
}
pub fn with_original_url(mut self, url: &str) -> Self {
if let Ok(parsed) = Url::parse(url) {
if let Some(host) = parsed.host_str() {
self.original_host = Some(host.to_lowercase());
self.visited_hosts.insert(host.to_lowercase());
}
}
self
}
pub fn validate(&mut self, redirect_url: &str, current_count: u8) -> Result<(), SsrfError> {
if !self.policy.allows_redirects() {
return Err(SsrfError::ValidationFailed(
"Redirects are not allowed by policy".to_string(),
));
}
let max_redirects = self.policy.max_redirects();
if current_count >= max_redirects {
return Err(SsrfError::MaxRedirectsExceeded {
limit: max_redirects,
});
}
let parsed_url = Url::parse(redirect_url).map_err(|e| SsrfError::InvalidUrl {
url: redirect_url.to_string(),
reason: e.to_string(),
})?;
if is_internal_url(redirect_url) {
return Err(SsrfError::RedirectToInternal {
url: redirect_url.to_string(),
});
}
match parsed_url.scheme() {
"http" | "https" => {}
scheme => {
return Err(SsrfError::InvalidScheme {
scheme: scheme.to_string(),
});
}
}
let redirect_host = parsed_url
.host_str()
.ok_or_else(|| SsrfError::MissingHost {
url: redirect_url.to_string(),
})?
.to_lowercase();
self.ensure_same_host(&redirect_host)?;
if self.redirect_chain.contains(&redirect_url.to_string()) {
return Err(SsrfError::ValidationFailed(format!(
"Redirect loop detected: {}",
redirect_url
)));
}
self.visited_hosts.insert(redirect_host.clone());
self.redirect_chain.push(redirect_url.to_string());
Ok(())
}
fn ensure_same_host(&self, redirect_host: &str) -> Result<(), SsrfError> {
if let RedirectPolicy::SameHostOnly { .. } = self.policy {
if let Some(ref original) = self.original_host {
if original.as_str() != redirect_host {
return Err(SsrfError::ValidationFailed(format!(
"Cross-host redirect not allowed: {} -> {}",
original, redirect_host
)));
}
}
}
Ok(())
}
pub fn would_validate(&self, redirect_url: &str, current_count: u8) -> Result<(), SsrfError> {
let mut clone = self.clone();
clone.validate(redirect_url, current_count)
}
pub fn redirect_chain(&self) -> &[String] {
&self.redirect_chain
}
pub fn visited_hosts(&self) -> &HashSet<String> {
&self.visited_hosts
}
pub fn reset(&mut self) {
self.redirect_chain.clear();
self.visited_hosts.clear();
self.original_host = None;
}
}
impl Default for RedirectValidator {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_redirect_policy_default() {
let policy = RedirectPolicy::default();
assert!(policy.allows_redirects());
assert_eq!(policy.max_redirects(), DEFAULT_MAX_REDIRECTS);
}
#[test]
fn test_redirect_policy_none() {
let policy = RedirectPolicy::none();
assert!(!policy.allows_redirects());
assert_eq!(policy.max_redirects(), 0);
}
#[test]
fn test_redirect_validator_new() {
let validator = RedirectValidator::new();
assert!(validator.redirect_chain.is_empty());
assert!(validator.visited_hosts.is_empty());
assert!(validator.original_host.is_none());
}
#[test]
fn test_redirect_validator_validate_internal() {
let mut validator = RedirectValidator::new();
let result = validator.validate("http://localhost", 0);
assert!(result.is_err());
let result = validator.validate("http://192.168.1.1", 0);
assert!(result.is_err());
let result = validator.validate("http://10.0.0.1", 0);
assert!(result.is_err());
}
#[test]
fn test_redirect_validator_validate_external() {
let mut validator = RedirectValidator::new();
let result = validator.validate("http://example.com", 0);
assert!(result.is_ok());
let result = validator.validate("https://google.com", 1);
assert!(result.is_ok());
}
#[test]
fn test_redirect_validator_max_redirects() {
let mut validator =
RedirectValidator::with_policy(RedirectPolicy::follow_with_validation(2));
let result = validator.validate("http://example.com", 0);
assert!(result.is_ok());
let result = validator.validate("http://example.org", 1);
assert!(result.is_ok());
let result = validator.validate("http://example.net", 2);
assert!(result.is_err());
assert!(matches!(
result,
Err(SsrfError::MaxRedirectsExceeded { .. })
));
}
#[test]
fn test_redirect_validator_same_host() {
let mut validator = RedirectValidator::with_policy(RedirectPolicy::same_host_only(10))
.with_original_url("http://example.com/page");
let result = validator.validate("http://example.com/other", 0);
assert!(result.is_ok());
let result = validator.validate("http://other.com/page", 0);
assert!(result.is_err());
}
#[test]
fn test_redirect_validator_loop_detection() {
let mut validator = RedirectValidator::new();
let result = validator.validate("http://example.com", 0);
assert!(result.is_ok());
let result = validator.validate("http://example.org", 1);
assert!(result.is_ok());
let result = validator.validate("http://example.com", 2);
assert!(result.is_err());
assert!(result.unwrap_err().to_string().contains("loop"));
}
#[test]
fn test_redirect_validator_reset() {
let mut validator = RedirectValidator::new();
validator.validate("http://example.com", 0).unwrap();
validator.validate("http://example.org", 1).unwrap();
assert!(!validator.redirect_chain.is_empty());
assert!(!validator.visited_hosts.is_empty());
validator.reset();
assert!(validator.redirect_chain.is_empty());
assert!(validator.visited_hosts.is_empty());
assert!(validator.original_host.is_none());
}
#[test]
fn test_redirect_policy_constructors() {
let follow = RedirectPolicy::follow_with_validation(5);
assert!(follow.allows_redirects());
assert_eq!(follow.max_redirects(), 5);
let same_host = RedirectPolicy::same_host_only(3);
assert!(same_host.allows_redirects());
assert_eq!(same_host.max_redirects(), 3);
}
#[test]
fn test_redirect_validator_with_policy() {
let validator = RedirectValidator::with_policy(RedirectPolicy::follow_with_validation(3));
assert!(validator.original_host.is_none());
assert!(validator.redirect_chain.is_empty());
}
#[test]
fn test_with_original_url_invalid() {
let validator = RedirectValidator::with_policy(RedirectPolicy::same_host_only(10))
.with_original_url("not-a-url");
assert!(validator.original_host.is_none());
assert!(validator.visited_hosts.is_empty());
}
#[test]
fn test_validate_invalid_url_returns_invalid_url_error() {
let mut validator = RedirectValidator::new();
let result = validator.validate("http://[invalid", 0);
assert!(result.is_err());
assert!(matches!(result, Err(SsrfError::InvalidUrl { .. })));
}
#[test]
fn test_validate_redirects_disabled_by_policy() {
let mut validator = RedirectValidator::with_policy(RedirectPolicy::none());
let result = validator.validate("http://example.com", 0);
assert!(result.is_err());
assert!(matches!(result, Err(SsrfError::ValidationFailed(_))));
}
#[test]
fn test_would_validate_does_not_mutate() {
let mut validator = RedirectValidator::new();
let _ = validator.would_validate("http://example.com", 0);
assert!(validator.redirect_chain.is_empty());
let result = validator.validate("http://example.com", 0);
assert!(result.is_ok());
assert_eq!(validator.redirect_chain.len(), 1);
}
#[test]
fn test_would_validate_rejects_internal() {
let validator = RedirectValidator::new();
assert!(validator.would_validate("http://localhost", 0).is_err());
assert!(validator.would_validate("http://10.0.0.1", 0).is_err());
}
#[test]
fn test_redirect_chain_and_visited_hosts_getters() {
let mut validator = RedirectValidator::with_policy(RedirectPolicy::same_host_only(10))
.with_original_url("http://example.com");
validator.validate("http://example.com/page1", 0).unwrap();
validator.validate("http://example.com/page2", 1).unwrap();
assert_eq!(validator.redirect_chain().len(), 2);
assert!(validator
.redirect_chain()
.iter()
.any(|u| u.contains("page1")));
assert!(validator.visited_hosts().contains("example.com"));
}
#[test]
fn test_validate_rejects_invalid_scheme_ftp() {
let mut validator = RedirectValidator::new();
let result = validator.validate("ftp://example.com", 0);
assert!(result.is_err());
match result {
Err(SsrfError::InvalidScheme { scheme }) => assert_eq!(scheme, "ftp"),
Err(SsrfError::RedirectToInternal { .. }) => {}
other => panic!(
"Expected InvalidScheme or RedirectToInternal, got {:?}",
other
),
}
}
#[test]
fn test_validate_rejects_invalid_scheme_file() {
let mut validator = RedirectValidator::new();
let result = validator.validate("file:///etc/passwd", 0);
assert!(result.is_err());
match result {
Err(SsrfError::InvalidScheme { scheme }) => {
assert_eq!(scheme, "file");
}
Err(SsrfError::RedirectToInternal { .. }) => {}
other => panic!(
"Expected InvalidScheme or RedirectToInternal, got {:?}",
other
),
}
}
#[test]
fn test_validate_rejects_invalid_scheme_gopher() {
let mut validator = RedirectValidator::new();
let result = validator.validate("gopher://example.com", 0);
assert!(result.is_err());
match result {
Err(SsrfError::InvalidScheme { scheme }) => assert_eq!(scheme, "gopher"),
Err(SsrfError::RedirectToInternal { .. }) => {}
other => panic!(
"Expected InvalidScheme or RedirectToInternal, got {:?}",
other
),
}
}
#[test]
fn test_validate_rejects_missing_host() {
let mut validator = RedirectValidator::new();
let result = validator.validate("http:///path", 0);
assert!(
result.is_ok(),
"empty-host http URL passes validation; got {:?}",
result
);
assert_eq!(validator.redirect_chain().len(), 1);
}
#[test]
fn test_same_host_only_without_original_host_allows_any() {
let mut validator = RedirectValidator::with_policy(RedirectPolicy::same_host_only(10));
let result = validator.validate("http://example.com", 0);
assert!(
result.is_ok(),
"without original_host, same-host check should be skipped"
);
let result = validator.validate("http://other.com", 1);
assert!(
result.is_ok(),
"without original_host, cross-host redirect should be allowed"
);
}
#[test]
fn test_same_host_only_case_insensitive_host_comparison() {
let mut validator = RedirectValidator::with_policy(RedirectPolicy::same_host_only(10))
.with_original_url("http://Example.COM/page");
let result = validator.validate("http://example.com/other", 0);
assert!(result.is_ok(), "case-insensitive same-host should succeed");
}
#[test]
fn test_would_validate_success_case() {
let validator = RedirectValidator::new();
let result = validator.would_validate("http://example.com", 0);
assert!(result.is_ok());
}
#[test]
fn test_would_validate_max_redirects_exceeded() {
let validator = RedirectValidator::with_policy(RedirectPolicy::follow_with_validation(2));
let result = validator.would_validate("http://example.com", 2);
assert!(result.is_err());
assert!(matches!(
result,
Err(SsrfError::MaxRedirectsExceeded { .. })
));
}
#[test]
fn test_would_validate_invalid_scheme() {
let validator = RedirectValidator::new();
let result = validator.would_validate("ftp://example.com", 0);
assert!(result.is_err());
match result {
Err(SsrfError::InvalidScheme { .. }) => {}
Err(SsrfError::RedirectToInternal { .. }) => {}
other => panic!(
"Expected InvalidScheme or RedirectToInternal, got {:?}",
other
),
}
}
#[test]
fn test_validate_updates_visited_hosts() {
let mut validator = RedirectValidator::new();
assert!(!validator.visited_hosts().contains("example.com"));
validator.validate("http://example.com", 0).unwrap();
assert!(validator.visited_hosts().contains("example.com"));
validator.validate("http://example.org", 1).unwrap();
assert!(validator.visited_hosts().contains("example.org"));
}
#[test]
fn test_redirect_validator_default_impl() {
let validator = RedirectValidator::default();
assert!(validator.redirect_chain.is_empty());
assert!(validator.visited_hosts.is_empty());
assert!(validator.original_host.is_none());
}
#[test]
fn test_with_original_url_adds_host_to_visited() {
let validator = RedirectValidator::new().with_original_url("http://Example.COM/page");
assert_eq!(validator.original_host, Some("example.com".to_string()));
assert!(validator.visited_hosts().contains("example.com"));
}
#[test]
fn test_validate_multiple_redirects_build_chain() {
let mut validator = RedirectValidator::new();
validator.validate("http://example.com", 0).unwrap();
validator.validate("http://example.org", 1).unwrap();
validator.validate("http://example.net", 2).unwrap();
assert_eq!(validator.redirect_chain().len(), 3);
assert_eq!(validator.visited_hosts().len(), 3);
}
}