laraindexnow 0.1.2

IndexNow for Laravel Rust: tell Bing, Yandex and other search engines a URL changed, the moment it changes.
Documentation
use std::collections::BTreeMap;

use url::Url;

use crate::config::IndexNowConfig;

/// Knows which key belongs to which host, and where each key file has to be readable.
#[derive(Debug, Clone, Default)]
pub struct KeyRepository {
    keys: BTreeMap<String, String>,
    fallback: Option<String>,
    key_location: Option<String>,
    hosts: Vec<String>,
    app_url: String,
}

impl KeyRepository {
    /// Build the repository from the configuration and the application's `APP_URL`.
    pub fn from_config(config: &IndexNowConfig, app_url: &str) -> Self {
        Self {
            keys: config.keys.clone(),
            fallback: config.key.clone().filter(|key| !key.is_empty()),
            key_location: config.key_location.clone().filter(|location| !location.is_empty()),
            hosts: config.hosts.clone(),
            app_url: app_url.to_owned(),
        }
    }

    /// The key for a host: its own, or the single `key` as the fallback.
    pub fn for_host(&self, host: &str) -> Option<String> {
        let host = normalize(host);

        self.keys
            .iter()
            .find(|(configured, _)| normalize(configured) == host)
            .map(|(_, key)| key.clone())
            .or_else(|| self.fallback.clone())
    }

    /// The hosts URLs may belong to: `hosts`, else the hosts of `keys`, else the application's.
    pub fn allowed_hosts(&self) -> Vec<String> {
        let hosts: Vec<String> = if !self.hosts.is_empty() {
            self.hosts.clone()
        } else if !self.keys.is_empty() {
            self.keys.keys().cloned().collect()
        } else {
            vec![self.app_host()]
        };

        let mut allowed: Vec<String> = Vec::new();

        for host in hosts {
            let host = normalize(&host);

            if !host.is_empty() && !allowed.contains(&host) {
                allowed.push(host);
            }
        }

        allowed
    }

    /// Whether URLs of this host may be submitted.
    pub fn allows(&self, host: &str) -> bool {
        self.allowed_hosts().contains(&normalize(host))
    }

    /// Where a host's key file has to be readable. `scheme` forces one, otherwise the
    /// application's own scheme and port are used for its host and `https` for the others.
    pub fn location_for(&self, host: &str, scheme: Option<&str>) -> Option<String> {
        let key = self.for_host(host)?;

        if let Some(location) = &self.key_location {
            return Some(location.clone());
        }

        let base = match scheme {
            Some(scheme) => format!("{scheme}://{}", normalize(host)),
            None => self.base_url_for(host),
        };

        Some(format!("{base}/{key}.txt"))
    }

    /// The address a host is reached at. For the application's own host that is the scheme and
    /// port of `APP_URL`, so a local `http://localhost:8000` is not reported as `https`.
    pub fn base_url_for(&self, host: &str) -> String {
        let host = normalize(host);

        if !host.is_empty()
            && host == self.app_host()
            && let Ok(url) = Url::parse(&self.app_url)
        {
            let port = url.port().map(|port| format!(":{port}")).unwrap_or_default();

            return format!("{}://{host}{port}", url.scheme());
        }

        format!("https://{host}")
    }

    /// The configured `key_location`, when one is set.
    pub fn explicit_location(&self) -> Option<&str> {
        self.key_location.as_deref()
    }

    /// The host of `APP_URL`.
    pub fn app_host(&self) -> String {
        Url::parse(&self.app_url)
            .ok()
            .and_then(|url| url.host_str().map(normalize))
            .unwrap_or_default()
    }

    /// Generate a key of `length` characters, clamped to the protocol's 8 to 128.
    pub fn generate(length: usize) -> String {
        laravel::str::random(length.clamp(8, 128)).to_lowercase()
    }

    /// Whether a key is 8 to 128 letters, numbers and dashes.
    pub fn is_valid(key: &str) -> bool {
        (8..=128).contains(&key.len()) && key.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')
    }
}

fn normalize(host: &str) -> String {
    host.trim().to_lowercase()
}

#[cfg(test)]
mod tests {
    use super::*;

    fn repository(configure: impl FnOnce(&mut IndexNowConfig)) -> KeyRepository {
        let mut config = IndexNowConfig::default();
        configure(&mut config);

        KeyRepository::from_config(&config, "http://example.com:8000")
    }

    #[test]
    fn a_host_falls_back_to_the_single_key() {
        let keys = repository(|config| config.key = Some("abcdefgh".into()));

        assert_eq!(keys.for_host("Anything.test"), Some("abcdefgh".into()));
    }

    #[test]
    fn a_host_prefers_its_own_key() {
        let keys = repository(|config| {
            config.key = Some("abcdefgh".into());
            config.keys.insert("example.org".into(), "orgorgorg".into());
        });

        assert_eq!(keys.for_host("EXAMPLE.org"), Some("orgorgorg".into()));
        assert_eq!(keys.for_host("example.com"), Some("abcdefgh".into()));
    }

    #[test]
    fn hosts_are_derived_from_the_keys_or_the_application() {
        assert_eq!(repository(|_| {}).allowed_hosts(), vec!["example.com"]);

        let keys = repository(|config| {
            config.keys.insert("a.test".into(), "aaaaaaaa".into());
            config.keys.insert("b.test".into(), "bbbbbbbb".into());
        });

        assert_eq!(keys.allowed_hosts(), vec!["a.test", "b.test"]);
        assert!(keys.allows("A.test"));
        assert!(!keys.allows("example.com"));
    }

    #[test]
    fn the_application_host_keeps_its_scheme_and_port() {
        let keys = repository(|config| config.key = Some("abcdefgh".into()));

        assert_eq!(keys.base_url_for("example.com"), "http://example.com:8000");
        assert_eq!(keys.base_url_for("other.test"), "https://other.test");
        assert_eq!(
            keys.location_for("example.com", None),
            Some("http://example.com:8000/abcdefgh.txt".into())
        );
    }

    #[test]
    fn a_key_is_8_to_128_letters_numbers_and_dashes() {
        assert!(KeyRepository::is_valid("abcdefgh"));
        assert!(KeyRepository::is_valid("ab-cd-ef-gh"));
        assert!(!KeyRepository::is_valid("short"));
        assert!(!KeyRepository::is_valid("not valid key"));
        assert!(KeyRepository::is_valid(&KeyRepository::generate(32)));
    }
}