use crate::config::{Config, Env};
use crate::{Error, Result};
#[derive(Clone, Debug, Default)]
pub struct Hosts {
allowed: Vec<String>,
}
impl Hosts {
pub fn new<I, S>(hosts: I) -> Self
where
I: IntoIterator<Item = S>,
S: AsRef<str>,
{
Self {
allowed: hosts
.into_iter()
.map(|h| h.as_ref().trim().to_ascii_lowercase())
.filter(|h| !h.is_empty())
.collect(),
}
}
pub(crate) fn from_config(config: &Config) -> Result<Option<Self>> {
let listed: Option<Vec<String>> = config.get_opt("hosts")?;
let production = config.env() == Env::Production;
let url: Option<String> = config.get_opt("url")?;
if listed.is_none() && !(production && url.is_some()) {
return Ok(None);
}
let mut allowed = listed.unwrap_or_default();
if let Some(url) = url {
let uri: http::Uri = url
.parse()
.map_err(|e| Error::internal(format!("config: `url` {url:?}: {e}")))?;
allowed.extend(uri.host().map(str::to_owned));
}
if !production {
allowed.extend(["localhost", "127.0.0.1", "[::1]"].map(str::to_owned));
}
Ok(Some(Self::new(allowed)))
}
pub fn allows(&self, host: &str) -> bool {
let host = without_port(host).to_ascii_lowercase();
let host = host.trim_end_matches('.');
self.allowed
.iter()
.any(|allowed| match allowed.strip_prefix('.') {
Some(domain) => {
host == domain
|| host
.strip_suffix(domain)
.is_some_and(|sub| sub.ends_with('.'))
}
None => host == allowed,
})
}
}
fn without_port(host: &str) -> &str {
match host.rfind(':') {
Some(at) if !host[at..].contains(']') => &host[..at],
_ => host,
}
}
pub(crate) fn of(parts: &http::request::Parts) -> Option<&str> {
parts
.headers
.get(http::header::HOST)
.and_then(|v| v.to_str().ok())
.or_else(|| parts.uri.authority().map(|a| a.as_str()))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn matches_hosts_and_subdomains() {
let hosts = Hosts::new(["example.com", ".example.org", "[::1]"]);
assert!(hosts.allows("example.com"));
assert!(hosts.allows("EXAMPLE.com:443"));
assert!(hosts.allows("example.com."));
assert!(!hosts.allows("www.example.com"));
assert!(!hosts.allows("evil.com"));
assert!(!hosts.allows("example.com.evil.com"));
assert!(hosts.allows("example.org"));
assert!(hosts.allows("a.b.example.org"));
assert!(!hosts.allows("notexample.org"));
assert!(hosts.allows("[::1]:4000"));
}
}