use std::collections::BTreeMap;
use url::Url;
use crate::config::IndexNowConfig;
#[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 {
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(),
}
}
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())
}
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
}
pub fn allows(&self, host: &str) -> bool {
self.allowed_hosts().contains(&normalize(host))
}
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"))
}
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}")
}
pub fn explicit_location(&self) -> Option<&str> {
self.key_location.as_deref()
}
pub fn app_host(&self) -> String {
Url::parse(&self.app_url)
.ok()
.and_then(|url| url.host_str().map(normalize))
.unwrap_or_default()
}
pub fn generate(length: usize) -> String {
laravel::str::random(length.clamp(8, 128)).to_lowercase()
}
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)));
}
}