aboutsummaryrefslogtreecommitdiffstats
path: root/src/federation/registry.rs
blob: 804ca1e109054b922d984d19b5a1d035eed85aa3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
//! 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<String, String>;

/// 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<String> {
    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<String> {
    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::<usize>().ok()?)),
        None => (text, None),
    };
    let (kind, parts, bits) = if let Ok(ip) = address.parse::<Ipv4Addr>() {
        let parts: Vec<String> = ip.octets().iter().map(u8::to_string).collect();
        ("ip4", parts, 8)
    } else if let Ok(ip) = address.parse::<Ipv6Addr>() {
        let parts: Vec<String> = 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<String>,
    pub(crate) lines: Option<Vec<Line<'a>>>,
}

impl Asks<'_> {
    /// Every place it asks for, its own and its lines'.
    fn every(&self) -> impl Iterator<Item = &str> {
        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<String>) -> Vec<Line<'_>> {
    text.lines()
        .map(|line| match line.trim() {
            "" => Line::Free(line),
            held => spelled(line, spell(held)),
        })
        .collect()
}

fn spelled(line: &str, place: Option<String>) -> 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<String>,
}

/// 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<Krebs, String> {
    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<String, BTreeSet<&str>> = 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<Json> = 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<Files, String> {
    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<String, Json>,
) -> 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<String, Json>) -> 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<String> = 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<String> {
    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<String> {
            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<Federation>,
    }

    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<u8>) -> 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<Id> = 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<String, Json> = [
            ("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<String, Json> = [
            ("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());
    }
}