const RESERVED: [&str; 5] = ["series", "fn", "takeover", "x", "catalog"];
pub(crate) const CODE: &str = "E_NAME_RESERVED";
pub(crate) fn check(host: &str, name: &str, signer_ns: Option<&str>) -> Result<(), String> {
check_for(host, name, signer_ns, false)
}
pub(crate) fn check_for(host: &str, name: &str, signer_ns: Option<&str>, job: bool) -> Result<(), String> {
let Some(rest) = name.strip_prefix(host).and_then(|r| r.strip_prefix('/')) else { return Ok(()) };
let first = rest.split('/').next().unwrap_or("");
if first == "catalog" && job {
return Ok(());
}
if RESERVED.contains(&first) {
return Err(format!("{CODE}: {name} is under {host}/{first}, a path the mesh reserves"));
}
if first == "key" {
let derived = signer_ns.is_some_and(|ns| name.strip_prefix(ns).is_some_and(|r| r.starts_with('/')));
let well_formed = rest.split('/').nth(1).is_some_and(is_key_segment);
let registered_other = signer_ns.is_some() && well_formed;
if !derived && !registered_other {
return Err(format!(
"{CODE}: {name} is under {host}/key, which takes only the names of the key it is derived from"
));
}
}
Ok(())
}
fn is_key_segment(seg: &str) -> bool {
seg.len() == 25
&& seg.starts_with('k')
&& seg[1..].bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
}
#[cfg(test)]
mod tests {
use super::*;
const H: &str = "mesh-test.datumesh.com";
#[test]
fn the_mesh_paths_are_reserved_and_their_look_alikes_are_not() {
for n in [
"series/a",
"fn/a",
"takeover/a",
"x/a",
"series/deep/er/a",
"catalog",
"catalog/a",
"catalog/subject/source",
] {
assert!(check(H, &format!("{H}/{n}"), None).is_err(), "{n}");
}
for n in [
"seriesx/a",
"series_a/b",
"fnord/a",
"h049/series/a",
"series_a",
"catalogue/a",
"catalog_x/a",
"h/catalog/a",
] {
assert!(check(H, &format!("{H}/{n}"), None).is_ok(), "{n}");
}
assert!(check(H, "other.example/series/a", None).is_ok());
}
#[test]
fn a_key_name_is_the_signers_own_only() {
let ns = format!("{H}/key/k0123456789abcdef01234567");
assert!(check(H, &format!("{ns}/f"), Some(&ns)).is_ok());
assert!(check(H, &format!("{ns}/f"), None).is_err());
assert!(check(H, &format!("{H}/key/foo"), Some(&ns)).is_err());
assert!(check(H, &format!("{H}/key/k0123456789abcdef01234567x/f"), Some(&ns)).is_err());
}
}