diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/access/rules.rs | 227 | ||||
| -rw-r--r-- | src/document/changes.rs | 12 | ||||
| -rw-r--r-- | src/document/store.rs | 78 | ||||
| -rw-r--r-- | src/simtest/policy.rs | 19 |
4 files changed, 81 insertions, 255 deletions
diff --git a/src/access/rules.rs b/src/access/rules.rs index 1df1d58..6844dc9 100644 --- a/src/access/rules.rs +++ b/src/access/rules.rs @@ -29,14 +29,13 @@ //! 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. -use std::collections::{BTreeSet, HashMap, HashSet}; +use std::collections::{BTreeSet, HashMap}; use crate::access::policy::Policy; use crate::access::registry; use crate::access::sealed::Declared; use crate::access::{Caps, Right}; use crate::document::at::At; -use crate::document::changes::in_history; use crate::document::inspect::{Action, Op, Path}; use crate::document::meta; use crate::document::replica::Epoch; @@ -95,12 +94,6 @@ pub(crate) struct Reads { member: HashMap<String, bool>, /// By user: what the registry lets it do. caps: HashMap<String, Caps>, - /// Whether the document's own policy, at its heads then, is strict - /// (`before_strict`): kept across `seen`, read again once the document takes more. - strict_now: Option<(Vec<ChangeHash>, bool)>, - /// The changes that turned the document strict, at its heads then (`turned_strict`): - /// kept as `strict_now` is. - turned_now: Option<(Vec<ChangeHash>, Vec<ChangeHash>)>, } impl Reads { @@ -109,35 +102,11 @@ impl Reads { if self.seen != seen { *self = Self { seen: seen.to_vec(), - strict_now: self.strict_now.take(), - turned_now: self.turned_now.take(), ..Self::default() }; } self } - - /// Whether `doc`'s policy, as it stands, is strict: read once for its heads. - fn strict_now(&mut self, doc: &Document) -> bool { - let heads = doc.get_heads(); - match &self.strict_now { - Some((at, strict)) if *at == heads => *strict, - _ => { - let strict = super::policy::of(doc).strict(); - self.strict_now = Some((heads, strict)); - strict - } - } - } - - /// The changes that turned `doc` strict (`turned_strict`): found once for its heads. - fn turned_now(&mut self, doc: &Document) -> &[ChangeHash] { - let heads = doc.get_heads(); - if self.turned_now.as_ref().is_none_or(|(at, _)| *at != heads) { - self.turned_now = Some((heads, turned_strict(doc))); - } - &self.turned_now.as_ref().expect("just found").1 - } } impl Reads { @@ -190,11 +159,13 @@ pub(crate) fn judge_reading( .policy .get_or_insert_with(|| super::policy::of(&at)) .clone(); - if !policy.strict() - && reads.strict_now(doc) - && let Some(why) = before_strict(doc, change, reads.turned_now(doc)) - { - return Err(Refusal::Rule(why)); + // 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.enforced() { return Ok(()); @@ -382,52 +353,20 @@ pub(crate) fn judge_reading( Ok(()) } -/// Why `change`, written under a policy that isn't strict, is refused where `doc`'s is: -/// a change that turned the swarm strict is beside it, neither in its history nor -/// built on it. Nothing is added to the time before a swarm turned strict, so nothing -/// planted there can stand where every value is its user's to sign; what a node held of -/// it beside that change it drops, once told (`swarm::refusals`). A policy written again -/// later, strict over strict, names the same change; one written beside it, strict or -/// not, is refused like any other, so a change made later to look as old can't take its -/// place. A swarm strict from its genesis change (`--bootstrap-policy`) has no such -/// time. Asked only where `doc`'s policy is strict: elsewhere, nothing changes. -fn before_strict(doc: &Document, change: &Change<'_>, turned: &[ChangeHash]) -> Option<String> { - let held = crate::document::changes::holds(doc, &change.hash); - let beside = turned.iter().find(|turned| { - **turned != change.hash - && !in_history(doc, turned, change.deps) - && !(held && in_history(doc, &change.hash, std::slice::from_ref(turned))) - })?; - Some(format!( - "written before the swarm turned strict, beside the change that turned it ({beside})" - )) -} - -/// The changes that turned `doc` strict: each wrote a strict policy where the one at its -/// history wasn't. Found by following back the writes of what the policy holds, each -/// write's history in turn, so every one is found however often the policy was written -/// since. -fn turned_strict(doc: &Document) -> Vec<ChangeHash> { - let path = super::policy::path(); - let strict_at = |heads: &[ChangeHash]| { - At::new(doc, heads).is_some_and(|at| super::policy::of(&at).strict()) - }; - let made = store::made(doc); - let mut turned = Vec::new(); - let mut looked: HashSet<ChangeHash> = HashSet::new(); - let mut writes = store::writers(&made, doc, &path); - while let Some((hash, deps)) = writes.pop() { - if !looked.insert(hash) { - continue; - } - if strict_at(&[hash]) && !strict_at(&deps) { - turned.push(hash); - } - if let Some(before) = At::new(doc, &deps) { - writes.extend(store::writers(&made, &before, &path)); - } - } - turned +/// Whether `ops` write a strict policy (`access::policy`): `"signed"` at its `values`, or +/// an envelope at its place asking for signed values. +fn turns_strict(ops: &[Op]) -> bool { + let policy = super::policy::path(); + let mut values = policy.clone(); + values.push("values".to_owned()); + ops.iter().any(|op| match &op.action { + Action::PutString(text) if op.path == values => text == "signed", + Action::PutString(text) if op.path == policy => crate::document::signed::read(text) + .is_some_and(|payload| { + payload.value.get("values") == Some(&serde_json::Value::from("signed")) + }), + _ => false, + }) } /// `hash`, which `doc` (of `epoch`) holds, judged by its rules now, as received: why @@ -550,8 +489,8 @@ fn signed_values(at: &At<'_>, ops: &[Op]) -> Result<(), String> { let checked = super::envelope::check(at, envelope, path, previous.as_deref()) .map_err(|why| format!("{}: {why}", shown(path)))?; // A strict swarm stays strict: its policy is written again only as strict, - // never relaxed nor deleted, so the time before it turned strict stays what - // it was (`before_strict`). + // never relaxed nor deleted, as it turns strict only by its epoch's first + // change (`turns_strict`). if *path == super::policy::path() && !super::policy::read(&checked.payload.value).strict() { @@ -1246,80 +1185,62 @@ mod tests { assert!(judged(&doc, "stranger", Some("mallory"), &["notes/x"]).is_ok()); } - /// Once a swarm turned strict, a change written before it, beside the change that - /// turned it, is refused, received or held: nothing is added to the time before. What - /// is in that change's history stands. A swarm that isn't strict judges as before. + /// A swarm turns strict only at its start or through a strict remake: a change + /// writing a strict policy where the policy isn't strict is refused, written as a map + /// or signed; one that isn't strict, as before. #[test] - fn nothing_added_before_a_strict_policy() { + fn a_swarm_turns_strict_only_at_its_start() { let mut doc = Document::new(); write(&mut doc, "_continuum/swarm", json!("s")); write(&mut doc, "_continuum/members/genesis", json!({"since": 1})); - let before = doc.get_heads(); - write(&mut doc, "notes/kept", json!(1)); - // Beside it: what turns the swarm strict, and a change the node holds already. - let mut beside = doc.fork_at(&before).unwrap(); - write(&mut beside, "notes/beside", json!(2)); - let planted = beside.get_heads()[0]; - let kept = doc.get_heads()[0]; - // A policy that isn't strict: the change beside stands. - let mut open = doc.clone(); - write(&mut open, "_continuum/access/policy", json!({"version": 1})); - open.merge(&mut beside.clone()).unwrap(); - assert_eq!(judge_held(&open, Epoch::GENESIS, &planted), Some(Ok(()))); - write( - &mut doc, - "_continuum/access/policy", - json!({"version": 1, "values": "signed"}), - ); - doc.merge(&mut beside).unwrap(); - assert!(matches!( - judge_held(&doc, Epoch::GENESIS, &planted), - Some(Err(_)) - )); - assert_eq!(judge_held(&doc, Epoch::GENESIS, &kept), Some(Ok(()))); - // The policy written again, by a change that saw the one beside: the change that - // turned the swarm strict is still the one, and the one beside still refused. - let mut again = doc.clone(); - write( - &mut again, - "_continuum/access/policy", - json!({"version": 1, "values": "signed"}), - ); - assert!(matches!( - judge_held(&again, Epoch::GENESIS, &planted), - Some(Err(_)) - )); - assert_eq!(judge_held(&again, Epoch::GENESIS, &kept), Some(Ok(()))); - // Turned strict beside it too: refused all the same, so a change made later to - // look as old can't take its place. - let mut rival = beside.fork_at(&before).unwrap(); - write( - &mut rival, + write(&mut doc, "_continuum/access/policy", json!({"version": 1})); + let judged = |ops: Vec<Op>| { + let deps = doc.get_heads(); + let touched: BTreeSet<Path> = ops.iter().map(|op| op.path.clone()).collect(); + judge( + &doc, + Epoch::GENESIS, + &Change { + hash: ChangeHash([9; 32]), + deps: &deps, + seen: &deps, + committer: Some("genesis"), + user: None, + paths: &touched, + ops: &ops, + }, + ) + }; + let op = |at: &str, action: Action| Op { + path: path(at), + action, + }; + assert!(refused(judged(vec![op( + "_continuum/access/policy/values", + Action::PutString("signed".to_owned()) + )]))); + let envelope = |value: serde_json::Value| { + use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; + let meta = json!({"swarm": "s", "path": ["_continuum", "access", "policy"], + "user": "alice", "at": 1, "seq": 0, "prev": ""}); + format!( + "{}{}.{}.c2ln", + crate::document::signed::START, + URL_SAFE_NO_PAD.encode(value.to_string()), + URL_SAFE_NO_PAD.encode(meta.to_string()) + ) + }; + assert!(refused(judged(vec![op( "_continuum/access/policy", - json!({"version": 1, "values": "signed"}), + Action::PutString(envelope(json!({"version": 1, "values": "signed"}))) + )]))); + assert!( + judged(vec![op( + "_continuum/access/policy/signatures", + Action::PutString("required".to_owned()) + )]) + .is_ok() ); - let rival_hash = rival.get_heads()[0]; - let mut both = doc.clone(); - both.merge(&mut rival).unwrap(); - assert!(matches!( - judge_held(&both, Epoch::GENESIS, &rival_hash), - Some(Err(_)) - )); - // Received, from the time before: refused too. - let touched = paths(&["notes/late"]); - assert!(refused(judge( - &doc, - Epoch::GENESIS, - &Change { - hash: ChangeHash([9; 32]), - deps: &before, - seen: &before, - committer: Some("genesis"), - user: None, - paths: &touched, - ops: &[], - }, - ))); } /// A map made on the way to what is written, where there was none: judged by what is diff --git a/src/document/changes.rs b/src/document/changes.rs index e1cbe21..800ea19 100644 --- a/src/document/changes.rs +++ b/src/document/changes.rs @@ -28,18 +28,6 @@ pub(crate) fn holds_all(doc: &impl ReadDoc, heads: &[ChangeHash]) -> bool { heads.iter().all(|head| holds(doc, head)) } -/// Whether `hash` is in the history of `heads`, which `doc` holds: one of them, or one -/// they build on. -pub(crate) fn in_history(doc: &Document, hash: &ChangeHash, heads: &[ChangeHash]) -> bool { - heads.contains(hash) - || (holds(doc, hash) - && holds_all(doc, heads) - && !doc - .get_changes(heads) - .iter() - .any(|later| later.hash() == *hash)) -} - /// Whether the history of `theirs` (of them, those `doc` has) holds all of `ours` /// (heads of `doc`): a peer at `theirs` has every change we have. pub(crate) fn covers(doc: &Document, theirs: &[ChangeHash], ours: &[ChangeHash]) -> bool { diff --git a/src/document/store.rs b/src/document/store.rs index a9d4379..77d5c81 100644 --- a/src/document/store.rs +++ b/src/document/store.rs @@ -297,84 +297,6 @@ fn policy_asks(doc: &impl ReadDoc, value: &Value<'_>, id: &ObjId) -> bool { } } -/// Every change a document holds, by its writer and the numbers of its operations, with -/// the changes it builds on: read once for any number of [`writers`]. -pub(crate) struct Made( - Vec<( - ActorId, - std::ops::Range<u64>, - automerge::ChangeHash, - Vec<automerge::ChangeHash>, - )>, -); - -/// What `doc` holds, for [`writers`]. -pub(crate) fn made(doc: &Automerge) -> Made { - Made( - doc.get_changes(&[]) - .into_iter() - .map(|change| { - let start = change.start_op().get(); - ( - change.actor_id().clone(), - start..start + change.len() as u64, - change.hash(), - change.deps().to_vec(), - ) - }) - .collect(), - ) -} - -/// The changes, of those `made` has, that wrote what `path` holds as `view` shows it: -/// each value written there at once and, of a map, every key within it, all the way -/// down; each with the changes it builds on. -pub(crate) fn writers( - made: &Made, - view: &impl ReadDoc, - path: &[String], -) -> Vec<(automerge::ChangeHash, Vec<automerge::ChangeHash>)> { - let mut ids = Vec::new(); - if let Some((leaf, parents)) = path.split_last() - && let Ok(Some(Resolved::Maps(maps))) = resolve_through(view, parents) - { - operations_within(view, &maps, leaf.as_str().into(), &mut ids); - } - made.0 - .iter() - .filter(|(actor, ops, _, _)| { - ids.iter() - .any(|(counter, by)| by == actor && ops.contains(counter)) - }) - .map(|(_, _, hash, deps)| (*hash, deps.clone())) - .collect() -} - -/// The operations that wrote `prop` of `parents` as `view` shows it, and, of a map, -/// every key within it. -fn operations_within( - view: &impl ReadDoc, - parents: &[ObjId], - prop: Prop, - ids: &mut Vec<(u64, ActorId)>, -) { - for parent in parents { - let Ok(all) = view.get_all(parent, prop.clone()) else { - continue; - }; - for (value, id) in all { - if let ObjId::Id(counter, actor, _) = &id { - ids.push((*counter, actor.clone())); - } - if matches!(value, Value::Object(ObjType::Map)) { - for key in view.keys(&id) { - operations_within(view, std::slice::from_ref(&id), key.into(), ids); - } - } - } - } -} - /// What `prop` of `parent` holds as a read shows it, of the values written there at /// once (`candidates`): the value, and its operation's ID. pub(crate) fn shown( diff --git a/src/simtest/policy.rs b/src/simtest/policy.rs index e5665cd..8f89b39 100644 --- a/src/simtest/policy.rs +++ b/src/simtest/policy.rs @@ -261,10 +261,10 @@ async fn plain(node: &AppState, at: &str) -> Option<serde_json::Value> { .flatten() } -/// A strict swarm (`"values": "signed"`), its first user's key given at genesis: values -/// signed by their user go everywhere, before and after a remake, which carries them -/// over; a node writing the registry plain, for a user that may, gets nothing past the -/// others. +/// A strict swarm (`"values": "signed"`), strict from its genesis change with its first +/// user's key: values signed by their user go everywhere, before and after a remake, +/// which carries them over; a node writing the registry plain, for a user that may, gets +/// nothing past the others. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn a_strict_swarm() { let key = ed25519_dalek::SigningKey::from_bytes(&[11; 32]); @@ -276,6 +276,7 @@ async fn a_strict_swarm() { [("laptop".to_owned(), line.clone())].into(), )] .into(); + config.first_policy = Some(json!({"version": 1, "values": "signed"})); }); let b = sim.start("b", &["a"], Start::Join); let c = sim.start("c", &["a"], Start::Join); @@ -293,20 +294,14 @@ async fn a_strict_swarm() { } }) .await; - write_as( + write_signed( &a, "alice", + &key, "_continuum/access/userSigned", json!([["config"]]), ) .await; - write_as( - &a, - "alice", - "_continuum/access/policy", - json!({"version": 1, "values": "signed"}), - ) - .await; sim.wait_converged(&[&a, &b, &c], SOON).await; // Signed, on any node: everywhere. |
