use std::collections::{BTreeSet, HashMap};
use oxttl::TurtleParser;
use stratum_node_core::{DidNostr, PodPath};
use crate::error::CliError;
use crate::output::sanitize;
const ACL: &str = "http://www.w3.org/ns/auth/acl#";
const RDF_TYPE: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type";
const FOAF_AGENT: &str = "http://xmlns.com/foaf/0.1/Agent";
const MAX_DIFF_CELLS: usize = 4_000_000;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub(crate) enum Mode {
Read,
Write,
Append,
Control,
}
impl Mode {
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,
}
}
fn curie(self) -> &'static str {
match self {
Self::Read => "acl:Read",
Self::Write => "acl:Write",
Self::Append => "acl:Append",
Self::Control => "acl:Control",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub(crate) enum Subject {
Named(String),
Blank(String),
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub(crate) struct Authorisation {
pub(crate) subject: Subject,
pub(crate) agents: BTreeSet<String>,
pub(crate) public: bool,
pub(crate) access_to: BTreeSet<String>,
pub(crate) default: BTreeSet<String>,
pub(crate) modes: BTreeSet<Mode>,
}
impl Authorisation {
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
}
pub(crate) fn names(&self, agent: &str) -> bool {
self.agents.contains(agent)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct AclDocument {
pub(crate) url: String,
pub(crate) authorisations: Vec<Authorisation>,
}
impl AclDocument {
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
}
}
#[derive(Debug, Clone)]
pub(crate) enum Governing {
Own(AclDocument),
Inherited {
acl: PodPath,
document: AclDocument,
},
Nothing,
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct Materialise<'a> {
pub(crate) owner: &'a DidNostr,
pub(crate) app: &'a DidNostr,
pub(crate) container: &'a PodPath,
pub(crate) url: &'a str,
pub(crate) governing: &'a Governing,
pub(crate) offered: &'a Authorisation,
}
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,
})
}
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(())
}
fn unbracket(text: &str) -> Option<&str> {
text.strip_prefix('<')?.strip_suffix('>')
}
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())
}
fn covers(target: &str, container: &str) -> bool {
container.starts_with(target)
}
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)
}
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))
}
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 {
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)
}
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(())
}
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,
})
}
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()
}
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)
}
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();
}
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
}
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")
}
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();
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()])));
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/")])));
assert!(!friend.iter().any(|a| a.modes.contains(&Mode::Append)));
assert_eq!(friend.len(), 2, "{friend:?}");
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())));
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);
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(_))));
let text = serialise(&document).expect("text");
assert!(!text.contains("_:"), "{text}");
let back = parse_at(&acl, &text).expect("reparse");
assert!(document.same_statements(&back), "{text}");
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/");
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}");
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());
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}");
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"]);
}
}