diff options
| author | tv <tv@krebsco.de> | 2026-11-16 19:38:26 +0000 |
|---|---|---|
| committer | tv <tv@krebsco.de> | 2026-11-16 21:25:23 +0100 |
| commit | 3fccc4f6859cf0b4d93e7d166142e1ab9255723f (patch) | |
| tree | 7a76c8bfe5b186ec063feb8e454de583f0c87ff5 /src | |
| parent | 69d2aace79eb61d800afa3a0779cfe3a9dfe1039 (diff) | |
access: what a change of a swarm holding a store writes
Every node judges a change of a swarm holding a store by what it writes, at its history
(`docs/store.md`, What a change writes), in place of rules by path: `access::holding`.
It writes events, each at `_continuum/events/<ID>` the bytes whose SHA-256 that is, no
larger than the fold allows (the federation's 256 KiB), at a key held nowhere at the
change's history; and its node's entry, with the member list's map where there is none.
Everything else is refused, as closed: values outside `_continuum`, the policy, the
swarm's ID, users, bans, the topology, remakes and their acks. Nothing deletes or
replaces an event. A change names its node; the genesis change's writer names none, so
no change under it is taken but the genesis change.
In a swarm not holding a store, a change writing a policy naming one is refused: a swarm
holds a store from its genesis change, or not at all.
The inspector tells a put of bytes apart (`Action::PutBytes`), with the bytes, for the
events' check. All of it behind the `federation` feature.
Diffstat (limited to 'src')
| -rw-r--r-- | src/access/holding.rs | 282 | ||||
| -rw-r--r-- | src/access/mod.rs | 2 | ||||
| -rw-r--r-- | src/access/rules.rs | 12 | ||||
| -rw-r--r-- | src/document/events.rs | 10 | ||||
| -rw-r--r-- | src/document/inspect.rs | 5 |
5 files changed, 311 insertions, 0 deletions
diff --git a/src/access/holding.rs b/src/access/holding.rs new file mode 100644 index 0000000..8e58b66 --- /dev/null +++ b/src/access/holding.rs @@ -0,0 +1,282 @@ +//! What a change of a swarm holding a store writes (`docs/store.md`, What a change writes), +//! judged by every node by the change and its history alone, in place of rules by path +//! (`rules::judge`). It writes nothing but: +//! +//! * events: at `_continuum/events/<ID>` the bytes whose ID (SHA-256) it is, no more than +//! the fold allows, at a key held nowhere at the change's history; +//! * its node's entry (`_continuum/members/<node ID>`), and the member list's map where +//! there is none. +//! +//! Everything else is closed: whatever isn't under `_continuum`, the policy, the swarm's +//! ID, users, bans, the swarm's topology, remakes and their acks. Nothing deletes or +//! replaces an event. A change names its node, as signed (signatures are required): the +//! genesis change's writer (`document::events`) names none, so no change under it is +//! taken but the genesis change, which the epoch's root is. Which events the store takes +//! is the store's (`federation::held`); this judges none. +//! +//! In a swarm not holding a store, no change writes a policy naming one (`turns_store`): +//! a swarm holds a store from its genesis change, or not at all. + +use sha2::{Digest, Sha256}; + +use super::rules::{Change, Refusal}; +use crate::document::at::At; +use crate::document::inspect::{Action, Op, Path}; +use crate::document::{meta, store}; + +/// The most bytes an event of the fold `fold` may have. +fn largest(fold: &str) -> usize { + use crate::federation::store::Fold; + match fold { + crate::federation::fold::Federation::NAME => crate::federation::fold::Federation::LARGEST, + _ => 0, + } +} + +/// Judges `change`, of a swarm holding a store of the fold `fold`, at its history `at`. +pub(crate) fn judge(at: &At<'_>, change: &Change<'_>, fold: &str) -> Result<(), Refusal> { + let refuse = |why: String| Err(Refusal::Rule(why)); + let Some(node) = change.committer else { + return refuse("it names no node".to_owned()); + }; + let events = meta::path(&[meta::EVENTS]); + let members = meta::path(&[meta::MEMBERS]); + let entry = meta::path(&[meta::MEMBERS, node]); + for op in change.ops { + let allowed = if op.path.starts_with(&events) { + event(at, op, fold) + } else if op.path.starts_with(&entry) { + Ok(()) + } else if op.path == members { + // The member list's map, made where there is none. + if op.action == Action::MakeMap && !store::held_anywhere(at, &members) { + Ok(()) + } else { + Err("it writes the member list".to_owned()) + } + } else { + Err(format!("it writes {}, closed", shown(&op.path))) + }; + allowed.or_else(|why| refuse(format!("{node}: {why}")))?; + } + Ok(()) +} + +/// 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> { + let [_, _, key] = op.path.as_slice() else { + return Err(format!("it writes {}, no event's place", shown(&op.path))); + }; + let Action::PutBytes(bytes) = &op.action else { + return Err(format!("it writes {}, no event's bytes", shown(&op.path))); + }; + if bytes.len() > largest(fold) { + return Err(format!( + "an event of {} bytes, more than {} allows", + bytes.len(), + fold + )); + } + if hex(&Sha256::digest(bytes)) != *key { + return Err(format!("an event at {key}, which isn't its ID")); + } + if store::held_anywhere(at, &op.path) { + return Err(format!("an event at {key}, held there already")); + } + Ok(()) +} + +fn hex(bytes: &[u8]) -> String { + bytes.iter().map(|byte| format!("{byte:02x}")).collect() +} + +fn shown(path: &Path) -> String { + format!("/{}", path.join("/")) +} + +/// Whether `ops` write a policy naming a store: anything at its `store`, or an envelope +/// at its place naming one. +pub(crate) fn turns_store(ops: &[Op]) -> bool { + let policy = super::policy::path(); + let mut store = policy.clone(); + store.push("store".to_owned()); + ops.iter().any(|op| match &op.action { + _ if op.path.starts_with(&store) => true, + Action::PutString(text) if op.path == policy => crate::document::signed::read(text) + .is_some_and(|payload| payload.value.get("store").is_some()), + _ => false, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::clock::UnixMillis; + use crate::document::replica::{Epoch, Writer, transact}; + use crate::document::store::StoreError; + use crate::document::typed::{TimestampFormat, Val}; + use crate::document::{Document, ScalarValue, Transaction, events}; + use crate::federation::store::Id; + use serde_json::json; + + const ROOT: &[u8] = b"{\"a root\":true}"; + + /// A swarm holding a store, from its genesis change. + fn swarm() -> Document { + events::started("federation", ROOT).unwrap() + } + + /// The change `node` writes to `doc` with `f`, judged as every node judges it. + fn judged( + doc: &mut Document, + node: &str, + f: impl FnOnce(&mut Transaction<'_>) -> Result<(), StoreError>, + ) -> Result<(), String> { + let before = doc.get_heads(); + transact(doc, UnixMillis(1), &Writer { node, user: None }, f).unwrap(); + let after = doc.get_heads(); + assert_ne!(after, before, "no change written"); + super::super::rules::judge_held(doc, Epoch::GENESIS, &after[0]).unwrap() + } + + fn put(doc: &mut Transaction<'_>, key: &str, bytes: &[u8]) -> Result<(), StoreError> { + store::write_val_path( + doc, + &meta::path(&[meta::EVENTS, key]), + &Val::Scalar(ScalarValue::Bytes(bytes.to_vec())), + store::Writing::sticky(TimestampFormat::default()), + ) + .map(|_| ()) + } + + #[test] + fn a_change_puts_events_at_their_ids() { + let event = b"an event".to_vec(); + let id = Id::of(&event); + let key = id.to_string(); + let mut doc = swarm(); + let mut beside = doc.fork(); + assert_eq!( + judged(&mut doc, "node-a", |doc| put(doc, &key, &event)), + Ok(()) + ); + // The same, by another at once: one event. + assert_eq!( + judged(&mut beside, "node-b", |doc| put(doc, &key, &event)), + Ok(()) + ); + // Again, at a key held already: refused. + assert!( + judged(&mut doc, "node-a", |doc| { + events::put_held(doc, &id, &event); + Ok(()) + }) + .is_err() + ); + // At another key, or too large: refused. + let mut doc = swarm(); + assert!( + judged(&mut doc, "node-a", |doc| put( + doc, + &Id::of(b"else").to_string(), + &event + )) + .is_err() + ); + let mut doc = swarm(); + let large = vec![b' '; crate::federation::event::LARGEST + 1]; + assert!( + judged(&mut doc, "node-a", |doc| put( + doc, + &Id::of(&large).to_string(), + &large + )) + .is_err() + ); + // A string, not bytes: refused. + let mut doc = swarm(); + assert!( + judged(&mut doc, "node-a", |doc| { + store::write_path(doc, &meta::path(&[meta::EVENTS, &key]), &json!("an event")) + }) + .is_err() + ); + } + + #[test] + fn nothing_deletes_or_replaces_an_event() { + let root = Id::of(ROOT).to_string(); + let mut doc = swarm(); + assert!( + judged(&mut doc, "node-a", |doc| { + store::delete_path(doc, &meta::path(&[meta::EVENTS, &root]), false) + }) + .is_err() + ); + let mut doc = swarm(); + assert!(judged(&mut doc, "node-a", |doc| put(doc, &root, b"other bytes")).is_err()); + } + + #[test] + fn a_node_writes_its_own_entry_and_nothing_else() { + let entry = |node: &str| meta::path(&[meta::MEMBERS, node]); + let mut doc = swarm(); + assert_eq!( + judged(&mut doc, "node-a", |doc| { + store::write_path(doc, &entry("node-a"), &json!({"alias": "a"})) + }), + Ok(()) + ); + assert!( + judged(&mut doc, "node-a", |doc| { + store::write_path(doc, &entry("node-b"), &json!({})) + }) + .is_err() + ); + for closed in [ + vec!["config".to_owned()], + meta::path(&[meta::USERS, "alice"]), + meta::path(&[meta::SWARM]), + meta::path(&[meta::NEIGHBOURS]), + meta::path(&[meta::VOTES, "node-a"]), + crate::access::policy::path(), + ] { + let mut doc = swarm(); + assert!( + judged(&mut doc, "node-a", |doc| store::write_path( + doc, + &closed, + &json!(1) + )) + .is_err(), + "{closed:?}" + ); + } + } + + #[test] + fn a_swarm_turns_into_no_store() { + let mut doc = Document::new(); + transact( + &mut doc, + UnixMillis(1), + &Writer { + node: "node-a", + user: None, + }, + |doc| store::write_path(doc, &meta::path(&[meta::SWARM]), &json!("s")), + ) + .unwrap(); + assert!( + judged(&mut doc, "node-a", |doc| { + store::write_path( + doc, + &crate::access::policy::path(), + &events::policy("federation"), + ) + }) + .is_err() + ); + } +} diff --git a/src/access/mod.rs b/src/access/mod.rs index cc6b7a2..65c3817 100644 --- a/src/access/mod.rs +++ b/src/access/mod.rs @@ -17,6 +17,8 @@ use crate::document::meta; pub(crate) mod bans; pub(crate) mod challenge; pub(crate) mod envelope; +#[cfg(feature = "federation")] +pub(crate) mod holding; pub(crate) mod policy; pub(crate) mod registry; pub(crate) mod rules; diff --git a/src/access/rules.rs b/src/access/rules.rs index 6844dc9..d1edfd5 100644 --- a/src/access/rules.rs +++ b/src/access/rules.rs @@ -167,6 +167,18 @@ pub(crate) fn judge_reading( "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, 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(), + )); + } + _ => {} + } if !policy.enforced() { return Ok(()); } diff --git a/src/document/events.rs b/src/document/events.rs index 7b0fe5e..2b3a7e0 100644 --- a/src/document/events.rs +++ b/src/document/events.rs @@ -117,6 +117,16 @@ pub(crate) fn is_genesis(change: &Change, fold: &str, id: &Id) -> bool { root.is_some_and(|root| genesis(fold, &root).hash() == change.hash()) } +/// Puts `bytes` at the event `id`, held there or not, as no change of a node puts an +/// event: for tests of what a change may write. +#[cfg(test)] +pub(crate) fn put_held(doc: &mut super::Transaction<'_>, id: &Id, bytes: &[u8]) { + use automerge::transaction::Transactable; + let events = events_map(doc).expect("the events' map"); + doc.put(&events, id.to_string(), ScalarValue::Bytes(bytes.to_vec())) + .expect("a put"); +} + #[cfg(test)] mod tests { use super::*; diff --git a/src/document/inspect.rs b/src/document/inspect.rs index ffdf536..350b69c 100644 --- a/src/document/inspect.rs +++ b/src/document/inspect.rs @@ -36,6 +36,8 @@ pub(crate) enum Action { MakeMap, /// Puts a string there. PutString(String), + /// Puts bytes there. + PutBytes(Vec<u8>), /// Deletes what is there. Delete, /// Changes what is there, a list or text it is in (`Place::in_list`). @@ -198,6 +200,9 @@ impl<'a> Inspector<'a> { OpType::Put(automerge::ScalarValue::Str(text)) => { Action::PutString(text.to_string()) } + OpType::Put(automerge::ScalarValue::Bytes(bytes)) => { + Action::PutBytes(bytes.clone()) + } OpType::Delete => Action::Delete, _ => Action::Other, }, |
