From 438b0ee5d1fe5d40f18e16d94904fc9bdd89783a Mon Sep 17 00:00:00 2001 From: tv Date: Sun, 29 Nov 2026 02:56:54 +0000 Subject: access: the rules judge a unit at the state its writer saw, a change being Automerge's rules::judge_seen is the rules: given a unit (who made it, for whom, what it writes where) and the document as its writer saw it, to read, why they refuse it. rules::judge keeps what is Automerge's of judging a change: an epoch's root, by the change's hash, and the document at the change's heads, by which it also keeps what was read there (Reads over Seen). A swarm holding a store is judged alike (holding::judge), a founding change told by the unit's name. --- src/access/holding.rs | 58 ++++++++------- src/access/rules.rs | 197 ++++++++++++++++++++++++++++++-------------------- 2 files changed, 151 insertions(+), 104 deletions(-) (limited to 'src/access') diff --git a/src/access/holding.rs b/src/access/holding.rs index 798ba46..c68ca92 100644 --- a/src/access/holding.rs +++ b/src/access/holding.rs @@ -25,8 +25,8 @@ use sha2::{Digest, Sha256}; -use super::rules::{Change, Refusal, coordinator, made_the_epoch}; -use crate::document::at::At; +use super::rules::{Unit, coordinator, made_the_epoch}; +use crate::document::ReadDoc; use crate::document::inspect::{Action, Op, Path}; use crate::document::replica::Epoch; use crate::document::{events, meta, store}; @@ -54,14 +54,14 @@ fn keeps(fold: &str, root: &[u8]) -> Option> { /// Whether `change`, naming no node, is one of those founding the swarm, which every node /// builds from the store's root and the events it keeps (`events::is_founding`). -fn founding(at: &At<'_>, change: &Change<'_>, fold: &str) -> bool { +fn founding(at: &impl ReadDoc, unit: &Unit<'_>, fold: &str) -> bool { let Some(root) = events::swarm(at).and_then(|swarm| events::bytes(at, &swarm)) else { return false; }; let Some(keeps) = keeps(fold, &root) else { return false; }; - let written: Vec> = change + let written: Vec> = unit .ops .iter() .filter_map(|op| match &op.action { @@ -69,20 +69,26 @@ fn founding(at: &At<'_>, change: &Change<'_>, fold: &str) -> bool { _ => None, }) .collect(); - events::is_founding(at, fold, (&root, &keeps), &change.hash, &written) + events::is_founding( + at, + fold, + (&root, &keeps), + &crate::document::ChangeHash(unit.id), + &written, + ) } /// Judges `change`, of a swarm holding a store of the fold `fold`, at its history `at`, in /// the document of `epoch`. pub(crate) fn judge( - at: &At<'_>, + at: &impl ReadDoc, epoch: Epoch, - change: &Change<'_>, + unit: &Unit<'_>, fold: &str, -) -> Result<(), Refusal> { - let refuse = |why: String| Err(Refusal::Rule(why)); - let Some(node) = change.committer else { - if founding(at, change, fold) { +) -> Result<(), String> { + let refuse = |why: String| Err(why); + let Some(node) = unit.committer else { + if founding(at, unit, fold) { return Ok(()); } return refuse("it names no node".to_owned()); @@ -93,7 +99,7 @@ pub(crate) fn judge( let votes = meta::path(&[meta::VOTES]); let acks = meta::path(&[meta::VOTES, node]); let remakes = meta::path(&[meta::REMAKES]); - for op in change.ops { + for op in unit.ops { let allowed = if op.path.starts_with(&events) { event(at, op, fold) } else if op.path.starts_with(&entry) || op.path.starts_with(&acks) { @@ -101,7 +107,7 @@ pub(crate) fn judge( } else if op.path == members || op.path == votes || op.path == remakes { made(at, op) } else if op.path.starts_with(&remakes) { - remake(at, epoch, change, node, op) + remake(at, epoch, unit, node, op) } else { Err(format!("it writes {}, closed", shown(&op.path))) }; @@ -111,7 +117,7 @@ pub(crate) fn judge( } /// Whether `op` makes the map at its path, where there is none at `at`. -fn made(at: &At<'_>, op: &Op) -> Result<(), String> { +fn made(at: &impl ReadDoc, op: &Op) -> Result<(), String> { if op.action == Action::MakeMap && !store::held_anywhere(at, &op.path) { Ok(()) } else { @@ -125,9 +131,9 @@ fn made(at: &At<'_>, op: &Op) -> Result<(), String> { /// the record of the remake that made the epoch, carried into it whole by its /// coordinator, where there is none. fn remake( - at: &At<'_>, + at: &impl ReadDoc, epoch: Epoch, - change: &Change<'_>, + unit: &Unit<'_>, node: &str, op: &Op, ) -> Result<(), String> { @@ -142,7 +148,7 @@ fn remake( Err(format!( "it writes the proposal of remake {id}, written already" )) - } else if !proposes(change, &proposal, node) { + } else if !proposes(unit, &proposal, node) { Err(format!( "it proposes remake {id}, no compaction that {node} coordinates" )) @@ -155,7 +161,7 @@ fn remake( Some(coordinator) => Err(format!( "it decides remake {id}, which is {coordinator}'s to decide" )), - None if change.paths.contains(&proposal) + None if unit.paths.contains(&proposal) && !store::held_anywhere(at, &meta::path(&[meta::REMAKES, id])) && made_the_epoch(at, epoch, id, node) => { @@ -172,7 +178,7 @@ fn remake( /// Whether `change` writes at `proposal` a compaction's proposal that names `node` its /// coordinator. -fn proposes(change: &Change<'_>, proposal: &Path, node: &str) -> bool { +fn proposes(unit: &Unit<'_>, proposal: &Path, node: &str) -> bool { let at = |key: &str| { let mut path = proposal.clone(); path.push(key.to_owned()); @@ -180,14 +186,14 @@ fn proposes(change: &Change<'_>, proposal: &Path, node: &str) -> bool { }; let (coordinator, kind) = (at("coordinator"), at("kind")); let put = |path: &Path| { - change.ops.iter().find_map(|op| match &op.action { + unit.ops.iter().find_map(|op| match &op.action { Action::PutString(text) if op.path == *path => Some(text.as_str()), _ => None, }) }; put(&coordinator) == Some(node) && put(&kind).is_none_or(|kind| kind == crate::remake::DEFAULT_KIND) - && change + && unit .ops .iter() .filter(|op| op.path == kind) @@ -196,7 +202,7 @@ fn proposes(change: &Change<'_>, proposal: &Path, node: &str) -> bool { /// Whether `op`, under `_continuum/events`, puts an event at its ID, held nowhere at `at`, /// no larger than the fold `fold` allows. -fn event(at: &At<'_>, op: &Op, fold: &str) -> Result<(), String> { +fn event(at: &impl ReadDoc, op: &Op, fold: &str) -> Result<(), String> { let [_, _, key] = op.path.as_slice() else { return Err(format!("it writes {}, no event's place", shown(&op.path))); }; @@ -309,12 +315,10 @@ mod tests { // Again, at a key held already: refused. Automerge writes no put of the value a // key holds, so the change is one made by hand. let heads = doc.get_heads(); - let at = At::new(&doc, &heads).unwrap(); + let at = crate::document::at::At::new(&doc, &heads).unwrap(); let path = meta::path(&[meta::EVENTS, &key]); - let again = Change { - hash: crate::document::ChangeHash([0; 32]), - deps: &heads, - seen: &heads, + let again = Unit { + id: [0; 32], committer: Some("node-b"), user: None, paths: &std::collections::BTreeSet::from([path.clone()]), diff --git a/src/access/rules.rs b/src/access/rules.rs index 9597774..cda7111 100644 --- a/src/access/rules.rs +++ b/src/access/rules.rs @@ -28,6 +28,11 @@ //! In a swarm without a user registry (`access::registry`), whatever a user would need, //! any member may. A change written while the document had no policy (at its //! dependencies) is judged by none: the rules hold from the policy on. +//! +//! The rules themselves (`judge_seen`) know of no change: they judge a unit, who made it, +//! for whom, and what it writes where, reading the document as its writer saw it. What is +//! Automerge's of it, a change, its hash, an epoch's root, the document at the change's +//! heads, is `judge`'s, which hands them on. use std::collections::{BTreeSet, HashMap}; @@ -60,6 +65,36 @@ pub(crate) struct Change<'a> { pub(crate) ops: &'a [Op], } +impl<'a> Change<'a> { + /// The change as the rules see it. + fn unit(&self) -> Unit<'a> { + Unit { + id: self.hash.0, + committer: self.committer, + user: self.user, + paths: self.paths, + ops: self.ops, + } + } +} + +/// What the rules judge, whatever kind of document it is of: who made it, for whom, and +/// what it writes where. With it they are given the document as its writer saw it +/// (`judge_seen`). +#[derive(Debug, Clone)] +pub(crate) struct Unit<'a> { + /// Its name, as its kind of document has it: a change's hash. + pub(crate) id: [u8; 32], + /// The node that made it (its node ID), as its signature proves. + pub(crate) committer: Option<&'a str>, + /// The user it names, if any. + pub(crate) user: Option<&'a str>, + /// What it touches. + pub(crate) paths: &'a BTreeSet, + /// Its writes, where each is and what it does there. + pub(crate) ops: &'a [Op], +} + /// Why a change is refused. #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) enum Refusal { @@ -78,14 +113,11 @@ impl std::fmt::Display for Refusal { } } -/// What `judge` reads at the heads a change is judged at, whatever the change: the same -/// for every change judged there, so read once (`judge_reading`). Each read at given -/// heads costs as much as working out what they cover, and screening judges most of a -/// batch at the same heads (`access::screen`). What the heads hold doesn't change as the -/// document takes more changes, so nothing here goes stale but by other heads. +/// What `judge_seen` reads of the document as a writer saw it, whatever is judged there: +/// the same for everything judged at that state, so read once. Nothing here goes stale +/// but by another state. #[derive(Debug, Default)] -pub(crate) struct Reads { - seen: Vec, +pub(crate) struct Seen { policy: Option, registry: Option, declared: Option>, @@ -96,20 +128,29 @@ pub(crate) struct Reads { caps: HashMap, } +/// What `judge` reads at the heads a change is judged at (`Seen`), kept while the heads +/// stay the same (`judge_reading`). Each read at given heads costs as much as working out +/// what they cover, and screening judges most of a batch at the same heads +/// (`access::screen`). What the heads hold doesn't change as the document takes more +/// changes. +#[derive(Debug, Default)] +pub(crate) struct Reads { + seen: Vec, + read: Seen, +} + impl Reads { /// Read at `seen`: what was read at other heads forgotten. - fn at(&mut self, seen: &[ChangeHash]) -> &mut Self { + fn at(&mut self, seen: &[ChangeHash]) -> &mut Seen { if self.seen != seen { *self = Self { seen: seen.to_vec(), - ..Self::default() + read: Seen::default(), }; } - self + &mut self.read } -} -impl Reads { /// Whether the policy at `seen` requires changes signed (`Policy::required`): read /// once for the heads, as `judge_reading` reads it. False if `doc` lacks one of them. pub(crate) fn required(&mut self, doc: &Document, seen: &[ChangeHash]) -> bool { @@ -128,7 +169,9 @@ pub(crate) fn judge(doc: &Document, epoch: Epoch, change: &Change<'_>) -> Result judge_reading(doc, epoch, change, &mut Reads::default()) } -/// `judge`, with what was read at the same heads before (`Reads`). +/// `judge`, with what was read at the same heads before (`Reads`): what is Automerge's +/// of judging a change, an epoch's root and the document as it was at the change's +/// heads; the rules are `judge_seen`'s. pub(crate) fn judge_reading( doc: &Document, epoch: Epoch, @@ -152,75 +195,80 @@ pub(crate) fn judge_reading( }; } let at = At::new(doc, change.seen).ok_or(Refusal::Unready)?; - let reads = reads.at(change.seen); + judge_seen(&at, epoch, &change.unit(), reads.at(change.seen)).map_err(Refusal::Rule) +} + +/// Judges `unit` by the rules, reading `at`, the document (of `epoch`) as its writer saw +/// it, with what was read of it before (`read`): why they refuse it, where they do. Not +/// an epoch's root, which writes what its document starts with and is judged by none. +pub(crate) fn judge_seen( + at: &impl ReadDoc, + epoch: Epoch, + unit: &Unit<'_>, + read: &mut Seen, +) -> Result<(), String> { // Written while the document had no policy (or one this node doesn't know): judged // as it was then, by none. History from before the policy stays as it is. - let policy = reads + let policy = read .policy - .get_or_insert_with(|| super::policy::of(&at)) + .get_or_insert_with(|| super::policy::of(at)) .clone(); // A swarm turns strict only at its start (`--bootstrap-policy`) or through a strict // remake, each its epoch's first change: so no change of a strict epoch is from // before its policy. - if !policy.strict() && turns_strict(change.ops) { - return Err(Refusal::Rule( - "a swarm turns strict only at its start or through a strict remake".to_owned(), - )); + if !policy.strict() && turns_strict(unit.ops) { + return Err("a swarm turns strict only at its start or through a strict remake".to_owned()); } // A swarm holding a store: judged by what its changes write. A swarm holds one from // its genesis change, or not at all. #[cfg(feature = "federation")] match policy { - Policy::Store(fold) => return super::holding::judge(&at, epoch, change, fold), - _ if super::holding::turns_store(change.ops) => { - return Err(Refusal::Rule( - "a swarm holds a store from its genesis change only".to_owned(), - )); + Policy::Store(fold) => return super::holding::judge(at, epoch, unit, fold), + _ if super::holding::turns_store(unit.ops) => { + return Err("a swarm holds a store from its genesis change only".to_owned()); } _ => {} } if !policy.enforced() { return Ok(()); } - let refuse = |why: String| Err(Refusal::Rule(why)); - let Some(node) = change.committer else { + let refuse = |why: String| Err(why); + let Some(node) = unit.committer else { return refuse("it names no node".to_owned()); }; - let banned = *reads + let banned = *read .banned .entry(node.to_owned()) - .or_insert_with(|| super::bans::banned(&at, node)); + .or_insert_with(|| super::bans::banned(at, node)); if banned { return refuse(format!("{node} is banned")); } let own_entry = meta::path(&[meta::MEMBERS, node]); - let member = *reads + let member = *read .member .entry(node.to_owned()) - .or_insert_with(|| store::read_path(&at, &own_entry).ok().flatten().is_some()); - let registering = change + .or_insert_with(|| store::read_path(at, &own_entry).ok().flatten().is_some()); + let registering = unit .paths .iter() .all(|path| path.starts_with(&own_entry) || *path == meta::path(&[meta::MEMBERS])); if !member && !registering { return refuse(format!("{node} isn't a member")); } - let registry = *reads.registry.get_or_insert_with(|| registry::exists(&at)); - if registry && let Some(user) = change.user { - reads - .caps + let registry = *read.registry.get_or_insert_with(|| registry::exists(at)); + if registry && let Some(user) = unit.user { + read.caps .entry(user.to_owned()) - .or_insert_with(|| registry::caps_of(&at, user)); + .or_insert_with(|| registry::caps_of(at, user)); } - reads - .declared - .get_or_insert_with(|| super::sealed::declared(&at)); - let reads = &*reads; + read.declared + .get_or_insert_with(|| super::sealed::declared(at)); + let read = &*read; // Whether the user may write `path`: as the registry at its dependencies says, or, // without one, any member. - let user_may = |path: &Path| match (registry, change.user) { + let user_may = |path: &Path| match (registry, unit.user) { (false, _) => true, - (true, Some(user)) => reads + (true, Some(user)) => read .caps .get(user) .is_some_and(|caps| caps.allows(Right::Write, path)), @@ -228,36 +276,35 @@ pub(crate) fn judge_reading( }; // Maps made on the way to what the change writes, where there were none // (`store::write_path` makes them): judged by what is written within them. - let on_the_way: BTreeSet<&Path> = change + let on_the_way: BTreeSet<&Path> = unit .paths .iter() .filter(|path| { - let mut here = change.ops.iter().filter(|op| op.path == **path).peekable(); + let mut here = unit.ops.iter().filter(|op| op.path == **path).peekable(); here.peek().is_some() && here.all(|op| op.action == Action::MakeMap) - && change + && unit .paths .iter() .any(|other| other.len() > path.len() && other.starts_with(path)) - && store::read_path(&at, path).ok().flatten().is_none() + && store::read_path(at, path).ok().flatten().is_none() }) .collect(); // Whether the change only makes a map at `path`, where there is none. let made = |path: &Path| { - change - .ops + unit.ops .iter() .filter(|op| op.path == *path) .all(|op| op.action == Action::MakeMap) - && store::read_path(&at, path).ok().flatten().is_none() + && store::read_path(at, path).ok().flatten().is_none() }; - for path in change.paths { + for path in unit.paths { if on_the_way.contains(path) { continue; } if !meta::is_protocol(path) { if !user_may(path) { - return refuse(format!("{} may not write {}", who(change), shown(path))); + return refuse(format!("{} may not write {}", who(unit), shown(path))); } continue; } @@ -265,13 +312,13 @@ pub(crate) fn judge_reading( let owner = path.get(2).map(String::as_str); let allowed = match (part, owner) { // A member's entry, its votes: its own. Removing an entry, also a user's: one - // who may write it, or forgets the member in the same change + // who may write it, or forgets the member in the same unit // (`DELETE /peers/{pk}`, which needs `_continuum/forgotten` alone). (Some(meta::MEMBERS), Some(owner)) => { let forgetting = meta::path(&[meta::FORGOTTEN, owner]); owner == node || user_may(path) - || (change + || (unit .paths .iter() .any(|other| other.starts_with(&forgetting)) @@ -292,14 +339,12 @@ pub(crate) fn judge_reading( // Ending a session: a user its own (`DELETE /auth/session`); one who manages // users, anyone's. (Some(meta::LOGOUTS | meta::SESSIONS), Some(owner)) => { - change.user == Some(owner) - || user_may(path) - || user_may(&meta::path(&[meta::USERS])) + unit.user == Some(owner) || user_may(path) || user_may(&meta::path(&[meta::USERS])) } // Under a strict policy, a user's own entry, as an envelope: signed by the user // with only its keys changed (`envelope::check`, run by `signed_values`). (Some(meta::USERS), Some(owner)) - if path.len() == 3 && change.user == Some(owner) && policy.strict() => + if path.len() == 3 && unit.user == Some(owner) && policy.strict() => { true } @@ -307,8 +352,7 @@ pub(crate) fn judge_reading( // (the node it asks keeps that from one without a password there, which no // other node can tell). (Some(meta::USERS), Some(owner)) - if path.get(3).map(String::as_str) == Some("keys") - && change.user == Some(owner) => + if path.get(3).map(String::as_str) == Some("keys") && unit.user == Some(owner) => { true } @@ -320,19 +364,18 @@ pub(crate) fn judge_reading( // its snapshot names (`remake::switch`), where there is none. // Also by one who may write it (an operator aborting an expired remake, // or superseding it, `remake::api`). - Some("decision") => match coordinator(&at, id) { + Some("decision") => match coordinator(at, id) { Some(coordinator) => coordinator == node || user_may(path), None if user_may(path) => true, None => { - change - .paths + unit.paths .iter() .any(|other| other == &meta::path(&[meta::REMAKES, id, "proposal"])) - && store::read_path(&at, &meta::path(&[meta::REMAKES, id])) + && store::read_path(at, &meta::path(&[meta::REMAKES, id])) .ok() .flatten() .is_none() - && made_the_epoch(&at, epoch, id, node) + && made_the_epoch(at, epoch, id, node) } }, // The record, made where there is none, and its proposal, written where @@ -340,7 +383,7 @@ pub(crate) fn judge_reading( // one who may write them. None => made(path) || user_may(path), Some("proposal") => { - store::read_path(&at, &meta::path(&[meta::REMAKES, id, "proposal"])) + store::read_path(at, &meta::path(&[meta::REMAKES, id, "proposal"])) .ok() .flatten() .is_none() @@ -352,15 +395,15 @@ pub(crate) fn judge_reading( _ => user_may(path), }; if !allowed { - return refuse(format!("{} may not write {}", who(change), shown(path))); + return refuse(format!("{} may not write {}", who(unit), shown(path))); } } if policy.strict() { - signed_values(&at, change.ops).or_else(refuse)?; + signed_values(at, unit.ops).or_else(refuse)?; } - let declared = reads.declared.as_deref().unwrap_or_default(); + let declared = read.declared.as_deref().unwrap_or_default(); if !declared.is_empty() { - sealed_values(&at, declared, change.ops).or_else(refuse)?; + sealed_values(at, declared, unit.ops).or_else(refuse)?; } Ok(()) } @@ -439,7 +482,7 @@ pub(crate) fn judge_held( /// string put there that is one (or deleting what is there); nothing within one; nothing /// in an object nowhere to be found, which might be one. fn sealed_values( - at: &At<'_>, + at: &impl ReadDoc, declared: &[super::sealed::Declared], ops: &[Op], ) -> Result<(), String> { @@ -471,7 +514,7 @@ fn sealed_values( /// as a write replacing it does); nothing within one; above one, /// nothing replacing or deleting what holds one (a map made where there is none yet, /// what is inside a list or text, which holds none). -fn signed_values(at: &At<'_>, ops: &[Op]) -> Result<(), String> { +fn signed_values(at: &impl ReadDoc, ops: &[Op]) -> Result<(), String> { let signed = super::envelope::signed_paths(at); for op in ops { let path = &op.path; @@ -526,7 +569,7 @@ fn signed_values(at: &At<'_>, ops: &[Op]) -> Result<(), String> { /// Whether what is at `path` in `at` holds a value at a place for one its user signs, /// of `signed` (`envelope::signed_paths`), signed or from before the policy; one that /// doesn't read, as if it did. -fn holds_signed(at: &At<'_>, path: &[String], signed: &[Vec]) -> bool { +fn holds_signed(at: &impl ReadDoc, path: &[String], signed: &[Vec]) -> bool { fn within(value: &serde_json::Value, place: &mut Vec, signed: &[Vec]) -> bool { if super::envelope::is_signed(signed, place) { return true; @@ -551,8 +594,8 @@ fn holds_signed(at: &At<'_>, path: &[String], signed: &[Vec]) -> bool { } /// Who wrote it, for a refusal. -fn who(change: &Change<'_>) -> String { - match (change.committer, change.user) { +fn who(unit: &Unit<'_>) -> String { + match (unit.committer, unit.user) { (Some(node), Some(user)) => format!("{user} at {node}"), (Some(node), None) => node.to_owned(), (None, _) => "nobody".to_owned(), @@ -565,7 +608,7 @@ fn shown(path: &Path) -> String { /// Whether remake `id`, coordinated by `node`, made `epoch`: as its snapshot's metadata /// says (`remake::snapshot`), at `at`. Never genesis. -pub(super) fn made_the_epoch(at: &At<'_>, epoch: Epoch, id: &str, node: &str) -> bool { +pub(super) fn made_the_epoch(at: &impl ReadDoc, epoch: Epoch, id: &str, node: &str) -> bool { if epoch.generation == 0 { return false; } @@ -584,7 +627,7 @@ pub(super) fn made_the_epoch(at: &At<'_>, epoch: Epoch, id: &str, node: &str) -> } /// The coordinator remake `id`'s proposal names, at `at`. -pub(super) fn coordinator(at: &At<'_>, id: &str) -> Option { +pub(super) fn coordinator(at: &impl ReadDoc, id: &str) -> Option { let proposal = store::read_path(at, &meta::path(&[meta::REMAKES, id, "proposal"])) .ok() .flatten()?; -- cgit v1.3.1