glacier-web 0.4.0

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
//! The hosts an app answers for: a request whose `Host` header names
//! another is refused with `403`, as Rails' `config.hosts` does. That stops
//! DNS rebinding, and a forged host reaching anything that trusts it.
//!
//! The list is `hosts` in the config, plus the host in `url`:
//!
//! ```toml
//! url = "https://example.com"
//! hosts = ["www.example.com", ".example.org"]   # .x: x and its subdomains
//! ```
//!
//! It's checked in production when either is set, and in other
//! environments only when `hosts` is, which then also allows `localhost`.
//! The health check is never refused, for load balancers asking by IP.

use crate::config::{Config, Env};
use crate::{Error, Result};

/// The hosts the app answers for.
#[derive(Clone, Debug, Default)]
pub struct Hosts {
    allowed: Vec<String>,
}

impl Hosts {
    /// Allows exactly these hosts; one starting with `.` (`.example.com`)
    /// also allows its subdomains.
    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(),
        }
    }

    /// The list from `hosts` and `url`, or `None` when nothing is checked.
    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)))
    }

    /// Whether `host` (`example.com:443` or `example.com`) is 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 {
    // `[::1]:4000` keeps its brackets; `example.com:443` loses its port.
    match host.rfind(':') {
        Some(at) if !host[at..].contains(']') => &host[..at],
        _ => host,
    }
}

/// The request's host: the `Host` header, or the authority of an HTTP/2
/// request's URI.
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"));
    }
}