pub fn is_subdomain_of(host: &str, suffix: &str) -> bool {
let Some(cut) = host.len().checked_sub(suffix.len()) else {
return false;
};
if !host.is_char_boundary(cut) {
return false;
}
let (label, tail) = host.split_at(cut);
tail.eq_ignore_ascii_case(suffix) && label.len() > 1 && label.ends_with('.')
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn subdomain_requires_a_real_label_and_a_dot_boundary() {
assert!(is_subdomain_of("api.example.com", "example.com"));
assert!(is_subdomain_of("a.b.example.com", "example.com"));
assert!(
!is_subdomain_of("example.com", "example.com"),
"the apex is not a subdomain of itself"
);
assert!(
!is_subdomain_of("evilexample.com", "example.com"),
"no dot boundary — this routed an attacker-chosen host to the named upstream"
);
assert!(
!is_subdomain_of("com", "example.com"),
"shorter than the suffix"
);
assert!(
is_subdomain_of("API.Example.COM", "example.com"),
"hostnames are case-insensitive (RFC 4343)"
);
}
#[test]
fn subdomain_does_not_panic_when_the_cut_lands_inside_a_multibyte_char() {
assert!(!is_subdomain_of("hé.com", "x.com"));
assert!(!is_subdomain_of("héllo.com", "llo.com"));
}
}