stratum-node-cli 0.1.0-alpha.4

The `stratum` client for Stratum pod nodes: operator key files, bootstrap, config, backup, invitations and members over the loopback API; join, pod access and export for tenants through the gate
Documentation
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
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
//! The Web Access Control documents `stratum app` reads and writes: parsing
//! a governing ACL into the authorisations the client evaluates, building a
//! container's new ACL for an offered grant, checking it, writing it as
//! Turtle, comparing a read-back, and editing an installation's
//! authorisation out again at cleanup.
//!
//! Everything here is pure: the network reads and writes are in `app.rs`.
//! Turtle is parsed with `oxttl`; only the client's own documents are
//! written, in one fixed layout.
//!
//! **What the client evaluates.** A statement is evaluated only when its
//! subject is an `acl:Authorization` and its predicate is one of `rdf:type`
//! (with the object `acl:Authorization`), `acl:agent` (an IRI),
//! `acl:agentClass` (only `foaf:Agent`), `acl:accessTo` and `acl:default`
//! (paths in the same pod on the canonical origin; `acl:default` naming a
//! container), and `acl:mode` (`acl:Read`, `acl:Write`, `acl:Append`,
//! `acl:Control`). Any other statement, an `acl:agentGroup`, an
//! `acl:origin`, an `acl:condition`, another agent class, a literal or a
//! blank node where an IRI belongs, a statement about something that is not
//! an authorisation, or a document that is not Turtle, is refused with
//! [`CliError::AclNotEvaluated`] naming it: the client never writes an ACL
//! it cannot reason about (contract "The client previews").

use std::collections::{BTreeSet, HashMap};

use oxttl::TurtleParser;
use stratum_node_core::{DidNostr, PodPath};

use crate::error::CliError;
use crate::output::sanitize;

/// The WAC vocabulary.
const ACL: &str = "http://www.w3.org/ns/auth/acl#";
/// `rdf:type`.
const RDF_TYPE: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type";
/// `foaf:Agent`: everyone, signed or not.
const FOAF_AGENT: &str = "http://xmlns.com/foaf/0.1/Agent";

/// Above this many line pairs the preview diff is shown as the whole old
/// text removed and the whole new text added, rather than computed.
const MAX_DIFF_CELLS: usize = 4_000_000;

/// An access mode the client evaluates.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub(crate) enum Mode {
    /// `acl:Read`.
    Read,
    /// `acl:Write`.
    Write,
    /// `acl:Append`.
    Append,
    /// `acl:Control`.
    Control,
}

impl Mode {
    /// The mode named by a full IRI, or `None`.
    fn from_iri(iri: &str) -> Option<Self> {
        match iri.strip_prefix(ACL)? {
            "Read" => Some(Self::Read),
            "Write" => Some(Self::Write),
            "Append" => Some(Self::Append),
            "Control" => Some(Self::Control),
            _ => None,
        }
    }

    /// The compact name written in Turtle.
    fn curie(self) -> &'static str {
        match self {
            Self::Read => "acl:Read",
            Self::Write => "acl:Write",
            Self::Append => "acl:Append",
            Self::Control => "acl:Control",
        }
    }
}

/// The subject of an authorisation.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub(crate) enum Subject {
    /// An absolute IRI, usually `<acl url>#<fragment>`.
    Named(String),
    /// A blank node, by the label the parser gave it.
    Blank(String),
}

/// One `acl:Authorization`, reduced to what WAC evaluates.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub(crate) struct Authorisation {
    /// Its subject.
    pub(crate) subject: Subject,
    /// `acl:agent` IRIs.
    pub(crate) agents: BTreeSet<String>,
    /// `acl:agentClass foaf:Agent`.
    pub(crate) public: bool,
    /// `acl:accessTo` targets, as pod paths.
    pub(crate) access_to: BTreeSet<String>,
    /// `acl:default` targets, as container pod paths.
    pub(crate) default: BTreeSet<String>,
    /// `acl:mode` values.
    pub(crate) modes: BTreeSet<Mode>,
}

impl Authorisation {
    /// Whether two authorisations grant the same thing, ignoring subjects.
    fn same_grant(&self, other: &Self) -> bool {
        self.agents == other.agents
            && self.public == other.public
            && self.access_to == other.access_to
            && self.default == other.default
            && self.modes == other.modes
    }

    /// Whether `agent` (a full IRI) is named by `acl:agent`.
    pub(crate) fn names(&self, agent: &str) -> bool {
        self.agents.contains(agent)
    }
}

/// A parsed ACL: its absolute URL (the base its relative IRIs resolve
/// against) and its authorisations, in document order.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct AclDocument {
    /// The ACL's absolute URL on the canonical origin.
    pub(crate) url: String,
    /// Its authorisations.
    pub(crate) authorisations: Vec<Authorisation>,
}

impl AclDocument {
    /// Whether `other` holds the same statements, compared as sets of
    /// authorisations (subjects included).
    pub(crate) fn same_statements(&self, other: &Self) -> bool {
        let mine: BTreeSet<&Authorisation> = self.authorisations.iter().collect();
        let theirs: BTreeSet<&Authorisation> = other.authorisations.iter().collect();
        self.authorisations.len() == mine.len()
            && other.authorisations.len() == theirs.len()
            && mine == theirs
    }
}

/// What governs a container's access before the client writes its ACL.
#[derive(Debug, Clone)]
pub(crate) enum Governing {
    /// The container's own ACL.
    Own(AclDocument),
    /// The nearest ancestor's ACL, at `acl`.
    Inherited {
        /// The ancestor ACL's path.
        acl: PodPath,
        /// Its parsed statements.
        document: AclDocument,
    },
    /// No ACL exists up to the pod root.
    Nothing,
}

/// The inputs of [`materialise`].
#[derive(Debug, Clone, Copy)]
pub(crate) struct Materialise<'a> {
    /// The pod's owner, the signer of every write.
    pub(crate) owner: &'a DidNostr,
    /// The installation's application key.
    pub(crate) app: &'a DidNostr,
    /// The granted container.
    pub(crate) container: &'a PodPath,
    /// The absolute URL of the container's ACL.
    pub(crate) url: &'a str,
    /// What governs the container now.
    pub(crate) governing: &'a Governing,
    /// The offered authorisation, parsed from the node's Turtle with the
    /// container's ACL URL as base.
    pub(crate) offered: &'a Authorisation,
}

/// Parses the ACL at `acl` (its full URL `url`) into the authorisations the
/// client evaluates.
///
/// # Errors
///
/// [`CliError::AclNotEvaluated`] naming the ACL and the first statement the
/// client does not evaluate, or saying the document is not Turtle.
pub(crate) fn parse(
    url: &str,
    acl: &PodPath,
    origin: &str,
    bytes: &[u8],
) -> Result<AclDocument, CliError> {
    let refuse = |what: String| CliError::AclNotEvaluated(format!("{acl}: {what}"));
    let parser = TurtleParser::new()
        .with_base_iri(url)
        .map_err(|_| refuse("its URL is not an IRI".to_owned()))?;
    let pod = acl.owner();
    let mut order: Vec<Subject> = Vec::new();
    let mut found: HashMap<Subject, (bool, Authorisation)> = HashMap::new();
    for triple in parser.for_slice(bytes) {
        let triple = triple.map_err(|err| {
            refuse(format!(
                "not Turtle the client can read ({})",
                sanitize(&err.to_string())
            ))
        })?;
        let subject_text = triple.subject.to_string();
        let subject = if triple.subject.is_named_node() {
            Subject::Named(unbracket(&subject_text).unwrap_or_default().to_owned())
        } else {
            Subject::Blank(subject_text.clone())
        };
        let entry = found.entry(subject.clone()).or_insert_with(|| {
            order.push(subject.clone());
            (
                false,
                Authorisation {
                    subject: subject.clone(),
                    agents: BTreeSet::new(),
                    public: false,
                    access_to: BTreeSet::new(),
                    default: BTreeSet::new(),
                    modes: BTreeSet::new(),
                },
            )
        });
        let predicate = triple.predicate.as_str();
        let object_text = triple.object.to_string();
        let object = if triple.object.is_named_node() {
            unbracket(&object_text)
        } else {
            None
        };
        record(entry, predicate, object, origin, &pod).map_err(|what| {
            refuse(format!(
                "{what}: {}",
                sanitize(&format!("{subject_text} <{predicate}> {object_text}"))
            ))
        })?;
    }
    let mut authorisations = Vec::with_capacity(order.len());
    for subject in order {
        let Some((typed, authorisation)) = found.remove(&subject) else {
            continue;
        };
        if !typed {
            let shown = match &subject {
                Subject::Named(iri) => format!("<{iri}>"),
                Subject::Blank(label) => label.clone(),
            };
            return Err(refuse(format!(
                "statements about {}, which is not an acl:Authorization",
                sanitize(&shown)
            )));
        }
        authorisations.push(authorisation);
    }
    Ok(AclDocument {
        url: url.to_owned(),
        authorisations,
    })
}

/// Records one statement about an authorisation, or says why the client
/// does not evaluate it.
fn record(
    entry: &mut (bool, Authorisation),
    predicate: &str,
    object: Option<&str>,
    origin: &str,
    pod: &DidNostr,
) -> Result<(), String> {
    let authorisation = &mut entry.1;
    if predicate == RDF_TYPE {
        if object == Some(&format!("{ACL}Authorization")[..]) {
            entry.0 = true;
            return Ok(());
        }
        return Err("a type the client does not evaluate".to_owned());
    }
    match predicate.strip_prefix(ACL) {
        Some("agent") => {
            let iri = object.ok_or("an agent that is not an IRI")?;
            authorisation.agents.insert(iri.to_owned());
        }
        Some("agentClass") => {
            if object != Some(FOAF_AGENT) {
                return Err("an agent class other than foaf:Agent".to_owned());
            }
            authorisation.public = true;
        }
        Some(name @ ("accessTo" | "default")) => {
            let target = object
                .and_then(|iri| target_path(iri, origin, pod))
                .ok_or("a target that is not a path in this pod on its origin")?;
            if name == "accessTo" {
                authorisation.access_to.insert(target);
            } else if target.ends_with('/') {
                authorisation.default.insert(target);
            } else {
                return Err("an acl:default that names a resource, not a container".to_owned());
            }
        }
        Some("mode") => {
            let mode = object
                .and_then(Mode::from_iri)
                .ok_or("a mode the client does not evaluate")?;
            authorisation.modes.insert(mode);
        }
        Some(name @ ("agentGroup" | "origin" | "condition")) => {
            return Err(format!("an acl:{name}, which the client does not evaluate"));
        }
        _ => return Err("a predicate the client does not evaluate".to_owned()),
    }
    Ok(())
}

/// Strips the angle brackets of an IRI as `Display` prints it.
fn unbracket(text: &str) -> Option<&str> {
    text.strip_prefix('<')?.strip_suffix('>')
}

/// The pod path an absolute IRI names, when it is on `origin` and inside
/// `pod`'s pod.
fn target_path(iri: &str, origin: &str, pod: &DidNostr) -> Option<String> {
    let rest = iri.strip_prefix(origin)?;
    let path = PodPath::parse(rest).ok()?;
    (path.owner() == *pod).then(|| path.as_str().to_owned())
}

/// Whether the container `target` covers `container` under `acl:default`:
/// the container itself or anything beneath it.
fn covers(target: &str, container: &str) -> bool {
    container.starts_with(target)
}

/// Builds the container's new ACL (contract "The client previews"):
///
/// - for an ACL the container already has, every authorisation in it,
///   unchanged;
/// - for an inherited ACL, each authorisation with an `acl:default` that
///   covers the container, copied with the same agents and modes and with
///   `acl:accessTo` and `acl:default` naming the container; one whose
///   `acl:default` targets lie only beneath the container is copied with
///   those targets alone, so it keeps exactly its reach; an
///   `acl:accessTo`-only one never reached the container and is not copied;
/// - the owner's authorisation, with `acl:accessTo` and `acl:default` naming
///   the container and Read, Write and Control (unless the same grant is
///   already there);
/// - the offered authorisation (unless the identical one is already there).
///
/// Every subject the client adds is a fragment not yet used in the document,
/// and blank-node subjects are given such fragments, so that no added
/// statement merges into an existing authorisation and the written text has
/// no blank nodes.
///
/// # Errors
///
/// [`CliError::Refused`] when an existing authorisation names the
/// application key other than as offered, when the offered authorisation's
/// subject is taken by another, when the application key is the owner's, or
/// when the result would give the application key `Control`
/// ([`check_no_app_control`]).
pub(crate) fn materialise(input: &Materialise<'_>) -> Result<AclDocument, CliError> {
    let app = input.app.to_string();
    let container = input.container.as_str();
    if input.app == input.owner {
        return Err(CliError::Refused(
            "the node offered the pod owner's own key as the application key".to_owned(),
        ));
    }
    let (kept, copied, offered_present) = match input.governing {
        Governing::Own(document) => {
            let (kept, present) = keep_own(document, input.offered, &app, container)?;
            (kept, Vec::new(), present)
        }
        Governing::Inherited { acl, document } => (
            Vec::new(),
            copy_inherited(acl, document, &app, container)?,
            false,
        ),
        Governing::Nothing => (Vec::new(), Vec::new(), false),
    };
    let owner_rule = Authorisation {
        subject: Subject::Blank(String::new()),
        agents: BTreeSet::from([input.owner.to_string()]),
        public: false,
        access_to: BTreeSet::from([container.to_owned()]),
        default: BTreeSet::from([container.to_owned()]),
        modes: BTreeSet::from([Mode::Read, Mode::Write, Mode::Control]),
    };
    let owner_present = kept
        .iter()
        .chain(&copied)
        .any(|a| a.same_grant(&owner_rule));
    let mut used: BTreeSet<String> = kept
        .iter()
        .chain(std::iter::once(input.offered))
        .filter_map(|a| match &a.subject {
            Subject::Named(iri) => Some(iri.clone()),
            Subject::Blank(_) => None,
        })
        .collect();
    let mut mint = |base: &str| -> Subject {
        let mut n = 1_u32;
        loop {
            let candidate = if n == 1 {
                format!("{}#{base}", input.url)
            } else {
                format!("{}#{base}-{n}", input.url)
            };
            if used.insert(candidate.clone()) {
                return Subject::Named(candidate);
            }
            n = n.saturating_add(1);
        }
    };
    let mut authorisations = Vec::new();
    if !owner_present {
        let mut rule = owner_rule;
        rule.subject = mint("owner");
        authorisations.push(rule);
    }
    for mut authorisation in kept {
        if matches!(authorisation.subject, Subject::Blank(_)) {
            authorisation.subject = mint("rule");
        }
        authorisations.push(authorisation);
    }
    for mut authorisation in copied {
        authorisation.subject = mint("inherited");
        authorisations.push(authorisation);
    }
    if !offered_present {
        authorisations.push(input.offered.clone());
    }
    let document = AclDocument {
        url: input.url.to_owned(),
        authorisations,
    };
    check_no_app_control(&document, input.app, input.container)?;
    Ok(document)
}

/// Every authorisation of the container's own ACL, unchanged, and whether
/// the offered one is already among them.
fn keep_own(
    document: &AclDocument,
    offered: &Authorisation,
    app: &str,
    container: &str,
) -> Result<(Vec<Authorisation>, bool), CliError> {
    let mut present = false;
    for authorisation in &document.authorisations {
        if authorisation.subject == offered.subject {
            if authorisation != offered {
                return Err(CliError::Refused(format!(
                    "{container}: its ACL already has an authorisation named like the offered \
                     one, with other statements"
                )));
            }
            present = true;
        } else if authorisation.names(app) {
            return Err(CliError::Refused(format!(
                "{container}: its ACL already names the application key {app} in an \
                 authorisation the node did not offer"
            )));
        }
    }
    Ok((document.authorisations.clone(), present))
}

/// The inherited authorisations that reach the container, materialised on
/// it (subjects to be minted).
fn copy_inherited(
    acl: &PodPath,
    document: &AclDocument,
    app: &str,
    container: &str,
) -> Result<Vec<Authorisation>, CliError> {
    let mut copied = Vec::new();
    for authorisation in &document.authorisations {
        if authorisation.names(app) {
            if authorisation.agents.len() == 1 && !authorisation.public {
                // The application's own grant on an ancestor (a container
                // granted earlier in this install): the offered rule for
                // this container replaces it, so the ancestor's modes are
                // not copied down.
                continue;
            }
            return Err(CliError::Refused(format!(
                "{container}: the governing ACL {acl} names the application key {app} together \
                 with other agents"
            )));
        }
        let reaches = authorisation.default.iter().any(|t| covers(t, container));
        let beneath: BTreeSet<String> = authorisation
            .default
            .iter()
            .filter(|t| t.as_str() != container && t.starts_with(container))
            .cloned()
            .collect();
        let mut copy = authorisation.clone();
        if reaches {
            copy.access_to = BTreeSet::from([container.to_owned()]);
            copy.default = BTreeSet::from([container.to_owned()]);
        } else if !beneath.is_empty() {
            copy.access_to = BTreeSet::new();
            copy.default = beneath;
        } else {
            continue;
        }
        copy.subject = Subject::Blank(String::new());
        copied.push(copy);
    }
    Ok(copied)
}

/// Refuses a document in which any authorisation gives the application key
/// `Control`: one naming the key, or one for `foaf:Agent` (everyone,
/// the key included), with `acl:Control`.
///
/// # Errors
///
/// [`CliError::Refused`] naming the container.
pub(crate) fn check_no_app_control(
    document: &AclDocument,
    app: &DidNostr,
    container: &PodPath,
) -> Result<(), CliError> {
    let app = app.to_string();
    for authorisation in &document.authorisations {
        if authorisation.modes.contains(&Mode::Control)
            && (authorisation.names(&app) || authorisation.public)
        {
            let whom = if authorisation.public {
                "everyone (foaf:Agent), the application key included"
            } else {
                "the application key"
            };
            return Err(CliError::Refused(format!(
                "{container}: the ACL would give {whom} acl:Control; the client never writes that"
            )));
        }
    }
    Ok(())
}

/// The installation's authorisation removed from `document`: the
/// application key is taken out of the authorisation the client wrote
/// (subject `<acl>#app-<key hex>`), and that authorisation is dropped when
/// it names no one else. Blank-node subjects are given fresh fragments, as
/// [`materialise`] does. Returns `None` when the document does not name the
/// key in that authorisation, so there is nothing to remove.
pub(crate) fn remove_installation(document: &AclDocument, app: &DidNostr) -> Option<AclDocument> {
    let app_iri = app.to_string();
    let subject = Subject::Named(format!("{}#app-{}", document.url, app.to_hex()));
    let index = document
        .authorisations
        .iter()
        .position(|a| a.subject == subject && a.names(&app_iri))?;
    let mut authorisations = document.authorisations.clone();
    let mut rule = authorisations.remove(index);
    rule.agents.remove(&app_iri);
    if !rule.agents.is_empty() || rule.public {
        authorisations.insert(index, rule);
    }
    let mut used: BTreeSet<String> = authorisations
        .iter()
        .filter_map(|a| match &a.subject {
            Subject::Named(iri) => Some(iri.clone()),
            Subject::Blank(_) => None,
        })
        .collect();
    for authorisation in &mut authorisations {
        if matches!(authorisation.subject, Subject::Blank(_)) {
            let mut n = 1_u32;
            loop {
                let candidate = format!("{}#rule-{n}", document.url);
                if used.insert(candidate.clone()) {
                    authorisation.subject = Subject::Named(candidate);
                    break;
                }
                n = n.saturating_add(1);
            }
        }
    }
    Some(AclDocument {
        url: document.url.clone(),
        authorisations,
    })
}

/// How many authorisations other than the installation's own name the key.
pub(crate) fn other_mentions(document: &AclDocument, app: &DidNostr) -> usize {
    let app_iri = app.to_string();
    let own = Subject::Named(format!("{}#app-{}", document.url, app.to_hex()));
    document
        .authorisations
        .iter()
        .filter(|a| a.subject != own && a.names(&app_iri))
        .count()
}

/// Writes `document` as Turtle in the client's one layout: the `acl:` (and,
/// when used, `foaf:`) prefix, then one block per authorisation, subjects
/// on the document's own URL written as `<#fragment>`, pod paths written
/// relative to the origin (`</pods/…>`), as the node's own ACLs are.
///
/// # Errors
///
/// [`CliError::AclNotEvaluated`] if an IRI could not be written safely
/// (one the parser accepted never fails this).
pub(crate) fn serialise(document: &AclDocument) -> Result<String, CliError> {
    let unsafe_iri = |iri: &str| {
        CliError::AclNotEvaluated(format!(
            "{}: an IRI the client cannot write back safely: {}",
            document.url,
            sanitize(iri)
        ))
    };
    let checked = |iri: &str| -> Result<String, CliError> {
        if iri.is_empty()
            || iri
                .chars()
                .any(|c| c.is_control() || c.is_whitespace() || "<>\"{}|^`\\".contains(c))
        {
            return Err(unsafe_iri(iri));
        }
        Ok(format!("<{iri}>"))
    };
    let mut text = String::from("@prefix acl: <http://www.w3.org/ns/auth/acl#> .\n");
    if document.authorisations.iter().any(|a| a.public) {
        text.push_str("@prefix foaf: <http://xmlns.com/foaf/0.1/> .\n");
    }
    let own = format!("{}#", document.url);
    for (index, authorisation) in document.authorisations.iter().enumerate() {
        text.push('\n');
        let subject = match &authorisation.subject {
            Subject::Named(iri) => match iri.strip_prefix(&own) {
                Some(fragment) if !fragment.is_empty() => checked(&format!("#{fragment}"))?,
                _ => checked(iri)?,
            },
            Subject::Blank(_) => format!("_:b{index}"),
        };
        let mut lines = vec![format!("{subject} a acl:Authorization")];
        if !authorisation.agents.is_empty() {
            let agents = authorisation
                .agents
                .iter()
                .map(|a| checked(a))
                .collect::<Result<Vec<_>, _>>()?;
            lines.push(format!("    acl:agent {}", agents.join(", ")));
        }
        if authorisation.public {
            lines.push("    acl:agentClass foaf:Agent".to_owned());
        }
        for (name, targets) in [
            ("accessTo", &authorisation.access_to),
            ("default", &authorisation.default),
        ] {
            if !targets.is_empty() {
                let targets = targets
                    .iter()
                    .map(|t| checked(t))
                    .collect::<Result<Vec<_>, _>>()?;
                lines.push(format!("    acl:{name} {}", targets.join(", ")));
            }
        }
        if !authorisation.modes.is_empty() {
            let modes: Vec<&str> = authorisation.modes.iter().map(|m| m.curie()).collect();
            lines.push(format!("    acl:mode {}", modes.join(", ")));
        }
        text.push_str(&lines.join(" ;\n"));
        text.push_str(" .\n");
    }
    Ok(text)
}

/// A line diff of `old` against `new`: removed lines start `- `, added
/// lines `+ `, kept lines two spaces.
pub(crate) fn diff(old: &str, new: &str) -> Vec<String> {
    let a: Vec<&str> = old.lines().collect();
    let b: Vec<&str> = new.lines().collect();
    if a.len().saturating_mul(b.len()) > MAX_DIFF_CELLS {
        return a
            .iter()
            .map(|l| format!("- {l}"))
            .chain(b.iter().map(|l| format!("+ {l}")))
            .collect();
    }
    // Longest common subsequence, filled from the end.
    let width = b.len() + 1;
    let mut table = vec![0_usize; (a.len() + 1) * width];
    for i in (0..a.len()).rev() {
        for j in (0..b.len()).rev() {
            table[i * width + j] = if a[i] == b[j] {
                table[(i + 1) * width + j + 1] + 1
            } else {
                table[(i + 1) * width + j].max(table[i * width + j + 1])
            };
        }
    }
    let (mut i, mut j) = (0, 0);
    let mut lines = Vec::new();
    while i < a.len() && j < b.len() {
        if a[i] == b[j] {
            lines.push(format!("  {}", a[i]));
            i += 1;
            j += 1;
        } else if table[(i + 1) * width + j] >= table[i * width + j + 1] {
            lines.push(format!("- {}", a[i]));
            i += 1;
        } else {
            lines.push(format!("+ {}", b[j]));
            j += 1;
        }
    }
    lines.extend(a[i..].iter().map(|l| format!("- {l}")));
    lines.extend(b[j..].iter().map(|l| format!("+ {l}")));
    lines
}

/// The containers whose ACLs may govern `container`, nearest first: the
/// container itself, then each ancestor up to the pod root.
pub(crate) fn governing_candidates(container: &PodPath) -> Vec<PodPath> {
    let root = PodPath::pod_root(&container.owner());
    let mut candidates = vec![container.clone()];
    let mut current = container.clone();
    while current != root {
        let text = current.as_str();
        let trimmed = text.strip_suffix('/').unwrap_or(text);
        let Some(index) = trimmed.rfind('/') else {
            break;
        };
        let Ok(parent) = PodPath::parse(&trimmed[..=index]) else {
            break;
        };
        candidates.push(parent.clone());
        current = parent;
    }
    candidates
}

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

    const ORIGIN: &str = "https://stratum.test";
    const OWNER: &str = "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798";
    const APP: &str = "c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5";
    const OTHER: &str = "f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9";

    fn did(hex: &str) -> DidNostr {
        DidNostr::from_hex(hex).expect("key")
    }

    fn path(text: &str) -> PodPath {
        PodPath::parse(&format!("/pods/{OWNER}/{text}")).expect("path")
    }

    fn acl_of(container: &PodPath) -> PodPath {
        container.acl_path().expect("acl")
    }

    fn parse_at(acl: &PodPath, text: &str) -> Result<AclDocument, CliError> {
        parse(&format!("{ORIGIN}{acl}"), acl, ORIGIN, text.as_bytes())
    }

    fn root_acl() -> PodPath {
        PodPath::parse(&format!("/pods/{OWNER}.acl")).expect("root acl")
    }

    /// The offered rule for `container`, as node-core renders it.
    fn offered(container: &PodPath, modes: &str) -> Authorisation {
        let acl = acl_of(container);
        let text = format!(
            "@prefix acl: <http://www.w3.org/ns/auth/acl#> .\n\n<#app-{APP}> a acl:Authorization ;\n    \
             acl:agent <did:nostr:{APP}> ;\n    acl:default <{container}> ;\n    acl:mode {modes} .\n"
        );
        parse_at(&acl, &text)
            .expect("offered")
            .authorisations
            .remove(0)
    }

    fn build(container: &PodPath, governing: &Governing) -> Result<AclDocument, CliError> {
        let url = format!("{ORIGIN}{}", acl_of(container));
        materialise(&Materialise {
            owner: &did(OWNER),
            app: &did(APP),
            container,
            url: &url,
            governing,
            offered: &offered(container, "acl:Read, acl:Write"),
        })
    }

    fn inherited(text: &str) -> Governing {
        let acl = root_acl();
        Governing::Inherited {
            document: parse_at(&acl, text).expect("root"),
            acl,
        }
    }

    #[test]
    fn e3b_7_unevaluated_statements_are_refused_and_named() {
        let acl = root_acl();
        let head = "@prefix acl: <http://www.w3.org/ns/auth/acl#>.\n@prefix foaf: <http://xmlns.com/foaf/0.1/>.\n";
        for (body, says) in [
            ("<#g> a acl:Authorization; acl:agentGroup </pods/x/g#team>; acl:mode acl:Read.", "agentGroup"),
            ("<#o> a acl:Authorization; acl:origin <https://app.example>; acl:mode acl:Read.", "acl:origin"),
            ("<#c> a acl:Authorization; acl:agentClass acl:AuthenticatedAgent; acl:mode acl:Read.", "agent class"),
            ("<#u> a acl:Authorization; acl:unknown <x:y>; acl:mode acl:Read.", "predicate"),
            ("<#k> a acl:Authorization; acl:condition <#cond>; acl:mode acl:Read.", "condition"),
            ("<#t> a acl:Authorization, foaf:Document; acl:mode acl:Read.", "type"),
            ("<#l> a acl:Authorization; acl:agent \"did:nostr:x\"; acl:mode acl:Read.", "not an IRI"),
            ("<#m> a acl:Authorization; acl:mode acl:Delete.", "mode"),
            ("<#e> a acl:Authorization; acl:accessTo <https://elsewhere.example/pods/>; acl:mode acl:Read.", "target"),
            ("<#r> a acl:Authorization; acl:default </pods/x.txt>; acl:mode acl:Read.", "target"),
            ("<#n> acl:agent <did:nostr:x>.", "not an acl:Authorization"),
            ("this is not turtle", "not Turtle"),
        ] {
            let err = parse_at(&acl, &format!("{head}{body}")).expect_err(body);
            assert!(matches!(err, CliError::AclNotEvaluated(_)), "{body}: {err}");
            assert!(err.to_string().contains(says), "{body}: {err}");
            assert!(err.to_string().contains(acl.as_str()), "{body}: names the ACL: {err}");
        }
    }

    #[test]
    fn e3b_7_a_default_on_a_resource_is_refused() {
        let acl = root_acl();
        let text = format!(
            "@prefix acl: <http://www.w3.org/ns/auth/acl#>.\n<#r> a acl:Authorization; acl:default </pods/{OWNER}/x.txt>; acl:mode acl:Read."
        );
        let err = parse_at(&acl, &text).expect_err("resource default");
        assert!(err.to_string().contains("names a resource"), "{err}");
    }

    #[test]
    fn e3b_7_inherited_default_rules_are_materialised_and_access_to_only_rules_are_not() {
        let c = path("reports/");
        let governing = inherited(&format!(
            "@prefix acl: <http://www.w3.org/ns/auth/acl#>.\n\
             <#owner> a acl:Authorization; acl:agent <did:nostr:{OWNER}>; acl:accessTo </pods/{OWNER}/>; acl:default </pods/{OWNER}/>; acl:mode acl:Read, acl:Write, acl:Control.\n\
             <#friend> a acl:Authorization; acl:agent <did:nostr:{OTHER}>; acl:default </pods/{OWNER}/>; acl:mode acl:Read.\n\
             <#top> a acl:Authorization; acl:agent <did:nostr:{OTHER}>; acl:accessTo </pods/{OWNER}/>; acl:mode acl:Write.\n\
             <#sibling> a acl:Authorization; acl:agent <did:nostr:{OTHER}>; acl:default </pods/{OWNER}/other/>; acl:mode acl:Append.\n\
             <#deep> a acl:Authorization; acl:agent <did:nostr:{OTHER}>; acl:default </pods/{OWNER}/reports/deep/>; acl:mode acl:Write.\n"
        ));
        let document = build(&c, &governing).expect("materialised");
        let other = format!("did:nostr:{OTHER}");
        let friend: Vec<&Authorisation> = document
            .authorisations
            .iter()
            .filter(|a| a.names(&other))
            .collect();
        // The pod-root default reaches reports/ and is copied onto it.
        assert!(friend
            .iter()
            .any(|a| a.modes == BTreeSet::from([Mode::Read])
                && a.access_to == BTreeSet::from([c.as_str().to_owned()])
                && a.default == BTreeSet::from([c.as_str().to_owned()])));
        // A default beneath reports/ keeps exactly its reach.
        assert!(friend
            .iter()
            .any(|a| a.modes == BTreeSet::from([Mode::Write])
                && a.access_to.is_empty()
                && a.default == BTreeSet::from([format!("/pods/{OWNER}/reports/deep/")])));
        // The accessTo-only rule and the sibling's default never reached it.
        assert!(!friend.iter().any(|a| a.modes.contains(&Mode::Append)));
        assert_eq!(friend.len(), 2, "{friend:?}");
        // The owner's rule on the container, with Control.
        let owner = format!("did:nostr:{OWNER}");
        assert!(document.authorisations.iter().any(|a| a.names(&owner)
            && a.modes.contains(&Mode::Control)
            && a.default.contains(c.as_str())
            && a.access_to.contains(c.as_str())));
        // The offered rule, and the app has no Control anywhere.
        assert!(document
            .authorisations
            .contains(&offered(&c, "acl:Read, acl:Write")));
        let app = format!("did:nostr:{APP}");
        assert!(!document
            .authorisations
            .iter()
            .any(|a| a.names(&app) && a.modes.contains(&Mode::Control)));
    }

    #[test]
    fn e3b_7_an_own_acl_is_kept_and_new_subjects_never_merge() {
        let c = path("reports/");
        let acl = acl_of(&c);
        // The existing ACL uses `#owner` for someone else, and a blank node.
        let own = parse_at(
            &acl,
            &format!(
                "@prefix acl: <http://www.w3.org/ns/auth/acl#>.\n\
                 <#owner> a acl:Authorization; acl:agent <did:nostr:{OTHER}>; acl:accessTo </pods/{OWNER}/reports/>; acl:mode acl:Read.\n\
                 [] a acl:Authorization; acl:agent <did:nostr:{OWNER}>; acl:accessTo </pods/{OWNER}/reports/>; acl:mode acl:Read, acl:Write, acl:Control.\n"
            ),
        )
        .expect("own");
        let document = build(&c, &Governing::Own(own)).expect("built");
        let other = format!("did:nostr:{OTHER}");
        let kept = document
            .authorisations
            .iter()
            .find(|a| a.subject == Subject::Named(format!("{ORIGIN}{acl}#owner")))
            .expect("kept");
        assert_eq!(kept.agents, BTreeSet::from([other]), "no merge into #owner");
        assert!(!kept.modes.contains(&Mode::Control));
        assert!(document
            .authorisations
            .iter()
            .all(|a| matches!(a.subject, Subject::Named(_))));
        // The written text parses back to the same statements.
        let text = serialise(&document).expect("text");
        assert!(!text.contains("_:"), "{text}");
        let back = parse_at(&acl, &text).expect("reparse");
        assert!(document.same_statements(&back), "{text}");
        // Building again from what was written changes nothing.
        let again = build(&c, &Governing::Own(back)).expect("rebuilt");
        assert!(again.same_statements(&document));
    }

    #[test]
    fn e3b_7_the_application_never_gets_control() {
        let c = path("reports/");
        // Inherited public Control would reach the app.
        let governing = inherited(&format!(
            "@prefix acl: <http://www.w3.org/ns/auth/acl#>.\n@prefix foaf: <http://xmlns.com/foaf/0.1/>.\n\
             <#pub> a acl:Authorization; acl:agentClass foaf:Agent; acl:default </pods/{OWNER}/>; acl:mode acl:Read, acl:Control.\n"
        ));
        let err = build(&c, &governing).expect_err("public control");
        assert!(err.to_string().contains("acl:Control"), "{err}");
        // An own ACL already naming the key with Control.
        let acl = acl_of(&c);
        let own = parse_at(
            &acl,
            &format!(
                "@prefix acl: <http://www.w3.org/ns/auth/acl#>.\n\
                 <#x> a acl:Authorization; acl:agent <did:nostr:{APP}>; acl:default </pods/{OWNER}/reports/>; acl:mode acl:Control.\n"
            ),
        )
        .expect("own");
        assert!(build(&c, &Governing::Own(own)).is_err());
        // The owner's key offered as the application key.
        let url = format!("{ORIGIN}{acl}");
        let err = materialise(&Materialise {
            owner: &did(OWNER),
            app: &did(OWNER),
            container: &c,
            url: &url,
            governing: &Governing::Nothing,
            offered: &offered(&c, "acl:Read"),
        })
        .expect_err("owner as app");
        assert!(err.to_string().contains("owner"), "{err}");
        // The direct check on a finished document.
        let mut document = build(&c, &Governing::Nothing).expect("built");
        for authorisation in &mut document.authorisations {
            if authorisation.names(&format!("did:nostr:{APP}")) {
                authorisation.modes.insert(Mode::Control);
            }
        }
        assert!(check_no_app_control(&document, &did(APP), &c).is_err());
    }

    #[test]
    fn e3b_7_an_ancestor_grant_to_the_application_is_not_copied_down() {
        let c = path("reports/2026/");
        let parent = path("reports/");
        let acl = acl_of(&parent);
        let document = parse_at(
            &acl,
            &format!(
                "@prefix acl: <http://www.w3.org/ns/auth/acl#>.\n\
                 <#owner> a acl:Authorization; acl:agent <did:nostr:{OWNER}>; acl:accessTo </pods/{OWNER}/reports/>; acl:default </pods/{OWNER}/reports/>; acl:mode acl:Read, acl:Write, acl:Control.\n\
                 <#app-{APP}> a acl:Authorization; acl:agent <did:nostr:{APP}>; acl:default </pods/{OWNER}/reports/>; acl:mode acl:Read, acl:Write.\n"
            ),
        )
        .expect("parent");
        let url = format!("{ORIGIN}{}", acl_of(&c));
        let built = materialise(&Materialise {
            owner: &did(OWNER),
            app: &did(APP),
            container: &c,
            url: &url,
            governing: &Governing::Inherited { acl, document },
            offered: &offered(&c, "acl:Read"),
        })
        .expect("built");
        let app = format!("did:nostr:{APP}");
        let app_rules: Vec<&Authorisation> = built
            .authorisations
            .iter()
            .filter(|a| a.names(&app))
            .collect();
        assert_eq!(app_rules.len(), 1);
        assert_eq!(app_rules[0].modes, BTreeSet::from([Mode::Read]));
    }

    #[test]
    fn e3b_24_cleanup_removes_only_the_installations_authorisation() {
        let c = path("reports/");
        let built = build(
            &c,
            &inherited(&format!(
                "@prefix acl: <http://www.w3.org/ns/auth/acl#>.\n\
                 <#friend> a acl:Authorization; acl:agent <did:nostr:{OTHER}>; acl:default </pods/{OWNER}/>; acl:mode acl:Read.\n"
            )),
        )
        .expect("built");
        let cleaned = remove_installation(&built, &did(APP)).expect("removed");
        let app = format!("did:nostr:{APP}");
        assert!(!cleaned.authorisations.iter().any(|a| a.names(&app)));
        assert_eq!(cleaned.authorisations.len(), built.authorisations.len() - 1);
        for authorisation in &cleaned.authorisations {
            assert!(built.authorisations.contains(authorisation));
        }
        assert!(
            remove_installation(&cleaned, &did(APP)).is_none(),
            "already clean"
        );
        assert_eq!(other_mentions(&cleaned, &did(APP)), 0);
    }

    #[test]
    fn candidates_walk_up_to_the_pod_root() {
        let names: Vec<String> = governing_candidates(&path("a/b/"))
            .iter()
            .map(|p| p.as_str().to_owned())
            .collect();
        assert_eq!(
            names,
            [
                format!("/pods/{OWNER}/a/b/"),
                format!("/pods/{OWNER}/a/"),
                format!("/pods/{OWNER}/"),
            ]
        );
    }

    #[test]
    fn the_diff_marks_added_and_removed_lines() {
        assert_eq!(
            diff("a\nb\nc\n", "a\nx\nc\nd\n"),
            ["  a", "- b", "+ x", "  c", "+ d"]
        );
        assert_eq!(diff("", "a\n"), ["+ a"]);
    }
}