//! The krebs registry on a federation (`docs/federation.md`, The registry on it): kartei's //! files ([krebs/kartei](https://github.com/krebs/kartei)), a namespace each, in its //! party's namespace, a place each file; what kartei's consumers read as one for all, at //! places of its own (`name`, `address`, `asks`); the rules for krebs, made from kartei //! (`rules`); kartei's files read and written (`read`, `write`); the writes signing them //! in (`writes`); and what kartei's consumers read, written out from what counts (`out`). use std::collections::{BTreeMap, BTreeSet}; use std::net::{Ipv4Addr, Ipv6Addr}; use std::path::Path; use super::jcs::Json; use super::version::{self, Version}; /// Files by their paths, `/` between segments, and their text. pub(crate) type Files = BTreeMap; /// The rules each party has by its name: its namespace, its names in `.r` and `.w` and /// those under them, and its user. pub(crate) const BY_NAME: &[&str] = &[ "home/{party}/**", "names/r/{party}", "names/r/{party}/**", "names/w/{party}", "names/w/{party}/**", "users/{party}", ]; /// The place of a name, at its labels, last first: `names/r/tv/cgit` for `cgit.tv.r`. pub(crate) fn name(name: &str) -> Option { let labels: Vec<&str> = name.split('.').rev().collect(); if labels .iter() .any(|label| label.is_empty() || label.contains('/')) { return None; } Some(format!("names/{}", labels.join("/"))) } /// The place of an address or a block, by its parts: `ip4/10/243/7/3`, `ip6/42/1/a46e` for /// `42:1:a46e::/48`. A block spells one only on the bounds of its parts, with no bits set /// beyond its length; a tinc subnet's weight (`#10`) changes nothing. pub(crate) fn address(text: &str) -> Option { let text = match text.split_once('#') { Some((text, weight)) if !weight.is_empty() && weight.bytes().all(|byte| byte.is_ascii_digit()) => { text } Some(_) => return None, None => text, }; let (address, length) = match text.split_once('/') { Some((address, length)) => (address, Some(length.parse::().ok()?)), None => (text, None), }; let (kind, parts, bits) = if let Ok(ip) = address.parse::() { let parts: Vec = ip.octets().iter().map(u8::to_string).collect(); ("ip4", parts, 8) } else if let Ok(ip) = address.parse::() { let parts: Vec = ip .segments() .iter() .map(|part| format!("{part:x}")) .collect(); ("ip6", parts, 16) } else { return None; }; let length = length.unwrap_or(parts.len() * bits); if length == 0 || length > parts.len() * bits || length % bits != 0 { return None; } let (kept, beyond) = parts.split_at(length / bits); if beyond.iter().any(|part| part != "0") { return None; } Some(format!("{kind}/{}", kept.join("/"))) } /// What a line of a file asks of its party. #[derive(Debug, PartialEq, Eq)] pub(crate) enum Line<'a> { /// Nothing. Free(&'a str), /// That it holds the place of the line's name, address or block. Holds(&'a str, String), /// A name, an address or a block that spells no place. Unspelled, } /// What a file of a namespace asks of its party: the places it must hold for the file to /// be read at all, and, for a file of names, addresses or blocks, what each line asks. #[derive(Debug, PartialEq, Eq)] pub(crate) struct Asks<'a> { pub(crate) places: Vec, pub(crate) lines: Option>>, } impl Asks<'_> { /// Every place it asks for, its own and its lines'. fn every(&self) -> impl Iterator { let lines = self.lines.iter().flatten().filter_map(|line| match line { Line::Holds(_, place) => Some(place.as_str()), _ => None, }); self.places.iter().map(String::as_str).chain(lines) } } /// What the file at `path` of a namespace, holding `text`, asks of its party. A host /// (`hosts/{host}/…`) asks for its name in `.r`, and in `.i` where it is in the net /// `internet`; a user (`users/{user}/…`) for its name; a net's `aliases` for each name /// a line holds; in each net but `internet`, its addresses, blocks and subnets for each a /// line holds, and its `tinc.extra` for each `Subnet` a line sets. Any other file asks /// nothing. pub(crate) fn asks<'a>(path: &str, text: &'a str) -> Asks<'a> { let segments: Vec<&str> = path.split('/').collect(); match segments.as_slice() { ["hosts", host, rest @ ..] => { let mut places = vec![format!("names/r/{host}")]; if rest.first() == Some(&"internet") { places.push(format!("names/i/{host}")); } let lines = match rest { [_, "aliases"] => Some(each(text, name)), ["internet", _] => None, [ _, "ip4" | "ip6" | "addrs" | "tinc.subnets" | "wireguard.subnets", ] => Some(each(text, address)), [_, "tinc.extra"] => Some( text.lines() .map(|line| match subnet(line) { Some(value) => spelled(line, address(value)), None => Line::Free(line), }) .collect(), ), _ => None, }; Asks { places, lines } } ["users", user, ..] => Asks { places: vec![format!("users/{user}")], lines: None, }, _ => Asks { places: Vec::new(), lines: None, }, } } /// Each line of `text`, but blank ones, asking for the place `spell` gives what it holds. fn each(text: &str, spell: impl Fn(&str) -> Option) -> Vec> { text.lines() .map(|line| match line.trim() { "" => Line::Free(line), held => spelled(line, spell(held)), }) .collect() } fn spelled(line: &str, place: Option) -> Line<'_> { match place { Some(place) => Line::Holds(line, place), None => Line::Unspelled, } } /// The value a line of tinc's configuration sets `Subnet` to, where it sets it: its name /// in any case, then spaces or `=`. fn subnet(line: &str) -> Option<&str> { let line = line.trim_start(); let end = line .find(|c: char| c.is_whitespace() || c == '=') .unwrap_or(line.len()); let (name, value) = line.split_at(end); name.eq_ignore_ascii_case("subnet") .then(|| value.trim_start().trim_start_matches('=').trim()) } /// The rules for krebs, made from kartei. #[derive(Debug, PartialEq, Eq)] pub(crate) struct Krebs { /// Each place kartei gives a party that neither the version's own rules nor those by /// name give, with the party: a rule each. pub(crate) given: Vec<(String, String)>, /// Each place kartei gives a party that the rules don't give it: asked for by two /// parties, given to another, or spelling no rule; with who asks, and who writes /// there. pub(crate) not_given: Vec, } /// The rules for krebs, made from kartei's files `kartei` (`{namespace}/…`, from its /// checkout) for the version `version`: a namespace named as a party of it is that /// party's, any other `group`'s. Each place a namespace's files ask for that neither the /// version's own rules nor those by name give is given to its party by a rule of its own, /// unless another party asks for it too. pub(crate) fn rules( kartei: &Files, version: &Version, group: Option<&str>, ) -> Result { if let Some(group) = group.filter(|group| !version.parties.contains_key(*group)) { return Err(format!("{group} is no party of the version")); } let by_name = Version::read(&with_rules(version, &[]))?; let mut asked: BTreeMap> = BTreeMap::new(); let mut of_nobody = BTreeSet::new(); for (path, text) in kartei { let Some((namespace, path)) = path.split_once('/') else { continue; }; // kartei reads no namespace of its template. if namespace == "template" { continue; } let file = asks(path, text); if file.every().next().is_none() { continue; } let party = match (version.parties.get_key_value(namespace), group) { (Some((party, _)), _) => party.as_str(), (None, Some(group)) => group, (None, None) => { of_nobody.insert(namespace); continue; } }; for place in file.every() { asked.entry(place.to_owned()).or_default().insert(party); } } if !of_nobody.is_empty() { let namespaces: Vec<&str> = of_nobody.into_iter().collect(); return Err(format!( "namespaces of no party, and no group: {}", namespaces.join(", ") )); } let mut krebs = Krebs { given: Vec::new(), not_given: Vec::new(), }; for (place, parties) in asked { let segments = version::path(&place).filter(|segments| { segments .iter() .all(|segment| !matches!(segment.as_str(), "{party}" | "*" | "**")) }); let writer = segments .as_ref() .and_then(|segments| by_name.writer(segments)); let asking: Vec<&str> = parties.iter().copied().collect(); match (asking.as_slice(), writer, &segments) { ([party], Some(writer), _) if *party == writer => {} ([party], None, Some(_)) => krebs.given.push((place, (*party).to_owned())), _ => krebs.not_given.push(format!( "{place}: asked for by {}; {} writes there", asking.join(", "), writer.unwrap_or("nobody") )), } } Ok(krebs) } /// The version `version` with its own rules, then the rules `given`, each a place and the /// party writing there, then those by name. pub(crate) fn with_rules(version: &Version, given: &[(String, String)]) -> Json { let rule = |path: &str, writer: &str| { Json::object(vec![ ("path".to_owned(), Json::Str(path.to_owned())), ("writer".to_owned(), Json::Str(writer.to_owned())), ]) .expect("names once each") }; let own = version .json .get("rules") .and_then(Json::as_array) .unwrap_or_default(); let rules: Vec = own .iter() .cloned() .chain( given .iter() .map(|(path, party)| rule(path.as_str(), party.as_str())), ) .chain(BY_NAME.iter().map(|path| rule(*path, "{party}"))) .collect(); match &version.json { Json::Object(members) => Json::Object( members .iter() .map(|(name, value)| match name.as_str() { "rules" => (name.clone(), Json::Array(rules.clone())), _ => (name.clone(), value.clone()), }) .collect(), ), other => other.clone(), } } /// The files under `dir`, by their paths below it, as kartei's are read: what begins with /// `.` left out, a link read as the file it names, each file text (UTF-8). pub(crate) fn read(dir: &Path) -> Result { let mut files = Files::new(); let mut dirs = vec![(dir.to_path_buf(), String::new())]; while let Some((dir, at)) = dirs.pop() { let entries = std::fs::read_dir(&dir).map_err(|why| format!("{}: {why}", dir.display()))?; for entry in entries { let entry = entry.map_err(|why| format!("{}: {why}", dir.display()))?; let path = entry.path(); let Some(name) = entry.file_name().to_str().map(str::to_owned) else { return Err(format!("{}: a name that isn't UTF-8", path.display())); }; if name.starts_with('.') { continue; } let below = if at.is_empty() { name } else { format!("{at}/{name}") }; let kind = entry .file_type() .map_err(|why| format!("{}: {why}", path.display()))?; if kind.is_dir() { dirs.push((path, below)); } else { let text = std::fs::read_to_string(&path) .map_err(|why| format!("{}: {why}", path.display()))?; files.insert(below, text); } } } Ok(files) } /// Writes `files` under `dir`, which it makes: nothing may be there yet. Each path is a /// path below it: no segment empty, nor beginning with `.`. pub(crate) fn write(dir: &Path, files: &Files) -> Result<(), String> { if let Some(path) = files.keys().find(|path| { path.split('/') .any(|segment| segment.is_empty() || segment.starts_with('.')) }) { return Err(format!("{path:?} is no path below a directory")); } std::fs::create_dir(dir).map_err(|why| format!("{}: {why}", dir.display()))?; for (path, text) in files { let file = dir.join(path); if let Some(parent) = file.parent() { std::fs::create_dir_all(parent) .map_err(|why| format!("{}: {why}", parent.display()))?; } std::fs::write(&file, text).map_err(|why| format!("{}: {why}", file.display()))?; } Ok(()) } /// The writes making `party`'s namespace hold `files`, the files of its kartei namespaces, /// where `values` are what counts: each file at its place, where that doesn't hold the /// file's text, and `null` at each place of the namespace that no file is at. pub(crate) fn writes( party: &str, files: &Files, values: &BTreeMap, ) -> Vec<(String, Json)> { let home = format!("home/{party}/"); let mut writes: Vec<(String, Json)> = files .iter() .map(|(path, text)| (format!("{home}{path}"), Json::Str(text.clone()))) .filter(|(place, text)| values.get(place.as_str()) != Some(text)) .collect(); writes.extend( values .keys() .filter(|place| { place .strip_prefix(home.as_str()) .is_some_and(|path| !files.contains_key(path)) }) .map(|place| (place.clone(), Json::Null)), ); writes } /// What kartei's consumers read, written out from what counts, `values`, under the /// current version `version`: each party's namespace as its files (`{party}/…`), the text /// each place of it holds, but for what asks for a place the version doesn't give the /// party: a file whose own places it doesn't hold left out, and each line whose place it /// doesn't; a file left with blank lines alone left out too. What isn't text, what is at /// a path with a segment beginning with `.`, and what is at the way to another file is no /// file. pub(crate) fn out(version: &Version, values: &BTreeMap) -> Files { let mut files = Files::new(); for (place, value) in values { let Some((party, path)) = place .strip_prefix("home/") .and_then(|rest| rest.split_once('/')) else { continue; }; let Some(text) = value.as_str() else { continue; }; if std::iter::once(party) .chain(path.split('/')) .any(|segment| segment.starts_with('.')) { continue; } let holds = |place: &str| { version::path(place).is_some_and(|segments| version.writer(&segments) == Some(party)) }; if !holds(place.as_str()) { continue; } if let Some(text) = kept(&asks(path, text), text, &holds) { files.insert(format!("{party}/{path}"), text); } } let ways: BTreeSet = files .keys() .flat_map(|path| { path.match_indices('/') .map(move |(at, _)| path[..at].to_owned()) }) .collect(); files.retain(|path, _| !ways.contains(path)); files } /// What is written out of a file holding `text`, which asks `asks`, where `holds` says /// which places its party holds: nothing where it doesn't hold the file's own places, or /// where no line but blank ones is left; else its lines but those whose place it doesn't /// hold, the text as it is where that is none. fn kept(asks: &Asks<'_>, text: &str, holds: &impl Fn(&str) -> bool) -> Option { if !asks.places.iter().all(|place| holds(place.as_str())) { return None; } let Some(lines) = &asks.lines else { return Some(text.to_owned()); }; let kept: Vec<&str> = lines .iter() .filter_map(|line| match line { Line::Free(line) => Some(*line), Line::Holds(line, place) if holds(place.as_str()) => Some(*line), Line::Holds(..) | Line::Unspelled => None, }) .collect(); if kept.iter().all(|line| line.trim().is_empty()) { return None; } if kept.len() == lines.len() { return Some(text.to_owned()); } Some(kept.iter().map(|line| format!("{line}\n")).collect()) } #[cfg(test)] mod tests { use super::*; use crate::federation::fold::Federation; use crate::federation::harness::{self, Party, Spec}; use crate::federation::store::Id; use crate::federation::store::memory::{Offered, Store}; fn files(entries: &[(&str, &str)]) -> Files { entries .iter() .map(|(path, text)| ((*path).to_owned(), (*text).to_owned())) .collect() } /// A kartei of three namespaces, tv's and lass's, who are parties, and berber's, who /// isn't, and the files of kartei's own. fn kartei() -> Files { files(&[ ("tv/hosts/ne/retiolum/aliases", "ne.r\ncgit.ne.r\nne.tv.r\n"), ("tv/hosts/ne/retiolum/ip4", "10.243.0.5\n"), ("tv/hosts/ne/retiolum/ip6", "42:0:a46e::1\n"), ("tv/hosts/ne/retiolum/ed25519.key", "AAAA\n"), ( "tv/hosts/ne/wiregrill/wireguard.subnets", "42:1:a46e::/48\n", ), ("tv/hosts/ne/internet/aliases", "ne.i\n"), ("tv/hosts/ne/internet/ip4", "203.0.113.5\n"), ("tv/users/tv/mail", "tv@example.org\n"), ("tv/users/vv/mail", "vv@example.org\n"), ("tv/ssh/tv.pub", "ssh-ed25519 AAAA tv\n"), ("lass/hosts/yellow/retiolum/aliases", "yellow.r\nwiki.r\n"), ("lass/hosts/yellow/retiolum/ip4", "10.243.0.6\n"), ( "lass/hosts/yellow/retiolum/tinc.extra", "Subnet = 10.243.6.0/24\nSPTPSCipher = aes-256-gcm\n", ), ( "berber/hosts/schlepptop/retiolum/aliases", "schlepptop.berber.r\n", ), ("berber/users/berber/mail", "berber@example.org\n"), ("template/hosts/DUMMYHOST/retiolum/aliases", "DUMMYHOST.r\n"), ("lib/default.nix", "{ }\n"), ]) } /// tv and lass, and krebs, the group holding the others' namespaces: the first /// version, with no rules of its own. fn parties() -> (Party, Party, Party, Spec) { let (tv, lass, krebs) = ( Party::new("tv", 1), Party::new("lass", 2), Party::new("krebs", 3), ); let mut first = Spec::first(&[&tv, &lass, &krebs], &[]); first.rules.clear(); (tv, lass, krebs, first) } fn version(spec: &Spec) -> Version { Version::read(&spec.json()).expect("a version") } fn given(given: &[(&str, &str)]) -> Vec<(String, String)> { given .iter() .map(|(place, party)| ((*place).to_owned(), (*party).to_owned())) .collect() } #[test] fn names_and_addresses_are_spelled_by_their_parts() { assert_eq!(name("cgit.tv.r").as_deref(), Some("names/r/tv/cgit")); assert_eq!(name("tv.r").as_deref(), Some("names/r/tv")); assert_eq!(name("a..r"), None); assert_eq!(name("a/b.r"), None); assert_eq!(address("10.243.7.3").as_deref(), Some("ip4/10/243/7/3")); assert_eq!( address("10.244.245.0/24").as_deref(), Some("ip4/10/244/245") ); assert_eq!(address("10.243.0.1#10").as_deref(), Some("ip4/10/243/0/1")); assert_eq!( address("42:0:a46e::1").as_deref(), Some("ip6/42/0/a46e/0/0/0/0/1") ); assert_eq!(address("42:1:a46e::/48").as_deref(), Some("ip6/42/1/a46e")); assert_eq!( address("42:0000:002b:1605:3::/80").as_deref(), Some("ip6/42/0/2b/1605/3") ); // Off the bounds of its parts, bits set beyond its length, or no address. assert_eq!(address("10.243.0.0/20"), None); assert_eq!(address("10.244.245.1/24"), None); assert_eq!(address("10.243.0.1#x"), None); assert_eq!(address("bernie.thalheim.io"), None); } #[test] fn a_file_asks_for_the_names_and_addresses_it_holds() { let asks_for = |path: &str, text: &str| -> Vec { asks(path, text).every().map(str::to_owned).collect() }; assert_eq!( asks_for("hosts/ne/retiolum/aliases", "ne.r\n\ncgit.ne.r\n"), ["names/r/ne", "names/r/ne", "names/r/ne/cgit"] ); assert_eq!( asks_for("hosts/ne/internet/ip4", "203.0.113.5\n"), ["names/r/ne", "names/i/ne"] ); assert_eq!( asks_for( "hosts/ne/retiolum/tinc.extra", "subnet=10.243.6.0/24\nPort = 655\n" ), ["names/r/ne", "ip4/10/243/6"] ); assert_eq!(asks_for("users/vv/mail", "vv@example.org\n"), ["users/vv"]); assert!(asks_for("ssh/tv.pub", "ssh-ed25519 AAAA tv\n").is_empty()); assert_eq!( asks("hosts/ne/retiolum/ip4", "10.243.0.0/20\n").lines, Some(vec![Line::Unspelled]) ); } #[test] fn krebs_rules_give_each_party_what_kartei_gives_it() { let (_, _, _, first) = parties(); let krebs = rules(&kartei(), &version(&first), Some("krebs")).expect("rules"); assert_eq!( krebs, Krebs { given: given(&[ ("ip4/10/243/0/5", "tv"), ("ip4/10/243/0/6", "lass"), ("ip4/10/243/6", "lass"), ("ip6/42/0/a46e/0/0/0/0/1", "tv"), ("ip6/42/1/a46e", "tv"), ("names/i/ne", "tv"), ("names/r/berber/schlepptop", "krebs"), ("names/r/ne", "tv"), ("names/r/ne/cgit", "tv"), ("names/r/schlepptop", "krebs"), ("names/r/wiki", "lass"), ("names/r/yellow", "lass"), ("users/berber", "krebs"), ("users/vv", "tv"), ]), not_given: Vec::new(), } ); // The version with them: its own rules, those given, those by name. let with = Version::read(&with_rules(&version(&first), &krebs.given)).expect("one"); let writer = |place: &str| with.writer(&version::path(place).expect("a path")); assert_eq!(writer("names/r/tv/ne"), Some("tv")); assert_eq!(writer("names/r/schlepptop"), Some("krebs")); assert_eq!(writer("home/lass/hosts/yellow/retiolum/ip4"), Some("lass")); assert_eq!(writer("names/r/toaster"), None); } #[test] fn what_two_parties_ask_for_nobody_is_given() { let (_, _, _, first) = parties(); let mut kartei = kartei(); kartei.insert( "lass/hosts/yellow/retiolum/aliases".to_owned(), "yellow.r\nwiki.r\ncgit.ne.r\n".to_owned(), ); // A host named as a party is that party's name. kartei.insert( "berber/hosts/tv/retiolum/ip4".to_owned(), "10.243.0.7\n".to_owned(), ); let krebs = rules(&kartei, &version(&first), Some("krebs")).expect("rules"); assert!( !krebs .given .iter() .any(|(place, _)| place == "names/r/ne/cgit") ); assert_eq!( krebs.not_given, [ "names/r/ne/cgit: asked for by lass, tv; nobody writes there", "names/r/tv: asked for by krebs; tv writes there", ] ); assert!( krebs .given .contains(&("ip4/10/243/0/7".to_owned(), "krebs".to_owned())) ); } #[test] fn a_namespace_of_no_party_needs_a_group() { let (_, _, _, first) = parties(); assert_eq!( rules(&kartei(), &version(&first), None), Err("namespaces of no party, and no group: berber".to_owned()) ); assert_eq!( rules(&kartei(), &version(&first), Some("berber")), Err("berber is no party of the version".to_owned()) ); } /// The files of `namespace` in `kartei`, by their paths in it. fn namespace(kartei: &Files, namespace: &str) -> Files { let prefix = format!("{namespace}/"); kartei .iter() .filter_map(|(path, text)| Some((path.strip_prefix(&prefix)?.to_owned(), text.clone()))) .collect() } /// The first version with krebs's rules, made from `kartei()`: tv, lass, and krebs. fn krebs() -> (Party, Party, Party, Spec) { let (tv, lass, krebs, mut first) = parties(); let given = rules(&kartei(), &version(&first), Some("krebs")) .expect("rules") .given; let json = with_rules(&version(&first), &given); first.rules = given .iter() .map(|(place, party)| (place.clone(), harness::str(party))) .chain( BY_NAME .iter() .map(|path| ((*path).to_owned(), harness::str("{party}"))), ) .collect(); assert_eq!(first.json(), json); (tv, lass, krebs, first) } /// A federation's store, kartei signed in. struct Registry { store: Store, } impl Registry { /// From the first version `first`, each party signing in its namespaces: tv and /// lass their own, the group krebs berber's. fn new(first: &Spec, tv: &Party, lass: &Party, krebs: &Party) -> Registry { let mut registry = Registry { store: Store::new(first.root(), Vec::new()).expect("a root"), }; let kartei = kartei(); registry.sign_in(tv, &namespace(&kartei, "tv")); registry.sign_in(lass, &namespace(&kartei, "lass")); registry.sign_in(krebs, &namespace(&kartei, "berber")); registry } fn take(&mut self, bytes: Vec) -> Id { match self.store.offer(bytes) { Offered::Taken(ids) => ids[0], other => panic!("not taken: {other:?}"), } } /// `party` signs in its namespace to hold `files`. fn sign_in(&mut self, party: &Party, files: &Files) { let values = self.store.state().values(); for (place, value) in writes(&party.name, files, &values) { let heads = self.store.heads(); self.take(party.write(&heads, &place, value)); } } /// `proposer` proposes `next`, changing the version of hash `on`, and `voters` /// back it: a version event writes it. fn pass(&mut self, proposer: &Party, next: &Spec, on: Id, voters: &[&Party]) { let heads = self.store.heads(); let proposal = self.take(proposer.propose(&heads, &next.json())); let votes: Vec = voters .iter() .map(|voter| self.take(voter.vote(&[proposal], on, next.hash(), true))) .collect(); self.take(harness::version_event(&votes, next.hash())); assert_eq!(self.store.state().current().hash, next.hash()); } fn out(&self) -> Files { let state = self.store.state(); out(state.current(), &state.values()) } } #[test] fn kartei_signed_in_is_written_out_as_it_was() { let (tv, lass, krebs, first) = krebs(); let mut registry = Registry::new(&first, &tv, &lass, &krebs); let kartei = kartei(); let mut was: Files = ["tv", "lass"] .iter() .flat_map(|party| { namespace(&kartei, party) .into_iter() .map(move |(path, text)| (format!("{party}/{path}"), text)) }) .collect(); was.extend( namespace(&kartei, "berber") .into_iter() .map(|(path, text)| (format!("krebs/{path}"), text)), ); assert_eq!(registry.out(), was); // Signed in again, the namespace holds them already. let values = registry.store.state().values(); assert!(writes("tv", &namespace(&kartei, "tv"), &values).is_empty()); // A file gone is emptied, and written out no more. let mut gone = namespace(&kartei, "tv"); gone.remove("users/vv/mail"); registry.sign_in(&tv, &gone); assert!(!registry.out().contains_key("tv/users/vv/mail")); } #[test] fn what_asks_for_a_place_its_party_doesnt_hold_is_left_out() { let (tv, lass, krebs, first) = krebs(); let mut registry = Registry::new(&first, &tv, &lass, &krebs); let mut files = namespace(&kartei(), "lass"); for (path, text) in [ // tv's name, tv's host, tv's address, a block nobody's, tv's user. ( "hosts/yellow/retiolum/aliases", "yellow.r\nwiki.r\ncgit.ne.r\n", ), ("hosts/ne/retiolum/ip4", "10.243.0.9\n"), ("hosts/yellow/retiolum/tinc.subnets", "10.243.0.5\n"), ( "hosts/yellow/retiolum/tinc.extra", "Subnet = 10.243.0.0/24\nSPTPSCipher = aes-256-gcm\n", ), ("users/tv/mail", "lass@example.org\n"), ] { files.insert(path.to_owned(), text.to_owned()); } registry.sign_in(&lass, &files); let out = registry.out(); assert_eq!( out["lass/hosts/yellow/retiolum/aliases"], "yellow.r\nwiki.r\n" ); assert!(!out.contains_key("lass/hosts/ne/retiolum/ip4")); assert!(!out.contains_key("lass/hosts/yellow/retiolum/tinc.subnets")); assert_eq!( out["lass/hosts/yellow/retiolum/tinc.extra"], "SPTPSCipher = aes-256-gcm\n" ); assert!(!out.contains_key("lass/users/tv/mail")); assert_eq!(out["tv/hosts/ne/retiolum/ip4"], "10.243.0.5\n"); assert_eq!(out["tv/users/tv/mail"], "tv@example.org\n"); } #[test] fn a_name_a_version_gives_another_party_is_that_partys_in_kartei() { let (tv, lass, krebs, first) = krebs(); let mut registry = Registry::new(&first, &tv, &lass, &krebs); let mut files = namespace(&kartei(), "tv"); files.insert( "hosts/ne/retiolum/aliases".to_owned(), "ne.r\ncgit.ne.r\nne.tv.r\nwiki.r\n".to_owned(), ); registry.sign_in(&tv, &files); let out = registry.out(); assert_eq!( out["tv/hosts/ne/retiolum/aliases"], "ne.r\ncgit.ne.r\nne.tv.r\n" ); assert_eq!( out["lass/hosts/yellow/retiolum/aliases"], "yellow.r\nwiki.r\n" ); let mut next = first.after(first.hash()); next.rules .insert(0, ("names/r/wiki".to_owned(), harness::str("tv"))); registry.pass(&tv, &next, first.hash(), &[&tv, &lass, &krebs]); let out = registry.out(); assert_eq!( out["tv/hosts/ne/retiolum/aliases"], "ne.r\ncgit.ne.r\nne.tv.r\nwiki.r\n" ); assert_eq!(out["lass/hosts/yellow/retiolum/aliases"], "yellow.r\n"); } #[test] fn signing_in_writes_what_changed_and_empties_what_went() { let values: BTreeMap = [ ("home/tv/a", "1"), ("home/tv/b", "2"), ("home/tv/e", "5"), ("home/lass/c", "3"), ] .iter() .map(|(place, text)| ((*place).to_owned(), harness::str(text))) .collect(); assert_eq!( writes( "tv", &files(&[("a", "1"), ("b", "two"), ("d", "4")]), &values ), [ ("home/tv/b".to_owned(), harness::str("two")), ("home/tv/d".to_owned(), harness::str("4")), ("home/tv/e".to_owned(), Json::Null), ] ); } #[test] fn what_no_file_can_be_is_left_out() { let (_, _, _, mut first) = parties(); first.rules = BY_NAME .iter() .map(|path| ((*path).to_owned(), harness::str("{party}"))) .collect(); let values: BTreeMap = [ ("home/tv/ssh/tv.pub", harness::str("ssh-ed25519 AAAA tv\n")), // The way to another file, at a dot, no text, of no party. ("home/tv/ssh", harness::str("x")), ("home/tv/.git/config", harness::str("x")), ("home/tv/ssh/../x", harness::str("x")), ("home/tv/n", Json::Int(1)), ("home/nobody/x", harness::str("x")), ] .into_iter() .map(|(place, value)| (place.to_owned(), value)) .collect(); assert_eq!( out(&version(&first), &values), files(&[("tv/ssh/tv.pub", "ssh-ed25519 AAAA tv\n")]) ); } #[cfg(unix)] #[test] fn kartei_is_read_from_its_files_and_written_to_new_ones() { let dir = crate::files::scratch_dir("registry"); let tv = dir.join("tv"); std::fs::create_dir_all(tv.join("ssh")).unwrap(); std::fs::create_dir_all(tv.join("users/tv")).unwrap(); std::fs::write(tv.join("ssh/tv.pub"), "ssh-ed25519 AAAA tv\n").unwrap(); std::os::unix::fs::symlink("../../ssh/tv.pub", tv.join("users/tv/ssh.pub")).unwrap(); std::fs::write(tv.join(".hidden"), "x").unwrap(); let held = read(&tv).expect("read"); assert_eq!( held, files(&[ ("ssh/tv.pub", "ssh-ed25519 AAAA tv\n"), ("users/tv/ssh.pub", "ssh-ed25519 AAAA tv\n"), ]) ); let written = dir.join("out"); write(&written, &held).expect("written"); assert_eq!(read(&written), Ok(held.clone())); // Nothing may be there yet, and no path may leave it. assert!(write(&written, &held).is_err()); assert!(write(&dir.join("other"), &files(&[("../x", "1")])).is_err()); assert!(!dir.join("other").exists()); } }