From 753d41ace7a90098717fac862089da47fc509f84 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 11 Oct 2026 23:03:58 -0500 Subject: [PATCH 01/40] docs(id): start phase 2, membership, auth frontier, and delegation [phase 2 start] --- ...2026-10-12T04-03-47Z_phase_2_membership.md | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 doc/2026-10-12T04-03-47Z_phase_2_membership/2026-10-12T04-03-47Z_phase_2_membership.md diff --git a/doc/2026-10-12T04-03-47Z_phase_2_membership/2026-10-12T04-03-47Z_phase_2_membership.md b/doc/2026-10-12T04-03-47Z_phase_2_membership/2026-10-12T04-03-47Z_phase_2_membership.md new file mode 100644 index 0000000000..5e342ebdca --- /dev/null +++ b/doc/2026-10-12T04-03-47Z_phase_2_membership/2026-10-12T04-03-47Z_phase_2_membership.md @@ -0,0 +1,41 @@ +# Phase 2: membership, auth frontier, and delegation + +- Plan: [phased plan](../../2026-10-11T11-08-42Z_design_remaining_work/plan-phases.md), section 7. +- Start commit: `8bea0731` (phase-1 head at the start of Phase 2; Phase 1 was still in its final fix, see its record). +- Base branch: `phase-2`. Track branches: `p2-auth` (P2.1, P2.2), `p2-friend` (P2.4), `p2-caps` (P2.6); `p2-voiding` (P2.3) and `p2-delegation` (P2.5) after the auth track; P2.7 and P2.8 at the end. +- Phase 1 fixes still in flight (p1-liveness) are merged into this branch when they land. + +## Steps + +| Step | Track | Status | Commits | Tests added | Notes | +| --------------------------------- | ---------- | ------ | ------- | ----------- | ------------------------------------- | +| P2.1 Auth-frontier mapping | auth | todo | | | | +| P2.2 Admission gate | auth | todo | | | | +| P2.3 Authority-based voiding | voiding | todo | | | replaces the Phase 1 rule | +| P2.4 Friendship cap and dissolve | friend | todo | | | | +| P2.5 Delegation modes | delegation | todo | | | | +| P2.6 World capabilities | caps | todo | | | use-count bounds dropped (decision 3) | +| P2.7 Cross-world reconciliation | later | todo | | | | +| P2.8 Property and mutation checks | later | todo | | | | + +## Decisions + +- Voiding is authority-based: a dependent is voided only when its author lost authority at the dependency's point (decision 1). +- Transfer on removal is derived from the signed removal (decision 2). +- Use-count bounds on world capabilities are dropped; enforcement stays local (decision 3). Content on removal is kept (decision 4). + +## Open questions + +- None yet. + +## Changes to the plan + +- None yet. + +## Review notes and regression tests + +- To be filled. + +## End + +- End commit and full test result: pending. From b3315bfab5ba68fb6e546c693a8d8d06b1561853 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 11 Oct 2026 23:17:09 -0500 Subject: [PATCH 02/40] feat(rust): friendship with a cap and a dissolve projection [P2.4] A pure module, src/friendship.rs, with no dependency on p2panda-auth. Requests are one-way and become a friendship on accept. Each account has at most MAX_FRIENDS friends. A removal names the requests it covers: naming the request that formed a friendship dissolves it on both sides, and naming an open request voids it. Each operation is judged against its own causal past. A removal wins over a concurrent accept of the request it names. Where concurrent accepts would exceed the cap, canonical order decides: causal order, then the smaller ID. The friend set is therefore the same for every delivery order. Tests cover the operations, the cap boundaries on both sides, S2 findings F2 to F5, and property tests over random operation sets. Three planted bugs were checked against the tests: the dissolve check removed, the requester side of the cap ignored, and the cap off by one. --- pkgs/id/proptest-regressions/friendship.txt | 7 + pkgs/id/src/friendship.rs | 1247 +++++++++++++++++++ pkgs/id/src/lib.rs | 1 + 3 files changed, 1255 insertions(+) create mode 100644 pkgs/id/proptest-regressions/friendship.txt create mode 100644 pkgs/id/src/friendship.rs diff --git a/pkgs/id/proptest-regressions/friendship.txt b/pkgs/id/proptest-regressions/friendship.txt new file mode 100644 index 0000000000..16330d29d5 --- /dev/null +++ b/pkgs/id/proptest-regressions/friendship.txt @@ -0,0 +1,7 @@ +# Seeds for failure cases proptest has generated in the past. It is +# automatically read and these particular cases re-run before any +# novel cases are generated. +# +# It is recommended to check this file in to source control so that +# everyone who runs the test benefits from these saved cases. +cc 8f1c16e287e31eaee32015dce22c133194284dda35ff888ce7e180a0592df0bc # shrinks to script = [(0, 2, 0, 0, 0), (0, 2, 3, 0, 0), (3, 0, 0, 0, 0), (1, 0, 0, 223, 7953), (1, 0, 0, 10820, 1808)], cap = 1 diff --git a/pkgs/id/src/friendship.rs b/pkgs/id/src/friendship.rs new file mode 100644 index 0000000000..0db5af14c3 --- /dev/null +++ b/pkgs/id/src/friendship.rs @@ -0,0 +1,1247 @@ +//! Friendship: one-way requests that become a friendship on accept, a cap on +//! friends per account, and a dissolve that ends a friendship on both sides. +//! +//! p2panda-auth has no member cap and no dissolve, so both are ours (S2, friendship). +//! The module is pure. Accounts and operation IDs are plain strings, and each +//! operation arrives already signed. Nothing here reads a clock or the network. +//! +//! The rules: +//! +//! - A request is one-way. It stays open until its recipient accepts or declines +//! it, or a removal names it. Two accounts have at most one open request, and no +//! request while they are friends. +//! - An accept makes a friendship if both accounts have fewer than the cap. +//! - A removal names the requests it covers, as the directory's `FriendRemove` +//! does. Naming a request voids it. Naming the request that formed a friendship +//! dissolves the friendship on both sides. A dissolved friendship is not revived +//! by an accept of its request. Only a new request makes a new friendship. +//! +//! Each operation is judged against the state of its own causal past: its `after` +//! set, closed transitively. A later operation cannot change what an earlier one +//! meant. Two things depend on the whole set rather than on arrival. A removal wins +//! over a concurrent accept of the request it names. Where concurrent accepts would +//! exceed the cap, the one that comes first in the canonical order is kept. That +//! order is causal order, with ties going to the smaller ID. So every server that +//! holds the same operations reaches the same friend set. + +use std::collections::{BTreeMap, BTreeSet}; + +/// The most friends one account may have. Our number, not p2panda-auth's. +pub const MAX_FRIENDS: usize = 100; + +/// An account ID. +pub type Account = String; + +/// An operation ID. A request's ID names the request. +pub type OpId = String; + +/// Two accounts, smaller first. +pub type Pair = (Account, Account); + +/// What an operation asks for. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Op { + /// `from` asks `to` to be friends. + Request { + /// The sender. + from: Account, + /// The recipient. + to: Account, + }, + /// The recipient `by` accepts `request`. + Accept { + /// The request accepted. + request: OpId, + /// The recipient, who must be the request's `to`. + by: Account, + }, + /// The recipient `by` declines `request`, which voids it. + Decline { + /// The request declined. + request: OpId, + /// The recipient, who must be the request's `to`. + by: Account, + }, + /// `by` ends its friendship with `other`, and voids the requests it names + /// between them. Naming the request that formed the friendship dissolves it. + Remove { + /// The account removing. + by: Account, + /// The other account. + other: Account, + /// The requests it covers. + requests: Vec, + }, +} + +/// An operation with its ID and the IDs it saw. The caller has checked the signature. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Signed { + /// The operation's ID. + pub id: OpId, + /// The IDs of the operations it saw, directly. + pub after: BTreeSet, + /// What it does. + pub op: Op, +} + +/// Why an operation had no effect. +#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] +pub enum Refusal { + /// A request to oneself. + #[error("no one befriends themselves")] + SelfRequest, + /// A removal of oneself. + #[error("no one removes themselves")] + SameAccount, + /// Only the recipient of a request may accept or decline it. + #[error("{by} is not the recipient of request {request}")] + NotRecipient { + /// The request. + request: OpId, + /// The account that tried to answer it. + by: Account, + }, + /// The request is not among the operations this one saw. + #[error("request {request} is not among the operations this one saw")] + UnknownRequest { + /// The request. + request: OpId, + }, + /// A removal names a request between two other accounts. + #[error("request {request} is not between these two accounts")] + NotThisPair { + /// The request. + request: OpId, + }, + /// The request was already accepted, declined or voided. + #[error("request {request} is no longer open")] + NotOpen { + /// The request. + request: OpId, + }, + /// A removal that names the request dissolved the friendship it formed. + #[error("request {request} was dissolved by a removal that names it")] + Dissolved { + /// The request. + request: OpId, + }, + /// The two accounts are already friends. + #[error("already friends")] + AlreadyFriends, + /// An open request already exists between the two accounts. + #[error("a request is already open between them")] + AlreadyOpen, + /// One account already has the maximum number of friends. + #[error("{account} already has {cap} friends")] + AtCap { + /// The account at the cap. + account: Account, + /// The cap that was reached. + cap: usize, + }, + /// The removal covers no friendship and no open request. + #[error("nothing to remove")] + NothingToRemove, +} + +/// What became of one operation. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Outcome { + /// It took effect. + Applied, + /// It had no effect. + Refused(Refusal), +} + +/// The operations are not a usable set. +#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] +pub enum ProjectError { + /// Two operations share an ID. + #[error("operation {0} appears twice")] + DuplicateId(OpId), + /// An operation names an ID that is not in the set. + #[error("operation {op} waits for {dependency}")] + MissingDependency { + /// The operation that names the missing one. + op: OpId, + /// The missing operation. + dependency: OpId, + }, + /// The `after` sets form a cycle. + #[error("the operations form a cycle")] + Cycle, +} + +/// The friend set that the operations determine, and what became of each one. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Projection { + friends: BTreeSet, + outcomes: BTreeMap, +} + +impl Projection { + /// Every friendship, as sorted pairs. + #[must_use] + pub fn friendships(&self) -> &BTreeSet { + &self.friends + } + + /// Whether two accounts are friends. + #[must_use] + pub fn are_friends(&self, a: &str, b: &str) -> bool { + self.friends.contains(&pair(a, b)) + } + + /// The friends of one account, sorted. + #[must_use] + pub fn friends_of(&self, account: &str) -> Vec { + let mut out: Vec = self + .friends + .iter() + .filter_map(|(a, b)| { + if a == account { + Some(b.clone()) + } else if b == account { + Some(a.clone()) + } else { + None + } + }) + .collect(); + out.sort(); + out + } + + /// What became of an operation, if it was in the set. + #[must_use] + pub fn outcome(&self, id: &str) -> Option<&Outcome> { + self.outcomes.get(id) + } +} + +/// Project signed operations to the friend set they determine. +/// +/// `ops` may come in any order. The result depends only on the operations and their +/// `after` sets. `cap` is the most friends one account may have. The product passes +/// [`MAX_FRIENDS`]. +pub fn project(ops: &[Signed], cap: usize) -> Result { + let by_id = index(ops)?; + let order = canonical_order(&by_id)?; + let past = pasts(&order); + + // Each operation is judged against its own causal past, which the canonical order + // has already settled. + let mut verdicts: BTreeMap<&str, Option> = BTreeMap::new(); + for &signed in &order { + let id = signed.id.as_str(); + let verdict = match static_refusal(signed, &by_id, &past[id]) { + Some(refusal) => Some(refusal), + None => check(&state_before(id, &order, &past, &verdicts), &signed.op, cap).err(), + }; + verdicts.insert(id, verdict); + } + + // A valid removal dissolves the friendship that its named request formed, whenever the + // removal arrived. So a removal wins over a concurrent accept. + let mut removed: BTreeSet<&str> = BTreeSet::new(); + for &signed in &order { + if let (Op::Remove { requests, .. }, None) = (&signed.op, &verdicts[signed.id.as_str()]) { + removed.extend(requests.iter().map(String::as_str)); + } + } + + // Accepts that survive are kept in canonical order, while both accounts are under the cap. + let mut friends: BTreeSet = BTreeSet::new(); + let mut kept: BTreeMap<&str, usize> = BTreeMap::new(); + let mut outcomes = BTreeMap::new(); + for &signed in &order { + let id = signed.id.as_str(); + let refusal = match verdicts[id].clone() { + Some(refusal) => Some(refusal), + None => match &signed.op { + Op::Accept { request, .. } => { + if removed.contains(request.as_str()) { + Some(Refusal::Dissolved { + request: request.clone(), + }) + } else if let Some((from, to)) = requested(request, &by_id, &past[id]) { + let p = pair(from, to); + let full = [from, to] + .into_iter() + .find(|account| kept.get(*account).copied().unwrap_or(0) >= cap); + if friends.contains(&p) { + Some(Refusal::AlreadyFriends) + } else if let Some(account) = full { + Some(Refusal::AtCap { + account: account.to_owned(), + cap, + }) + } else { + for account in [from, to] { + *kept.entry(account).or_insert(0) += 1; + } + friends.insert(p); + None + } + } else { + Some(Refusal::UnknownRequest { + request: request.clone(), + }) + } + } + _ => None, + }, + }; + outcomes.insert( + id.to_owned(), + refusal.map_or(Outcome::Applied, Outcome::Refused), + ); + } + Ok(Projection { friends, outcomes }) +} + +/// Operations by ID. +type Index<'a> = BTreeMap<&'a str, &'a Signed>; + +/// The causal past of each operation, by ID. +type Past<'a> = BTreeMap<&'a str, BTreeSet<&'a str>>; + +fn pair(a: &str, b: &str) -> Pair { + if a <= b { + (a.to_owned(), b.to_owned()) + } else { + (b.to_owned(), a.to_owned()) + } +} + +fn index(ops: &[Signed]) -> Result, ProjectError> { + let mut by_id = BTreeMap::new(); + for signed in ops { + if by_id.insert(signed.id.as_str(), signed).is_some() { + return Err(ProjectError::DuplicateId(signed.id.clone())); + } + } + Ok(by_id) +} + +/// A topological order that breaks ties by ID. It depends only on the operations. +fn canonical_order<'a>(by_id: &Index<'a>) -> Result, ProjectError> { + let mut waiting: BTreeMap<&str, usize> = BTreeMap::new(); + let mut dependents: BTreeMap<&str, Vec<&str>> = BTreeMap::new(); + for (&id, &signed) in by_id { + waiting.insert(id, signed.after.len()); + for dep in &signed.after { + if !by_id.contains_key(dep.as_str()) { + return Err(ProjectError::MissingDependency { + op: id.to_owned(), + dependency: dep.clone(), + }); + } + dependents.entry(dep.as_str()).or_default().push(id); + } + } + let mut ready: BTreeSet<&str> = waiting + .iter() + .filter(|(_, n)| **n == 0) + .map(|(id, _)| *id) + .collect(); + let mut order = Vec::with_capacity(by_id.len()); + while let Some(id) = ready.pop_first() { + order.push(by_id[id]); + for &next in dependents.get(id).into_iter().flatten() { + if let Some(n) = waiting.get_mut(next) { + *n -= 1; + if *n == 0 { + ready.insert(next); + } + } + } + } + if order.len() != by_id.len() { + return Err(ProjectError::Cycle); + } + Ok(order) +} + +/// Each operation's causal past. `order` must be topological. +fn pasts<'a>(order: &[&'a Signed]) -> Past<'a> { + let mut past: Past<'a> = BTreeMap::new(); + for &signed in order { + let mut seen: BTreeSet<&'a str> = BTreeSet::new(); + for dep in &signed.after { + seen.insert(dep.as_str()); + if let Some(before) = past.get(dep.as_str()) { + seen.extend(before.iter().copied()); + } + } + past.insert(signed.id.as_str(), seen); + } + past +} + +/// The state that the valid operations in `id`'s causal past build, in canonical order. +fn state_before( + id: &str, + order: &[&Signed], + past: &Past<'_>, + verdicts: &BTreeMap<&str, Option>, +) -> State { + let mut state = State::default(); + let before = &past[id]; + for &signed in order { + let sid = signed.id.as_str(); + if before.contains(sid) && verdicts.get(sid).is_some_and(Option::is_none) { + effect(&mut state, signed); + } + } + state +} + +/// The sender and recipient of a request in the causal past, if `id` is one. +fn requested<'a>(id: &str, by_id: &Index<'a>, past: &BTreeSet<&str>) -> Option<(&'a str, &'a str)> { + if !past.contains(id) { + return None; + } + let signed: &'a Signed = *by_id.get(id)?; + match &signed.op { + Op::Request { from, to } => Some((from.as_str(), to.as_str())), + _ => None, + } +} + +/// Refusals that depend only on the operation and its causal past. +fn static_refusal(signed: &Signed, by_id: &Index<'_>, past: &BTreeSet<&str>) -> Option { + match &signed.op { + Op::Request { from, to } if from == to => Some(Refusal::SelfRequest), + Op::Request { .. } => None, + Op::Accept { request, by } | Op::Decline { request, by } => { + match requested(request, by_id, past) { + None => Some(Refusal::UnknownRequest { + request: request.clone(), + }), + Some((_, to)) if to != by => Some(Refusal::NotRecipient { + request: request.clone(), + by: by.clone(), + }), + Some(_) => None, + } + } + Op::Remove { + by, + other, + requests, + } => { + if by == other { + return Some(Refusal::SameAccount); + } + let this = pair(by, other); + requests + .iter() + .find_map(|request| match requested(request, by_id, past) { + None => Some(Refusal::UnknownRequest { + request: request.clone(), + }), + Some((from, to)) if pair(from, to) != this => Some(Refusal::NotThisPair { + request: request.clone(), + }), + Some(_) => None, + }) + } + } +} + +/// The friendship state that operations build. +#[derive(Default)] +struct State { + /// Every request that took effect: its sender and recipient. + requests: BTreeMap, + /// Requests still open. + open: BTreeSet, + /// Friendships, each with the request that formed it. + friends: BTreeMap, +} + +impl State { + fn count(&self, account: &str) -> usize { + self.friends + .keys() + .filter(|(a, b)| a == account || b == account) + .count() + } + + fn open_between(&self, a: &str, b: &str) -> bool { + let p = pair(a, b); + self.open.iter().any(|id| { + self.requests + .get(id) + .is_some_and(|(from, to)| pair(from, to) == p) + }) + } +} + +/// Whether an operation takes effect in `state`. +fn check(state: &State, op: &Op, cap: usize) -> Result<(), Refusal> { + match op { + Op::Request { from, to } => { + if state.friends.contains_key(&pair(from, to)) { + Err(Refusal::AlreadyFriends) + } else if state.open_between(from, to) { + Err(Refusal::AlreadyOpen) + } else { + Ok(()) + } + } + Op::Accept { request, .. } => { + let Some((from, to)) = state + .requests + .get(request) + .filter(|_| state.open.contains(request)) + else { + return Err(Refusal::NotOpen { + request: request.clone(), + }); + }; + if state.friends.contains_key(&pair(from, to)) { + return Err(Refusal::AlreadyFriends); + } + for account in [from, to] { + if state.count(account) >= cap { + return Err(Refusal::AtCap { + account: account.clone(), + cap, + }); + } + } + Ok(()) + } + Op::Decline { request, .. } => { + if state.open.contains(request) { + Ok(()) + } else { + Err(Refusal::NotOpen { + request: request.clone(), + }) + } + } + Op::Remove { + by, + other, + requests, + } => { + let p = pair(by, other); + if requests + .iter() + .any(|r| state.open.contains(r) || state.friends.get(&p) == Some(r)) + { + Ok(()) + } else { + Err(Refusal::NothingToRemove) + } + } + } +} + +/// Apply an operation that took effect. +fn effect(state: &mut State, signed: &Signed) { + match &signed.op { + Op::Request { from, to } => { + state + .requests + .insert(signed.id.clone(), (from.clone(), to.clone())); + state.open.insert(signed.id.clone()); + } + Op::Accept { request, .. } => { + if let Some((from, to)) = state.requests.get(request).cloned() { + state.open.remove(request); + state.friends.insert(pair(&from, &to), request.clone()); + } + } + Op::Decline { request, .. } => { + state.open.remove(request); + } + Op::Remove { + by, + other, + requests, + } => { + let p = pair(by, other); + for request in requests { + state.open.remove(request); + if state.friends.get(&p) == Some(request) { + state.friends.remove(&p); + } + } + } + } +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used)] +mod tests { + use super::*; + use proptest::prelude::*; + + /// The cap for scenarios where it binds. Small, so that each boundary is reached. + const TEST_CAP: usize = 2; + + const ACCOUNTS: [&str; 5] = ["ann", "bo", "cy", "di", "ed"]; + + fn signed(id: &str, after: &[&str], op: Op) -> Signed { + Signed { + id: id.to_owned(), + after: after.iter().map(|d| (*d).to_owned()).collect(), + op, + } + } + + fn request(id: &str, after: &[&str], from: &str, to: &str) -> Signed { + signed( + id, + after, + Op::Request { + from: from.to_owned(), + to: to.to_owned(), + }, + ) + } + + fn accept(id: &str, after: &[&str], request: &str, by: &str) -> Signed { + signed( + id, + after, + Op::Accept { + request: request.to_owned(), + by: by.to_owned(), + }, + ) + } + + fn decline(id: &str, after: &[&str], request: &str, by: &str) -> Signed { + signed( + id, + after, + Op::Decline { + request: request.to_owned(), + by: by.to_owned(), + }, + ) + } + + fn remove(id: &str, after: &[&str], by: &str, other: &str, requests: &[&str]) -> Signed { + signed( + id, + after, + Op::Remove { + by: by.to_owned(), + other: other.to_owned(), + requests: requests.iter().map(|r| (*r).to_owned()).collect(), + }, + ) + } + + /// Every order that respects the `after` sets. S2 ran every causal order this way. + fn linearizations(ops: &[Signed]) -> Vec> { + fn extend(rest: &mut Vec, done: &mut Vec, out: &mut Vec>) { + if rest.is_empty() { + out.push(done.clone()); + return; + } + for i in 0..rest.len() { + if rest[i] + .after + .iter() + .all(|d| done.iter().any(|x| &x.id == d)) + { + let next = rest.remove(i); + done.push(next.clone()); + extend(rest, done, out); + done.pop(); + rest.insert(i, next); + } + } + } + let mut out = Vec::new(); + extend(&mut ops.to_vec(), &mut Vec::new(), &mut out); + out + } + + /// The projection of `ops`, which must be the same for every causal order. + fn settled(ops: &[Signed], cap: usize) -> Projection { + let expected = project(ops, cap).unwrap(); + for order in linearizations(ops) { + assert_eq!(project(&order, cap).unwrap(), expected); + } + expected + } + + fn applied(p: &Projection, id: &str) -> bool { + p.outcome(id) == Some(&Outcome::Applied) + } + + #[test] + fn a_request_is_one_way_and_becomes_a_friendship_on_accept() { + let open = settled(&[request("r0", &[], "ann", "bo")], TEST_CAP); + assert!(!open.are_friends("ann", "bo")); + assert!(applied(&open, "r0")); + + let ops = [ + request("r0", &[], "ann", "bo"), + accept("a0", &["r0"], "r0", "bo"), + ]; + let friends = settled(&ops, TEST_CAP); + assert!(friends.are_friends("bo", "ann")); + assert_eq!(friends.friends_of("ann"), ["bo"]); + } + + #[test] + fn only_the_recipient_may_accept() { + let ops = [ + request("r0", &[], "ann", "bo"), + accept("a0", &["r0"], "r0", "ann"), + ]; + let p = settled(&ops, TEST_CAP); + assert_eq!( + p.outcome("a0"), + Some(&Outcome::Refused(Refusal::NotRecipient { + request: "r0".into(), + by: "ann".into(), + })) + ); + assert!(!p.are_friends("ann", "bo")); + } + + #[test] + fn a_declined_request_is_void_and_its_later_accept_is_refused() { + let ops = [ + request("r0", &[], "ann", "bo"), + decline("d0", &["r0"], "r0", "bo"), + accept("a1", &["r0", "d0"], "r0", "bo"), + ]; + let p = settled(&ops, TEST_CAP); + assert!(applied(&p, "d0")); + assert_eq!( + p.outcome("a1"), + Some(&Outcome::Refused(Refusal::NotOpen { + request: "r0".into(), + })) + ); + assert!(!p.are_friends("ann", "bo")); + } + + #[test] + fn a_request_to_oneself_is_refused() { + let p = settled(&[request("r0", &[], "ann", "ann")], TEST_CAP); + assert_eq!( + p.outcome("r0"), + Some(&Outcome::Refused(Refusal::SelfRequest)) + ); + } + + #[test] + fn one_open_request_per_pair_in_either_direction() { + let ops = [ + request("r0", &[], "ann", "bo"), + request("r1", &["r0"], "bo", "ann"), + ]; + let p = settled(&ops, TEST_CAP); + assert_eq!( + p.outcome("r1"), + Some(&Outcome::Refused(Refusal::AlreadyOpen)) + ); + } + + #[test] + fn no_request_between_friends() { + let ops = [ + request("r0", &[], "ann", "bo"), + accept("a0", &["r0"], "r0", "bo"), + request("r1", &["a0"], "ann", "bo"), + ]; + let p = settled(&ops, TEST_CAP); + assert_eq!( + p.outcome("r1"), + Some(&Outcome::Refused(Refusal::AlreadyFriends)) + ); + } + + #[test] + fn an_accept_below_the_cap_is_applied_and_reaches_it() { + // cap - 1: ann has one friend, so the second is applied and fills the cap. + let ops = [ + request("r0", &[], "bo", "ann"), + accept("a0", &["r0"], "r0", "ann"), + request("r1", &["a0"], "cy", "ann"), + accept("a1", &["r1"], "r1", "ann"), + ]; + let p = settled(&ops, TEST_CAP); + assert!(applied(&p, "a1")); + assert_eq!(p.friends_of("ann"), ["bo", "cy"]); + } + + #[test] + fn an_accept_at_the_cap_is_refused_with_the_account_named() { + // cap: ann already has cap friends, so a third accept is refused. + let ops = [ + request("r0", &[], "bo", "ann"), + accept("a0", &["r0"], "r0", "ann"), + request("r1", &["a0"], "cy", "ann"), + accept("a1", &["r1"], "r1", "ann"), + request("r2", &["a1"], "di", "ann"), + accept("a2", &["r2"], "r2", "ann"), + ]; + let p = settled(&ops, TEST_CAP); + assert_eq!( + p.outcome("a2"), + Some(&Outcome::Refused(Refusal::AtCap { + account: "ann".into(), + cap: TEST_CAP, + })) + ); + assert_eq!(p.friends_of("ann"), ["bo", "cy"]); + } + + #[test] + fn past_the_cap_nothing_more_is_added() { + // cap + 1: a fourth and a fifth request stay open and are never friends. + let ops = [ + request("r0", &[], "bo", "ann"), + accept("a0", &["r0"], "r0", "ann"), + request("r1", &["a0"], "cy", "ann"), + accept("a1", &["r1"], "r1", "ann"), + request("r2", &["a1"], "di", "ann"), + accept("a2", &["r2"], "r2", "ann"), + request("r3", &["a2"], "ed", "ann"), + accept("a3", &["r3"], "r3", "ann"), + ]; + let p = settled(&ops, TEST_CAP); + assert!(!applied(&p, "a3")); + assert_eq!(p.friends_of("ann").len(), TEST_CAP); + } + + #[test] + fn the_requester_side_counts_toward_the_cap() { + // bo is at the cap, so bo cannot make a friend of dan. + let ops = [ + request("r0", &[], "ann", "bo"), + accept("a0", &["r0"], "r0", "bo"), + request("r1", &["a0"], "cy", "bo"), + accept("a1", &["r1"], "r1", "bo"), + request("r2", &["a1"], "bo", "di"), + accept("a2", &["r2"], "r2", "di"), + ]; + let p = settled(&ops, TEST_CAP); + assert_eq!( + p.outcome("a2"), + Some(&Outcome::Refused(Refusal::AtCap { + account: "bo".into(), + cap: TEST_CAP, + })) + ); + } + + #[test] + fn an_accept_refused_at_the_cap_is_not_revived_when_a_friend_leaves() { + // ann is at the cap with bo and cy. The accept of di is refused. When bo leaves, + // di must not become a friend through that old accept. + let ops = [ + request("r0", &[], "bo", "ann"), + accept("a0", &["r0"], "r0", "ann"), + request("r1", &["a0"], "cy", "ann"), + accept("a1", &["r1"], "r1", "ann"), + request("r2", &["a1"], "di", "ann"), + accept("a2", &["r2"], "r2", "ann"), + remove("x", &["a2"], "ann", "bo", &["r0"]), + ]; + let p = settled(&ops, TEST_CAP); + assert!(applied(&p, "x")); + assert!(matches!( + p.outcome("a2"), + Some(Outcome::Refused(Refusal::AtCap { .. })) + )); + assert_eq!(p.friends_of("ann"), ["cy"]); + } + + #[test] + fn a_request_side_accept_refused_at_the_cap_is_not_revived_when_a_friend_leaves() { + // bo is at the cap with ann and cy. The accept of di, which bo requested, is + // refused. When ann leaves, di must not become a friend of bo. + let ops = [ + request("r0", &[], "ann", "bo"), + accept("a0", &["r0"], "r0", "bo"), + request("r1", &["a0"], "cy", "bo"), + accept("a1", &["r1"], "r1", "bo"), + request("r2", &["a1"], "bo", "di"), + accept("a2", &["r2"], "r2", "di"), + remove("x", &["a2"], "bo", "ann", &["r0"]), + ]; + let p = settled(&ops, TEST_CAP); + assert!(applied(&p, "x")); + assert!(matches!( + p.outcome("a2"), + Some(Outcome::Refused(Refusal::AtCap { .. })) + )); + assert_eq!(p.friends_of("bo"), ["cy"]); + assert!(p.friends_of("di").is_empty()); + } + + #[test] + fn a_removal_dissolves_the_friendship_on_both_sides() { + for (by, other) in [("ann", "bo"), ("bo", "ann")] { + let ops = [ + request("r0", &[], "ann", "bo"), + accept("a0", &["r0"], "r0", "bo"), + remove("x", &["a0"], by, other, &["r0"]), + ]; + let p = settled(&ops, TEST_CAP); + assert!(applied(&p, "x")); + assert!(!p.are_friends("ann", "bo")); + assert!(p.friends_of("bo").is_empty()); + assert!(p.friends_of("ann").is_empty()); + } + } + + #[test] + fn a_removal_voids_a_request_that_was_never_delivered() { + // The chain: bo accepts after the removal, so the request is already gone. + let chained = [ + request("r0", &[], "ann", "bo"), + remove("x", &["r0"], "ann", "bo", &["r0"]), + accept("a0", &["x"], "r0", "bo"), + ]; + let p = settled(&chained, TEST_CAP); + assert_eq!( + p.outcome("a0"), + Some(&Outcome::Refused(Refusal::NotOpen { + request: "r0".into(), + })) + ); + + // The concurrent case: bo accepted without seeing the removal. The removal wins. + let concurrent = [ + request("r0", &[], "ann", "bo"), + remove("x", &["r0"], "ann", "bo", &["r0"]), + accept("a0", &["r0"], "r0", "bo"), + ]; + let p = settled(&concurrent, TEST_CAP); + assert!(applied(&p, "x")); + assert_eq!( + p.outcome("a0"), + Some(&Outcome::Refused(Refusal::Dissolved { + request: "r0".into(), + })) + ); + assert!(!p.are_friends("ann", "bo")); + } + + #[test] + fn a_removal_with_nothing_to_remove_is_refused() { + let p = settled(&[remove("x", &[], "ann", "bo", &[])], TEST_CAP); + assert_eq!( + p.outcome("x"), + Some(&Outcome::Refused(Refusal::NothingToRemove)) + ); + } + + #[test] + fn a_removal_naming_a_request_between_other_accounts_is_refused() { + let ops = [ + request("r0", &[], "ann", "bo"), + request("r1", &[], "cy", "di"), + remove("x", &["r0", "r1"], "ann", "bo", &["r1"]), + ]; + let p = settled(&ops, TEST_CAP); + assert_eq!( + p.outcome("x"), + Some(&Outcome::Refused(Refusal::NotThisPair { + request: "r1".into(), + })) + ); + } + + #[test] + fn an_accept_of_a_request_outside_its_causal_past_is_refused() { + let ops = [ + request("r0", &[], "ann", "bo"), + accept("a0", &[], "r0", "bo"), + ]; + let p = settled(&ops, TEST_CAP); + assert_eq!( + p.outcome("a0"), + Some(&Outcome::Refused(Refusal::UnknownRequest { + request: "r0".into(), + })) + ); + } + + #[test] + fn a_missing_dependency_a_duplicate_and_a_cycle_are_errors() { + assert_eq!( + project(&[request("r0", &["ghost"], "ann", "bo")], TEST_CAP).unwrap_err(), + ProjectError::MissingDependency { + op: "r0".into(), + dependency: "ghost".into(), + } + ); + assert_eq!( + project( + &[ + request("r0", &[], "ann", "bo"), + request("r0", &[], "ann", "cy") + ], + TEST_CAP + ) + .unwrap_err(), + ProjectError::DuplicateId("r0".into()) + ); + assert_eq!( + project( + &[ + request("a", &["b"], "ann", "bo"), + request("b", &["a"], "ann", "cy") + ], + TEST_CAP + ) + .unwrap_err(), + ProjectError::Cycle + ); + } + + // ----- S2 friendship findings (spikes/shared/s2-auth, friendship.rs and RESULTS.md) ----- + + /// F2: two concurrent adds beyond the cap. Every order keeps the same two friends, + /// and the later add is refused at the cap. + #[test] + fn s2_f2_concurrent_adds_beyond_the_cap_resolve_the_same_in_every_order() { + let ops = [ + request("r0", &[], "ann", "bo"), + accept("a0", &["r0"], "r0", "bo"), + request("r1", &["a0"], "cy", "ann"), + request("r2", &["a0"], "di", "ann"), + accept("a1", &["r1"], "r1", "ann"), + accept("a2", &["r2"], "r2", "ann"), + ]; + let p = settled(&ops, TEST_CAP); + assert_eq!(p.friends_of("ann"), ["bo", "cy"]); + assert_eq!( + p.outcome("a2"), + Some(&Outcome::Refused(Refusal::AtCap { + account: "ann".into(), + cap: TEST_CAP, + })) + ); + } + + /// F3: the concurrent adds, and a removal of bo. The removal dissolves bo's + /// friendship, and the freed place goes to the two new friends. + #[test] + fn s2_f3_concurrent_adds_and_a_removal_of_one_side_dissolve_in_every_order() { + let ops = [ + request("r0", &[], "ann", "bo"), + accept("a0", &["r0"], "r0", "bo"), + request("r1", &["a0"], "cy", "ann"), + request("r2", &["a0"], "di", "ann"), + accept("a1", &["r1"], "r1", "ann"), + accept("a2", &["r2"], "r2", "ann"), + remove("x", &["a0"], "ann", "bo", &["r0"]), + ]; + let p = settled(&ops, TEST_CAP); + assert!(applied(&p, "x")); + assert_eq!( + p.outcome("a0"), + Some(&Outcome::Refused(Refusal::Dissolved { + request: "r0".into(), + })) + ); + assert_eq!(p.friends_of("ann"), ["cy", "di"]); + assert!(p.friends_of("bo").is_empty()); + } + + /// F4: mutual removal. Both removals apply, and the friendship ends once. + #[test] + fn s2_f4_mutual_removal_dissolves_once_and_stays_dissolved() { + let ops = [ + request("r0", &[], "ann", "bo"), + accept("a0", &["r0"], "r0", "bo"), + remove("x", &["a0"], "ann", "bo", &["r0"]), + remove("y", &["a0"], "bo", "ann", &["r0"]), + ]; + let p = settled(&ops, TEST_CAP); + assert!(applied(&p, "x")); + assert!(applied(&p, "y")); + assert!(p.friendships().is_empty()); + } + + /// F5: after a dissolve, the same request and its accept do not bring the + /// friendship back, in any order. Only a new request does. + #[test] + fn s2_f5_a_dissolved_friendship_is_not_revived_by_its_own_accept() { + let concurrent = [ + request("r0", &[], "ann", "bo"), + remove("x", &["r0"], "ann", "bo", &["r0"]), + accept("a0", &["r0"], "r0", "bo"), + ]; + let p = settled(&concurrent, TEST_CAP); + assert!(p.friendships().is_empty()); + assert_eq!( + p.outcome("a0"), + Some(&Outcome::Refused(Refusal::Dissolved { + request: "r0".into(), + })) + ); + } + + /// F5, the other half: a new request after a dissolve is open, and accepting it is + /// a new friendship. This is the product's rule, and it differs from the S2 group + /// model, where dissolution was terminal. The owner decides which one holds. + #[test] + fn s2_f5_a_new_request_after_a_dissolve_is_the_only_way_back() { + let ops = [ + request("r0", &[], "ann", "bo"), + accept("a0", &["r0"], "r0", "bo"), + remove("x", &["a0"], "ann", "bo", &["r0"]), + request("r2", &["x"], "ann", "bo"), + ]; + let open = settled(&ops, TEST_CAP); + assert!(applied(&open, "r2")); + assert!(!open.are_friends("ann", "bo")); + + let mut again = ops.to_vec(); + again.push(accept("a3", &["r2"], "r2", "bo")); + assert!(settled(&again, TEST_CAP).are_friends("ann", "bo")); + } + + // ----- Properties over random operation sets ----- + + fn script() -> impl Strategy> { + proptest::collection::vec((0u8..4, 0u8..5, 0u8..5, any::(), any::()), 1..=10) + } + + /// Build a set from a script. Each operation sees a subset of the earlier ones, so every + /// generated set is a DAG. + fn build(script: &[(u8, u8, u8, u16, u16)]) -> Vec { + let mut ops: Vec = Vec::new(); + for (i, &(kind, a, b, pick, seen)) in script.iter().enumerate() { + let me = ACCOUNTS[usize::from(a) % ACCOUNTS.len()]; + let other = ACCOUNTS[usize::from(b) % ACCOUNTS.len()]; + let id = format!("{pick:04x}-{i:02}"); + let mut after: BTreeSet = BTreeSet::new(); + for (j, earlier) in ops.iter().enumerate() { + if (seen >> j) & 1 == 1 { + after.insert(earlier.id.clone()); + } + } + let mut open: Vec<(OpId, Account, Account)> = Vec::new(); + for s in &ops { + if let Op::Request { from, to } = &s.op { + open.push((s.id.clone(), from.clone(), to.clone())); + } + } + let op = match kind { + 1 | 2 if !open.is_empty() => { + let (request, _from, to) = open[usize::from(pick) % open.len()].clone(); + after.insert(request.clone()); + // A wrong recipient sometimes, so the static refusal is exercised. + let by = if seen % 7 == 0 { other.to_owned() } else { to }; + if kind == 1 { + Op::Accept { request, by } + } else { + Op::Decline { request, by } + } + } + 3 => { + let mut named = Vec::new(); + for (k, (request, from, to)) in open.iter().enumerate() { + if pair(from, to) == pair(me, other) && (pick >> (k % 16)) & 1 == 1 { + named.push(request.clone()); + } + } + after.extend(named.iter().cloned()); + Op::Remove { + by: me.to_owned(), + other: other.to_owned(), + requests: named, + } + } + _ => Op::Request { + from: me.to_owned(), + to: other.to_owned(), + }, + }; + ops.push(Signed { id, after, op }); + } + ops + } + + /// A random order that respects the `after` sets. `prio` picks among the ready operations. + fn linearize(ops: &[Signed], prio: &[u16]) -> Vec { + let mut rest: Vec<&Signed> = ops.iter().collect(); + let mut done: BTreeSet<&str> = BTreeSet::new(); + let mut out = Vec::new(); + while !rest.is_empty() { + let ready: Vec = (0..rest.len()) + .filter(|&i| rest[i].after.iter().all(|d| done.contains(d.as_str()))) + .collect(); + if ready.is_empty() { + break; + } + let next = rest.remove(ready[usize::from(prio[out.len() % prio.len()]) % ready.len()]); + done.insert(next.id.as_str()); + out.push(next.clone()); + } + out + } + + fn requested_pair(ops: &[Signed], request: &str) -> Option { + ops.iter().find_map(|s| match &s.op { + Op::Request { from, to } if s.id == request => Some(pair(from, to)), + _ => None, + }) + } + + proptest! { + #![proptest_config(ProptestConfig::with_cases(1000))] + + #[test] + fn the_cap_is_never_exceeded(script in script(), cap in 1usize..=3) { + let ops = build(&script); + let p = project(&ops, cap).unwrap(); + for account in ACCOUNTS { + let friends = p.friends_of(account).len(); + prop_assert!(friends <= cap, "{account} has {friends} friends, cap {cap}"); + } + } + + #[test] + fn the_result_does_not_depend_on_the_order( + script in script(), + cap in 1usize..=3, + prio in proptest::collection::vec(any::(), 12), + ) { + let ops = build(&script); + let expected = project(&ops, cap).unwrap(); + let shuffled = linearize(&ops, &prio); + prop_assert_eq!(shuffled.len(), ops.len()); + prop_assert_eq!(project(&shuffled, cap).unwrap(), expected.clone()); + let mut reversed = ops.clone(); + reversed.reverse(); + prop_assert_eq!(project(&reversed, cap).unwrap(), expected); + } + + #[test] + fn every_friendship_is_formed_by_an_applied_accept(script in script(), cap in 1usize..=3) { + let ops = build(&script); + let p = project(&ops, cap).unwrap(); + for (a, b) in p.friendships() { + let formed = ops.iter().any(|s| match &s.op { + Op::Accept { request, .. } => { + applied(&p, &s.id) + && requested_pair(&ops, request) == Some((a.clone(), b.clone())) + } + _ => false, + }); + prop_assert!(formed, "{a} and {b} are friends with no applied accept"); + } + } + } +} diff --git a/pkgs/id/src/lib.rs b/pkgs/id/src/lib.rs index 4ed2f2c54e..d7f48c4274 100644 --- a/pkgs/id/src/lib.rs +++ b/pkgs/id/src/lib.rs @@ -176,6 +176,7 @@ pub mod envelope_net; pub mod envelope_outbox; pub mod event_store; pub mod fileops; +pub mod friendship; pub mod helpers; pub mod invite; pub mod local; From 965b749bbaaef20f3ca84f3d121ebe95499d70f0 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 11 Oct 2026 23:20:05 -0500 Subject: [PATCH 03/40] refactor(rust): drop use-count bounds from signed capability grants [P2.6] A delegation no longer carries a use count. Its scopes and expiry are the grant; the host counts its actions against the host-issued limit above it, if any. Decision 3: counts do not converge across partitions, so they are not part of the grant. - core: delegate() refuses a use count; the client frames for attenuate and delegate_to_friend drop their uses field - host-issued limits (invites, account grants) stay enforced by the host from its own journal; the journal format is unchanged - module docs say what a grant carries, what is signed (the directory's artifacts), and what is local (the counts and the granted set) --- pkgs/id/src/world.rs | 171 +++++++++++++++++++++++++++++------ pkgs/id/src/world_caps.rs | 5 + pkgs/id/src/world_session.rs | 18 ++-- pkgs/id/src/world_store.rs | 5 +- 4 files changed, 160 insertions(+), 39 deletions(-) diff --git a/pkgs/id/src/world.rs b/pkgs/id/src/world.rs index 3425385a1a..1d01f19c72 100644 --- a/pkgs/id/src/world.rs +++ b/pkgs/id/src/world.rs @@ -4,6 +4,17 @@ //! messages to it serially. This module does not open sockets or persist world //! state. Capability tokens are returned only at issuance and retained only as //! SHA-256 digests for revocation and membership checks. +//! +//! ## What a grant carries, and what stays local +//! +//! A participant capability is a bearer secret. Its digest, scopes, expiry, +//! parent and subject are the grant, and the journal records them. Nothing +//! about a participant grant is signed here; the signed records are the +//! directory's artifacts (friendships and their removals). A grant carries no +//! use count. A delegation narrows scopes and may set an expiry, nothing else. +//! The host alone enforces a use limit, and only on a capability it issued (an +//! invite or an account grant), by counting actions in its own journal. Those +//! counts are local to the hosting node and need not converge across partitions. use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque}; use std::sync::Arc; @@ -341,10 +352,12 @@ pub enum JournalEntry { /// Unix milliseconds at which the capability stops working. #[serde(default, skip_serializing_if = "Option::is_none")] expires_at: Option, - /// Committed chat and input actions the capability may take. + /// Committed chat and input actions the capability may take. Host-local: + /// only a capability the host issued has one, never a delegation. #[serde(default, skip_serializing_if = "Option::is_none")] uses: Option, /// Actions already taken, written at checkpoint so counts survive compaction. + /// Host-local, like `uses`. #[serde(default)] used: u32, /// Account the capability acts for; its ceiling and friendships bound it. @@ -610,11 +623,15 @@ pub struct WorldSnapshot { } /// Limits on what a capability may do before it stops working. +/// +/// Only the host sets `uses`, on a capability it issues. A delegation may set +/// `expires_at` and never `uses` (see [`WorldCore::attenuate`]). #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct CapabilityBounds { /// Unix milliseconds at which the capability stops working. pub expires_at: Option, - /// Committed chat and input actions the capability may take. + /// Committed chat and input actions the capability may take. Enforced by + /// the host alone, from its own journal. pub uses: Option, } @@ -1083,8 +1100,8 @@ impl WorldCore { /// Delegate a capability: a new participant whose scopes are a subset of /// the delegating capability's, and which is revoked with it. Its expiry - /// may not be later than the delegator's, and its use limit may not exceed - /// what the delegator and its ancestors have left. + /// may not be later than the delegator's. It carries no use count: each + /// action it takes counts against the host-issued limit above it, if any. pub fn attenuate( &mut self, token: &JoinCapability, @@ -1155,13 +1172,10 @@ impl WorldCore { "this capability may not delegate a later expiry" ); } - if let Some(uses) = bounds.uses { - ensure!(uses >= 1, "delegated use limit must be at least one"); - ensure!( - self.uses_left(parent).is_none_or(|left| uses <= left), - "this capability does not have that many uses left to delegate" - ); - } + ensure!( + bounds.uses.is_none(), + "a delegated capability carries no use count; the host's limit still applies" + ); self.mint(display_name, scopes, Some(parent), subject, bounds) } @@ -3787,7 +3801,7 @@ mod tests { } #[test] - fn use_limits_draw_down_every_ancestor() { + fn a_host_issued_limit_draws_down_through_every_delegation() { let mut core = world(8); let (_, owner) = core .issue_capability( @@ -3799,32 +3813,135 @@ mod tests { }, ) .unwrap(); - let two = CapabilityBounds { - expires_at: None, - uses: Some(2), - }; let (_, child) = core - .attenuate(&owner, WorldScopes::GUEST, two, "Bo") + .attenuate( + &owner, + WorldScopes::GUEST, + CapabilityBounds::default(), + "Bo", + ) .unwrap(); core.chat(&child, "one").unwrap(); core.chat(&child, "two").unwrap(); - assert!(core.chat(&child, "three").is_err()); + core.chat(&owner, "last").unwrap(); assert!( - core.attenuate(&owner, WorldScopes::GUEST, two, "Cy") - .is_err(), - "the owner has one use left to delegate" + core.chat(&child, "three").is_err(), + "the host's limit bounds the delegate" ); - let one = CapabilityBounds { + assert!(core.chat(&owner, "over").is_err()); + assert!(core.snapshot(&owner).is_ok(), "reading is not a use"); + } + + #[test] + fn a_delegated_grant_carries_no_use_count() { + let mut core = world(8); + let delegator = WorldScopes(WorldScopes::GUEST.bits() | WorldScopes::DELEGATE.bits()); + let (_, owner) = core + .issue_capability("Ada", delegator, CapabilityBounds::default()) + .unwrap(); + let limited = CapabilityBounds { expires_at: None, uses: Some(1), }; assert!( - core.attenuate(&owner, WorldScopes::GUEST, one, "Di") - .is_ok() + core.attenuate(&owner, WorldScopes::GUEST, limited, "Bo") + .is_err(), + "a delegation carries no use count" ); - core.chat(&owner, "last").unwrap(); - assert!(core.chat(&owner, "over").is_err()); - assert!(core.snapshot(&owner).is_ok(), "reading is not a use"); + let (child, child_token) = core + .attenuate( + &owner, + WorldScopes::GUEST, + CapabilityBounds::default(), + "Cy", + ) + .unwrap(); + for text in ["one", "two", "three"] { + core.chat(&child_token, text).unwrap(); + } + let record = serde_json::to_value(core.issued_entry(child.id).unwrap()).unwrap(); + assert!( + record.get("uses").is_none(), + "the grant record has no use count: {record}" + ); + } + + #[test] + fn a_grant_without_a_bound_is_never_refused_for_count() { + let mut core = world(8); + let (_, token) = join(&mut core, "Ada"); + for i in 0..50 { + core.chat(&token, &format!("m{i}")).unwrap(); + } + assert!(core.snapshot(&token).is_ok()); + } + + #[test] + fn a_host_issued_limit_is_enforced_by_the_host_alone() { + let mut core = world(8); + let (_, token) = core + .issue_capability( + "Ada", + WorldScopes::GUEST, + CapabilityBounds { + expires_at: None, + uses: Some(2), + }, + ) + .unwrap(); + core.chat(&token, "one").unwrap(); + core.chat(&token, "two").unwrap(); + assert!(core.chat(&token, "three").is_err()); + assert_eq!(core.current_sequence(), 2, "a refused use commits nothing"); + } + + #[test] + fn use_counts_are_local_and_do_not_converge_across_partitions() { + let mut source = world(8); + let (owner, token) = source + .issue_capability( + "Ada", + WorldScopes::GUEST, + CapabilityBounds { + expires_at: None, + uses: Some(1), + }, + ) + .unwrap(); + let entries = vec![ + JournalEntry::Created { + world_id: "test-world".to_owned(), + version: JOURNAL_VERSION, + }, + JournalEntry::Issued { + participant: owner.clone(), + digest: hex_encode(&token_digest(token.expose())), + scopes: WorldScopes::GUEST.bits(), + parent: None, + expires_at: None, + uses: Some(1), + used: 0, + subject: None, + }, + ]; + // Two partitions start from the same journal and do not see each other. + let mut north = WorldCore::restore("test-world", WorldLimits::default(), entries.clone()) + .unwrap() + .core; + let mut south = WorldCore::restore("test-world", WorldLimits::default(), entries) + .unwrap() + .core; + north.chat(&token, "north").unwrap(); + south.chat(&token, "south").unwrap(); + // Each side counted its own use, so the one-use grant was used twice. + assert!(north.chat(&token, "north again").is_err()); + assert!(south.chat(&token, "south again").is_err()); + // Each state is still valid: sequence and tally agree, and the grant is held. + for core in [&north, &south] { + assert_eq!(core.current_sequence(), 1); + assert_eq!(core.capabilities[&owner.id].used, 1); + assert_eq!(core.participants().len(), 1); + } } #[test] diff --git a/pkgs/id/src/world_caps.rs b/pkgs/id/src/world_caps.rs index 0165460184..13d4e43e8d 100644 --- a/pkgs/id/src/world_caps.rs +++ b/pkgs/id/src/world_caps.rs @@ -22,6 +22,11 @@ //! This module holds the pure parts: the schema and its bounds, the catalog of //! capability names, and the grant policy with its usage accounting. The //! actor in [`crate::world`] executes providers because they need the world. +//! +//! **Local, not signed.** The granted set, the policy and the usage counts +//! ([`CapUsage`]) belong to the hosting node and are journaled there. None of +//! them is signed or replicated. A usage count reports what happened and bounds +//! nothing, so two hosts of one world may keep different counts. use std::collections::{BTreeMap, BTreeSet}; diff --git a/pkgs/id/src/world_session.rs b/pkgs/id/src/world_session.rs index 82355b11cf..f38bd2ee88 100644 --- a/pkgs/id/src/world_session.rs +++ b/pkgs/id/src/world_session.rs @@ -195,14 +195,13 @@ enum ClientFrame { Chat { text: String, }, - /// Joined: mint a capability with a subset of this session's scopes. + /// Joined: mint a capability with a subset of this session's scopes. A + /// delegation carries no use count. Attenuate { name: String, scopes: Vec, /// Unix milliseconds at which the delegated capability stops working. expires_at: Option, - /// Committed chat and input actions the delegated capability may take. - uses: Option, }, /// Joined as an account: delegate a subset of its scopes to one of its friends. DelegateToFriend { @@ -210,7 +209,6 @@ enum ClientFrame { name: String, scopes: Vec, expires_at: Option, - uses: Option, }, Input { data_hex: String, @@ -1920,12 +1918,14 @@ async fn handle_client_frame( name, scopes, expires_at, - uses, } => { let Some(scopes) = WorldScopes::from_names(scopes.iter().map(String::as_str)) else { return send_error(io, "unknown scope").await; }; - let bounds = CapabilityBounds { expires_at, uses }; + let bounds = CapabilityBounds { + expires_at, + uses: None, + }; let result = world.attenuate(token.clone(), scopes, bounds, name).await; return send_delegation(io, result).await; } @@ -1934,12 +1934,14 @@ async fn handle_client_frame( name, scopes, expires_at, - uses, } => { let Some(scopes) = WorldScopes::from_names(scopes.iter().map(String::as_str)) else { return send_error(io, "unknown scope").await; }; - let bounds = CapabilityBounds { expires_at, uses }; + let bounds = CapabilityBounds { + expires_at, + uses: None, + }; let result = world .delegate_to_friend(token.clone(), friend, scopes, bounds, name) .await; diff --git a/pkgs/id/src/world_store.rs b/pkgs/id/src/world_store.rs index 7cd9122757..70f5d77ec0 100644 --- a/pkgs/id/src/world_store.rs +++ b/pkgs/id/src/world_store.rs @@ -646,10 +646,7 @@ mod tests { .attenuate( owner_token.clone(), WorldScopes::JOIN.union(WorldScopes::DELEGATE), - CapabilityBounds { - expires_at: None, - uses: Some(3), - }, + CapabilityBounds::default(), "bo", ) .await From 4b5787a0068ad27b5946513f5db82b4a28faa5cc Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 11 Oct 2026 23:20:53 -0500 Subject: [PATCH 04/40] test(rust): pin that content concurrent with a removal is kept [P2.6] Nothing in pkgs/id hides or voids a removed member's content: revocation stops new actions (authorize), and events already committed stay in the retained log and in snapshots. No fix was needed. These tests pin decision 4: content committed before a removal is kept, content after it is refused, and a removal racing a stream of chat keeps exactly the lines it accepted. A planted bug that filters a revoked member's events out of snapshots makes both tests fail. --- pkgs/id/src/world.rs | 62 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) diff --git a/pkgs/id/src/world.rs b/pkgs/id/src/world.rs index 1d01f19c72..9d842a7945 100644 --- a/pkgs/id/src/world.rs +++ b/pkgs/id/src/world.rs @@ -4071,6 +4071,68 @@ mod tests { assert!(core.chat(&token, "hello").is_err()); } + #[test] + fn content_before_a_removal_is_kept_and_content_after_it_is_refused() { + let mut core = world(8); + let (ada, ada_token) = join(&mut core, "Ada"); + let (_, bo_token) = join(&mut core, "Bo"); + core.chat(&ada_token, "before").unwrap(); + assert_eq!(core.revoke_tree(ada.id), vec![ada.id]); + assert!(core.chat(&ada_token, "after").is_err()); + assert!(core.input(&ada_token, b"move").is_err()); + assert_eq!( + core.current_sequence(), + 1, + "a refused action commits nothing" + ); + let kept: Vec = core + .snapshot(&bo_token) + .unwrap() + .events + .into_iter() + .filter_map(|event| match event.kind { + WorldEventKind::Chat(text) => Some(text), + _ => None, + }) + .collect(); + assert_eq!(kept, vec!["before"]); + assert_eq!(core.events_after(&bo_token, 0).unwrap().events.len(), 1); + } + + #[tokio::test] + async fn a_removal_racing_chat_keeps_every_accepted_line() { + let handle = WorldHandle::spawn(WorldCore::new("w", WorldLimits::default()).unwrap()); + let (ada, ada_token) = handle.issue("Ada", WorldScopes::GUEST).await.unwrap(); + let (_, bo_token) = handle.issue("Bo", WorldScopes::GUEST).await.unwrap(); + let chatter = { + let handle = handle.clone(); + let token = ada_token.clone(); + tokio::spawn(async move { + let mut accepted = 0; + for i in 0..200 { + if handle.chat(token.clone(), format!("m{i}")).await.is_ok() { + accepted += 1; + } + } + accepted + }) + }; + tokio::task::yield_now().await; + assert!(handle.revoke(ada.id).await.unwrap()); + let accepted = chatter.await.unwrap(); + assert!(handle.chat(ada_token, "late").await.is_err()); + let snapshot = handle.snapshot(bo_token).await.unwrap(); + let from_ada = snapshot + .events + .iter() + .filter(|event| event.participant_id == ada.id) + .count(); + assert_eq!( + from_ada, accepted, + "every line accepted before the removal is kept, and none after it" + ); + } + #[test] fn attenuation_only_narrows_and_needs_delegate() { let join = WorldScopes::JOIN; From 862401c9f79f68245d248e76f38f841a491f15de Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 11 Oct 2026 23:23:43 -0500 Subject: [PATCH 05/40] feat(rust): auth-frontier mapping for p2panda-auth [P2.1] p2panda-auth orders group operations only by their explicit dependencies. Our events order by `after`, which can name any event. The mapping derives each auth operation's dependencies from its causal past: the maximal group operations of its group, found by walking `after` through non-auth events and through operations of other groups. - CausalIndex memoises the frontier per (event, group) with an iterative walk, so a long chain of non-auth events cannot exhaust the stack. - An `after` hash the index does not hold is an error, never a root. - Adds the p2panda-auth git dependency at the pinned rev, default features (no test_utils). Tests: unit (frontier cases, unknown dependency, long chain), the S2 scenarios in every causal order, the S2 failure modes as regressions (raw after stalls, literal mapping panics, root dependency voids a valid add, unknown dependency is an error), and properties against a brute-force walk. --- pkgs/id/Cargo.lock | 50 ++- pkgs/id/Cargo.toml | 3 + pkgs/id/src/lib.rs | 1 + pkgs/id/src/membership/frontier.rs | 310 ++++++++++++++++++ pkgs/id/src/membership/mod.rs | 114 +++++++ pkgs/id/tests/membership_properties.rs | 175 ++++++++++ pkgs/id/tests/membership_scenarios.rs | 430 +++++++++++++++++++++++++ 7 files changed, 1078 insertions(+), 5 deletions(-) create mode 100644 pkgs/id/src/membership/frontier.rs create mode 100644 pkgs/id/src/membership/mod.rs create mode 100644 pkgs/id/tests/membership_properties.rs create mode 100644 pkgs/id/tests/membership_scenarios.rs diff --git a/pkgs/id/Cargo.lock b/pkgs/id/Cargo.lock index b387e08a08..a3c51da161 100644 --- a/pkgs/id/Cargo.lock +++ b/pkgs/id/Cargo.lock @@ -1365,7 +1365,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c54e03a951783e8b327515db3f2a2fd0e3bed362a96b066f341ce66ed49b4ead" dependencies = [ "data-encoding", - "syn 3.0.8", + "syn 1.0.109", ] [[package]] @@ -1811,7 +1811,7 @@ version = "0.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ef975e30683b2d965054bb0a836f8973857c4ebf6acf274fe46617cd285060d8" dependencies = [ - "foldhash", + "foldhash 0.2.0", "libm", "portable-atomic", "siphasher", @@ -1918,6 +1918,12 @@ version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + [[package]] name = "foldhash" version = "0.2.0" @@ -2306,13 +2312,22 @@ dependencies = [ "byteorder", ] +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "foldhash 0.1.5", +] + [[package]] name = "hashbrown" version = "0.16.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" dependencies = [ - "foldhash", + "foldhash 0.2.0", "serde", "serde_core", ] @@ -2323,7 +2338,7 @@ version = "0.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" dependencies = [ - "foldhash", + "foldhash 0.2.0", ] [[package]] @@ -2702,6 +2717,7 @@ dependencies = [ "iroh-tickets", "libc", "mime_guess", + "p2panda-auth", "p2panda-core", "p2panda-store", "postcard", @@ -4204,6 +4220,17 @@ dependencies = [ "sha2 0.11.0", ] +[[package]] +name = "p2panda-auth" +version = "0.7.1" +source = "git+https://github.com/p2panda/p2panda?rev=3e84cac48bba05c6857cce2ec433862b97f8d53c#3e84cac48bba05c6857cce2ec433862b97f8d53c" +dependencies = [ + "p2panda-core", + "petgraph", + "thiserror 2.0.21", + "tracing", +] + [[package]] name = "p2panda-core" version = "0.7.1" @@ -4366,6 +4393,19 @@ version = "2.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" +[[package]] +name = "petgraph" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8701b58ea97060d5e5b155d383a69952a60943f0e6dfe30b04c287beb0b27455" +dependencies = [ + "fixedbitset", + "hashbrown 0.15.5", + "indexmap", + "serde", + "serde_derive", +] + [[package]] name = "pharos" version = "0.5.3" @@ -6144,7 +6184,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.4.3", + "getrandom 0.3.4", "once_cell", "rustix", "windows-sys 0.61.2", diff --git a/pkgs/id/Cargo.toml b/pkgs/id/Cargo.toml index 458a691ece..4e63284952 100644 --- a/pkgs/id/Cargo.toml +++ b/pkgs/id/Cargo.toml @@ -54,6 +54,9 @@ iroh-gossip = { version = "0.101", features = ["net"] } p2panda-core = { git = "https://github.com/p2panda/p2panda", rev = "3e84cac48bba05c6857cce2ec433862b97f8d53c" } # Store traits only. The default features would pull in SQLite (explainers section 14). p2panda-store = { git = "https://github.com/p2panda/p2panda", rev = "3e84cac48bba05c6857cce2ec433862b97f8d53c", default-features = false } +# Group membership and the auth DAG (P2.1). Default features only: `test_utils` turns on +# test-only behaviour in p2panda-core, so the test types come from our own tests. +p2panda-auth = { git = "https://github.com/p2panda/p2panda", rev = "3e84cac48bba05c6857cce2ec433862b97f8d53c" } postcard = { version = "1", features = ["alloc"] } rand = "0.10" redb = "=4.3.0" diff --git a/pkgs/id/src/lib.rs b/pkgs/id/src/lib.rs index 4ed2f2c54e..76f8103045 100644 --- a/pkgs/id/src/lib.rs +++ b/pkgs/id/src/lib.rs @@ -179,6 +179,7 @@ pub mod fileops; pub mod helpers; pub mod invite; pub mod local; +pub mod membership; pub mod meta_client; #[cfg(feature = "world")] pub mod petname; diff --git a/pkgs/id/src/membership/frontier.rs b/pkgs/id/src/membership/frontier.rs new file mode 100644 index 0000000000..076a472998 --- /dev/null +++ b/pkgs/id/src/membership/frontier.rs @@ -0,0 +1,310 @@ +//! The auth-frontier mapping (P2.1). +//! +//! An auth event names its causal past through `after`, and that can include events which are +//! not group operations. p2panda-auth orders group operations only by their explicit +//! `dependencies`. So each auth operation needs the maximal group operations of its group in its +//! full causal past, found by walking `after` through the other events. That set is its auth +//! frontier. +//! +//! The index holds every event the membership layer has decided, with its `after` hashes and +//! whether it stands in the auth graph. The frontier of a past is memoised per group, so each +//! event does work only for the part of its past that the index has not seen for that group. +//! +//! Three rules keep the mapping honest (S2 showed each failure): +//! +//! - An `after` hash the index does not hold is an error, never a root. Treating it as a root +//! drops an add the author had seen, which voids a valid operation. +//! - Only events that stand in the auth graph are named. An event that stands for no graph node +//! (any non-auth event, or a refused event with no placeholder) is walked through. +//! - The result is minimal: an operation dominated by another in the set is dropped. + +use std::collections::{HashMap, HashSet}; + +use p2panda_core::Hash; +use thiserror::Error; + +/// Why the index refused a lookup or an insert. +#[derive(Clone, Debug, PartialEq, Eq, Error)] +pub enum FrontierError { + /// An `after` hash the index does not hold. The event must wait for it. + #[error("event {0} is not in the causal index")] + UnknownEvent(Hash), + /// The event is already indexed. Inserting it again would corrupt the memo. + #[error("event {0} is already in the causal index")] + AlreadyIndexed(Hash), +} + +#[derive(Clone, Debug)] +struct Node { + after: Vec, + /// The group of this event as a node of the auth graph, if it is one. + graph_group: Option, +} + +/// The decided events, with the auth frontier of each past memoised per group. +#[derive(Clone, Debug, Default)] +pub struct CausalIndex { + nodes: HashMap, + /// `memo[(event, group)]` is the auth frontier of the past of `event` for `group`. + memo: HashMap<(Hash, Hash), Vec>, +} + +impl CausalIndex { + /// An empty index. + pub fn new() -> Self { + Self::default() + } + + /// Whether the event is indexed (decided, in any way). + pub fn contains(&self, id: &Hash) -> bool { + self.nodes.contains_key(id) + } + + /// Records a decided event. Its `after` hashes must already be indexed, which the caller + /// checks by holding the event until they are. + /// + /// `graph_group` is the group of the event as a node of the auth graph, or `None` when the + /// event stands for no graph node. + pub fn insert( + &mut self, + id: Hash, + after: Vec, + graph_group: Option, + ) -> Result<(), FrontierError> { + if self.nodes.contains_key(&id) { + return Err(FrontierError::AlreadyIndexed(id)); + } + if let Some(missing) = after.iter().find(|hash| !self.nodes.contains_key(hash)) { + return Err(FrontierError::UnknownEvent(*missing)); + } + self.nodes.insert(id, Node { after, graph_group }); + Ok(()) + } + + /// The auth frontier for `group` of an event whose `after` is `after`: the maximal group + /// operations in the causal past of that event, sorted. An `after` hash that is itself a group + /// operation of `group` counts as its own candidate. + pub fn frontier(&mut self, after: &[Hash], group: Hash) -> Result, FrontierError> { + self.fill(after, group)?; + self.combine(after, group) + } + + /// Memoises the frontier of every event in the past of `roots` for `group`. The walk is + /// iterative, so a long chain of non-auth events cannot exhaust the stack. + fn fill(&mut self, roots: &[Hash], group: Hash) -> Result<(), FrontierError> { + let mut stack: Vec<(Hash, bool)> = roots.iter().map(|id| (*id, false)).collect(); + while let Some((id, expanded)) = stack.pop() { + if self.memo.contains_key(&(id, group)) { + continue; + } + let after = self + .nodes + .get(&id) + .ok_or(FrontierError::UnknownEvent(id))? + .after + .clone(); + if expanded { + let frontier = self.combine(&after, group)?; + self.memo.insert((id, group), frontier); + } else { + stack.push((id, true)); + for parent in after { + if !self.memo.contains_key(&(parent, group)) { + stack.push((parent, false)); + } + } + } + } + Ok(()) + } + + /// The minimal set of group operations that a past built from `after` contains. Each `after` + /// hash contributes itself when it is a group operation, and otherwise its own frontier. The + /// memo must already cover the past. + fn combine(&self, after: &[Hash], group: Hash) -> Result, FrontierError> { + let mut candidates = Vec::new(); + for parent in after { + let node = self + .nodes + .get(parent) + .ok_or(FrontierError::UnknownEvent(*parent))?; + if node.graph_group == Some(group) { + candidates.push(*parent); + } else { + let frontier = self + .memo + .get(&(*parent, group)) + .ok_or(FrontierError::UnknownEvent(*parent))?; + candidates.extend(frontier.iter().copied()); + } + } + candidates.sort(); + candidates.dedup(); + + let maximal = candidates + .iter() + .filter(|candidate| { + !candidates + .iter() + .any(|other| other != *candidate && self.below(**candidate, *other, group)) + }) + .copied() + .collect(); + Ok(maximal) + } + + /// Whether `candidate` lies in the causal past of `of`, a group operation. Reads only the + /// memoised frontiers, walking from `of` through the frontiers of the operations it reaches. + fn below(&self, candidate: Hash, of: Hash, group: Hash) -> bool { + let mut seen = HashSet::new(); + let mut stack = vec![of]; + while let Some(current) = stack.pop() { + let Some(frontier) = self.memo.get(&(current, group)) else { + continue; + }; + for hash in frontier { + if *hash == candidate { + return true; + } + if seen.insert(*hash) { + stack.push(*hash); + } + } + } + false + } +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used)] +mod tests { + use super::*; + + const G: u8 = 1; + const H: u8 = 2; + + fn h(n: u8) -> Hash { + Hash::digest([n]) + } + + /// Indexes an event: `auth` is the group it stands for in the auth graph. + fn put(index: &mut CausalIndex, id: u8, after: &[u8], auth: Option) { + let after: Vec = after.iter().map(|n| h(*n)).collect(); + index.insert(h(id), after, auth.map(h)).unwrap(); + } + + #[test] + fn test_group_operations_over_each_other_name_the_latest() { + // 10 (group G) is the create. 11 (group G) names 10. 12 (group G) names 11. + let mut index = CausalIndex::new(); + put(&mut index, 10, &[], Some(G)); + put(&mut index, 11, &[10], Some(G)); + put(&mut index, 12, &[11], Some(G)); + assert_eq!(index.frontier(&[h(12)], h(G)).unwrap(), vec![h(12)]); + assert_eq!(index.frontier(&[h(11)], h(G)).unwrap(), vec![h(11)]); + } + + #[test] + fn test_a_non_auth_hop_is_walked_through() { + // X (auth) -> D (document) -> R names D. R's frontier is X, not D (S2 mapping case). + let mut index = CausalIndex::new(); + put(&mut index, 1, &[], Some(G)); + put(&mut index, 2, &[1], None); + assert_eq!(index.frontier(&[h(2)], h(G)).unwrap(), vec![h(1)]); + } + + #[test] + fn test_frontier_is_minimal_across_non_auth_hops() { + // X1 -> D1 -> X2 -> D2 -> R. X2's frontier is {X1}; R's is {X2}, never {X1, X2}. + let mut index = CausalIndex::new(); + put(&mut index, 1, &[], Some(G)); + put(&mut index, 2, &[1], None); + put(&mut index, 3, &[2], Some(G)); + put(&mut index, 4, &[3], None); + // The frontier of an event is taken over its `after`: X2 names [2], R names [4]. + assert_eq!(index.frontier(&[h(2)], h(G)).unwrap(), vec![h(1)]); + assert_eq!(index.frontier(&[h(4)], h(G)).unwrap(), vec![h(3)]); + } + + #[test] + fn test_concurrent_group_operations_are_both_kept() { + // Two group operations by different authors, neither in the other's past. + let mut index = CausalIndex::new(); + put(&mut index, 1, &[], Some(G)); + put(&mut index, 2, &[1], Some(G)); + put(&mut index, 3, &[1], Some(G)); + assert_eq!( + index.frontier(&[h(2), h(3)], h(G)).unwrap(), + vec![h(2), h(3)] + ); + } + + #[test] + fn test_another_groups_operation_is_walked_through() { + // X (group G) -> Y (group H) -> R (group G). R's frontier for G is X: Y is another group, + // but X is in R's past through Y. + let mut index = CausalIndex::new(); + put(&mut index, 1, &[], Some(G)); + put(&mut index, 2, &[1], Some(H)); + assert_eq!(index.frontier(&[h(2)], h(G)).unwrap(), vec![h(1)]); + assert_eq!(index.frontier(&[h(2)], h(H)).unwrap(), vec![h(2)]); + } + + #[test] + fn test_a_refused_event_with_no_graph_node_is_walked_through() { + // X refused without a placeholder (graph_group None): R's frontier is X's own frontier. + let mut index = CausalIndex::new(); + put(&mut index, 1, &[], Some(G)); + put(&mut index, 2, &[1], None); + put(&mut index, 3, &[2], Some(G)); + assert_eq!(index.frontier(&[h(3)], h(G)).unwrap(), vec![h(3)]); + assert_eq!(index.frontier(&[h(2)], h(G)).unwrap(), vec![h(1)]); + } + + #[test] + fn test_unknown_after_is_an_error_not_a_root() { + // The event names 99, which the index does not hold. A root would drop X from its past. + let mut index = CausalIndex::new(); + put(&mut index, 1, &[], Some(G)); + assert_eq!( + index.frontier(&[h(1), h(99)], h(G)), + Err(FrontierError::UnknownEvent(h(99))) + ); + } + + #[test] + fn test_insert_rejects_an_unknown_after() { + let mut index = CausalIndex::new(); + assert_eq!( + index.insert(h(2), vec![h(99)], None), + Err(FrontierError::UnknownEvent(h(99))) + ); + assert!(!index.contains(&h(2))); + } + + #[test] + fn test_insert_rejects_a_second_copy() { + let mut index = CausalIndex::new(); + put(&mut index, 1, &[], Some(G)); + assert_eq!( + index.insert(h(1), vec![], Some(h(G))), + Err(FrontierError::AlreadyIndexed(h(1))) + ); + } + + #[test] + fn test_a_long_non_auth_chain_does_not_exhaust_the_stack() { + let mut index = CausalIndex::new(); + let mut prev = Hash::digest(b"root"); + index.insert(prev, vec![], Some(h(G))).unwrap(); + for n in 0..20_000u32 { + let id = Hash::digest(n.to_be_bytes()); + index.insert(id, vec![prev], None).unwrap(); + prev = id; + } + assert_eq!( + index.frontier(&[prev], h(G)).unwrap(), + vec![Hash::digest(b"root")] + ); + } +} diff --git a/pkgs/id/src/membership/mod.rs b/pkgs/id/src/membership/mod.rs new file mode 100644 index 0000000000..89d3142eb1 --- /dev/null +++ b/pkgs/id/src/membership/mod.rs @@ -0,0 +1,114 @@ +//! Group membership on p2panda-auth (Phase 2). +//! +//! p2panda-auth orders group operations by their explicit `dependencies`, and it panics or stalls +//! on a dependency it cannot place. Our events order by `after`, which can name any event. This +//! module bridges the two: +//! +//! - [`frontier`] derives each auth operation's dependencies from its causal past (P2.1). The +//! result is the maximal group operations of the same group, found by walking `after` through +//! non-auth events. The stored `after` is never passed to p2panda-auth directly. +//! +//! The admission gate and the membership layer that holds events until their `after` is decided +//! follow in P2.2. + +pub mod frontier; + +use std::fmt; + +use p2panda_auth::group::resolver::StrongRemove; +use p2panda_auth::group::{GroupAction, GroupCrdt, GroupCrdtState}; +use p2panda_auth::traits::Operation; +use p2panda_core::Hash; +use serde::{Deserialize, Serialize}; + +/// The identity type of p2panda-auth. It names both members and groups, so it is one type with +/// two kinds of value. +/// +/// A member is a key. A group is the BLAKE3 hash of its `group.create` event (design §5.5). +#[derive( + Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, std::hash::Hash, Serialize, Deserialize, +)] +pub enum AuthId { + /// An author's Ed25519 verifying key. + Key([u8; 32]), + /// A group's ID, when it is a member of another group or the target of an operation. + Group(Hash), +} + +impl p2panda_core::traits::Author for AuthId {} + +impl fmt::Display for AuthId { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Key(key) => { + f.write_str("key:")?; + for byte in key { + write!(f, "{byte:02x}")?; + } + Ok(()) + } + Self::Group(id) => write!(f, "group:{id}"), + } + } +} + +/// A group operation as p2panda-auth sees it. The dependencies are the auth frontier, derived by +/// [`frontier`], never copied from the event's `after`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct AuthOperation { + /// The event's ID. + pub id: Hash, + /// The key that signed the event. + pub author: AuthId, + /// The auth frontier: the maximal group operations of this group in the causal past. + pub dependencies: Vec, + /// The group the action applies to. + pub group_id: AuthId, + /// The membership change. + pub action: GroupAction, +} + +impl Operation for AuthOperation { + fn id(&self) -> Hash { + self.id + } + + fn author(&self) -> AuthId { + self.author + } + + fn dependencies(&self) -> Vec { + self.dependencies.clone() + } + + fn group_id(&self) -> AuthId { + self.group_id + } + + fn action(&self) -> GroupAction { + self.action.clone() + } +} + +/// The p2panda-auth state for every group in one store. +pub type GroupState = GroupCrdtState; + +/// The p2panda-auth processor, with the strong-remove concurrency rules. +pub type Graph = + GroupCrdt>; + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used)] +mod tests { + use super::*; + + #[test] + fn test_auth_id_orders_keys_and_groups_apart() { + let key = AuthId::Key([0; 32]); + let group = AuthId::Group(Hash::digest(b"group")); + assert_ne!(key, group); + assert!(key < group, "keys sort before groups"); + assert!(key.to_string().starts_with("key:")); + assert!(group.to_string().starts_with("group:")); + } +} diff --git a/pkgs/id/tests/membership_properties.rs b/pkgs/id/tests/membership_properties.rs new file mode 100644 index 0000000000..2c02bb5389 --- /dev/null +++ b/pkgs/id/tests/membership_properties.rs @@ -0,0 +1,175 @@ +//! Property tests for the membership layer (plan P2.1 and P2.2). +//! +//! A scenario is a random causal DAG: each event names some earlier events in `after`, and some of +//! the events are group operations of one of two groups. The mapping is checked against a +//! brute-force walk of each event's full causal past. + +#![allow(clippy::unwrap_used, clippy::expect_used)] + +use std::collections::{BTreeSet, HashMap, HashSet}; + +use id::membership::frontier::CausalIndex; +use p2panda_core::Hash; +use proptest::prelude::*; + +/// SplitMix64. A scenario is a pure function of its seed. +struct Rng(u64); + +impl Rng { + fn next_u64(&mut self) -> u64 { + self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15); + let mut z = self.0; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) + } + + /// A number in `0..n`. + fn below(&mut self, n: u64) -> u64 { + self.next_u64() % n + } +} + +/// Cases per property. `PROPTEST_CASES` raises it. +fn config() -> ProptestConfig { + let cases = std::env::var("PROPTEST_CASES") + .ok() + .and_then(|value| value.parse().ok()) + .unwrap_or(256); + ProptestConfig { + cases, + ..ProptestConfig::default() + } +} + +/// One event of a random DAG. `group` is `Some` for a group operation. +#[derive(Clone, Debug)] +struct DagEvent { + id: Hash, + after: Vec, + group: Option, +} + +fn group_hash(n: u64) -> Hash { + Hash::digest([n as u8]) +} + +/// A random causal DAG of `size` events. Event `i` names up to four earlier events, and about two +/// thirds of the events are group operations of one of two groups. +fn random_dag(seed: u64, size: usize) -> Vec { + let mut rng = Rng(seed); + let mut events: Vec = Vec::with_capacity(size); + for i in 0..size { + let id = Hash::digest((i as u32).to_be_bytes()); + let mut after: Vec = Vec::new(); + if i > 0 { + let wanted = rng.below(4.min(i as u64) + 1); + for _ in 0..wanted { + let pick = events[rng.below(i as u64) as usize].id; + if !after.contains(&pick) { + after.push(pick); + } + } + } + let group = (rng.below(3) != 0).then(|| group_hash(rng.below(2))); + events.push(DagEvent { id, after, group }); + } + events +} + +/// Every event in the causal past of `id`, walked through `after`. Excludes `id`. +fn past(by_id: &HashMap, id: Hash) -> HashSet { + let mut seen = HashSet::new(); + let mut stack = by_id[&id].after.clone(); + while let Some(next) = stack.pop() { + if seen.insert(next) { + stack.extend(by_id[&next].after.iter().copied()); + } + } + seen +} + +/// The reference frontier: the maximal group operations of `group` in the full causal past of +/// `event`, sorted. Computed by walking the whole past, with no memo. +fn reference_frontier(dag: &[DagEvent], event: &DagEvent, group: Hash) -> Vec { + let by_id: HashMap = dag.iter().map(|e| (e.id, e)).collect(); + let candidates: Vec = past_of_after(&by_id, &event.after) + .into_iter() + .filter(|id| by_id[id].group == Some(group)) + .collect(); + let mut maximal: Vec = candidates + .iter() + .filter(|candidate| { + !candidates + .iter() + .any(|other| other != *candidate && past(&by_id, *other).contains(*candidate)) + }) + .copied() + .collect(); + maximal.sort(); + maximal +} + +/// The past of an event whose `after` is `after`: the `after` hashes and everything below them. +fn past_of_after(by_id: &HashMap, after: &[Hash]) -> HashSet { + let mut seen: HashSet = HashSet::new(); + let mut stack = after.to_vec(); + while let Some(next) = stack.pop() { + if seen.insert(next) { + stack.extend(by_id[&next].after.iter().copied()); + } + } + seen +} + +proptest! { + #![proptest_config(config())] + + /// The memoised, incremental frontier equals the full walk for every event, in causal order, + /// for both groups. The memo is shared across calls, so this also checks that reuse is sound. + #[test] + fn test_frontier_equals_the_full_walk_for_every_event_and_group( + seed in any::(), + size in 1usize..=40, + ) { + let dag = random_dag(seed, size); + let mut index = CausalIndex::new(); + for event in &dag { + for group in [group_hash(0), group_hash(1)] { + let got = index.frontier(&event.after, group).unwrap(); + let want = reference_frontier(&dag, event, group); + prop_assert_eq!(got, want, "event {} group {}", event.id, group); + } + index.insert(event.id, event.after.clone(), event.group).unwrap(); + } + } + + /// The frontier never names an event outside the group, never names an event that is in the + /// past of another frontier member, and never names anything that is not in the past. + #[test] + fn test_frontier_is_an_antichain_of_group_operations_in_the_past( + seed in any::(), + size in 1usize..=40, + ) { + let dag = random_dag(seed, size); + let by_id: HashMap = dag.iter().map(|e| (e.id, e)).collect(); + let mut index = CausalIndex::new(); + for event in &dag { + let group = group_hash(0); + let frontier = index.frontier(&event.after, group).unwrap(); + let below = past_of_after(&by_id, &event.after); + let unique: BTreeSet = frontier.iter().copied().collect(); + prop_assert_eq!(unique.len(), frontier.len()); + for member in &frontier { + prop_assert!(below.contains(member)); + prop_assert_eq!(by_id[member].group, Some(group)); + for other in &frontier { + if other != member { + prop_assert!(!past(&by_id, *other).contains(member)); + } + } + } + index.insert(event.id, event.after.clone(), event.group).unwrap(); + } + } +} diff --git a/pkgs/id/tests/membership_scenarios.rs b/pkgs/id/tests/membership_scenarios.rs new file mode 100644 index 0000000000..4d72db2e62 --- /dev/null +++ b/pkgs/id/tests/membership_scenarios.rs @@ -0,0 +1,430 @@ +//! The S2 scenarios and failure modes (spike S2, `RESULTS.md`), run through the auth-frontier +//! mapping of `id::membership::frontier` and p2panda-auth's `GroupCrdt`. +//! +//! Each scenario is checked in every causal-delivery order. The final membership must be the same +//! in all of them. The failure modes are regressions: the literal mapping, the raw `after`, the +//! root dependency, and an unknown dependency. + +#![allow(clippy::unwrap_used, clippy::expect_used)] + +use std::panic::{AssertUnwindSafe, catch_unwind}; + +use id::membership::frontier::CausalIndex; +use id::membership::{AuthId, AuthOperation, Graph, GroupState}; +use p2panda_auth::Access; +use p2panda_auth::group::{GroupAction, GroupCrdtError, GroupMember}; +use p2panda_core::Hash; + +/// The group is the create event's ID, which is event 0 in every scenario. +const GROUP: u8 = 0; + +fn key(letter: char) -> AuthId { + AuthId::Key([letter as u8; 32]) +} + +fn ident(n: u8) -> Hash { + Hash::digest([n]) +} + +fn group_id() -> AuthId { + AuthId::Group(ident(GROUP)) +} + +/// One event of a scenario. `action` is `None` for an event with no membership effect. +#[derive(Clone)] +struct Ev { + id: u8, + author: char, + after: Vec, + action: Option>, +} + +fn ev(id: u8, author: char, after: &[u8], action: GroupAction) -> Ev { + Ev { + id, + author, + after: after.to_vec(), + action: Some(action), + } +} + +fn other(id: u8, author: char, after: &[u8]) -> Ev { + Ev { + id, + author, + after: after.to_vec(), + action: None, + } +} + +fn create() -> GroupAction { + GroupAction::Create { + initial_members: [ + ('A', Access::manage()), + ('B', Access::manage()), + ('C', Access::manage()), + ] + .into_iter() + .map(|(letter, access)| (GroupMember::Individual(key(letter)), access)) + .collect(), + } +} + +fn add(member: char, access: Access<()>) -> GroupAction { + GroupAction::Add { + member: GroupMember::Individual(key(member)), + access, + } +} + +fn remove(member: char) -> GroupAction { + GroupAction::Remove { + member: GroupMember::Individual(key(member)), + } +} + +/// The base of every scenario: group created by Alice with Alice, Bob and Claire as managers. +fn base() -> Vec { + vec![ev(0, 'A', &[], create())] +} + +/// Maps the auth events to operations, with the auth frontier as dependencies. Each event is +/// indexed as it is read, the way the layer does, so `after` may name any earlier event. +fn operations(events: &[Ev]) -> Vec { + let mut index = CausalIndex::new(); + let mut out = Vec::new(); + for event in events { + let after: Vec = event.after.iter().map(|n| ident(*n)).collect(); + match &event.action { + None => index.insert(ident(event.id), after, None).unwrap(), + Some(action) => { + let group = if action.is_create() { + ident(event.id) + } else { + ident(GROUP) + }; + let dependencies = index.frontier(&after, group).unwrap(); + index.insert(ident(event.id), after, Some(group)).unwrap(); + out.push(AuthOperation { + id: ident(event.id), + author: key(event.author), + dependencies, + group_id: AuthId::Group(group), + action: action.clone(), + }); + } + } + } + out +} + +/// Every causal-delivery order of `ops`: each operation after all of its dependencies. +fn causal_orders(ops: &[AuthOperation]) -> Vec> { + fn walk(ops: &[AuthOperation], placed: &mut Vec, out: &mut Vec>) { + if placed.len() == ops.len() { + out.push(placed.clone()); + return; + } + for (i, op) in ops.iter().enumerate() { + let ready = op + .dependencies + .iter() + .all(|dep| placed.iter().any(|p| ops[*p].id == *dep)); + if ready && !placed.contains(&i) { + placed.push(i); + walk(ops, placed, out); + placed.pop(); + } + } + } + let mut out = Vec::new(); + walk(ops, &mut Vec::new(), &mut out); + out +} + +fn apply(ops: &[AuthOperation], order: &[usize]) -> Result { + order.iter().try_fold(Graph::init(), |state, i| { + Graph::process(state, &ops[*i]).map_err(|error| format!("{error:?}")) + }) +} + +fn members(state: &GroupState) -> Vec<(AuthId, Access<()>)> { + let mut list = state.members(group_id()); + list.sort_by_key(|(id, _)| *id); + list +} + +/// Runs every causal order and checks each one gives `expected`. +fn check(name: &str, events: &[Ev], expected: &[(AuthId, Access<()>)]) { + let ops = operations(events); + let orders = causal_orders(&ops); + assert!(!orders.is_empty(), "{name}: no causal order"); + for order in &orders { + let state = apply(&ops, order).expect(name); + assert_eq!(members(&state), expected, "{name} in order {order:?}"); + } +} + +fn expected(list: &[(char, Access<()>)]) -> Vec<(AuthId, Access<()>)> { + let mut out: Vec<(AuthId, Access<()>)> = + list.iter().map(|(l, a)| (key(*l), a.clone())).collect(); + out.sort_by_key(|(id, _)| *id); + out +} + +#[test] +fn test_s2_week_late_add_by_a_removed_member_is_voided() { + // Alice removes Bob (R). Bob's add of Dave (X) was made without seeing R. + let mut events = base(); + events.push(ev(1, 'A', &[0], remove('B'))); + events.push(ev(2, 'B', &[0], add('D', Access::manage()))); + check( + "1 week-late add", + &events, + &expected(&[('A', Access::manage()), ('C', Access::manage())]), + ); +} + +#[test] +fn test_s2_causally_prior_add_survives() { + // Bob adds Dave (Y). Alice sees Y, then removes Bob (R names Y). + let mut events = base(); + events.push(ev(1, 'B', &[0], add('D', Access::manage()))); + events.push(ev(2, 'A', &[1], remove('B'))); + check( + "2 causally prior add", + &events, + &expected(&[ + ('A', Access::manage()), + ('C', Access::manage()), + ('D', Access::manage()), + ]), + ); +} + +#[test] +fn test_s2_transitive_void_by_authority() { + // Dave's authority comes from Bob's add Z, which is concurrent with R. Dave adds Eve after Z. + let mut events = base(); + events.push(ev(1, 'B', &[0], add('D', Access::manage()))); + events.push(ev(2, 'A', &[0], remove('B'))); + events.push(ev(3, 'D', &[1], add('E', Access::read()))); + check( + "3 transitive void", + &events, + &expected(&[('A', Access::manage()), ('C', Access::manage())]), + ); +} + +#[test] +fn test_s2_dependent_add_by_an_independent_author_stands() { + // The same shape, but the add after Z is by Claire, who has her own authority (rule 3b). + let mut events = base(); + events.push(ev(1, 'B', &[0], add('D', Access::manage()))); + events.push(ev(2, 'A', &[0], remove('B'))); + events.push(ev(3, 'C', &[1], add('E', Access::read()))); + check( + "3b dependent add by independent author", + &events, + &expected(&[ + ('A', Access::manage()), + ('C', Access::manage()), + ('E', Access::read()), + ]), + ); +} + +#[test] +fn test_s2_mutual_removal_removes_both() { + let mut events = base(); + events.push(ev(1, 'A', &[0], remove('B'))); + events.push(ev(2, 'B', &[0], remove('A'))); + check( + "4 mutual removal", + &events, + &expected(&[('C', Access::manage())]), + ); +} + +#[test] +fn test_s2_three_cycle_removes_every_member() { + let mut events = base(); + events.push(ev(1, 'A', &[0], remove('B'))); + events.push(ev(2, 'B', &[0], remove('C'))); + events.push(ev(3, 'C', &[0], remove('A'))); + check("4b three-cycle", &events, &[]); +} + +#[test] +fn test_s2_concurrent_re_add_is_voided() { + // Claire removes and re-adds Bob, without seeing Alice's removal of Bob. + let mut events = base(); + events.push(ev(1, 'C', &[0], remove('B'))); + events.push(ev(2, 'C', &[1], add('B', Access::manage()))); + events.push(ev(3, 'A', &[0], remove('B'))); + check( + "5 concurrent re-add", + &events, + &expected(&[('A', Access::manage()), ('C', Access::manage())]), + ); +} + +#[test] +fn test_s2_re_add_concurrent_with_another_managers_removal_is_voided() { + // Alice removes and re-adds Bob. Claire removes Bob concurrently. + let mut events = base(); + events.push(ev(1, 'A', &[0], remove('B'))); + events.push(ev(2, 'A', &[1], add('B', Access::manage()))); + events.push(ev(3, 'C', &[0], remove('B'))); + check( + "5c re-add concurrent with a removal", + &events, + &expected(&[('A', Access::manage()), ('C', Access::manage())]), + ); +} + +#[test] +fn test_s2_causal_re_add_control_stands() { + let mut events = base(); + events.push(ev(1, 'A', &[0], remove('B'))); + events.push(ev(2, 'A', &[1], add('B', Access::manage()))); + check( + "5b causal re-add (control)", + &events, + &expected(&[ + ('A', Access::manage()), + ('B', Access::manage()), + ('C', Access::manage()), + ]), + ); +} + +/// The S2 DAG for the mapping cases: X (Bob adds Dave), D (a document naming X), R (Alice removes +/// Bob, naming D). Bob's add is in Alice's causal past, so it must stand. +fn mapping_dag() -> Vec { + let mut events = base(); + events.push(ev(1, 'B', &[0], add('D', Access::manage()))); + events.push(other(2, 'B', &[1])); + events.push(ev(3, 'A', &[2], remove('B'))); + events +} + +#[test] +fn test_s2_frontier_of_the_remove_names_the_add_not_the_document() { + let events = mapping_dag(); + let mut index = CausalIndex::new(); + for event in &events[..3] { + let after: Vec = event.after.iter().map(|n| ident(*n)).collect(); + let graph = event.action.as_ref().map(|_| ident(GROUP)); + index.insert(ident(event.id), after, graph).unwrap(); + } + // The remove names the document (2), which is not a group operation. The frontier is the add. + assert_eq!( + index.frontier(&[ident(2)], ident(GROUP)).unwrap(), + vec![ident(1)] + ); +} + +#[test] +fn test_s2_frontier_mapping_keeps_the_add_in_every_order() { + let ops = operations(&mapping_dag()); + assert_eq!(ops[2].dependencies, vec![ident(1)]); + let expected = expected(&[ + ('A', Access::manage()), + ('C', Access::manage()), + ('D', Access::manage()), + ]); + for order in causal_orders(&ops) { + let state = apply(&ops, &order).unwrap(); + assert_eq!(members(&state), expected, "order {order:?}"); + } +} + +/// The state after the create and the add, which is every op before the remove. +fn state_before_remove(ops: &[AuthOperation]) -> GroupState { + apply(&ops[..2], &[0, 1]).unwrap() +} + +#[test] +fn test_s2_regression_raw_after_as_dependencies_stalls_with_missing_dependencies() { + // Naming the document (a non-auth event) as the dependency: p2panda-auth holds the remove on + // an operation that does not exist, forever. + let ops = operations(&mapping_dag()); + let state = state_before_remove(&ops); + let raw = AuthOperation { + dependencies: vec![ident(2)], + ..ops[2].clone() + }; + let result = Graph::process(state, &raw); + assert!( + matches!(result, Err(GroupCrdtError::MissingDependencies(dep, _)) if dep == ident(2)), + "raw after must stall on the document" + ); +} + +#[test] +fn test_s2_regression_literal_mapping_with_no_auth_dependency_does_not_apply() { + // The literal mapping gives the remove no auth dependency, because the auth ops named in `after` + // are none. p2panda-auth panics on a non-create with no dependencies. The mapping must never + // produce that case for a group that exists. + let ops = operations(&mapping_dag()); + let state = state_before_remove(&ops); + let literal = AuthOperation { + dependencies: Vec::new(), + ..ops[2].clone() + }; + let outcome = catch_unwind(AssertUnwindSafe(|| Graph::process(state, &literal))); + assert!( + outcome.is_err(), + "the crate panics on a non-create with no dependencies" + ); +} + +#[test] +fn test_s2_regression_root_dependency_voids_a_valid_add() { + // Naming only the create (a root) drops Bob's add from the remove's past. Dave is then + // removed although Alice had seen his add. The frontier keeps him (checked above). + let ops = operations(&mapping_dag()); + let state = state_before_remove(&ops); + let root = AuthOperation { + dependencies: vec![ident(0)], + ..ops[2].clone() + }; + let after_root = Graph::process(state, &root).unwrap(); + let got = members(&after_root); + assert!( + !got.iter().any(|(id, _)| *id == key('D')), + "the root dependency voids Dave's add" + ); +} + +#[test] +fn test_s2_regression_unknown_dependency_is_an_error_not_a_panic() { + let ops = operations(&mapping_dag()); + let state = state_before_remove(&ops); + let unknown = AuthOperation { + dependencies: vec![ident(99)], + ..ops[2].clone() + }; + let result = catch_unwind(AssertUnwindSafe(|| Graph::process(state, &unknown))); + assert!( + matches!(result, Ok(Err(GroupCrdtError::MissingDependencies(dep, _))) if dep == ident(99)), + "an unknown dependency is an error" + ); +} + +#[test] +fn test_s2_frontier_is_order_independent_across_every_causal_order_of_the_scenarios() { + // Every scenario above gives one outcome in every order. This asserts it once more on the + // longest of them, the three-cycle, so a change in the mapping shows up here too. + let mut events = base(); + events.push(ev(1, 'A', &[0], remove('B'))); + events.push(ev(2, 'B', &[0], remove('C'))); + events.push(ev(3, 'C', &[0], remove('A'))); + let ops = operations(&events); + let outcomes: std::collections::BTreeSet = causal_orders(&ops) + .iter() + .map(|order| format!("{:?}", members(&apply(&ops, order).unwrap()))) + .collect(); + assert_eq!(outcomes.len(), 1); +} From 236dcbc7e0ac20935cc1083ee514f77e42f930f8 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 11 Oct 2026 23:32:31 -0500 Subject: [PATCH 06/40] feat(rust): admission gate for auth operations [P2.2] The membership layer decides each causal event once. An event whose `after` is not decided yet is held and released when it is. A membership operation goes through the gate before p2panda-auth sees it: - a non-create with no dependencies is rejected (the crate would panic); - an operation whose group does not exist at its dependencies is rejected (the crate panics at group/crdt/mod.rs, the expect in apply_action). p2panda-auth consumes its state when `process` fails, so a refusal rebuilds the state by replaying the accepted operations. A refused event leaves a no-op placeholder when a manager stands at its dependencies: a Promote of that manager to Read, which the crate accepts whoever signed it, because the promoted member already manages. Without a manager, the event is walked through like a non-auth event, so its descendants do not stall. Tests: unit (gate outcomes, held and released in causal order, placeholder and walk-through, the group-absent regression, malformed), the S2 scenarios through the layer in every arrival order, and a property over random scenarios and arrival orders with repeats: every event is decided, and the outcomes, state, and derived dependencies match the canonical order. --- pkgs/id/src/membership/gate.rs | 173 ++++++++ pkgs/id/src/membership/layer.rs | 590 +++++++++++++++++++++++++ pkgs/id/src/membership/mod.rs | 14 +- pkgs/id/tests/membership_properties.rs | 184 +++++++- pkgs/id/tests/membership_scenarios.rs | 73 ++- 5 files changed, 1029 insertions(+), 5 deletions(-) create mode 100644 pkgs/id/src/membership/gate.rs create mode 100644 pkgs/id/src/membership/layer.rs diff --git a/pkgs/id/src/membership/gate.rs b/pkgs/id/src/membership/gate.rs new file mode 100644 index 0000000000..92cac8c3e0 --- /dev/null +++ b/pkgs/id/src/membership/gate.rs @@ -0,0 +1,173 @@ +//! The admission gate (P2.2). +//! +//! The gate decides whether an operation may reach `GroupCrdt::process`. p2panda-auth panics on +//! some inputs that it could have refused: a non-create with no dependencies, and an operation +//! whose group does not exist at its dependencies (`group/crdt/mod.rs`, the `expect` in +//! `apply_action`). The gate turns both into a decision before the crate sees them. +//! +//! The gate does not validate authority. An operation by an author without manage access reaches +//! the crate, which refuses it with a state-change error. Only the crate can say whether the +//! author had authority at the operation's position. + +use std::collections::HashSet; + +use p2panda_core::Hash; + +use super::{AuthOperation, GroupState}; + +/// Why the gate rejected an operation. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Rejection { + /// A group operation other than a create, with no dependencies. It has no position to apply + /// at, so the crate would panic on it. + NoDependencies, + /// The operation's group does not exist at its dependencies. The crate would panic on it. + GroupAbsent, +} + +/// What the gate decides for one operation. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Admission { + /// The operation may be processed now. + Admit, + /// Hold the operation until these dependencies are in the state. + Wait(Vec), + /// Refuse the operation. The reason is for the void record. + Reject(Rejection), +} + +/// Decides whether `op` may be processed on `state`. Does not change the state. +pub fn admit(state: &GroupState, op: &AuthOperation) -> Admission { + let missing: Vec = op + .dependencies + .iter() + .filter(|dep| !state.inner.operations.contains_key(dep)) + .copied() + .collect(); + if !missing.is_empty() { + return Admission::Wait(missing); + } + if op.action.is_create() { + return Admission::Admit; + } + if op.dependencies.is_empty() { + return Admission::Reject(Rejection::NoDependencies); + } + let dependencies: HashSet = op.dependencies.iter().copied().collect(); + match state.inner.state_at(&dependencies) { + Ok(groups) if groups.contains_key(&op.group_id) => Admission::Admit, + _ => Admission::Reject(Rejection::GroupAbsent), + } +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used)] +mod tests { + use p2panda_auth::Access; + use p2panda_auth::group::{GroupAction, GroupMember}; + + use super::*; + use crate::membership::{AuthId, Graph}; + + fn key(n: u8) -> AuthId { + AuthId::Key([n; 32]) + } + + fn group(n: u8) -> AuthId { + AuthId::Group(Hash::digest([n])) + } + + fn op(id: u8, group_id: AuthId, deps: &[u8], action: GroupAction) -> AuthOperation { + AuthOperation { + id: Hash::digest([id]), + author: key(1), + dependencies: deps.iter().map(|d| Hash::digest([*d])).collect(), + group_id, + action, + } + } + + fn create(id: u8, members: &[u8]) -> AuthOperation { + let initial_members = members + .iter() + .map(|m| (GroupMember::Individual(key(*m)), Access::manage())) + .collect(); + op(id, group(id), &[], GroupAction::Create { initial_members }) + } + + /// The state after creating group `id` with keys 1 and 2 as managers. + fn state_with_group(id: u8) -> GroupState { + Graph::process(Graph::init(), &create(id, &[1, 2])).unwrap() + } + + #[test] + fn test_a_create_is_admitted_with_no_dependencies() { + assert_eq!(admit(&Graph::init(), &create(10, &[1])), Admission::Admit); + } + + #[test] + fn test_a_non_create_with_no_dependencies_is_rejected() { + let remove = op( + 11, + group(10), + &[], + GroupAction::Remove { + member: GroupMember::Individual(key(2)), + }, + ); + assert_eq!( + admit(&state_with_group(10), &remove), + Admission::Reject(Rejection::NoDependencies) + ); + } + + #[test] + fn test_a_group_absent_at_its_dependencies_is_rejected() { + // Group 20 was never created. Its operation names group 10's create, which is present. + let add = op( + 21, + group(20), + &[10], + GroupAction::Add { + member: GroupMember::Individual(key(3)), + access: Access::read(), + }, + ); + assert_eq!( + admit(&state_with_group(10), &add), + Admission::Reject(Rejection::GroupAbsent) + ); + } + + #[test] + fn test_missing_dependencies_are_held() { + let add = op( + 21, + group(10), + &[99], + GroupAction::Add { + member: GroupMember::Individual(key(3)), + access: Access::read(), + }, + ); + assert_eq!( + admit(&state_with_group(10), &add), + Admission::Wait(vec![Hash::digest([99])]) + ); + } + + #[test] + fn test_an_operation_on_a_present_group_is_admitted() { + let state = state_with_group(10); + let add = op( + 21, + group(10), + &[10], + GroupAction::Add { + member: GroupMember::Individual(key(3)), + access: Access::read(), + }, + ); + assert_eq!(admit(&state, &add), Admission::Admit); + } +} diff --git a/pkgs/id/src/membership/layer.rs b/pkgs/id/src/membership/layer.rs new file mode 100644 index 0000000000..c05db89b1e --- /dev/null +++ b/pkgs/id/src/membership/layer.rs @@ -0,0 +1,590 @@ +//! The membership layer: decides each causal event once, and holds the events whose past is +//! incomplete. +//! +//! [`Membership::receive`] takes one verified event. An event whose `after` hashes are not all +//! decided is held. An event that is ready is decided: a membership operation is mapped to its +//! auth frontier, passed through the gate, and processed by p2panda-auth. Its outcome is recorded, +//! and every held event it releases is decided in turn. +//! +//! Each decided event is indexed, so a later event can name it in `after`. A refused event +//! becomes a no-op placeholder in the auth graph when a manager stands at its dependencies, so its +//! descendants depend on it and do not stall. Otherwise it is walked through, as a non-auth event. +//! +//! The final state depends only on the set of events, not on the order they arrive in. That is +//! the property the tests in `tests/membership_properties.rs` check. + +use std::collections::{HashMap, HashSet, VecDeque}; + +use p2panda_auth::Access; +use p2panda_auth::group::{GroupAction, GroupMember}; +use p2panda_core::Hash; +use thiserror::Error; + +use super::frontier::{CausalIndex, FrontierError}; +use super::gate::{self, Admission, Rejection}; +use super::{AuthId, AuthOperation, Graph, GroupState}; + +/// One event as the membership layer sees it. The caller has verified it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct CausalEvent { + /// The event's ID. + pub id: Hash, + /// The event's `after` hashes, as signed. + pub after: Vec, + /// What the event means for membership. + pub role: Role, +} + +/// What an event means for membership. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Role { + /// Any event other than a membership operation. It has a causal position and nothing else. + Other, + /// A membership operation by `author`. `group` is the group named in the event; it is `None` + /// for a create, whose group is the event's own ID. + Auth { + /// The key that signed the event. + author: [u8; 32], + /// The group the event names, if any. + group: Option, + /// The membership change. + action: GroupAction, + }, +} + +/// Why the layer refused a membership operation. A refused event changes no membership. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Refusal { + /// A non-create with no group. + Malformed, + /// The gate rejected the operation before p2panda-auth saw it. + Gate(Rejection), + /// p2panda-auth refused the operation at its position. For example, its author lacked manage + /// access there. The message is the crate's. + Invalid(String), +} + +/// What became of one event. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Outcome { + /// Decided and applied. An event with no membership effect is applied too. + Applied, + /// Held until these `after` hashes are decided. + Held(Vec), + /// Refused. `placeholder` says whether a no-op stands in the auth graph in its place. + Refused { + /// Why it was refused. + reason: Refusal, + /// Whether a placeholder stands in the auth graph. + placeholder: bool, + }, + /// Already decided or held. Nothing changed. + Duplicate, +} + +/// A failure of the layer itself. None of these is a refusal of an event; each means the layer +/// cannot keep its invariants. +#[derive(Clone, Debug, PartialEq, Eq, Error)] +pub enum MembershipError { + /// The causal index refused a lookup or insert. + #[error(transparent)] + Frontier(#[from] FrontierError), + /// Rebuilding the auth graph from the accepted operations failed. Each one was accepted once, + /// so this means a broken invariant. + #[error("rebuilding the auth graph failed at {0}")] + Rebuild(String), + /// The gate admitted an operation that still names a missing dependency. + #[error("internal invariant broken: {0}")] + Internal(String), +} + +/// The membership state of one store: the causal index, the held events, and the auth graph. +#[derive(Debug, Default)] +pub struct Membership { + index: CausalIndex, + held: HashMap, + /// For each `after` hash not yet decided, the held events that name it. + waiting_on: HashMap>, + /// The auth frontier each membership operation was decided with. + dependencies: HashMap>, + state: GroupState, + /// Every operation accepted into the auth graph, in order. A rebuild replays these. + accepted: Vec, +} + +impl Membership { + /// An empty layer. + pub fn new() -> Self { + Self::default() + } + + /// Takes one verified event, and returns the outcome of each event it decided, in the order + /// they were decided. The first entry is the event itself, unless it was a duplicate or was + /// held. Held events it releases follow it. + /// + /// An error means an invariant broke, and the layer's state can no longer be trusted. Discard + /// the layer after one. + pub fn receive(&mut self, event: CausalEvent) -> Result, MembershipError> { + if self.index.contains(&event.id) || self.held.contains_key(&event.id) { + return Ok(vec![(event.id, Outcome::Duplicate)]); + } + let missing: Vec = event + .after + .iter() + .filter(|hash| !self.index.contains(hash)) + .copied() + .collect(); + if !missing.is_empty() { + for hash in &missing { + self.waiting_on.entry(*hash).or_default().push(event.id); + } + let id = event.id; + self.held.insert(id, event); + return Ok(vec![(id, Outcome::Held(missing))]); + } + + let mut outcomes = Vec::new(); + let mut ready = VecDeque::from([event]); + while let Some(next) = ready.pop_front() { + let id = next.id; + outcomes.push((id, self.decide(next)?)); + for waiter in self.waiting_on.remove(&id).unwrap_or_default() { + let Some(held) = self.held.get(&waiter) else { + continue; + }; + if held.after.iter().all(|hash| self.index.contains(hash)) + && let Some(event) = self.held.remove(&waiter) + { + ready.push_back(event); + } + } + } + Ok(outcomes) + } + + /// Decides one event whose `after` hashes are all indexed. + fn decide(&mut self, event: CausalEvent) -> Result { + let CausalEvent { id, after, role } = event; + let Role::Auth { + author, + group, + action, + } = role + else { + self.index.insert(id, after, None)?; + return Ok(Outcome::Applied); + }; + let group = if action.is_create() { Some(id) } else { group }; + let Some(group) = group else { + self.index.insert(id, after, None)?; + return Ok(Outcome::Refused { + reason: Refusal::Malformed, + placeholder: false, + }); + }; + + let dependencies = self.index.frontier(&after, group)?; + self.dependencies.insert(id, dependencies.clone()); + let op = AuthOperation { + id, + author: AuthId::Key(author), + dependencies, + group_id: AuthId::Group(group), + action, + }; + match gate::admit(&self.state, &op) { + Admission::Admit => {} + Admission::Wait(missing) => { + return Err(MembershipError::Internal(format!( + "{id} admitted with missing dependencies {missing:?}" + ))); + } + Admission::Reject(rejection) => { + return self.refuse(op, group, after, Refusal::Gate(rejection)); + } + } + match self.process(&op)? { + Ok(()) => { + self.index.insert(id, after, Some(group))?; + Ok(Outcome::Applied) + } + Err(message) => self.refuse(op, group, after, Refusal::Invalid(message)), + } + } + + /// Records a refusal. A placeholder stands in the graph when a manager is in the group at the + /// operation's dependencies. Otherwise the event is walked through. + fn refuse( + &mut self, + op: AuthOperation, + group: Hash, + after: Vec, + reason: Refusal, + ) -> Result { + let id = op.id; + let placeholder = match self.manager_at(group, &op.dependencies) { + Some(target) => { + // Promoting a member who already manages changes nothing, and the crate does not + // check the promoter for that case. So this operation is valid whoever wrote it. + let noop = AuthOperation { + action: GroupAction::Promote { + member: GroupMember::Individual(target), + access: Access::read(), + }, + ..op + }; + self.process(&noop)?.is_ok() + } + None => false, + }; + self.index.insert(id, after, placeholder.then_some(group))?; + Ok(Outcome::Refused { + reason, + placeholder, + }) + } + + /// The least active manager of `group` at `dependencies`, or `None` when there is none. The + /// choice is deterministic, so every peer makes the same placeholder. + fn manager_at(&self, group: Hash, dependencies: &[Hash]) -> Option { + let heads: HashSet = dependencies.iter().copied().collect(); + Graph::members_at(&self.state, heads, AuthId::Group(group)) + .ok()? + .into_iter() + .filter(|(id, access)| matches!(id, AuthId::Key(_)) && access.is_manage()) + .map(|(id, _)| id) + .min() + } + + /// Processes `op` on the auth graph and records it as accepted. `process` consumes the state, + /// so when the crate refuses the operation the state is rebuilt from the accepted operations. + /// The inner result is the crate's refusal message. + fn process(&mut self, op: &AuthOperation) -> Result, MembershipError> { + let state = std::mem::take(&mut self.state); + match Graph::process(state, op) { + Ok(next) => { + self.state = next; + self.accepted.push(op.clone()); + Ok(Ok(())) + } + Err(error) => { + self.state = rebuild(&self.accepted)?; + Ok(Err(error.to_string())) + } + } + } + + /// The members of `group` and their access, in the current state. + pub fn members(&self, group: Hash) -> Vec<(AuthId, Access<()>)> { + self.state.members(AuthId::Group(group)) + } + + /// The auth frontier that the layer derived for a decided membership operation. The stored + /// `after` of the event is never used as a dependency, so this is what the crate saw. + pub fn dependencies(&self, id: &Hash) -> Option<&[Hash]> { + self.dependencies.get(id).map(Vec::as_slice) + } + + /// Whether the event is held, waiting for an `after` hash. + pub fn is_held(&self, id: &Hash) -> bool { + self.held.contains_key(id) + } + + /// How many events are held. + pub fn held_len(&self) -> usize { + self.held.len() + } +} + +/// Replays `accepted` on a fresh graph. +fn rebuild(accepted: &[AuthOperation]) -> Result { + accepted.iter().try_fold(Graph::init(), |state, op| { + Graph::process(state, op) + .map_err(|error| MembershipError::Rebuild(format!("{}: {error}", op.id))) + }) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used)] +mod tests { + use super::*; + + fn key(n: u8) -> [u8; 32] { + [n; 32] + } + + fn id(n: u8) -> Hash { + Hash::digest([n]) + } + + /// An event with no membership effect. + fn other(n: u8, after: &[u8]) -> CausalEvent { + CausalEvent { + id: id(n), + after: after.iter().map(|a| id(*a)).collect(), + role: Role::Other, + } + } + + /// A membership operation by `author` on group `group` (`None` for a create). + fn auth( + n: u8, + author: u8, + group: Option, + after: &[u8], + action: GroupAction, + ) -> CausalEvent { + CausalEvent { + id: id(n), + after: after.iter().map(|a| id(*a)).collect(), + role: Role::Auth { + author: key(author), + group: group.map(id), + action, + }, + } + } + + fn create(n: u8, author: u8, managers: &[u8]) -> CausalEvent { + let initial_members = managers + .iter() + .map(|m| { + ( + GroupMember::Individual(AuthId::Key(key(*m))), + Access::manage(), + ) + }) + .collect(); + auth( + n, + author, + None, + &[], + GroupAction::Create { initial_members }, + ) + } + + fn add(member: u8, access: Access<()>) -> GroupAction { + GroupAction::Add { + member: GroupMember::Individual(AuthId::Key(key(member))), + access, + } + } + + fn remove(member: u8) -> GroupAction { + GroupAction::Remove { + member: GroupMember::Individual(AuthId::Key(key(member))), + } + } + + fn outcome_of(outcomes: &[(Hash, Outcome)], n: u8) -> Outcome { + outcomes + .iter() + .find(|(hash, _)| *hash == id(n)) + .map(|(_, outcome)| outcome.clone()) + .unwrap() + } + + fn member_keys(layer: &Membership, group: u8) -> Vec { + let mut keys: Vec = layer + .members(id(group)) + .into_iter() + .map(|(k, _)| k) + .collect(); + keys.sort(); + keys + } + + #[test] + fn test_a_create_is_applied_and_its_group_is_its_own_id() { + let mut layer = Membership::new(); + let outcomes = layer.receive(create(10, 1, &[1, 2])).unwrap(); + assert_eq!(outcomes, vec![(id(10), Outcome::Applied)]); + assert_eq!( + member_keys(&layer, 10), + vec![AuthId::Key(key(1)), AuthId::Key(key(2))] + ); + assert_eq!(layer.dependencies(&id(10)), Some(&[][..])); + } + + #[test] + fn test_a_duplicate_changes_nothing() { + let mut layer = Membership::new(); + layer.receive(create(10, 1, &[1])).unwrap(); + let again = layer.receive(create(10, 1, &[1])).unwrap(); + assert_eq!(again, vec![(id(10), Outcome::Duplicate)]); + } + + #[test] + fn test_an_event_naming_an_undecided_hash_is_held_until_it_arrives() { + // Regression: an unknown `after` is held, never treated as a root. Treating it as a root + // would derive an empty frontier and apply the remove without the add it depends on. + let mut layer = Membership::new(); + let held = layer + .receive(auth(12, 1, Some(10), &[99], remove(2))) + .unwrap(); + assert_eq!(held, vec![(id(12), Outcome::Held(vec![id(99)]))]); + assert!(layer.is_held(&id(12))); + assert!(layer.dependencies(&id(12)).is_none()); + + layer.receive(create(10, 1, &[1, 2])).unwrap(); + let released = layer.receive(other(99, &[10])).unwrap(); + assert_eq!(released.len(), 2); + assert_eq!(released[0], (id(99), Outcome::Applied)); + assert_eq!(released[1], (id(12), Outcome::Applied)); + assert_eq!(member_keys(&layer, 10), vec![AuthId::Key(key(1))]); + assert_eq!(layer.held_len(), 0); + } + + #[test] + fn test_held_events_are_released_in_causal_order_whatever_the_arrival_order() { + let mut layer = Membership::new(); + assert!(matches!( + layer + .receive(auth(12, 1, Some(10), &[11], add(3, Access::read()))) + .unwrap()[0] + .1, + Outcome::Held(_) + )); + assert!(matches!( + layer + .receive(auth(11, 1, Some(10), &[10], add(4, Access::read()))) + .unwrap()[0] + .1, + Outcome::Held(_) + )); + let released = layer.receive(create(10, 1, &[1])).unwrap(); + let order: Vec = released.iter().map(|(hash, _)| *hash).collect(); + assert_eq!(order, vec![id(10), id(11), id(12)]); + assert_eq!(layer.held_len(), 0); + } + + #[test] + fn test_the_frontier_names_the_auth_operation_not_the_document_between() { + // Regression for the literal mapping: a remove whose `after` names a non-auth event must + // not name that event. p2panda-auth would hold the remove on it forever. + let mut layer = Membership::new(); + layer.receive(create(10, 1, &[1, 2, 3])).unwrap(); + layer.receive(other(11, &[10])).unwrap(); + layer + .receive(auth(12, 1, Some(10), &[11], remove(3))) + .unwrap(); + assert_eq!(layer.dependencies(&id(12)), Some(&[id(10)][..])); + assert_eq!( + member_keys(&layer, 10), + vec![AuthId::Key(key(1)), AuthId::Key(key(2))] + ); + } + + #[test] + fn test_a_refused_event_leaves_a_placeholder_so_descendants_apply() { + // Key 2 has read access only, so its add is refused by the crate. The placeholder keeps + // key 1's later add, which names the refused event, from stalling. + let mut layer = Membership::new(); + layer.receive(create(10, 1, &[1])).unwrap(); + layer + .receive(auth(11, 1, Some(10), &[10], add(2, Access::read()))) + .unwrap(); + let refused = layer + .receive(auth(12, 2, Some(10), &[11], add(3, Access::manage()))) + .unwrap(); + assert!(matches!( + outcome_of(&refused, 12), + Outcome::Refused { + reason: Refusal::Invalid(_), + placeholder: true + } + )); + + let after_placeholder = layer + .receive(auth(13, 1, Some(10), &[12], add(4, Access::read()))) + .unwrap(); + assert_eq!(outcome_of(&after_placeholder, 13), Outcome::Applied); + assert_eq!(layer.dependencies(&id(13)), Some(&[id(12)][..])); + assert_eq!( + member_keys(&layer, 10), + vec![ + AuthId::Key(key(1)), + AuthId::Key(key(2)), + AuthId::Key(key(4)) + ] + ); + } + + #[test] + fn test_a_refused_event_with_no_manager_is_walked_through_so_descendants_do_not_stall() { + // No manager at all: no placeholder. The descendant names the refused event but depends + // on the create, and is refused by the crate, not held. + let mut layer = Membership::new(); + let read_only = GroupAction::Create { + initial_members: vec![(GroupMember::Individual(AuthId::Key(key(2))), Access::read())], + }; + layer.receive(auth(10, 1, None, &[], read_only)).unwrap(); + let refused = layer + .receive(auth(11, 1, Some(10), &[10], remove(2))) + .unwrap(); + assert!(matches!( + outcome_of(&refused, 11), + Outcome::Refused { + reason: Refusal::Invalid(_), + placeholder: false + } + )); + let descendant = layer + .receive(auth(12, 2, Some(10), &[11], add(3, Access::read()))) + .unwrap(); + assert!(matches!( + outcome_of(&descendant, 12), + Outcome::Refused { + reason: Refusal::Invalid(_), + .. + } + )); + assert_eq!(layer.dependencies(&id(12)), Some(&[id(10)][..])); + assert!(!layer.is_held(&id(12))); + } + + #[test] + fn test_an_operation_for_a_group_absent_at_its_dependencies_is_refused_without_a_panic() { + // Regression for group/crdt/mod.rs (the expect in apply_action). Group 20 was never + // created, and its operation names group 10's create. The mapping finds no group-20 + // operation in the past, so the gate refuses it before the crate can panic. + let mut layer = Membership::new(); + layer.receive(create(10, 1, &[1])).unwrap(); + let outcomes = layer + .receive(auth(21, 1, Some(20), &[10], add(3, Access::read()))) + .unwrap(); + assert_eq!( + outcome_of(&outcomes, 21), + Outcome::Refused { + reason: Refusal::Gate(Rejection::NoDependencies), + placeholder: false, + } + ); + assert_eq!(member_keys(&layer, 10), vec![AuthId::Key(key(1))]); + } + + #[test] + fn test_a_non_create_with_no_group_is_refused_as_malformed() { + let mut layer = Membership::new(); + layer.receive(create(10, 1, &[1])).unwrap(); + let outcomes = layer + .receive(CausalEvent { + id: id(11), + after: vec![id(10)], + role: Role::Auth { + author: key(1), + group: None, + action: remove(2), + }, + }) + .unwrap(); + assert_eq!( + outcome_of(&outcomes, 11), + Outcome::Refused { + reason: Refusal::Malformed, + placeholder: false + } + ); + } +} diff --git a/pkgs/id/src/membership/mod.rs b/pkgs/id/src/membership/mod.rs index 89d3142eb1..bf744c76da 100644 --- a/pkgs/id/src/membership/mod.rs +++ b/pkgs/id/src/membership/mod.rs @@ -7,11 +7,19 @@ //! - [`frontier`] derives each auth operation's dependencies from its causal past (P2.1). The //! result is the maximal group operations of the same group, found by walking `after` through //! non-auth events. The stored `after` is never passed to p2panda-auth directly. +//! - [`gate`] decides whether an operation may reach `GroupCrdt::process` (P2.2). It holds an +//! operation whose dependencies are missing and rejects one whose group does not exist at its +//! dependencies, which is the case where p2panda-auth panics. +//! - [`layer`] puts the two together. It holds events whose `after` is incomplete, decides each +//! event once, and leaves a no-op placeholder for an event it refuses, so that its descendants +//! do not stall. //! -//! The admission gate and the membership layer that holds events until their `after` is decided -//! follow in P2.2. +//! The layer takes events that the caller has already verified (signature, encoding, and +//! `after` closure are the event store's job). It does not read the event store itself. pub mod frontier; +pub mod gate; +pub mod layer; use std::fmt; @@ -21,6 +29,8 @@ use p2panda_auth::traits::Operation; use p2panda_core::Hash; use serde::{Deserialize, Serialize}; +pub use layer::{CausalEvent, Membership, MembershipError, Outcome, Refusal, Role}; + /// The identity type of p2panda-auth. It names both members and groups, so it is one type with /// two kinds of value. /// diff --git a/pkgs/id/tests/membership_properties.rs b/pkgs/id/tests/membership_properties.rs index 2c02bb5389..c8605d573b 100644 --- a/pkgs/id/tests/membership_properties.rs +++ b/pkgs/id/tests/membership_properties.rs @@ -6,9 +6,12 @@ #![allow(clippy::unwrap_used, clippy::expect_used)] -use std::collections::{BTreeSet, HashMap, HashSet}; +use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use id::membership::frontier::CausalIndex; +use id::membership::{AuthId, CausalEvent, Membership, Outcome, Role}; +use p2panda_auth::Access; +use p2panda_auth::group::{GroupAction, GroupMember}; use p2panda_core::Hash; use proptest::prelude::*; @@ -173,3 +176,182 @@ proptest! { } } } + +/// The identity of event `i`, which is also the ID of the group it creates, for `i` in 0 and 1. +fn id_of(i: usize) -> Hash { + Hash::digest((i as u32).to_be_bytes()) +} + +fn key(n: u64) -> AuthId { + AuthId::Key([n as u8; 32]) +} + +fn access_of(level: u64) -> Access<()> { + match level { + 0 => Access::read(), + 1 => Access::write(), + _ => Access::manage(), + } +} + +fn create_role(members: &[(u64, u64)]) -> Role { + Role::Auth { + author: [1; 32], + group: None, + action: GroupAction::Create { + initial_members: members + .iter() + .map(|(n, level)| (GroupMember::Individual(key(*n)), access_of(*level))) + .collect(), + }, + } +} + +/// A random membership scenario of `size` events. Event 0 creates group 0. Event 1 sometimes +/// creates group 1. Later events are membership operations by random authors, some of whom are not +/// members, on random groups, or other events. Each names up to four earlier events. Some +/// operations are invalid where they sit, so the layer refuses them. +fn scenario(seed: u64, size: usize) -> Vec { + let mut rng = Rng(seed); + let mut events: Vec = Vec::with_capacity(size); + let mut groups = vec![id_of(0)]; + for i in 0..size { + let mut after: Vec = Vec::new(); + if i > 0 { + for _ in 0..rng.below(5) { + let pick = events[rng.below(i as u64) as usize].id; + if !after.contains(&pick) { + after.push(pick); + } + } + } + let role = if i == 0 { + create_role(&[(1, 2), (2, 2), (3, 2)]) + } else if i == 1 && rng.below(2) == 0 { + groups.push(id_of(1)); + create_role(&[(1, 2), (2, 0)]) + } else if rng.below(4) == 0 { + Role::Other + } else { + let group = groups[rng.below(groups.len() as u64) as usize]; + let member = key(1 + rng.below(5)); + let access = access_of(rng.below(3)); + let action = match rng.below(4) { + 0 => GroupAction::Add { + member: GroupMember::Individual(member), + access, + }, + 1 => GroupAction::Remove { + member: GroupMember::Individual(member), + }, + 2 => GroupAction::Promote { + member: GroupMember::Individual(member), + access, + }, + _ => GroupAction::Demote { + member: GroupMember::Individual(member), + access, + }, + }; + Role::Auth { + author: [1 + rng.below(4) as u8; 32], + group: Some(group), + action, + } + }; + events.push(CausalEvent { + id: id_of(i), + after, + role, + }); + } + events +} + +/// What one arrival order produces. +#[derive(Debug, PartialEq, Eq)] +struct Run { + /// The final outcome of each event that was decided. + decided: BTreeMap, + /// The members of groups 0 and 1, sorted. + members: Vec<(Hash, Vec<(AuthId, Access<()>)>)>, + /// The auth frontier the layer derived for each decided event. + dependencies: BTreeMap>, + /// How many events are still held after the last arrival. + held: usize, +} + +/// Delivers `arrivals` to a fresh layer, in order. Each arrival is one event by index. +fn run(events: &[CausalEvent], arrivals: &[usize]) -> Run { + let mut layer = Membership::new(); + let mut decided = BTreeMap::new(); + for &i in arrivals { + for (id, outcome) in layer.receive(events[i].clone()).unwrap() { + if !matches!(outcome, Outcome::Held(_) | Outcome::Duplicate) { + decided.insert(id, outcome); + } + } + } + let members = [id_of(0), id_of(1)] + .into_iter() + .map(|group| { + let mut list = layer.members(group); + list.sort_by_key(|(id, _)| *id); + (group, list) + }) + .collect(); + let dependencies = decided + .keys() + .filter_map(|id| layer.dependencies(id).map(|deps| (*id, deps.to_vec()))) + .collect(); + Run { + decided, + members, + dependencies, + held: layer.held_len(), + } +} + +/// Fisher-Yates shuffle with the scenario generator. +fn shuffle(list: &mut [usize], rng: &mut Rng) { + for i in (1..list.len()).rev() { + let j = rng.below(i as u64 + 1) as usize; + list.swap(i, j); + } +} + +proptest! { + #![proptest_config(config())] + + /// Every arrival order decides every event, and reaches the same outcomes, the same state, and + /// the same derived dependencies. Arrivals are random, and some are repeated. + #[test] + fn test_every_arrival_order_gives_the_same_outcomes_and_state( + seed in any::(), + size in 1usize..=30, + order_seed in any::(), + ) { + let events = scenario(seed, size); + let causal: Vec = (0..events.len()).collect(); + let canonical = run(&events, &causal); + prop_assert_eq!(canonical.held, 0); + prop_assert_eq!(canonical.decided.len(), events.len()); + + let mut rng = Rng(order_seed); + for _ in 0..3 { + let mut arrivals: Vec = (0..events.len()).collect(); + shuffle(&mut arrivals, &mut rng); + for _ in 0..rng.below(4) { + let repeat = rng.below(events.len() as u64) as usize; + let at = rng.below(arrivals.len() as u64 + 1) as usize; + arrivals.insert(at, repeat); + } + let got = run(&events, &arrivals); + prop_assert_eq!(got.held, 0, "arrivals {:?}", arrivals); + prop_assert_eq!(got.decided.len(), events.len(), "arrivals {:?}", arrivals); + prop_assert_eq!(&got.decided, &canonical.decided, "arrivals {:?}", arrivals); + prop_assert_eq!(&got.members, &canonical.members, "arrivals {:?}", arrivals); + prop_assert_eq!(&got.dependencies, &canonical.dependencies, "arrivals {:?}", arrivals); + } + } +} diff --git a/pkgs/id/tests/membership_scenarios.rs b/pkgs/id/tests/membership_scenarios.rs index 4d72db2e62..2dc174aea7 100644 --- a/pkgs/id/tests/membership_scenarios.rs +++ b/pkgs/id/tests/membership_scenarios.rs @@ -10,7 +10,9 @@ use std::panic::{AssertUnwindSafe, catch_unwind}; use id::membership::frontier::CausalIndex; -use id::membership::{AuthId, AuthOperation, Graph, GroupState}; +use id::membership::{ + AuthId, AuthOperation, CausalEvent, Graph, GroupState, Membership, Outcome, Role, +}; use p2panda_auth::Access; use p2panda_auth::group::{GroupAction, GroupCrdtError, GroupMember}; use p2panda_core::Hash; @@ -154,7 +156,67 @@ fn members(state: &GroupState) -> Vec<(AuthId, Access<()>)> { list } -/// Runs every causal order and checks each one gives `expected`. +/// Every arrival order of `n` events, not only the causal ones. +fn permutations(n: usize) -> Vec> { + fn walk(current: &mut Vec, rest: &mut Vec, out: &mut Vec>) { + if rest.is_empty() { + out.push(current.clone()); + return; + } + for i in 0..rest.len() { + let next = rest.remove(i); + current.push(next); + walk(current, rest, out); + current.pop(); + rest.insert(i, next); + } + } + let mut out = Vec::new(); + walk(&mut Vec::new(), &mut (0..n).collect(), &mut out); + out +} + +/// The membership the layer reaches when `events` arrive in `order`. The layer holds an event +/// until its `after` is decided, so the order need not be causal. +fn layer_members(events: &[Ev], order: &[usize]) -> Vec<(AuthId, Access<()>)> { + let mut layer = Membership::new(); + for i in order { + let event = &events[*i]; + let role = match &event.action { + None => Role::Other, + Some(action) => Role::Auth { + author: [event.author as u8; 32], + group: (!action.is_create()).then(|| ident(GROUP)), + action: action.clone(), + }, + }; + let after = event.after.iter().map(|n| ident(*n)).collect(); + let outcomes = layer + .receive(CausalEvent { + id: ident(event.id), + after, + role, + }) + .expect("the layer decides every event"); + assert!( + outcomes + .iter() + .all(|(_, outcome)| !matches!(outcome, Outcome::Refused { .. })), + "a valid S2 event is refused in order {order:?}" + ); + } + assert_eq!( + layer.held_len(), + 0, + "every event is decided in order {order:?}" + ); + let mut list = layer.members(ident(GROUP)); + list.sort_by_key(|(id, _)| *id); + list +} + +/// Runs every causal order, and every arrival order through the layer, and checks each gives +/// `expected`. fn check(name: &str, events: &[Ev], expected: &[(AuthId, Access<()>)]) { let ops = operations(events); let orders = causal_orders(&ops); @@ -163,6 +225,13 @@ fn check(name: &str, events: &[Ev], expected: &[(AuthId, Access<()>)]) { let state = apply(&ops, order).expect(name); assert_eq!(members(&state), expected, "{name} in order {order:?}"); } + for order in permutations(events.len()) { + assert_eq!( + layer_members(events, &order), + expected, + "{name} through the layer in arrival order {order:?}" + ); + } } fn expected(list: &[(char, Access<()>)]) -> Vec<(AuthId, Access<()>)> { From e857a7edfb8b345d5ed287b80892a06f01c93311 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 11 Oct 2026 23:32:50 -0500 Subject: [PATCH 07/40] docs(id): record P2.1 and P2.2 in the phase 2 record [P2] Steps, commits, tests, regressions, and the open questions the two steps leave. --- ...2026-10-12T04-03-47Z_phase_2_membership.md | 31 ++++++++++++------- 1 file changed, 19 insertions(+), 12 deletions(-) diff --git a/doc/2026-10-12T04-03-47Z_phase_2_membership/2026-10-12T04-03-47Z_phase_2_membership.md b/doc/2026-10-12T04-03-47Z_phase_2_membership/2026-10-12T04-03-47Z_phase_2_membership.md index 5e342ebdca..a68faef71f 100644 --- a/doc/2026-10-12T04-03-47Z_phase_2_membership/2026-10-12T04-03-47Z_phase_2_membership.md +++ b/doc/2026-10-12T04-03-47Z_phase_2_membership/2026-10-12T04-03-47Z_phase_2_membership.md @@ -7,16 +7,16 @@ ## Steps -| Step | Track | Status | Commits | Tests added | Notes | -| --------------------------------- | ---------- | ------ | ------- | ----------- | ------------------------------------- | -| P2.1 Auth-frontier mapping | auth | todo | | | | -| P2.2 Admission gate | auth | todo | | | | -| P2.3 Authority-based voiding | voiding | todo | | | replaces the Phase 1 rule | -| P2.4 Friendship cap and dissolve | friend | todo | | | | -| P2.5 Delegation modes | delegation | todo | | | | -| P2.6 World capabilities | caps | todo | | | use-count bounds dropped (decision 3) | -| P2.7 Cross-world reconciliation | later | todo | | | | -| P2.8 Property and mutation checks | later | todo | | | | +| Step | Track | Status | Commits | Tests added | Notes | +| --------------------------------- | ---------- | ------ | -------- | -------------------------------- | ---------------------------------------------------------------------- | +| P2.1 Auth-frontier mapping | auth | done | 862401c9 | 13 unit, 2 property, 16 scenario | `membership::frontier`; S2 cases and failure modes as regressions | +| P2.2 Admission gate | auth | done | 236dcbc7 | 14 unit, 1 property | `membership::{gate, layer}`; placeholders; regression for group absent | +| P2.3 Authority-based voiding | voiding | todo | | | replaces the Phase 1 rule | +| P2.4 Friendship cap and dissolve | friend | todo | | | | +| P2.5 Delegation modes | delegation | todo | | | | +| P2.6 World capabilities | caps | todo | | | use-count bounds dropped (decision 3) | +| P2.7 Cross-world reconciliation | later | todo | | | | +| P2.8 Property and mutation checks | later | todo | | | | ## Decisions @@ -26,7 +26,12 @@ ## Open questions -- None yet. +- Group identity. A group's ID is the BLAKE3 hash of its create event (design §5.5). p2panda-auth needs one `Author` type for members and groups, so the membership code uses `AuthId`: a key or a group hash. Confirm before P2.3 depends on it. +- Nested groups. The frontier covers the target group only. A `GroupMember::Group` in an action names another group's state, and its frontier is not included. +- A refusal rebuilds the auth graph from the accepted operations (`process` consumes its state on error). That is O(accepted) per refusal. Measure before scaling. +- The gate computes `state_at(dependencies)` per operation, so it is O(state) each time. Not measured. +- The layer is not wired into the event store yet, and it has no expiry for held events. Both belong to the store integration. +- Refused events with no manager at their dependencies are walked through, not given a placeholder. Descendants depend on whatever sits below them. ## Changes to the plan @@ -34,7 +39,9 @@ ## Review notes and regression tests -- To be filled. +- P2.1: the raw `after` stalls with `MissingDependencies` (`raw_after_as_dependencies_stalls_with_missing_dependencies`). The literal mapping panics (`literal_mapping_with_no_auth_dependency_does_not_apply`). A root dependency voids a valid add (`root_dependency_voids_a_valid_add`). An unknown dependency is an error (`unknown_dependency_is_an_error_not_a_panic`, and `unknown_after_is_an_error_not_a_root` in the index). +- P2.2: an event naming an undecided hash is held, not treated as a root (`an_event_naming_an_undecided_hash_is_held_until_it_arrives`). A group absent at its dependencies is refused without the crate's panic (`an_operation_for_a_group_absent_at_its_dependencies_is_refused_without_a_panic`). A refused event leaves a placeholder that its descendants apply (`a_refused_event_leaves_a_placeholder_so_descendants_apply`). +- Found while writing P2.2, in the test rather than the code: the frontier of an event is taken over its `after`, so a group operation named directly is its own candidate. The minimality test was corrected to query X2's and R's `after`. ## End From 3974cb29e6677c9d633bbfc1da9f70ff530548e4 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 11 Oct 2026 23:35:22 -0500 Subject: [PATCH 08/40] fix(rust): a delegation frame that carries uses is refused [P2.6] The caps track removed the uses field from the attenuate and delegate_to_friend frames. serde ignores unknown fields, so a client that still sent uses got an unbounded delegation with no error. A delegation frame now refuses uses by name at any depth, in any field order, before it is parsed. Other frames are unchanged. --- pkgs/id/src/world_session.rs | 103 ++++++++++++++++++++++++++++++++++- 1 file changed, 102 insertions(+), 1 deletion(-) diff --git a/pkgs/id/src/world_session.rs b/pkgs/id/src/world_session.rs index f38bd2ee88..dbba6714d8 100644 --- a/pkgs/id/src/world_session.rs +++ b/pkgs/id/src/world_session.rs @@ -1902,6 +1902,30 @@ async fn send_view( } } +const USES_REFUSED: &str = "a delegation may not carry `uses`: a delegated grant has no use count, and the host's limit still applies"; + +/// Whether a delegation frame names `uses` anywhere in it. The field was +/// removed from delegations, and serde would ignore it, minting an unbounded +/// grant from a client that still sends it. Any depth is refused, so no +/// position hides the field. +fn delegation_names_uses(value: &serde_json::Value) -> bool { + let delegating = matches!( + value.get("type").and_then(serde_json::Value::as_str), + Some("attenuate" | "delegate_to_friend") + ); + delegating && names_uses(value) +} + +fn names_uses(value: &serde_json::Value) -> bool { + match value { + serde_json::Value::Object(map) => map + .iter() + .any(|(key, inner)| key == "uses" || names_uses(inner)), + serde_json::Value::Array(items) => items.iter().any(names_uses), + _ => false, + } +} + /// Handle one frame from a joined participant. Returns `false` to end the session. async fn handle_client_frame( service: &WorldService, @@ -1910,7 +1934,13 @@ async fn handle_client_frame( text: &str, ) -> bool { let world = service.world(); - let Ok(frame) = serde_json::from_str::(text) else { + let Ok(value) = serde_json::from_str::(text) else { + return send_error(io, "invalid world frame").await; + }; + if delegation_names_uses(&value) { + return send_error(io, USES_REFUSED).await; + } + let Ok(frame) = serde_json::from_value::(value) else { return send_error(io, "invalid world frame").await; }; let result = match frame { @@ -2174,6 +2204,14 @@ mod tests { .unwrap(); } + /// Sends the frame text as given, so a test controls field order. + async fn say_text(&self, text: &str) { + self.to_server + .send(Inbound::Text(text.to_owned())) + .await + .unwrap(); + } + async fn next(&mut self) -> Option { // An upload takes several seconds in a debug build, so 5 s was too // tight. The deadline still bounds a real hang. @@ -2604,6 +2642,69 @@ mod tests { assert_eq!(child_peer.next().await.unwrap()["message"], "unknown scope"); } + /// A joined participant that may delegate `join`. + async fn delegator(svc: &WorldService) -> Peer { + let delegate = WorldScopes::from_names(["join", "chat", "input", "delegate"]).unwrap(); + let (_, owner) = svc.world().issue("ann".to_owned(), delegate).await.unwrap(); + let mut peer = Peer::connect(svc.clone(), SessionConfig::default()); + peer.say(serde_json::json!({"type":"join","capability":owner.expose()})) + .await; + assert_eq!(peer.next().await.unwrap()["type"], "snapshot"); + peer + } + + /// Delegation frames that name `uses`, in each position a client could put + /// it. Serde would ignore the field and mint an unbounded grant. + const FRAMES_NAMING_USES: [&str; 9] = [ + r#"{"type":"attenuate","uses":1,"name":"bo","scopes":["join"]}"#, + r#"{"type":"attenuate","name":"bo","uses":1,"scopes":["join"]}"#, + r#"{"type":"attenuate","name":"bo","scopes":["join"],"uses":1}"#, + r#"{"type":"attenuate","name":"bo","scopes":["join"],"expires_at":null,"uses":null}"#, + r#"{"type":"attenuate","name":"bo","scopes":["join"],"bounds":{"uses":1}}"#, + r#"{"type":"attenuate","name":"bo","scopes":[{"uses":1}]}"#, + r#"{"type":"delegate_to_friend","uses":1,"friend":"nobody","name":"bo","scopes":["join"]}"#, + r#"{"type":"delegate_to_friend","friend":"nobody","name":"bo","scopes":["join"],"uses":1}"#, + r#"{"type":"delegate_to_friend","friend":"nobody","name":"bo","scopes":["join"],"bounds":{"uses":1}}"#, + ]; + + #[tokio::test] + async fn a_delegation_frame_that_names_uses_is_refused_by_name() { + let svc = service(None); + let mut peer = delegator(&svc).await; + for text in FRAMES_NAMING_USES { + peer.say_text(text).await; + let reply = peer.next().await.unwrap(); + assert_eq!(reply["type"], "error", "{text}"); + assert!( + reply["message"] + .as_str() + .unwrap_or_default() + .contains("`uses`"), + "{text}: {reply}" + ); + } + } + + #[tokio::test] + async fn a_delegation_frame_without_uses_is_accepted() { + let svc = service(None); + let mut peer = delegator(&svc).await; + for text in [ + r#"{"type":"attenuate","name":"bo","scopes":["join"]}"#, + r#"{"type":"attenuate","scopes":["join"],"expires_at":null,"name":"cy"}"#, + ] { + peer.say_text(text).await; + assert_eq!(peer.next().await.unwrap()["type"], "invite", "{text}"); + } + // Past the uses check, this delegate has no account, so the friend + // delegation is denied for that reason alone. + peer.say_text( + r#"{"type":"delegate_to_friend","friend":"nobody","name":"di","scopes":["join"]}"#, + ) + .await; + assert_eq!(peer.next().await.unwrap()["message"], "delegation denied"); + } + #[tokio::test] async fn records_are_paged_prefixed_and_queryable_while_joined() { let svc = service_with_records(None); From 6cd014e51231eb52c73b99e655d00add62abc84a Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 11 Oct 2026 23:36:58 -0500 Subject: [PATCH 09/40] fix(rust): world feature tests compile without the web feature [P2.6] The mail path in world_session calls anyhow's Context on the blocking send, but the import was gated on the sandbox feature. A build with --no-default-features --features world failed to compile. The import is now unconditional. cargo test --no-default-features --features world --no-run and cargo test --features world --no-run both build. --- pkgs/id/src/world_session.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/pkgs/id/src/world_session.rs b/pkgs/id/src/world_session.rs index dbba6714d8..6c61a22a96 100644 --- a/pkgs/id/src/world_session.rs +++ b/pkgs/id/src/world_session.rs @@ -17,7 +17,6 @@ use std::sync::Arc; use std::time::Duration; -#[cfg(feature = "sandbox")] use anyhow::Context as _; use iroh_blobs::{ BlobFormat, Hash, From b985da4f980f8b214d70dd306af2856bd32c4fa7 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 12 Oct 2026 00:08:35 -0500 Subject: [PATCH 10/40] docs(id): owner decisions on groups and friendship, P2.4 re-scoped --- ...6-10-11T11-08-42Z_design_remaining_work.md | 237 +++++++++--------- 1 file changed, 123 insertions(+), 114 deletions(-) diff --git a/doc/2026-10-11T11-08-42Z_design_remaining_work/2026-10-11T11-08-42Z_design_remaining_work.md b/doc/2026-10-11T11-08-42Z_design_remaining_work/2026-10-11T11-08-42Z_design_remaining_work.md index 9e81cf484e..d785f15f8c 100644 --- a/doc/2026-10-11T11-08-42Z_design_remaining_work/2026-10-11T11-08-42Z_design_remaining_work.md +++ b/doc/2026-10-11T11-08-42Z_design_remaining_work/2026-10-11T11-08-42Z_design_remaining_work.md @@ -14,27 +14,27 @@ ## 1. Decisions (the original 19, and the new answers) -| # | Decision | Status | Answer, or what is still open | -| --- | --- | --- | --- | -| 1 | Dependents of voided events | Decided | Authority-based, as p2panda's StrongRemove does | -| 2 | Transfer on removal | Decided | Derived from the signed removal | -| 3 | Use-count bounds on world capabilities | Decided | Dropped from the protocol; local enforcement only | -| 4 | Content on removal | Decided | Content is kept. Removal stops new content | -| 5 | `observe` gating on blobs | Decided | Each request is gated by the world's fetch rules. Observe is off by default | -| 6 | Waiting caps | Decided | 256 per author and 7 days, configurable per world | -| 7 | Joiner history | Changed | `full` by default. `recent:N` per world. Presets 32 and 128 (owner question 5) | -| 8 | `scheme: none` notice | Decided | Explicit notice in the UI and in group metadata | -| 9 | Large-group gate | Decided | No gate. Warnings only, at 96, 128 and 1,000 members | -| 10 | Invite style | Decided | Bearer link (Seitan V2), with expiry and single use. Typed key optional with approval | -| 11 | Pull default | Decided | Open pull, with an authorized option | -| 12 | Our relay | Changed | No Tunnel account now. The n0 relay is used, and users see the server's public IP. Later: a local server behind a Cloudflare Tunnel, and VPS for testing | -| 13 | Relay access control | Decided | None now. Revisit at implementation | -| 14 | mDNS default | Changed | On for `serve` (`--no-mdns` turns it off). Off in the library. The earlier design said off | -| 15 | DHT default | Decided | Off. Opt-in per world | -| 16 | Ticket policy | Changed | Regular tickets work. Addresses are allowed when needed. Signatures are optional (option E) | -| 17 | Fork recovery | Decided | Removal and re-enrolment under a new device key. The alternative, quarantine with approval, is elaborated in task 10 and is a later option | -| 18 | Upstream patch policy | Decided | Patches stay in our fork (developing-today). Nothing goes upstream. No upstream issues or PRs. The scheme v1 change is in the same fork | -| 19 | ed25519 version | Changed | Round 2: stay on 3.0.0 with a conversion shim, and switch to `verify_strict`. Moving to 2.x is not possible while iroh 1.3.0 is pinned (owner question 1) | +| # | Decision | Status | Answer, or what is still open | +| --- | -------------------------------------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | +| 1 | Dependents of voided events | Decided | Authority-based, as p2panda's StrongRemove does | +| 2 | Transfer on removal | Decided | Derived from the signed removal | +| 3 | Use-count bounds on world capabilities | Decided | Dropped from the protocol; local enforcement only | +| 4 | Content on removal | Decided | Content is kept. Removal stops new content | +| 5 | `observe` gating on blobs | Decided | Each request is gated by the world's fetch rules. Observe is off by default | +| 6 | Waiting caps | Decided | 256 per author and 7 days, configurable per world | +| 7 | Joiner history | Changed | `full` by default. `recent:N` per world. Presets 32 and 128 (owner question 5) | +| 8 | `scheme: none` notice | Decided | Explicit notice in the UI and in group metadata | +| 9 | Large-group gate | Decided | No gate. Warnings only, at 96, 128 and 1,000 members | +| 10 | Invite style | Decided | Bearer link (Seitan V2), with expiry and single use. Typed key optional with approval | +| 11 | Pull default | Decided | Open pull, with an authorized option | +| 12 | Our relay | Changed | No Tunnel account now. The n0 relay is used, and users see the server's public IP. Later: a local server behind a Cloudflare Tunnel, and VPS for testing | +| 13 | Relay access control | Decided | None now. Revisit at implementation | +| 14 | mDNS default | Changed | On for `serve` (`--no-mdns` turns it off). Off in the library. The earlier design said off | +| 15 | DHT default | Decided | Off. Opt-in per world | +| 16 | Ticket policy | Changed | Regular tickets work. Addresses are allowed when needed. Signatures are optional (option E) | +| 17 | Fork recovery | Decided | Removal and re-enrolment under a new device key. The alternative, quarantine with approval, is elaborated in task 10 and is a later option | +| 18 | Upstream patch policy | Decided | Patches stay in our fork (developing-today). Nothing goes upstream. No upstream issues or PRs. The scheme v1 change is in the same fork | +| 19 | ed25519 version | Changed | Round 2: stay on 3.0.0 with a conversion shim, and switch to `verify_strict`. Moving to 2.x is not possible while iroh 1.3.0 is pinned (owner question 1) | ## 2. Owner questions (answers needed before Phase 0 starts) @@ -51,111 +51,111 @@ The plan lists the preferred answer for each in its section 4. Short form: ## 3. New items found in round 2 (each has a step in the plan) -| # | Item | Source | Plan step | -| --- | --- | --- | --- | -| N35 | A fork inside a range-sync batch aborts the batch and loses unrelated events | range-config | P3.1a | -| N36 | T=0 never terminates on a mismatched key. Validate K and T | range-config | P3.1b | -| N37 | Range flights above about 524,000 IDs exceed the 16 MiB frame limit. Chunk to a budget | range-config | P3.1c | -| N38 | p2panda-sync depends on p2panda-store with its SQLite default. Fork the one dependency line, or implement LogSync ourselves | store-fit, explainers 5 | P3.2 | -| N39 | `pkgs/id/default.nix` runs `rustup default 1.89.0`, so the Nix check ignores the pin | toolchain | P0.12 | -| N40 | Five plain `verify` calls must become `verify_strict`, with regression tests | ed25519 | P0.11 | -| N41 | A `recent:N` joiner: pre-welcome history must stay outside the crate. Delivering it failed 80 of 120 welcome runs (agent-reported; reproduce first) | welcome-recent | P4.5 | -| N42 | Welcome size budget and chunking above the frame cap | welcome-recent | P4.12 | -| N43 | iroh probes only the first five relays for QAD. QAD-capable relays must come first | cloudflare-workers | P3.6 | -| N44 | The web identity store moves from libsql to redb, with AES-GCM values | turso | P1.9, P1.10 | -| N45 | First creation of the store file: create under a temporary name, commit, rename, fsync the directory | crash-tests | P1.3 | -| N46 | Clippy 1.99 lints and the lints review | toolchain | P8.8 (owner question 6) | -| N47 | Lazy full history for `recent:N` joiners | explainers 4 | P4.6 | -| N48 | Welcome determinism: sort before signing or hashing | scheme-serde | P4.4 | -| N49 | Debug and release builds recover different valid prefixes at four boundary points. Explain it. If it is a redb bug, revisit the engine | crash-tests | P1.4 | -| N50 | Identity: `check_target` does not trim pasted text | ticket-signing | P6.3 | +| # | Item | Source | Plan step | +| --- | --------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------- | ----------------------- | +| N35 | A fork inside a range-sync batch aborts the batch and loses unrelated events | range-config | P3.1a | +| N36 | T=0 never terminates on a mismatched key. Validate K and T | range-config | P3.1b | +| N37 | Range flights above about 524,000 IDs exceed the 16 MiB frame limit. Chunk to a budget | range-config | P3.1c | +| N38 | p2panda-sync depends on p2panda-store with its SQLite default. Fork the one dependency line, or implement LogSync ourselves | store-fit, explainers 5 | P3.2 | +| N39 | `pkgs/id/default.nix` runs `rustup default 1.89.0`, so the Nix check ignores the pin | toolchain | P0.12 | +| N40 | Five plain `verify` calls must become `verify_strict`, with regression tests | ed25519 | P0.11 | +| N41 | A `recent:N` joiner: pre-welcome history must stay outside the crate. Delivering it failed 80 of 120 welcome runs (agent-reported; reproduce first) | welcome-recent | P4.5 | +| N42 | Welcome size budget and chunking above the frame cap | welcome-recent | P4.12 | +| N43 | iroh probes only the first five relays for QAD. QAD-capable relays must come first | cloudflare-workers | P3.6 | +| N44 | The web identity store moves from libsql to redb, with AES-GCM values | turso | P1.9, P1.10 | +| N45 | First creation of the store file: create under a temporary name, commit, rename, fsync the directory | crash-tests | P1.3 | +| N46 | Clippy 1.99 lints and the lints review | toolchain | P8.8 (owner question 6) | +| N47 | Lazy full history for `recent:N` joiners | explainers 4 | P4.6 | +| N48 | Welcome determinism: sort before signing or hashing | scheme-serde | P4.4 | +| N49 | Debug and release builds recover different valid prefixes at four boundary points. Explain it. If it is a redb bug, revisit the engine | crash-tests | P1.4 | +| N50 | Identity: `check_target` does not trim pasted text | ticket-signing | P6.3 | ## 4. Remaining open questions, with the preferred answer -| # | Question | Preferred | Alternatives | -| --- | --- | --- | --- | -| N1 | Storage engine | redb everywhere (Turso rejected by the spike) | Turso, if its performance problems are fixed upstream | -| N2 | Identity store | redb with AES-GCM values | Keep libsql. Turso (smaller diff, experimental encryption) | -| N3 | p2panda-store | Traits over redb, no fork now | Fork p2panda-store and replace its SQLite part | -| N4 | Chain identity | ChainExt on every event | One log per group | -| N5 | Sync method per session | Range above the 3.5% crossover, LogSync below | Range always. LogSync always | -| N6 | Range parameters | K and T local, validated, no wire change | Protocol-negotiated K and T | -| N7 | Periodic rotation | Off. Rotate on removal and explicit update | Rotate every N events, or weekly | -| N8 | Recovery from a compromised device | Manual remove and re-add, as a CLI procedure | Automatic on a detected key change | -| N9 | from_join membership fix | Keep the fork (decision 18). Revisit moving it into our DGM | Our DGM's `from_welcome` inserts the joiner, with no fork | -| N10 | serde_bytes | Scheme v1 (owner question 2) | Stay on stock (3.66 times the welcome size) | -| N11 | Warning thresholds | 96, 128, 1,000 | Other values from the cost data | -| N12 | BeeKEM | Not adopted now | Adopt when the conditions in its assessment are met | -| N13 | Storage power-loss testing | In-process gate in CI. LazyFS as an optional Linux job | VM power cut for final sign-off | -| N14 | p2panda source | Git rev `3e84cac` | crates.io 0.7.x with patches | -| N15 | Toolchain | 1.99.0 | Stay on 1.97.0 | -| N16 | `recent:N` default N | 32, with 128 as the churn-heavy preset | 8, or 1 | -| N17 | `store.rs` doc comment | Fix it: FsStore is redb | none | -| N18 | Observe default | Same as decision 5 | none | -| N19 | Tunnel account | None now. You create any account yourself | Later, with your go | -| N20 | Scheme v1 mechanism | A fork change of two lines (owner question 2) | The transcoder on the outer field (76.9 B per epoch, no fork) | -| N21 | `recent:N` implementation | Adapter calls `Dcgka::add` directly. `EncryptionGroup::add` always sends the full bundle | Patch the high-level add | -| N22 | Heads rule | Cap 32, the author's latest always named, merge on overflow | Cap 16 (162 merges per storm), or cap 2 (3,159) | -| N23 | Freshness window | 5 minutes, configurable per server, world and inviter | A wall-clock window only | -| N24 | Ticket signing | Option E: standard paste, signed invite event checked when present | Option B (our envelope; standard clients refuse it) | -| N25 | Relay operation defaults | SIGINT, config required, metrics on loopback (applied in the kit) | Keep SIGTERM (not recommended) | -| N26 | BeeKEM for groups above 1,000 | Not adopted now. DataScheme everywhere, with warnings | Fix and extend BeeKEM ourselves | -| N27 | Bulk catch-up parameters | K=4, T=8 locally, for bulk catch-up only | K=16 always | -| N28 | Migrating DataScheme groups | Not needed while nothing has shipped | A scheme switch at a barrier, later | -| N29 | QAD source | n0 default, verified on real networks | A QAD VPS first | -| N30 | Address exposure | Documented. "Authorize before connecting" is access control, not privacy | Relay-only transports, or a patched iroh | -| N31 | Relay capacity for fallback pairs | Plan for symmetric-to-symmetric pairs falling back | Accept lower direct-path rates | -| N32 | Startup wait on relays | Wait only for the home relay, with a deadline | Wait for every entry | -| N33 | Tag compaction | Snapshot at a causal cut, then the tail | No compaction | -| N34 | Churn warnings | Warn on re-add churn as well as size | Size only | +| # | Question | Preferred | Alternatives | +| --- | ---------------------------------- | ---------------------------------------------------------------------------------------- | ------------------------------------------------------------- | +| N1 | Storage engine | redb everywhere (Turso rejected by the spike) | Turso, if its performance problems are fixed upstream | +| N2 | Identity store | redb with AES-GCM values | Keep libsql. Turso (smaller diff, experimental encryption) | +| N3 | p2panda-store | Traits over redb, no fork now | Fork p2panda-store and replace its SQLite part | +| N4 | Chain identity | ChainExt on every event | One log per group | +| N5 | Sync method per session | Range above the 3.5% crossover, LogSync below | Range always. LogSync always | +| N6 | Range parameters | K and T local, validated, no wire change | Protocol-negotiated K and T | +| N7 | Periodic rotation | Off. Rotate on removal and explicit update | Rotate every N events, or weekly | +| N8 | Recovery from a compromised device | Manual remove and re-add, as a CLI procedure | Automatic on a detected key change | +| N9 | from_join membership fix | Keep the fork (decision 18). Revisit moving it into our DGM | Our DGM's `from_welcome` inserts the joiner, with no fork | +| N10 | serde_bytes | Scheme v1 (owner question 2) | Stay on stock (3.66 times the welcome size) | +| N11 | Warning thresholds | 96, 128, 1,000 | Other values from the cost data | +| N12 | BeeKEM | Not adopted now | Adopt when the conditions in its assessment are met | +| N13 | Storage power-loss testing | In-process gate in CI. LazyFS as an optional Linux job | VM power cut for final sign-off | +| N14 | p2panda source | Git rev `3e84cac` | crates.io 0.7.x with patches | +| N15 | Toolchain | 1.99.0 | Stay on 1.97.0 | +| N16 | `recent:N` default N | 32, with 128 as the churn-heavy preset | 8, or 1 | +| N17 | `store.rs` doc comment | Fix it: FsStore is redb | none | +| N18 | Observe default | Same as decision 5 | none | +| N19 | Tunnel account | None now. You create any account yourself | Later, with your go | +| N20 | Scheme v1 mechanism | A fork change of two lines (owner question 2) | The transcoder on the outer field (76.9 B per epoch, no fork) | +| N21 | `recent:N` implementation | Adapter calls `Dcgka::add` directly. `EncryptionGroup::add` always sends the full bundle | Patch the high-level add | +| N22 | Heads rule | Cap 32, the author's latest always named, merge on overflow | Cap 16 (162 merges per storm), or cap 2 (3,159) | +| N23 | Freshness window | 5 minutes, configurable per server, world and inviter | A wall-clock window only | +| N24 | Ticket signing | Option E: standard paste, signed invite event checked when present | Option B (our envelope; standard clients refuse it) | +| N25 | Relay operation defaults | SIGINT, config required, metrics on loopback (applied in the kit) | Keep SIGTERM (not recommended) | +| N26 | BeeKEM for groups above 1,000 | Not adopted now. DataScheme everywhere, with warnings | Fix and extend BeeKEM ourselves | +| N27 | Bulk catch-up parameters | K=4, T=8 locally, for bulk catch-up only | K=16 always | +| N28 | Migrating DataScheme groups | Not needed while nothing has shipped | A scheme switch at a barrier, later | +| N29 | QAD source | n0 default, verified on real networks | A QAD VPS first | +| N30 | Address exposure | Documented. "Authorize before connecting" is access control, not privacy | Relay-only transports, or a patched iroh | +| N31 | Relay capacity for fallback pairs | Plan for symmetric-to-symmetric pairs falling back | Accept lower direct-path rates | +| N32 | Startup wait on relays | Wait only for the home relay, with a deadline | Wait for every entry | +| N33 | Tag compaction | Snapshot at a causal cut, then the tail | No compaction | +| N34 | Churn warnings | Warn on re-add churn as well as size | Size only | ## 5. Round 2 results (eleven questions, one folder each) -| Folder | Question | Verdict | -| --- | --- | --- | -| `ed25519` | Versions, compatibility, the newest release | 3.0.0 is newest. 2.x and 3.x are wire-compatible. Stay on 3.0.0 with a shim | -| `turso` | Turso versus redb for the event store, and libsql removal | redb wins on every measure. Identity moves to redb | -| `crash-tests` | LazyFS and a portable crash test | In-process model: 7,808 runs, zero failures. LazyFS optional (user namespace only) | -| `toolchain` | Newest stable, flake update, MSRV | 1.99.0. No lock update needed. The Nix check pins 1.89.0 (a bug) | -| `range-config` | Are K and T on the wire; LogSync crossover | Local only. Crossover is 3.5% of chains, not 40. Fork-in-batch bug found | -| `scheme-serde` | Scheme versions and the welcome encoding | v1 (serde_bytes) is 3.66 times smaller, and the only option that reaches the floor | -| `iroh-allowlist` | Can iroh refuse peers before it exposes addresses | No: identity is known only after the TLS handshake. It is access control, not privacy | -| `ticket-signing` | Signed tickets without breaking regular ones | Option E. Regular paste works, and signed events are checked when present | -| `welcome-recent` | What `recent:N` and `full` cost, and what 32 means | 32 is 5.3 KB per join (stock). `full` grows linearly, and re-adds grow quadratically | -| `store-fit` | Implementing the store traits over redb | About 650 to 900 lines plus tests. No fork needed. LogSync pulls SQLite (N38) | -| `cloudflare-workers` | Later relay options | Tunnel carries no QAD. QAD probes five relays. Workers can serve pkarr HTTP and DoH only | +| Folder | Question | Verdict | +| -------------------- | --------------------------------------------------------- | ---------------------------------------------------------------------------------------- | +| `ed25519` | Versions, compatibility, the newest release | 3.0.0 is newest. 2.x and 3.x are wire-compatible. Stay on 3.0.0 with a shim | +| `turso` | Turso versus redb for the event store, and libsql removal | redb wins on every measure. Identity moves to redb | +| `crash-tests` | LazyFS and a portable crash test | In-process model: 7,808 runs, zero failures. LazyFS optional (user namespace only) | +| `toolchain` | Newest stable, flake update, MSRV | 1.99.0. No lock update needed. The Nix check pins 1.89.0 (a bug) | +| `range-config` | Are K and T on the wire; LogSync crossover | Local only. Crossover is 3.5% of chains, not 40. Fork-in-batch bug found | +| `scheme-serde` | Scheme versions and the welcome encoding | v1 (serde_bytes) is 3.66 times smaller, and the only option that reaches the floor | +| `iroh-allowlist` | Can iroh refuse peers before it exposes addresses | No: identity is known only after the TLS handshake. It is access control, not privacy | +| `ticket-signing` | Signed tickets without breaking regular ones | Option E. Regular paste works, and signed events are checked when present | +| `welcome-recent` | What `recent:N` and `full` cost, and what 32 means | 32 is 5.3 KB per join (stock). `full` grows linearly, and re-adds grow quadratically | +| `store-fit` | Implementing the store traits over redb | About 650 to 900 lines plus tests. No fork needed. LogSync pulls SQLite (N38) | +| `cloudflare-workers` | Later relay options | Tunnel carries no QAD. QAD probes five relays. Workers can serve pkarr HTTP and DoH only | ## 6. Spikes (round 1, all done) -| Spike | Verdict | -| --- | --- | -| S1 to S6, C1 | Done. Earlier results stand, with the corrections recorded in round 2 | -| S7 range sync on real stores | Works and matches S1. Keep K=16 and T=16 as defaults | -| S8 observed-remove tags | Hold. The clock covers the causal past. Compaction needs a snapshot | -| S9 Seitan V2 | Derivations match Keybase's vectors. Verify the accept bytes and admin handler before shipping | -| S10 heads orderer | Cap 32 needs the merge rule and the own-latest rule | -| S11 relay operation | Restart is survived. Fix SIGTERM. Metrics on loopback | -| S12 welcome size | 146.6 B per epoch stock, 40.0 B with serde_bytes | -| C1 t2, t4 re-run | Both pass | -| C2 holepunching | Full cone and port-restricted succeed. Symmetric pairs fall back. QAD is required | -| BeeKEM | Not adopted now. See its assessment | +| Spike | Verdict | +| ---------------------------- | ---------------------------------------------------------------------------------------------- | +| S1 to S6, C1 | Done. Earlier results stand, with the corrections recorded in round 2 | +| S7 range sync on real stores | Works and matches S1. Keep K=16 and T=16 as defaults | +| S8 observed-remove tags | Hold. The clock covers the causal past. Compaction needs a snapshot | +| S9 Seitan V2 | Derivations match Keybase's vectors. Verify the accept bytes and admin handler before shipping | +| S10 heads orderer | Cap 32 needs the merge rule and the own-latest rule | +| S11 relay operation | Restart is survived. Fix SIGTERM. Metrics on loopback | +| S12 welcome size | 146.6 B per epoch stock, 40.0 B with serde_bytes | +| C1 t2, t4 re-run | Both pass | +| C2 holepunching | Full cone and port-restricted succeed. Symmetric pairs fall back. QAD is required | +| BeeKEM | Not adopted now. See its assessment | ## 7. Remaining work by task doc -| Task | Area | Status | Plan phase | -| --- | --- | --- | --- | -| [01](./task-01-phase0-fixes.md) | Phase 0 fixes: tuple (done), pull bytes, MSRV, dial deadlines | Partly done | Phase 0 | -| [02](./task-02-events-and-storage.md) | Events, storage, caps, crash gate | Designed; decisions made | Phase 1 | -| [03](./task-03-membership-and-delegation.md) | Membership, delegation | Designed | Phase 2 | -| [04](./task-04-sync-blobs-transport.md) | Range and LogSync, blobs, `observe` | Designed; decisions made | Phase 3 | -| [05](./task-05-encryption-and-history.md) | Scheme v1, history, heads, warnings | Designed; decisions made | Phase 4 | -| [06](./task-06-tags-documents-search.md) | Tags, documents, search | Designed; S8 done | Phase 5 | -| [07](./task-07-invites-and-pull.md) | Seitan V2, invites, pull | Designed; decisions made | Phase 6 | -| [08](./task-08-connectivity-extensions.md) | Relays, tickets, mDNS | Designed; decisions made | Phases 3 and 7 | -| [09](./task-09-time-and-witnesses.md) | Time and witnesses | Deferred | Phase 8 | -| [10](./task-10-open-design-items.md) | Retention, multi-device, fork recovery, editing, views | Designed; preferred answers recorded | Phase 8 (and 6 for fork recovery) | -| [11](./task-11-dependencies-and-upstream.md) | Upstream and forks | Decisions made | Phase 0 | -| [12](./task-12-dependencies-and-toolchain.md) | Toolchain and dependencies | Decisions made | Phase 0 | +| Task | Area | Status | Plan phase | +| --------------------------------------------- | ------------------------------------------------------------- | ------------------------------------ | --------------------------------- | +| [01](./task-01-phase0-fixes.md) | Phase 0 fixes: tuple (done), pull bytes, MSRV, dial deadlines | Partly done | Phase 0 | +| [02](./task-02-events-and-storage.md) | Events, storage, caps, crash gate | Designed; decisions made | Phase 1 | +| [03](./task-03-membership-and-delegation.md) | Membership, delegation | Designed | Phase 2 | +| [04](./task-04-sync-blobs-transport.md) | Range and LogSync, blobs, `observe` | Designed; decisions made | Phase 3 | +| [05](./task-05-encryption-and-history.md) | Scheme v1, history, heads, warnings | Designed; decisions made | Phase 4 | +| [06](./task-06-tags-documents-search.md) | Tags, documents, search | Designed; S8 done | Phase 5 | +| [07](./task-07-invites-and-pull.md) | Seitan V2, invites, pull | Designed; decisions made | Phase 6 | +| [08](./task-08-connectivity-extensions.md) | Relays, tickets, mDNS | Designed; decisions made | Phases 3 and 7 | +| [09](./task-09-time-and-witnesses.md) | Time and witnesses | Deferred | Phase 8 | +| [10](./task-10-open-design-items.md) | Retention, multi-device, fork recovery, editing, views | Designed; preferred answers recorded | Phase 8 (and 6 for fork recovery) | +| [11](./task-11-dependencies-and-upstream.md) | Upstream and forks | Decisions made | Phase 0 | +| [12](./task-12-dependencies-and-toolchain.md) | Toolchain and dependencies | Decisions made | Phase 0 | ## 8. Known discrepancies in the current code @@ -183,3 +183,12 @@ The plan lists the preferred answer for each in its section 4. Short form: - Research round 2: `doc/2026-10-11T11-08-42Z_design_remaining_work/research-round2/` (copies of each folder's results, logs and harness code, without vendored crate sources). - Raw research workspace (outside the repo): `/home/user/work/research-round2/`. - Spike workspace (outside the repo): `/home/user/work/spikes-next/`. + +## Owner decisions on groups and friendship (2026-10-12) + +- Anyone may create a group. +- A normal group makes its creator Admin. +- A friendship is a group template (member_cap 2, mutual request and accept, dissolve on removal). It has no Admin by default. A config option at creation can make both friends Admin. +- If the friends are Admin, either one can change the other's role afterwards. +- Changing a group's size later is a policy change by an Admin (member_cap is a policy field). +- Friendship is therefore built on the group model, not as a standalone pair module. The earlier friendship module (P2.4, per-account cap 100) is superseded. From 750acdd18cc02fb79164de3837d8d04fe3214119 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 12 Oct 2026 00:15:14 -0500 Subject: [PATCH 11/40] docs(id): owner decisions on group creation, provisioning, and names --- .../2026-10-11T11-08-42Z_design_remaining_work.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/doc/2026-10-11T11-08-42Z_design_remaining_work/2026-10-11T11-08-42Z_design_remaining_work.md b/doc/2026-10-11T11-08-42Z_design_remaining_work/2026-10-11T11-08-42Z_design_remaining_work.md index d785f15f8c..da5c9d38c5 100644 --- a/doc/2026-10-11T11-08-42Z_design_remaining_work/2026-10-11T11-08-42Z_design_remaining_work.md +++ b/doc/2026-10-11T11-08-42Z_design_remaining_work/2026-10-11T11-08-42Z_design_remaining_work.md @@ -192,3 +192,17 @@ The plan lists the preferred answer for each in its section 4. Short form: - If the friends are Admin, either one can change the other's role afterwards. - Changing a group's size later is a policy change by an Admin (member_cap is a policy field). - Friendship is therefore built on the group model, not as a standalone pair module. The earlier friendship module (P2.4, per-account cap 100) is superseded. + +## Owner decisions on group creation, provisioning, and names (2026-10-12) + +- Anyone may create a group by default. A server config can restrict creation to listed users, to members of listed groups, and optionally to a minimum role level. +- A server config can create users, create groups, and add members and roles by user ID. +- Server config keys name users and groups locally. The server translates each key to its user or group ID at load time. An unknown key fails startup. +- Groups have an automatic ID (BLAKE3 of the create event) and an official name (a field an Admin changes). Aliases are tag claims: any number per group, each attributed to the key that added it. +- Users and groups are taggable with the same tag mechanism used for documents and bytes. A group's subject is its create event ID. A user's subject needs a decision (see below). + +Open for the owner: + +1. User subject for tags: the user's first identity event ID, or the account key itself? +2. Two groups claim the same alias: show both as contested, never pick one silently (recommended). Does a server config key always win locally? +3. Official names unique per server, or not (recommended: not; aliases and config keys disambiguate)? From abab23c26a9b4b7a07138f94ed82f5147e7ceb63 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 12 Oct 2026 00:15:25 -0500 Subject: [PATCH 12/40] docs(id): add P2.9 for server config and aliases --- .../plan-phases.md | 233 +++++++++--------- 1 file changed, 118 insertions(+), 115 deletions(-) diff --git a/doc/2026-10-11T11-08-42Z_design_remaining_work/plan-phases.md b/doc/2026-10-11T11-08-42Z_design_remaining_work/plan-phases.md index d619f7387b..41dd0b9309 100644 --- a/doc/2026-10-11T11-08-42Z_design_remaining_work/plan-phases.md +++ b/doc/2026-10-11T11-08-42Z_design_remaining_work/plan-phases.md @@ -34,17 +34,17 @@ These rules govern how each phase runs. They are repeated in every phase documen ## 3. Phase overview -| Phase | Purpose | Parallel tracks | Blocked by | Owner-blocked | -| --- | --- | --- | --- | --- | -| 0 | Baseline, toolchain, dependencies, small fixes, test harness | 5 | owner approval | none | -| 1 | Events, storage, crash safety, identity store | 4 | Phase 0 | none | -| 2 | Membership, auth frontier, delegation | 3 | P1.2, P1.3 | none | -| 3 | Sync, blobs, relays | 3 | P1.3, P1.6 | real-network tests (P3.7) | -| 4 | Groups, encryption, history | 4 | Phases 1 and 2 | none | -| 5 | Tags, documents, search | 3 | Phases 1 and 2 | none | -| 6 | Invites, pull, CLI | 4 | Phases 2, 3 and 4 | none | -| 7 | Connectivity for later servers | 2 | Phase 3 | deployment, accounts, networks | -| 8 | Later items | several | the phases above | none | +| Phase | Purpose | Parallel tracks | Blocked by | Owner-blocked | +| ----- | ------------------------------------------------------------ | --------------- | ----------------- | ------------------------------ | +| 0 | Baseline, toolchain, dependencies, small fixes, test harness | 5 | owner approval | none | +| 1 | Events, storage, crash safety, identity store | 4 | Phase 0 | none | +| 2 | Membership, auth frontier, delegation | 3 | P1.2, P1.3 | none | +| 3 | Sync, blobs, relays | 3 | P1.3, P1.6 | real-network tests (P3.7) | +| 4 | Groups, encryption, history | 4 | Phases 1 and 2 | none | +| 5 | Tags, documents, search | 3 | Phases 1 and 2 | none | +| 6 | Invites, pull, CLI | 4 | Phases 2, 3 and 4 | none | +| 7 | Connectivity for later servers | 2 | Phase 3 | deployment, accounts, networks | +| 8 | Later items | several | the phases above | none | ## 4. Owner questions to answer before Phase 0 starts @@ -63,20 +63,20 @@ These do not block the first steps, but each answer changes a step. The preferre Goal: a green baseline on the newest toolchain, with current dependencies and the small known fixes done. -| Step | What | Blocked by | Parallel with | Tests | -| --- | --- | --- | --- | --- | -| P0.1 | Baseline: record the current result. Fix or quarantine the three known failures (`world_compile` needs `host.wasm`; the Roc test fails; a world-module test hangs). Every network or process test gets a timeout, so no hang can block the suite | owner approval | P0.4, P0.6, P0.7, P0.8, P0.9, P0.10, P0.12 | unit; each fix gets a test | -| P0.2 | Toolchain 1.99.0 in `rust-toolchain.toml`. No lock update is needed, since the locked overlays contain it | P0.1 | P0.4, P0.6 to P0.10, P0.12 | build, clippy and rustfmt on 1.99.0 | -| P0.3 | Dependencies, one group per commit: iroh stack; redb 4.3.0; cbor-core 0.10.1; ed25519-dalek 3.0.0 with the shim and `verify_strict`; p2panda stays on git rev `3e84cac` (decided). Serialized, because every group touches `Cargo.lock` | P0.2 | none within the track | full test run after each group; the report to the owner lists each change | -| P0.4 | Pull pages capped by bytes, not item count (task 01) | none | everything | unit; property over page sizes | -| P0.5 | `rust-version` set to 1.96, the true minimum for the p2panda rev, and the clippy MSRV matched | P0.2 | P0.3 | build on 1.96 | -| P0.6 | Dial deadlines in the remaining modules (`artifact.rs` pull) | none | everything | integration with a dead peer; the deadline is enforced | -| P0.7 | mDNS on `serve`, on by default with `--no-mdns` to turn it off (decided). The library default is off. The connectivity design is corrected | none | everything | e2e: `serve` defaults; `--no-mdns` disables it; the library default is off | -| P0.8 | `src/store.rs` says FsStore is SQLite. It is redb (N17) | none | everything | grep check in the test run | -| P0.9 | Tuple encoding: property tests over random values for order and the prefix rule; a fuzz target; the regression list | none | everything | property with many cases; fuzz smoke; regression replay | -| P0.10 | Test harness: the regression-list runner; a multi-node loopback helper for integration tests; the full test run script (section 13); naming rules | none | everything | the harness has its own tests | -| P0.11 | `verify_strict` regressions: a non-canonical signature and a small-order key are rejected at every call site | P0.3 | P0.4, P0.6 | regression per call site; property over signature mutations | -| P0.12 | Nix check uses the pinned toolchain. `pkgs/id/default.nix` currently runs `rustup default 1.89.0`, so the Nix check ignores the pin. The version is read from `rust-toolchain.toml` | none | everything | a test that the Nix and rustup versions agree | +| Step | What | Blocked by | Parallel with | Tests | +| ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------- | ------------------------------------------ | -------------------------------------------------------------------------- | +| P0.1 | Baseline: record the current result. Fix or quarantine the three known failures (`world_compile` needs `host.wasm`; the Roc test fails; a world-module test hangs). Every network or process test gets a timeout, so no hang can block the suite | owner approval | P0.4, P0.6, P0.7, P0.8, P0.9, P0.10, P0.12 | unit; each fix gets a test | +| P0.2 | Toolchain 1.99.0 in `rust-toolchain.toml`. No lock update is needed, since the locked overlays contain it | P0.1 | P0.4, P0.6 to P0.10, P0.12 | build, clippy and rustfmt on 1.99.0 | +| P0.3 | Dependencies, one group per commit: iroh stack; redb 4.3.0; cbor-core 0.10.1; ed25519-dalek 3.0.0 with the shim and `verify_strict`; p2panda stays on git rev `3e84cac` (decided). Serialized, because every group touches `Cargo.lock` | P0.2 | none within the track | full test run after each group; the report to the owner lists each change | +| P0.4 | Pull pages capped by bytes, not item count (task 01) | none | everything | unit; property over page sizes | +| P0.5 | `rust-version` set to 1.96, the true minimum for the p2panda rev, and the clippy MSRV matched | P0.2 | P0.3 | build on 1.96 | +| P0.6 | Dial deadlines in the remaining modules (`artifact.rs` pull) | none | everything | integration with a dead peer; the deadline is enforced | +| P0.7 | mDNS on `serve`, on by default with `--no-mdns` to turn it off (decided). The library default is off. The connectivity design is corrected | none | everything | e2e: `serve` defaults; `--no-mdns` disables it; the library default is off | +| P0.8 | `src/store.rs` says FsStore is SQLite. It is redb (N17) | none | everything | grep check in the test run | +| P0.9 | Tuple encoding: property tests over random values for order and the prefix rule; a fuzz target; the regression list | none | everything | property with many cases; fuzz smoke; regression replay | +| P0.10 | Test harness: the regression-list runner; a multi-node loopback helper for integration tests; the full test run script (section 13); naming rules | none | everything | the harness has its own tests | +| P0.11 | `verify_strict` regressions: a non-canonical signature and a small-order key are rejected at every call site | P0.3 | P0.4, P0.6 | regression per call site; property over signature mutations | +| P0.12 | Nix check uses the pinned toolchain. `pkgs/id/default.nix` currently runs `rustup default 1.89.0`, so the Nix check ignores the pin. The version is read from `rust-toolchain.toml` | none | everything | a test that the Nix and rustup versions agree | Phase 0 review focus: the toolchain change touches every test, so the full test run happens at the end of the phase, not only at the end of each step. @@ -84,114 +84,116 @@ Phase 0 review focus: the toolchain change touches every test, so the full test Goal: an event store on redb, with ChainExt, fork freezing, waiting caps, crash safety tested, and the web identity moved off libsql. -| Step | What | Blocked by | Parallel with | Tests | -| --- | --- | --- | --- | --- | -| P1.1 | Storage decision record: redb everywhere, Turso rejected by the round 2 spike, libsql replaced (decided) | Phase 0 baseline | P1.2, P1.4, P1.7 | the record links the spike | -| P1.2 | ChainExt: struct; validation (at most 32 `after`, no duplicates, canonical CBOR, domain tag); builder and reader | Phase 0 baseline | P1.4, P1.7 | unit; property; canonical vectors; fuzz of the decoder with a regression list | -| P1.3 | Event store on redb: events, chains, heads, subject and name/value indexes (tuple keys), unique (author, seq), fork freeze and proofs. Creation uses a temporary file, a first commit, then a rename with a directory fsync | P1.1, P1.2 | P1.5 | unit; integration (ingest, freeze, proof); property (random orders give the same state); the first-creation crash test | -| P1.4 | Crash-safety gate: the in-process fault model for redb, run in release mode as a CI gate; a corpus TSV with expected classes; the lying-sync control. LazyFS as an optional Linux job | Phase 0 baseline; uses redb directly | P1.2, P1.7 | the sweep (about 40 s release): zero failures; the control produces failures; corpus replay | -| P1.5 | Waiting caps: 256 per author, 7 days, with the drop behaviour | P1.3 for storage; the policy code can start now | P1.3 (policy part) | unit with a fake clock; property over arrival orders | -| P1.6 | Store traits over redb: the three LogStore methods, TopicStore::resolve, and the rest we need. Auth state in our own table, since the `groups` feature implies SQLite | P1.3 | P1.5 | trait contract tests; LogSync smoke test on the redb store; a check that sqlx is absent with the chosen features | -| P1.7 | Canonical CBOR: the S5 golden vectors as tests, cross-checked with dcbor (dev only) | Phase 0 baseline | P1.2, P1.4 | golden vectors; interop | -| P1.8 | Ingest pipeline: verify signatures with `AnyHeader::decode`, never the typed `verify`; reject and freeze forks | P1.2, P1.3 | P1.5 | unit; integration; regression test for the verify trap | -| P1.9 | Identity store moves from libsql to redb. Values are encrypted with AES-256-GCM (already in the lock). Data may be discarded | P1.1 | P1.3 to P1.8 | unit; a round trip with a wrong key fails; the 17 call sites are covered | -| P1.10 | Crash gate for the identity store | P1.9, P1.4 | P1.3 | the same sweep shape as P1.4 | +| Step | What | Blocked by | Parallel with | Tests | +| ----- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------- | ------------------ | ---------------------------------------------------------------------------------------------------------------------- | +| P1.1 | Storage decision record: redb everywhere, Turso rejected by the round 2 spike, libsql replaced (decided) | Phase 0 baseline | P1.2, P1.4, P1.7 | the record links the spike | +| P1.2 | ChainExt: struct; validation (at most 32 `after`, no duplicates, canonical CBOR, domain tag); builder and reader | Phase 0 baseline | P1.4, P1.7 | unit; property; canonical vectors; fuzz of the decoder with a regression list | +| P1.3 | Event store on redb: events, chains, heads, subject and name/value indexes (tuple keys), unique (author, seq), fork freeze and proofs. Creation uses a temporary file, a first commit, then a rename with a directory fsync | P1.1, P1.2 | P1.5 | unit; integration (ingest, freeze, proof); property (random orders give the same state); the first-creation crash test | +| P1.4 | Crash-safety gate: the in-process fault model for redb, run in release mode as a CI gate; a corpus TSV with expected classes; the lying-sync control. LazyFS as an optional Linux job | Phase 0 baseline; uses redb directly | P1.2, P1.7 | the sweep (about 40 s release): zero failures; the control produces failures; corpus replay | +| P1.5 | Waiting caps: 256 per author, 7 days, with the drop behaviour | P1.3 for storage; the policy code can start now | P1.3 (policy part) | unit with a fake clock; property over arrival orders | +| P1.6 | Store traits over redb: the three LogStore methods, TopicStore::resolve, and the rest we need. Auth state in our own table, since the `groups` feature implies SQLite | P1.3 | P1.5 | trait contract tests; LogSync smoke test on the redb store; a check that sqlx is absent with the chosen features | +| P1.7 | Canonical CBOR: the S5 golden vectors as tests, cross-checked with dcbor (dev only) | Phase 0 baseline | P1.2, P1.4 | golden vectors; interop | +| P1.8 | Ingest pipeline: verify signatures with `AnyHeader::decode`, never the typed `verify`; reject and freeze forks | P1.2, P1.3 | P1.5 | unit; integration; regression test for the verify trap | +| P1.9 | Identity store moves from libsql to redb. Values are encrypted with AES-256-GCM (already in the lock). Data may be discarded | P1.1 | P1.3 to P1.8 | unit; a round trip with a wrong key fails; the 17 call sites are covered | +| P1.10 | Crash gate for the identity store | P1.9, P1.4 | P1.3 | the same sweep shape as P1.4 | ## 7. Phase 2: membership, auth frontier, delegation Goal: the membership rules from S2 as code, with the admission gate and authority-based voiding. -| Step | What | Blocked by | Parallel with | Tests | -| --- | --- | --- | --- | --- | -| P2.1 | Auth-frontier mapping: `after` to auth dependencies, walking through non-auth events | P1.2, P1.3 | none within the phase | unit; the S2 cases; property | -| P2.2 | Admission gate: hold, reject when the group is absent at its dependencies, placeholders for refused events | P2.1 | P2.3, P2.4 | unit; regression for the panic at `group/crdt/mod.rs:822` | -| P2.3 | Voiding: authority-based dependents (decision 1); StrongRemove semantics | P2.1 | P2.2, P2.4 | S2 scenarios; a planted bug must fail | -| P2.4 | Friendship with its cap, and the dissolve projection | P2.1 | P2.2, P2.3 | unit; integration | -| P2.5 | Delegation: edges, attenuation, chain search, veto, the modes cascade, keep_prior, and transfer derived from the signed removal (decision 2) | P2.3 | P2.6 | unit; property over delegation chains | -| P2.6 | World capabilities without use-count bounds (decision 3). Content on removal is kept (decision 4) | P2.3 | P2.5 | unit | -| P2.7 | Cross-world reconciliation (task 03, item 7) | P2.5, P2.6 | none | integration across two worlds | -| P2.8 | Property tests over random operation orders, and planted-bug checks | P2.3 | P2.4 to P2.7 | many cases; mutation checks on demand | +| Step | What | Blocked by | Parallel with | Tests | +| ---- | -------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | +| P2.1 | Auth-frontier mapping: `after` to auth dependencies, walking through non-auth events | P1.2, P1.3 | none within the phase | unit; the S2 cases; property | +| P2.2 | Admission gate: hold, reject when the group is absent at its dependencies, placeholders for refused events | P2.1 | P2.3, P2.4 | unit; regression for the panic at `group/crdt/mod.rs:822` | +| P2.3 | Voiding: authority-based dependents (decision 1); StrongRemove semantics | P2.1 | P2.2, P2.4 | S2 scenarios; a planted bug must fail | +| P2.4 | Friendship with its cap, and the dissolve projection | P2.1 | P2.2, P2.3 | unit; integration | +| P2.5 | Delegation: edges, attenuation, chain search, veto, the modes cascade, keep_prior, and transfer derived from the signed removal (decision 2) | P2.3 | P2.6 | unit; property over delegation chains | +| P2.6 | World capabilities without use-count bounds (decision 3). Content on removal is kept (decision 4) | P2.3 | P2.5 | unit | +| P2.7 | Cross-world reconciliation (task 03, item 7) | P2.5, P2.6 | none | integration across two worlds | +| P2.8 | Property tests over random operation orders, and planted-bug checks | P2.3 | P2.4 to P2.7 | many cases; mutation checks on demand | +| P2.9 | Server config: creation limits, provisioning by key, config keys, aliases as tags (decisions in the index, 2026-10-12) | P2.4 | P2.5, P2.8 | config parse tests; unknown key fails startup; creation limits by user, group and role; provisioning round trip; alias contest shown, never picked silently | ## 8. Phase 3: sync, blobs, and relays Goal: range sync and LogSync on the store, blob gating, and relay defaults that work. -| Step | What | Blocked by | Parallel with | Tests | -| --- | --- | --- | --- | --- | -| P3.1 | Range sync on the redb store, from S7. K=16 and T=16 by default. K and T are local, validated (K at least 2, T at least 1). Protocol ID `/id-sync/1` | P1.3 | P3.2, P3.4, P3.5 | unit; property over random sets; integration over loopback; interrupted-session test; regression tests for the three findings below | -| P3.1a | Fork in a batch: a fork aborts the whole batch in the harness, losing 20 unrelated events. The fix isolates the fork and continues | P3.1 | P3.2 | red test first, then the fix | -| P3.1b | T=0 never terminates on one mismatched key. Validation rejects it | P3.1 | P3.1a | regression test | -| P3.1c | Flights are chunked to a budget under the frame cap. A single flight above about 524,000 IDs exceeds 16 MiB | P3.1 | P3.1a | bootstrap test of a store above the limit | -| P3.2 | LogSync through p2panda-sync, on our traits. Its SQLite default is removed by a fork of the one dependency line (section 14 of the explainers) | P1.6 | P3.1, P3.4, P3.5 | integration over loopback; a check that sqlx is absent | -| P3.3 | Method selection: LogSync when the estimated difference exceeds 0.035 times the chains or when bootstrapping, otherwise range (decided) | P3.1, P3.2 | none | unit (the rule); integration: both sides agree on the method | -| P3.4 | Blob gating and `observe`: each request gated by the world's fetch rules; observe off by default (decision 5) | the membership check interface, stubbed first | P3.1, P3.2 | unit; e2e: a non-member can neither observe nor fetch | -| P3.5 | Relay defaults: n0 now (decided); startup waits only for the home relay, with a deadline (N32) | none | everything | integration with a dead entry; the deadline holds | -| P3.6 | Relay map order: QAD-capable relays come first, because iroh probes only the first five | none | P3.5 | a six-relay map with the QAD relay last is rejected or reordered | -| P3.7 | Real-network holepunch and n0 QAD tests on two networks (N29) | owner provides networks | everything | the C2 matrix on real networks (owner-blocked) | -| P3.8 | Relay operations: the systemd unit (already fixed: SIGINT, config required), metrics on loopback | none | P3.5 | a test parses the unit file | +| Step | What | Blocked by | Parallel with | Tests | +| ----- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------- | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------- | +| P3.1 | Range sync on the redb store, from S7. K=16 and T=16 by default. K and T are local, validated (K at least 2, T at least 1). Protocol ID `/id-sync/1` | P1.3 | P3.2, P3.4, P3.5 | unit; property over random sets; integration over loopback; interrupted-session test; regression tests for the three findings below | +| P3.1a | Fork in a batch: a fork aborts the whole batch in the harness, losing 20 unrelated events. The fix isolates the fork and continues | P3.1 | P3.2 | red test first, then the fix | +| P3.1b | T=0 never terminates on one mismatched key. Validation rejects it | P3.1 | P3.1a | regression test | +| P3.1c | Flights are chunked to a budget under the frame cap. A single flight above about 524,000 IDs exceeds 16 MiB | P3.1 | P3.1a | bootstrap test of a store above the limit | +| P3.2 | LogSync through p2panda-sync, on our traits. Its SQLite default is removed by a fork of the one dependency line (section 14 of the explainers) | P1.6 | P3.1, P3.4, P3.5 | integration over loopback; a check that sqlx is absent | +| P3.3 | Method selection: LogSync when the estimated difference exceeds 0.035 times the chains or when bootstrapping, otherwise range (decided) | P3.1, P3.2 | none | unit (the rule); integration: both sides agree on the method | +| P3.4 | Blob gating and `observe`: each request gated by the world's fetch rules; observe off by default (decision 5) | the membership check interface, stubbed first | P3.1, P3.2 | unit; e2e: a non-member can neither observe nor fetch | +| P3.5 | Relay defaults: n0 now (decided); startup waits only for the home relay, with a deadline (N32) | none | everything | integration with a dead entry; the deadline holds | +| P3.6 | Relay map order: QAD-capable relays come first, because iroh probes only the first five | none | P3.5 | a six-relay map with the QAD relay last is rejected or reordered | +| P3.7 | Real-network holepunch and n0 QAD tests on two networks (N29) | owner provides networks | everything | the C2 matrix on real networks (owner-blocked) | +| P3.8 | Relay operations: the systemd unit (already fixed: SIGINT, config required), metrics on loopback | none | P3.5 | a test parses the unit file | ## 9. Phase 4: groups, encryption, and history Goal: group encryption on DataScheme, with the history modes, the heads rule, warnings, and the scheme v1. -| Step | What | Blocked by | Parallel with | Tests | -| --- | --- | --- | --- | --- | -| P4.1 | DataScheme adapter around the crate: create, add, remove, update, process | Phase 1, P2.1 | P4.4, P4.8, P4.10 | unit; multi-member integration | -| P4.2 | Our DGM and the from_join membership fix, in our fork (decision 18) | P4.1 | P4.4 | regression: a joiner reads messages after joining; the fork's patch has its own test | -| P4.3 | from_join: immediate update, and the withholding rule for pre-join application messages | P4.1, P4.2 | P4.4, P4.5 | integration: a joiner cannot read pre-join messages but reads post-join ones | -| P4.4 | Scheme v1: `serde_bytes` on the two fields, the version bound to the signed policy and copied in the header and welcome envelope, and welcomes sorted before signing (owner question 2) | P4.1 | P4.3, P4.5 | interop: v0 and v1 do not decode each other (verified); size tests (40.0 B per epoch); determinism test: sorted bytes are stable | -| P4.5 | `recent:N` and `full`: the adapter checks the group secret ID before `receive`, and keeps pre-welcome history outside the crate. The reproduction of the 80-of-120 failure comes first, as a red test | P4.1, P3.1 (transport) | P4.3, P4.4 | integration: a `recent:N` joiner reads the last N epochs, is refused older ones, and the welcome succeeds for every N and K combination | -| P4.6 | Lazy full history: a joiner asks a member for older epoch secrets, sent encrypted to the joiner | P4.5 | P4.7 | integration: the request returns the older keys; a non-member gets nothing | -| P4.7 | Heads rule: cap 32, the author's latest event always named, merge when the heads would exceed the cap | P4.1, P1.3 | P4.8 | the S10 scenarios as tests; adversarial order tests | -| P4.8 | Rotation policy (no periodic rotation, N7). PCS recovery is a CLI procedure: remove and re-add (N8) | P4.1, P6.7 (CLI) | P4.7 | integration: a compromised member is replaced and cannot read new epochs | -| P4.9 | Warnings: 96, 128 and 1,000 members (N11); churn warnings (N34); local emission from the server; surfaces in logs and CLI status | P4.1 (counts) | P4.7, P4.8, P4.10 | unit: thresholds; e2e: the server warns at a threshold | -| P4.10 | "scheme: none" notice in the UI and in group metadata (decision 8) | P4.1 | P4.9 | e2e | -| P4.11 | Measure DataScheme update cost at 100, 1,000 and 5,000 members with our adapter, for the BeeKEM comparison | P4.1 | P4.4 to P4.10 | recorded in the phase document; no pass or fail | -| P4.12 | Welcome size budget: chunking above the frame cap (owner question 4) | P4.5 | P4.6 | a `full` welcome above the cap is chunked and reassembled | +| Step | What | Blocked by | Parallel with | Tests | +| ----- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------- | ----------------- | --------------------------------------------------------------------------------------------------------------------------------------- | +| P4.1 | DataScheme adapter around the crate: create, add, remove, update, process | Phase 1, P2.1 | P4.4, P4.8, P4.10 | unit; multi-member integration | +| P4.2 | Our DGM and the from_join membership fix, in our fork (decision 18) | P4.1 | P4.4 | regression: a joiner reads messages after joining; the fork's patch has its own test | +| P4.3 | from_join: immediate update, and the withholding rule for pre-join application messages | P4.1, P4.2 | P4.4, P4.5 | integration: a joiner cannot read pre-join messages but reads post-join ones | +| P4.4 | Scheme v1: `serde_bytes` on the two fields, the version bound to the signed policy and copied in the header and welcome envelope, and welcomes sorted before signing (owner question 2) | P4.1 | P4.3, P4.5 | interop: v0 and v1 do not decode each other (verified); size tests (40.0 B per epoch); determinism test: sorted bytes are stable | +| P4.5 | `recent:N` and `full`: the adapter checks the group secret ID before `receive`, and keeps pre-welcome history outside the crate. The reproduction of the 80-of-120 failure comes first, as a red test | P4.1, P3.1 (transport) | P4.3, P4.4 | integration: a `recent:N` joiner reads the last N epochs, is refused older ones, and the welcome succeeds for every N and K combination | +| P4.6 | Lazy full history: a joiner asks a member for older epoch secrets, sent encrypted to the joiner | P4.5 | P4.7 | integration: the request returns the older keys; a non-member gets nothing | +| P4.7 | Heads rule: cap 32, the author's latest event always named, merge when the heads would exceed the cap | P4.1, P1.3 | P4.8 | the S10 scenarios as tests; adversarial order tests | +| P4.8 | Rotation policy (no periodic rotation, N7). PCS recovery is a CLI procedure: remove and re-add (N8) | P4.1, P6.7 (CLI) | P4.7 | integration: a compromised member is replaced and cannot read new epochs | +| P4.9 | Warnings: 96, 128 and 1,000 members (N11); churn warnings (N34); local emission from the server; surfaces in logs and CLI status | P4.1 (counts) | P4.7, P4.8, P4.10 | unit: thresholds; e2e: the server warns at a threshold | +| P4.10 | "scheme: none" notice in the UI and in group metadata (decision 8) | P4.1 | P4.9 | e2e | +| P4.11 | Measure DataScheme update cost at 100, 1,000 and 5,000 members with our adapter, for the BeeKEM comparison | P4.1 | P4.4 to P4.10 | recorded in the phase document; no pass or fail | +| P4.12 | Welcome size budget: chunking above the frame cap (owner question 4) | P4.5 | P4.6 | a `full` welcome above the cap is chunked and reassembled | ## 10. Phase 5: tags, documents, search Goal: observed-remove tags, the tag index, compaction, documents, and search. -| Step | What | Blocked by | Parallel with | Tests | -| --- | --- | --- | --- | --- | -| P5.1 | Observed-remove tags (the S8 model) in the store. The clock covers the whole causal past | P1.3, P2.1 | P5.4 | the S8 properties; planted-bug checks | -| P5.2 | Tag index on the fixed tuple encoding: subject, name and value prefixes | P5.1, P0.9 | P5.4 | property over random tags; the `"a"` versus `"a\0b"` regression | -| P5.3 | Compaction: snapshot at a causal cut, then the tail (N33) | P5.1 | P5.2, P5.4 | the S8 counterexample as a regression test; a new device's state is preserved | -| P5.4 | Documents: content events; snapshots from the collab server; save on explicit save and on idle close (task 10, item 6) | P5.1 | P5.2, P5.3 | integration; e2e: edit, save, reload | -| P5.5 | Search over the tag index | P5.2 | P5.3, P5.4 | unit; e2e | -| P5.6 | Content on removal, kept (decision 4) | P2.6 | P5.3, P5.4 | integration | +| Step | What | Blocked by | Parallel with | Tests | +| ---- | ---------------------------------------------------------------------------------------------------------------------- | ---------- | ------------- | ----------------------------------------------------------------------------- | +| P5.1 | Observed-remove tags (the S8 model) in the store. The clock covers the whole causal past | P1.3, P2.1 | P5.4 | the S8 properties; planted-bug checks | +| P5.2 | Tag index on the fixed tuple encoding: subject, name and value prefixes | P5.1, P0.9 | P5.4 | property over random tags; the `"a"` versus `"a\0b"` regression | +| P5.3 | Compaction: snapshot at a causal cut, then the tail (N33) | P5.1 | P5.2, P5.4 | the S8 counterexample as a regression test; a new device's state is preserved | +| P5.4 | Documents: content events; snapshots from the collab server; save on explicit save and on idle close (task 10, item 6) | P5.1 | P5.2, P5.3 | integration; e2e: edit, save, reload | +| P5.5 | Search over the tag index | P5.2 | P5.3, P5.4 | unit; e2e | +| P5.6 | Content on removal, kept (decision 4) | P2.6 | P5.3, P5.4 | integration | ## 11. Phase 6: invites, pull, and the CLI Goal: invites and links that work, pull, fork recovery, and the CLI that exposes all of it. -| Step | What | Blocked by | Parallel with | Tests | -| --- | --- | --- | --- | --- | -| P6.1 | Seitan V2 from the S9 code: tokens, derivations, proofs, and the admin path. Before shipping, verify the accept-message bytes and the Keybase admin handler | Phases 1 and 2 | P6.2, P6.3 | the S9 vectors; admin-path tests; e2e: invite and accept | -| P6.2 | Freshness window per server, world or inviter, default 5 minutes (N23) | P6.1 | P6.3 | unit; boundary tests at the window edges | -| P6.3 | Tickets, option E: the pasted string is a standard ticket. The link carries `by=`. The signed invite event is checked when present, before the accept is sent (N24). Pasted text is trimmed | round 2 result (done); owner question 3 | P6.1, P6.2 | round trips through the iroh-tickets parser; a standard client accepts the paste; a paste with whitespace works | -| P6.4 | Invite events and links; address exposure documented (N30) | P6.1, P6.3 | P6.5 | e2e | -| P6.5 | Pull policy: open pull, with an authorized option (decision 11) | Phase 3 | P6.4, P6.6 | integration | -| P6.6 | Fork recovery: remove and re-enrol under a new device key (decision 17). Quarantine with approval is recorded as a later option | Phases 1 and 2 | P6.5 | integration: after a fork the old chain is frozen and the new device reaches the same state | -| P6.7a | CLI: groups (create, policy, join, add, remove, role, list) | Phases 2 and 4 | P6.7b, P6.7c | e2e per command | -| P6.7b | CLI: delegation (delegate, revoke) | P2.5 | P6.7a, P6.7c | e2e | -| P6.7c | CLI: documents and tags (publish, events, frontier, history) | Phase 5 | P6.7a, P6.7b | e2e | -| P6.8 | Rejection reasons everywhere: voided, waiting, frozen | P1.5, P2.3 | P6.7a | e2e: each reason appears | +| Step | What | Blocked by | Parallel with | Tests | +| ----- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------- | ------------- | --------------------------------------------------------------------------------------------------------------- | +| P6.1 | Seitan V2 from the S9 code: tokens, derivations, proofs, and the admin path. Before shipping, verify the accept-message bytes and the Keybase admin handler | Phases 1 and 2 | P6.2, P6.3 | the S9 vectors; admin-path tests; e2e: invite and accept | +| P6.2 | Freshness window per server, world or inviter, default 5 minutes (N23) | P6.1 | P6.3 | unit; boundary tests at the window edges | +| P6.3 | Tickets, option E: the pasted string is a standard ticket. The link carries `by=`. The signed invite event is checked when present, before the accept is sent (N24). Pasted text is trimmed | round 2 result (done); owner question 3 | P6.1, P6.2 | round trips through the iroh-tickets parser; a standard client accepts the paste; a paste with whitespace works | +| P6.4 | Invite events and links; address exposure documented (N30) | P6.1, P6.3 | P6.5 | e2e | +| P6.5 | Pull policy: open pull, with an authorized option (decision 11) | Phase 3 | P6.4, P6.6 | integration | +| P6.6 | Fork recovery: remove and re-enrol under a new device key (decision 17). Quarantine with approval is recorded as a later option | Phases 1 and 2 | P6.5 | integration: after a fork the old chain is frozen and the new device reaches the same state | +| P6.7a | CLI: groups (create, policy, join, add, remove, role, list) | Phases 2 and 4 | P6.7b, P6.7c | e2e per command | +| P6.7b | CLI: delegation (delegate, revoke) | P2.5 | P6.7a, P6.7c | e2e | +| P6.7c | CLI: documents and tags (publish, events, frontier, history) | Phase 5 | P6.7a, P6.7b | e2e | +| P6.8 | Rejection reasons everywhere: voided, waiting, frozen | P1.5, P2.3 | P6.7a | e2e: each reason appears | ## 12. Phases 7 and 8: connectivity for later servers, and later items **Phase 7** (nothing here is needed for a first working system): -| Step | What | Blocked by | Parallel with | Tests | -| --- | --- | --- | --- | --- | -| P7.1 | Relay kit for a server behind a Cloudflare Tunnel, and for VPS testing. Updated for the S11 findings | none | P7.2 | the unit file test (P3.8) | -| P7.2 | Cloudflare Workers pkarr option: HTTP PUT and GET and DNS over HTTPS only (round 2). Design only | owner's go | P7.1 | none yet | -| P7.3 | DHT opt-in per world (decision 15) | Phase 3 | P7.1 | integration over a test DHT | -| P7.4 | Access control (decision 13): none now; revisit at implementation | none | everything | none now | -| P7.5 | Deployments and real-network tests (owner-blocked) | owner accounts and networks | none | the C2 matrix; N29 on real networks | +| Step | What | Blocked by | Parallel with | Tests | +| ---- | ---------------------------------------------------------------------------------------------------- | --------------------------- | ------------- | ----------------------------------- | +| P7.1 | Relay kit for a server behind a Cloudflare Tunnel, and for VPS testing. Updated for the S11 findings | none | P7.2 | the unit file test (P3.8) | +| P7.2 | Cloudflare Workers pkarr option: HTTP PUT and GET and DNS over HTTPS only (round 2). Design only | owner's go | P7.1 | none yet | +| P7.3 | DHT opt-in per world (decision 15) | Phase 3 | P7.1 | integration over a test DHT | +| P7.4 | Access control (decision 13): none now; revisit at implementation | none | everything | none now | +| P7.5 | Deployments and real-network tests (owner-blocked) | owner accounts and networks | none | the C2 matrix; N29 on real networks | **Phase 8** (each becomes a phase document when it starts): + - P8.1 Time and witnesses (task 09, deferred). - P8.2 Retention and pruning (task 10, item 1). Needed before large groups run for a long time. - P8.3 Multi-device (task 10, item 2). @@ -205,20 +207,20 @@ Goal: invites and links that work, pull, fork recovery, and the CLI that exposes **Layers.** These follow the repo's six layers, and add the layers this work needs. -| Layer | What | When it runs | Used by | -| --- | --- | --- | --- | -| 1. Rust unit | `#[cfg(test)] mod tests` | every run | every step | -| 2. Rust integration | `tests/`, several nodes in one process over loopback | every run | sync, groups, invites, pull | -| 3. Property | proptest, many cases, fixed seeds in CI | every run | ChainExt, tuple, tags, membership, sync sets, caps | -| 4. Crash gate | in-process fault model for redb, release mode | every run (about 40 s) | storage, identity store | -| 5. Regression replay | `tests/regressions/*.txt`, every entry replayed | every run | every area | -| 6. Fuzz smoke | a bounded run of each fuzz target; long runs on demand | every run; long runs on demand | decoders, tuple, tickets | -| 7. End-to-end, CLI | the binaries as separate processes, with timeouts | every run | CLI, `serve`, invites | -| 8. NixOS VM | two or more VMs on the network | the nix check | relays, the systemd unit, real-looking topologies | -| 9. Playwright E2E | the web UI | `just test-e2e` when web code changes | web | -| 10. Live network | n0, real networks | on demand, marked ignored | connectivity | -| 11. Mutation checks | planted bugs must fail | on demand at phase end | membership, tags | -| 12. Interop and golden vectors | CBOR, Seitan, scheme versions | every run | encodings | +| Layer | What | When it runs | Used by | +| ------------------------------ | ------------------------------------------------------ | ------------------------------------- | -------------------------------------------------- | +| 1. Rust unit | `#[cfg(test)] mod tests` | every run | every step | +| 2. Rust integration | `tests/`, several nodes in one process over loopback | every run | sync, groups, invites, pull | +| 3. Property | proptest, many cases, fixed seeds in CI | every run | ChainExt, tuple, tags, membership, sync sets, caps | +| 4. Crash gate | in-process fault model for redb, release mode | every run (about 40 s) | storage, identity store | +| 5. Regression replay | `tests/regressions/*.txt`, every entry replayed | every run | every area | +| 6. Fuzz smoke | a bounded run of each fuzz target; long runs on demand | every run; long runs on demand | decoders, tuple, tickets | +| 7. End-to-end, CLI | the binaries as separate processes, with timeouts | every run | CLI, `serve`, invites | +| 8. NixOS VM | two or more VMs on the network | the nix check | relays, the systemd unit, real-looking topologies | +| 9. Playwright E2E | the web UI | `just test-e2e` when web code changes | web | +| 10. Live network | n0, real networks | on demand, marked ignored | connectivity | +| 11. Mutation checks | planted bugs must fail | on demand at phase end | membership, tags | +| 12. Interop and golden vectors | CBOR, Seitan, scheme versions | every run | encodings | **The full test run** is one script, with these parts: `just check` (the primary check in `AGENTS.md`), `just test` (fast Rust and TypeScript), the crate's full test set with the three known failures handled (P0.1), the regression replay, the property tests with the CI seed set, the crash gate, the fuzz smoke runs, and `doc` tests. At phase end, add `just test-nix` (27 checks, heavy) and `just test-e2e` when web code changed. The script reports what it skipped and why. @@ -238,6 +240,7 @@ Each phase document lives in `doc/_phase__/`, created at the ## 15. Decisions this plan depends on Recorded in the index, and accepted in this session: + - Joiner history `full` by default. `recent:N` per world, with presets 32 and 128 (decision 7). - mDNS on for `serve`, off in the library (decision 14). - Fork recovery by removal and re-enrolment (decision 17). Quarantine with approval is a later option. From 3e0d4bb3a57568cd2ebbed22d300f0ec8e822b08 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 12 Oct 2026 00:27:48 -0500 Subject: [PATCH 13/40] feat(rust): a create may name its group, so a friendship's group is derived [P2.4] MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A friendship's group is BLAKE3 over the label, the sorted pair and a counter (design §5.4), not the create's own event ID. A create that names a group now creates that group. A create without one keeps its own ID as before. --- pkgs/id/src/membership/layer.rs | 44 ++++++++++++++++++++++++++++++--- 1 file changed, 41 insertions(+), 3 deletions(-) diff --git a/pkgs/id/src/membership/layer.rs b/pkgs/id/src/membership/layer.rs index c05db89b1e..c5da38832f 100644 --- a/pkgs/id/src/membership/layer.rs +++ b/pkgs/id/src/membership/layer.rs @@ -40,8 +40,9 @@ pub struct CausalEvent { pub enum Role { /// Any event other than a membership operation. It has a causal position and nothing else. Other, - /// A membership operation by `author`. `group` is the group named in the event; it is `None` - /// for a create, whose group is the event's own ID. + /// A membership operation by `author`. `group` is the group named in the event. A create may + /// leave it `None`, and its group is then the event's own ID. A friendship's create names its + /// derived group (design §5.4). Auth { /// The key that signed the event. author: [u8; 32], @@ -174,7 +175,11 @@ impl Membership { self.index.insert(id, after, None)?; return Ok(Outcome::Applied); }; - let group = if action.is_create() { Some(id) } else { group }; + let group = if action.is_create() { + group.or(Some(id)) + } else { + group + }; let Some(group) = group else { self.index.insert(id, after, None)?; return Ok(Outcome::Refused { @@ -564,6 +569,39 @@ mod tests { assert_eq!(member_keys(&layer, 10), vec![AuthId::Key(key(1))]); } + #[test] + fn test_a_create_may_name_its_group_so_a_friendship_has_a_derived_id() { + // A friendship's group is derived from its pair and counter (design §5.4), not from the + // create's own event ID. The create names that group. + let mut layer = Membership::new(); + let friendship = id(30); + let initial_members = [1, 2] + .iter() + .map(|n| { + ( + GroupMember::Individual(AuthId::Key(key(*n))), + Access::manage(), + ) + }) + .collect(); + let create = CausalEvent { + id: id(10), + after: vec![], + role: Role::Auth { + author: key(1), + group: Some(friendship), + action: GroupAction::Create { initial_members }, + }, + }; + let outcomes = layer.receive(create).unwrap(); + assert_eq!(outcomes, vec![(id(10), Outcome::Applied)]); + assert_eq!( + member_keys(&layer, 30), + vec![AuthId::Key(key(1)), AuthId::Key(key(2))] + ); + assert!(layer.members(id(10)).is_empty()); + } + #[test] fn test_a_non_create_with_no_group_is_refused_as_malformed() { let mut layer = Membership::new(); From 7d5b84bd961e88994d72eb073901f5bdc9052161 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 12 Oct 2026 00:27:48 -0500 Subject: [PATCH 14/40] feat(rust): groups with policy records and templates [P2.4] Groups carry members with roles, a signed policy record, and a template (friendship, channel, private, custom). Anyone may create a group, and a normal group makes its creator Admin. Only an Admin may change a role or the policy, including member_cap. A friendship is a group from the friendship template: cap 2, mutual request, dissolve on removal. It has no Admin unless its create sets admins_on_create. The state is a fold over the whole event set, so arrival order does not change it. The pair model in src/friendship.rs is removed. Its S2 regressions F2 to F5 are ported to the group model in src/groups/tests.rs. The property tests check that the final state is the same for every arrival order. --- pkgs/id/src/friendship.rs | 1247 ------------------------------ pkgs/id/src/groups/fold.rs | 786 +++++++++++++++++++ pkgs/id/src/groups/friendship.rs | 65 ++ pkgs/id/src/groups/mod.rs | 114 +++ pkgs/id/src/groups/policy.rs | 224 ++++++ pkgs/id/src/groups/tests.rs | 822 ++++++++++++++++++++ pkgs/id/src/lib.rs | 2 +- 7 files changed, 2012 insertions(+), 1248 deletions(-) delete mode 100644 pkgs/id/src/friendship.rs create mode 100644 pkgs/id/src/groups/fold.rs create mode 100644 pkgs/id/src/groups/friendship.rs create mode 100644 pkgs/id/src/groups/mod.rs create mode 100644 pkgs/id/src/groups/policy.rs create mode 100644 pkgs/id/src/groups/tests.rs diff --git a/pkgs/id/src/friendship.rs b/pkgs/id/src/friendship.rs deleted file mode 100644 index 0db5af14c3..0000000000 --- a/pkgs/id/src/friendship.rs +++ /dev/null @@ -1,1247 +0,0 @@ -//! Friendship: one-way requests that become a friendship on accept, a cap on -//! friends per account, and a dissolve that ends a friendship on both sides. -//! -//! p2panda-auth has no member cap and no dissolve, so both are ours (S2, friendship). -//! The module is pure. Accounts and operation IDs are plain strings, and each -//! operation arrives already signed. Nothing here reads a clock or the network. -//! -//! The rules: -//! -//! - A request is one-way. It stays open until its recipient accepts or declines -//! it, or a removal names it. Two accounts have at most one open request, and no -//! request while they are friends. -//! - An accept makes a friendship if both accounts have fewer than the cap. -//! - A removal names the requests it covers, as the directory's `FriendRemove` -//! does. Naming a request voids it. Naming the request that formed a friendship -//! dissolves the friendship on both sides. A dissolved friendship is not revived -//! by an accept of its request. Only a new request makes a new friendship. -//! -//! Each operation is judged against the state of its own causal past: its `after` -//! set, closed transitively. A later operation cannot change what an earlier one -//! meant. Two things depend on the whole set rather than on arrival. A removal wins -//! over a concurrent accept of the request it names. Where concurrent accepts would -//! exceed the cap, the one that comes first in the canonical order is kept. That -//! order is causal order, with ties going to the smaller ID. So every server that -//! holds the same operations reaches the same friend set. - -use std::collections::{BTreeMap, BTreeSet}; - -/// The most friends one account may have. Our number, not p2panda-auth's. -pub const MAX_FRIENDS: usize = 100; - -/// An account ID. -pub type Account = String; - -/// An operation ID. A request's ID names the request. -pub type OpId = String; - -/// Two accounts, smaller first. -pub type Pair = (Account, Account); - -/// What an operation asks for. -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum Op { - /// `from` asks `to` to be friends. - Request { - /// The sender. - from: Account, - /// The recipient. - to: Account, - }, - /// The recipient `by` accepts `request`. - Accept { - /// The request accepted. - request: OpId, - /// The recipient, who must be the request's `to`. - by: Account, - }, - /// The recipient `by` declines `request`, which voids it. - Decline { - /// The request declined. - request: OpId, - /// The recipient, who must be the request's `to`. - by: Account, - }, - /// `by` ends its friendship with `other`, and voids the requests it names - /// between them. Naming the request that formed the friendship dissolves it. - Remove { - /// The account removing. - by: Account, - /// The other account. - other: Account, - /// The requests it covers. - requests: Vec, - }, -} - -/// An operation with its ID and the IDs it saw. The caller has checked the signature. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct Signed { - /// The operation's ID. - pub id: OpId, - /// The IDs of the operations it saw, directly. - pub after: BTreeSet, - /// What it does. - pub op: Op, -} - -/// Why an operation had no effect. -#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] -pub enum Refusal { - /// A request to oneself. - #[error("no one befriends themselves")] - SelfRequest, - /// A removal of oneself. - #[error("no one removes themselves")] - SameAccount, - /// Only the recipient of a request may accept or decline it. - #[error("{by} is not the recipient of request {request}")] - NotRecipient { - /// The request. - request: OpId, - /// The account that tried to answer it. - by: Account, - }, - /// The request is not among the operations this one saw. - #[error("request {request} is not among the operations this one saw")] - UnknownRequest { - /// The request. - request: OpId, - }, - /// A removal names a request between two other accounts. - #[error("request {request} is not between these two accounts")] - NotThisPair { - /// The request. - request: OpId, - }, - /// The request was already accepted, declined or voided. - #[error("request {request} is no longer open")] - NotOpen { - /// The request. - request: OpId, - }, - /// A removal that names the request dissolved the friendship it formed. - #[error("request {request} was dissolved by a removal that names it")] - Dissolved { - /// The request. - request: OpId, - }, - /// The two accounts are already friends. - #[error("already friends")] - AlreadyFriends, - /// An open request already exists between the two accounts. - #[error("a request is already open between them")] - AlreadyOpen, - /// One account already has the maximum number of friends. - #[error("{account} already has {cap} friends")] - AtCap { - /// The account at the cap. - account: Account, - /// The cap that was reached. - cap: usize, - }, - /// The removal covers no friendship and no open request. - #[error("nothing to remove")] - NothingToRemove, -} - -/// What became of one operation. -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum Outcome { - /// It took effect. - Applied, - /// It had no effect. - Refused(Refusal), -} - -/// The operations are not a usable set. -#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] -pub enum ProjectError { - /// Two operations share an ID. - #[error("operation {0} appears twice")] - DuplicateId(OpId), - /// An operation names an ID that is not in the set. - #[error("operation {op} waits for {dependency}")] - MissingDependency { - /// The operation that names the missing one. - op: OpId, - /// The missing operation. - dependency: OpId, - }, - /// The `after` sets form a cycle. - #[error("the operations form a cycle")] - Cycle, -} - -/// The friend set that the operations determine, and what became of each one. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct Projection { - friends: BTreeSet, - outcomes: BTreeMap, -} - -impl Projection { - /// Every friendship, as sorted pairs. - #[must_use] - pub fn friendships(&self) -> &BTreeSet { - &self.friends - } - - /// Whether two accounts are friends. - #[must_use] - pub fn are_friends(&self, a: &str, b: &str) -> bool { - self.friends.contains(&pair(a, b)) - } - - /// The friends of one account, sorted. - #[must_use] - pub fn friends_of(&self, account: &str) -> Vec { - let mut out: Vec = self - .friends - .iter() - .filter_map(|(a, b)| { - if a == account { - Some(b.clone()) - } else if b == account { - Some(a.clone()) - } else { - None - } - }) - .collect(); - out.sort(); - out - } - - /// What became of an operation, if it was in the set. - #[must_use] - pub fn outcome(&self, id: &str) -> Option<&Outcome> { - self.outcomes.get(id) - } -} - -/// Project signed operations to the friend set they determine. -/// -/// `ops` may come in any order. The result depends only on the operations and their -/// `after` sets. `cap` is the most friends one account may have. The product passes -/// [`MAX_FRIENDS`]. -pub fn project(ops: &[Signed], cap: usize) -> Result { - let by_id = index(ops)?; - let order = canonical_order(&by_id)?; - let past = pasts(&order); - - // Each operation is judged against its own causal past, which the canonical order - // has already settled. - let mut verdicts: BTreeMap<&str, Option> = BTreeMap::new(); - for &signed in &order { - let id = signed.id.as_str(); - let verdict = match static_refusal(signed, &by_id, &past[id]) { - Some(refusal) => Some(refusal), - None => check(&state_before(id, &order, &past, &verdicts), &signed.op, cap).err(), - }; - verdicts.insert(id, verdict); - } - - // A valid removal dissolves the friendship that its named request formed, whenever the - // removal arrived. So a removal wins over a concurrent accept. - let mut removed: BTreeSet<&str> = BTreeSet::new(); - for &signed in &order { - if let (Op::Remove { requests, .. }, None) = (&signed.op, &verdicts[signed.id.as_str()]) { - removed.extend(requests.iter().map(String::as_str)); - } - } - - // Accepts that survive are kept in canonical order, while both accounts are under the cap. - let mut friends: BTreeSet = BTreeSet::new(); - let mut kept: BTreeMap<&str, usize> = BTreeMap::new(); - let mut outcomes = BTreeMap::new(); - for &signed in &order { - let id = signed.id.as_str(); - let refusal = match verdicts[id].clone() { - Some(refusal) => Some(refusal), - None => match &signed.op { - Op::Accept { request, .. } => { - if removed.contains(request.as_str()) { - Some(Refusal::Dissolved { - request: request.clone(), - }) - } else if let Some((from, to)) = requested(request, &by_id, &past[id]) { - let p = pair(from, to); - let full = [from, to] - .into_iter() - .find(|account| kept.get(*account).copied().unwrap_or(0) >= cap); - if friends.contains(&p) { - Some(Refusal::AlreadyFriends) - } else if let Some(account) = full { - Some(Refusal::AtCap { - account: account.to_owned(), - cap, - }) - } else { - for account in [from, to] { - *kept.entry(account).or_insert(0) += 1; - } - friends.insert(p); - None - } - } else { - Some(Refusal::UnknownRequest { - request: request.clone(), - }) - } - } - _ => None, - }, - }; - outcomes.insert( - id.to_owned(), - refusal.map_or(Outcome::Applied, Outcome::Refused), - ); - } - Ok(Projection { friends, outcomes }) -} - -/// Operations by ID. -type Index<'a> = BTreeMap<&'a str, &'a Signed>; - -/// The causal past of each operation, by ID. -type Past<'a> = BTreeMap<&'a str, BTreeSet<&'a str>>; - -fn pair(a: &str, b: &str) -> Pair { - if a <= b { - (a.to_owned(), b.to_owned()) - } else { - (b.to_owned(), a.to_owned()) - } -} - -fn index(ops: &[Signed]) -> Result, ProjectError> { - let mut by_id = BTreeMap::new(); - for signed in ops { - if by_id.insert(signed.id.as_str(), signed).is_some() { - return Err(ProjectError::DuplicateId(signed.id.clone())); - } - } - Ok(by_id) -} - -/// A topological order that breaks ties by ID. It depends only on the operations. -fn canonical_order<'a>(by_id: &Index<'a>) -> Result, ProjectError> { - let mut waiting: BTreeMap<&str, usize> = BTreeMap::new(); - let mut dependents: BTreeMap<&str, Vec<&str>> = BTreeMap::new(); - for (&id, &signed) in by_id { - waiting.insert(id, signed.after.len()); - for dep in &signed.after { - if !by_id.contains_key(dep.as_str()) { - return Err(ProjectError::MissingDependency { - op: id.to_owned(), - dependency: dep.clone(), - }); - } - dependents.entry(dep.as_str()).or_default().push(id); - } - } - let mut ready: BTreeSet<&str> = waiting - .iter() - .filter(|(_, n)| **n == 0) - .map(|(id, _)| *id) - .collect(); - let mut order = Vec::with_capacity(by_id.len()); - while let Some(id) = ready.pop_first() { - order.push(by_id[id]); - for &next in dependents.get(id).into_iter().flatten() { - if let Some(n) = waiting.get_mut(next) { - *n -= 1; - if *n == 0 { - ready.insert(next); - } - } - } - } - if order.len() != by_id.len() { - return Err(ProjectError::Cycle); - } - Ok(order) -} - -/// Each operation's causal past. `order` must be topological. -fn pasts<'a>(order: &[&'a Signed]) -> Past<'a> { - let mut past: Past<'a> = BTreeMap::new(); - for &signed in order { - let mut seen: BTreeSet<&'a str> = BTreeSet::new(); - for dep in &signed.after { - seen.insert(dep.as_str()); - if let Some(before) = past.get(dep.as_str()) { - seen.extend(before.iter().copied()); - } - } - past.insert(signed.id.as_str(), seen); - } - past -} - -/// The state that the valid operations in `id`'s causal past build, in canonical order. -fn state_before( - id: &str, - order: &[&Signed], - past: &Past<'_>, - verdicts: &BTreeMap<&str, Option>, -) -> State { - let mut state = State::default(); - let before = &past[id]; - for &signed in order { - let sid = signed.id.as_str(); - if before.contains(sid) && verdicts.get(sid).is_some_and(Option::is_none) { - effect(&mut state, signed); - } - } - state -} - -/// The sender and recipient of a request in the causal past, if `id` is one. -fn requested<'a>(id: &str, by_id: &Index<'a>, past: &BTreeSet<&str>) -> Option<(&'a str, &'a str)> { - if !past.contains(id) { - return None; - } - let signed: &'a Signed = *by_id.get(id)?; - match &signed.op { - Op::Request { from, to } => Some((from.as_str(), to.as_str())), - _ => None, - } -} - -/// Refusals that depend only on the operation and its causal past. -fn static_refusal(signed: &Signed, by_id: &Index<'_>, past: &BTreeSet<&str>) -> Option { - match &signed.op { - Op::Request { from, to } if from == to => Some(Refusal::SelfRequest), - Op::Request { .. } => None, - Op::Accept { request, by } | Op::Decline { request, by } => { - match requested(request, by_id, past) { - None => Some(Refusal::UnknownRequest { - request: request.clone(), - }), - Some((_, to)) if to != by => Some(Refusal::NotRecipient { - request: request.clone(), - by: by.clone(), - }), - Some(_) => None, - } - } - Op::Remove { - by, - other, - requests, - } => { - if by == other { - return Some(Refusal::SameAccount); - } - let this = pair(by, other); - requests - .iter() - .find_map(|request| match requested(request, by_id, past) { - None => Some(Refusal::UnknownRequest { - request: request.clone(), - }), - Some((from, to)) if pair(from, to) != this => Some(Refusal::NotThisPair { - request: request.clone(), - }), - Some(_) => None, - }) - } - } -} - -/// The friendship state that operations build. -#[derive(Default)] -struct State { - /// Every request that took effect: its sender and recipient. - requests: BTreeMap, - /// Requests still open. - open: BTreeSet, - /// Friendships, each with the request that formed it. - friends: BTreeMap, -} - -impl State { - fn count(&self, account: &str) -> usize { - self.friends - .keys() - .filter(|(a, b)| a == account || b == account) - .count() - } - - fn open_between(&self, a: &str, b: &str) -> bool { - let p = pair(a, b); - self.open.iter().any(|id| { - self.requests - .get(id) - .is_some_and(|(from, to)| pair(from, to) == p) - }) - } -} - -/// Whether an operation takes effect in `state`. -fn check(state: &State, op: &Op, cap: usize) -> Result<(), Refusal> { - match op { - Op::Request { from, to } => { - if state.friends.contains_key(&pair(from, to)) { - Err(Refusal::AlreadyFriends) - } else if state.open_between(from, to) { - Err(Refusal::AlreadyOpen) - } else { - Ok(()) - } - } - Op::Accept { request, .. } => { - let Some((from, to)) = state - .requests - .get(request) - .filter(|_| state.open.contains(request)) - else { - return Err(Refusal::NotOpen { - request: request.clone(), - }); - }; - if state.friends.contains_key(&pair(from, to)) { - return Err(Refusal::AlreadyFriends); - } - for account in [from, to] { - if state.count(account) >= cap { - return Err(Refusal::AtCap { - account: account.clone(), - cap, - }); - } - } - Ok(()) - } - Op::Decline { request, .. } => { - if state.open.contains(request) { - Ok(()) - } else { - Err(Refusal::NotOpen { - request: request.clone(), - }) - } - } - Op::Remove { - by, - other, - requests, - } => { - let p = pair(by, other); - if requests - .iter() - .any(|r| state.open.contains(r) || state.friends.get(&p) == Some(r)) - { - Ok(()) - } else { - Err(Refusal::NothingToRemove) - } - } - } -} - -/// Apply an operation that took effect. -fn effect(state: &mut State, signed: &Signed) { - match &signed.op { - Op::Request { from, to } => { - state - .requests - .insert(signed.id.clone(), (from.clone(), to.clone())); - state.open.insert(signed.id.clone()); - } - Op::Accept { request, .. } => { - if let Some((from, to)) = state.requests.get(request).cloned() { - state.open.remove(request); - state.friends.insert(pair(&from, &to), request.clone()); - } - } - Op::Decline { request, .. } => { - state.open.remove(request); - } - Op::Remove { - by, - other, - requests, - } => { - let p = pair(by, other); - for request in requests { - state.open.remove(request); - if state.friends.get(&p) == Some(request) { - state.friends.remove(&p); - } - } - } - } -} - -#[cfg(test)] -#[allow(clippy::unwrap_used, clippy::expect_used)] -mod tests { - use super::*; - use proptest::prelude::*; - - /// The cap for scenarios where it binds. Small, so that each boundary is reached. - const TEST_CAP: usize = 2; - - const ACCOUNTS: [&str; 5] = ["ann", "bo", "cy", "di", "ed"]; - - fn signed(id: &str, after: &[&str], op: Op) -> Signed { - Signed { - id: id.to_owned(), - after: after.iter().map(|d| (*d).to_owned()).collect(), - op, - } - } - - fn request(id: &str, after: &[&str], from: &str, to: &str) -> Signed { - signed( - id, - after, - Op::Request { - from: from.to_owned(), - to: to.to_owned(), - }, - ) - } - - fn accept(id: &str, after: &[&str], request: &str, by: &str) -> Signed { - signed( - id, - after, - Op::Accept { - request: request.to_owned(), - by: by.to_owned(), - }, - ) - } - - fn decline(id: &str, after: &[&str], request: &str, by: &str) -> Signed { - signed( - id, - after, - Op::Decline { - request: request.to_owned(), - by: by.to_owned(), - }, - ) - } - - fn remove(id: &str, after: &[&str], by: &str, other: &str, requests: &[&str]) -> Signed { - signed( - id, - after, - Op::Remove { - by: by.to_owned(), - other: other.to_owned(), - requests: requests.iter().map(|r| (*r).to_owned()).collect(), - }, - ) - } - - /// Every order that respects the `after` sets. S2 ran every causal order this way. - fn linearizations(ops: &[Signed]) -> Vec> { - fn extend(rest: &mut Vec, done: &mut Vec, out: &mut Vec>) { - if rest.is_empty() { - out.push(done.clone()); - return; - } - for i in 0..rest.len() { - if rest[i] - .after - .iter() - .all(|d| done.iter().any(|x| &x.id == d)) - { - let next = rest.remove(i); - done.push(next.clone()); - extend(rest, done, out); - done.pop(); - rest.insert(i, next); - } - } - } - let mut out = Vec::new(); - extend(&mut ops.to_vec(), &mut Vec::new(), &mut out); - out - } - - /// The projection of `ops`, which must be the same for every causal order. - fn settled(ops: &[Signed], cap: usize) -> Projection { - let expected = project(ops, cap).unwrap(); - for order in linearizations(ops) { - assert_eq!(project(&order, cap).unwrap(), expected); - } - expected - } - - fn applied(p: &Projection, id: &str) -> bool { - p.outcome(id) == Some(&Outcome::Applied) - } - - #[test] - fn a_request_is_one_way_and_becomes_a_friendship_on_accept() { - let open = settled(&[request("r0", &[], "ann", "bo")], TEST_CAP); - assert!(!open.are_friends("ann", "bo")); - assert!(applied(&open, "r0")); - - let ops = [ - request("r0", &[], "ann", "bo"), - accept("a0", &["r0"], "r0", "bo"), - ]; - let friends = settled(&ops, TEST_CAP); - assert!(friends.are_friends("bo", "ann")); - assert_eq!(friends.friends_of("ann"), ["bo"]); - } - - #[test] - fn only_the_recipient_may_accept() { - let ops = [ - request("r0", &[], "ann", "bo"), - accept("a0", &["r0"], "r0", "ann"), - ]; - let p = settled(&ops, TEST_CAP); - assert_eq!( - p.outcome("a0"), - Some(&Outcome::Refused(Refusal::NotRecipient { - request: "r0".into(), - by: "ann".into(), - })) - ); - assert!(!p.are_friends("ann", "bo")); - } - - #[test] - fn a_declined_request_is_void_and_its_later_accept_is_refused() { - let ops = [ - request("r0", &[], "ann", "bo"), - decline("d0", &["r0"], "r0", "bo"), - accept("a1", &["r0", "d0"], "r0", "bo"), - ]; - let p = settled(&ops, TEST_CAP); - assert!(applied(&p, "d0")); - assert_eq!( - p.outcome("a1"), - Some(&Outcome::Refused(Refusal::NotOpen { - request: "r0".into(), - })) - ); - assert!(!p.are_friends("ann", "bo")); - } - - #[test] - fn a_request_to_oneself_is_refused() { - let p = settled(&[request("r0", &[], "ann", "ann")], TEST_CAP); - assert_eq!( - p.outcome("r0"), - Some(&Outcome::Refused(Refusal::SelfRequest)) - ); - } - - #[test] - fn one_open_request_per_pair_in_either_direction() { - let ops = [ - request("r0", &[], "ann", "bo"), - request("r1", &["r0"], "bo", "ann"), - ]; - let p = settled(&ops, TEST_CAP); - assert_eq!( - p.outcome("r1"), - Some(&Outcome::Refused(Refusal::AlreadyOpen)) - ); - } - - #[test] - fn no_request_between_friends() { - let ops = [ - request("r0", &[], "ann", "bo"), - accept("a0", &["r0"], "r0", "bo"), - request("r1", &["a0"], "ann", "bo"), - ]; - let p = settled(&ops, TEST_CAP); - assert_eq!( - p.outcome("r1"), - Some(&Outcome::Refused(Refusal::AlreadyFriends)) - ); - } - - #[test] - fn an_accept_below_the_cap_is_applied_and_reaches_it() { - // cap - 1: ann has one friend, so the second is applied and fills the cap. - let ops = [ - request("r0", &[], "bo", "ann"), - accept("a0", &["r0"], "r0", "ann"), - request("r1", &["a0"], "cy", "ann"), - accept("a1", &["r1"], "r1", "ann"), - ]; - let p = settled(&ops, TEST_CAP); - assert!(applied(&p, "a1")); - assert_eq!(p.friends_of("ann"), ["bo", "cy"]); - } - - #[test] - fn an_accept_at_the_cap_is_refused_with_the_account_named() { - // cap: ann already has cap friends, so a third accept is refused. - let ops = [ - request("r0", &[], "bo", "ann"), - accept("a0", &["r0"], "r0", "ann"), - request("r1", &["a0"], "cy", "ann"), - accept("a1", &["r1"], "r1", "ann"), - request("r2", &["a1"], "di", "ann"), - accept("a2", &["r2"], "r2", "ann"), - ]; - let p = settled(&ops, TEST_CAP); - assert_eq!( - p.outcome("a2"), - Some(&Outcome::Refused(Refusal::AtCap { - account: "ann".into(), - cap: TEST_CAP, - })) - ); - assert_eq!(p.friends_of("ann"), ["bo", "cy"]); - } - - #[test] - fn past_the_cap_nothing_more_is_added() { - // cap + 1: a fourth and a fifth request stay open and are never friends. - let ops = [ - request("r0", &[], "bo", "ann"), - accept("a0", &["r0"], "r0", "ann"), - request("r1", &["a0"], "cy", "ann"), - accept("a1", &["r1"], "r1", "ann"), - request("r2", &["a1"], "di", "ann"), - accept("a2", &["r2"], "r2", "ann"), - request("r3", &["a2"], "ed", "ann"), - accept("a3", &["r3"], "r3", "ann"), - ]; - let p = settled(&ops, TEST_CAP); - assert!(!applied(&p, "a3")); - assert_eq!(p.friends_of("ann").len(), TEST_CAP); - } - - #[test] - fn the_requester_side_counts_toward_the_cap() { - // bo is at the cap, so bo cannot make a friend of dan. - let ops = [ - request("r0", &[], "ann", "bo"), - accept("a0", &["r0"], "r0", "bo"), - request("r1", &["a0"], "cy", "bo"), - accept("a1", &["r1"], "r1", "bo"), - request("r2", &["a1"], "bo", "di"), - accept("a2", &["r2"], "r2", "di"), - ]; - let p = settled(&ops, TEST_CAP); - assert_eq!( - p.outcome("a2"), - Some(&Outcome::Refused(Refusal::AtCap { - account: "bo".into(), - cap: TEST_CAP, - })) - ); - } - - #[test] - fn an_accept_refused_at_the_cap_is_not_revived_when_a_friend_leaves() { - // ann is at the cap with bo and cy. The accept of di is refused. When bo leaves, - // di must not become a friend through that old accept. - let ops = [ - request("r0", &[], "bo", "ann"), - accept("a0", &["r0"], "r0", "ann"), - request("r1", &["a0"], "cy", "ann"), - accept("a1", &["r1"], "r1", "ann"), - request("r2", &["a1"], "di", "ann"), - accept("a2", &["r2"], "r2", "ann"), - remove("x", &["a2"], "ann", "bo", &["r0"]), - ]; - let p = settled(&ops, TEST_CAP); - assert!(applied(&p, "x")); - assert!(matches!( - p.outcome("a2"), - Some(Outcome::Refused(Refusal::AtCap { .. })) - )); - assert_eq!(p.friends_of("ann"), ["cy"]); - } - - #[test] - fn a_request_side_accept_refused_at_the_cap_is_not_revived_when_a_friend_leaves() { - // bo is at the cap with ann and cy. The accept of di, which bo requested, is - // refused. When ann leaves, di must not become a friend of bo. - let ops = [ - request("r0", &[], "ann", "bo"), - accept("a0", &["r0"], "r0", "bo"), - request("r1", &["a0"], "cy", "bo"), - accept("a1", &["r1"], "r1", "bo"), - request("r2", &["a1"], "bo", "di"), - accept("a2", &["r2"], "r2", "di"), - remove("x", &["a2"], "bo", "ann", &["r0"]), - ]; - let p = settled(&ops, TEST_CAP); - assert!(applied(&p, "x")); - assert!(matches!( - p.outcome("a2"), - Some(Outcome::Refused(Refusal::AtCap { .. })) - )); - assert_eq!(p.friends_of("bo"), ["cy"]); - assert!(p.friends_of("di").is_empty()); - } - - #[test] - fn a_removal_dissolves_the_friendship_on_both_sides() { - for (by, other) in [("ann", "bo"), ("bo", "ann")] { - let ops = [ - request("r0", &[], "ann", "bo"), - accept("a0", &["r0"], "r0", "bo"), - remove("x", &["a0"], by, other, &["r0"]), - ]; - let p = settled(&ops, TEST_CAP); - assert!(applied(&p, "x")); - assert!(!p.are_friends("ann", "bo")); - assert!(p.friends_of("bo").is_empty()); - assert!(p.friends_of("ann").is_empty()); - } - } - - #[test] - fn a_removal_voids_a_request_that_was_never_delivered() { - // The chain: bo accepts after the removal, so the request is already gone. - let chained = [ - request("r0", &[], "ann", "bo"), - remove("x", &["r0"], "ann", "bo", &["r0"]), - accept("a0", &["x"], "r0", "bo"), - ]; - let p = settled(&chained, TEST_CAP); - assert_eq!( - p.outcome("a0"), - Some(&Outcome::Refused(Refusal::NotOpen { - request: "r0".into(), - })) - ); - - // The concurrent case: bo accepted without seeing the removal. The removal wins. - let concurrent = [ - request("r0", &[], "ann", "bo"), - remove("x", &["r0"], "ann", "bo", &["r0"]), - accept("a0", &["r0"], "r0", "bo"), - ]; - let p = settled(&concurrent, TEST_CAP); - assert!(applied(&p, "x")); - assert_eq!( - p.outcome("a0"), - Some(&Outcome::Refused(Refusal::Dissolved { - request: "r0".into(), - })) - ); - assert!(!p.are_friends("ann", "bo")); - } - - #[test] - fn a_removal_with_nothing_to_remove_is_refused() { - let p = settled(&[remove("x", &[], "ann", "bo", &[])], TEST_CAP); - assert_eq!( - p.outcome("x"), - Some(&Outcome::Refused(Refusal::NothingToRemove)) - ); - } - - #[test] - fn a_removal_naming_a_request_between_other_accounts_is_refused() { - let ops = [ - request("r0", &[], "ann", "bo"), - request("r1", &[], "cy", "di"), - remove("x", &["r0", "r1"], "ann", "bo", &["r1"]), - ]; - let p = settled(&ops, TEST_CAP); - assert_eq!( - p.outcome("x"), - Some(&Outcome::Refused(Refusal::NotThisPair { - request: "r1".into(), - })) - ); - } - - #[test] - fn an_accept_of_a_request_outside_its_causal_past_is_refused() { - let ops = [ - request("r0", &[], "ann", "bo"), - accept("a0", &[], "r0", "bo"), - ]; - let p = settled(&ops, TEST_CAP); - assert_eq!( - p.outcome("a0"), - Some(&Outcome::Refused(Refusal::UnknownRequest { - request: "r0".into(), - })) - ); - } - - #[test] - fn a_missing_dependency_a_duplicate_and_a_cycle_are_errors() { - assert_eq!( - project(&[request("r0", &["ghost"], "ann", "bo")], TEST_CAP).unwrap_err(), - ProjectError::MissingDependency { - op: "r0".into(), - dependency: "ghost".into(), - } - ); - assert_eq!( - project( - &[ - request("r0", &[], "ann", "bo"), - request("r0", &[], "ann", "cy") - ], - TEST_CAP - ) - .unwrap_err(), - ProjectError::DuplicateId("r0".into()) - ); - assert_eq!( - project( - &[ - request("a", &["b"], "ann", "bo"), - request("b", &["a"], "ann", "cy") - ], - TEST_CAP - ) - .unwrap_err(), - ProjectError::Cycle - ); - } - - // ----- S2 friendship findings (spikes/shared/s2-auth, friendship.rs and RESULTS.md) ----- - - /// F2: two concurrent adds beyond the cap. Every order keeps the same two friends, - /// and the later add is refused at the cap. - #[test] - fn s2_f2_concurrent_adds_beyond_the_cap_resolve_the_same_in_every_order() { - let ops = [ - request("r0", &[], "ann", "bo"), - accept("a0", &["r0"], "r0", "bo"), - request("r1", &["a0"], "cy", "ann"), - request("r2", &["a0"], "di", "ann"), - accept("a1", &["r1"], "r1", "ann"), - accept("a2", &["r2"], "r2", "ann"), - ]; - let p = settled(&ops, TEST_CAP); - assert_eq!(p.friends_of("ann"), ["bo", "cy"]); - assert_eq!( - p.outcome("a2"), - Some(&Outcome::Refused(Refusal::AtCap { - account: "ann".into(), - cap: TEST_CAP, - })) - ); - } - - /// F3: the concurrent adds, and a removal of bo. The removal dissolves bo's - /// friendship, and the freed place goes to the two new friends. - #[test] - fn s2_f3_concurrent_adds_and_a_removal_of_one_side_dissolve_in_every_order() { - let ops = [ - request("r0", &[], "ann", "bo"), - accept("a0", &["r0"], "r0", "bo"), - request("r1", &["a0"], "cy", "ann"), - request("r2", &["a0"], "di", "ann"), - accept("a1", &["r1"], "r1", "ann"), - accept("a2", &["r2"], "r2", "ann"), - remove("x", &["a0"], "ann", "bo", &["r0"]), - ]; - let p = settled(&ops, TEST_CAP); - assert!(applied(&p, "x")); - assert_eq!( - p.outcome("a0"), - Some(&Outcome::Refused(Refusal::Dissolved { - request: "r0".into(), - })) - ); - assert_eq!(p.friends_of("ann"), ["cy", "di"]); - assert!(p.friends_of("bo").is_empty()); - } - - /// F4: mutual removal. Both removals apply, and the friendship ends once. - #[test] - fn s2_f4_mutual_removal_dissolves_once_and_stays_dissolved() { - let ops = [ - request("r0", &[], "ann", "bo"), - accept("a0", &["r0"], "r0", "bo"), - remove("x", &["a0"], "ann", "bo", &["r0"]), - remove("y", &["a0"], "bo", "ann", &["r0"]), - ]; - let p = settled(&ops, TEST_CAP); - assert!(applied(&p, "x")); - assert!(applied(&p, "y")); - assert!(p.friendships().is_empty()); - } - - /// F5: after a dissolve, the same request and its accept do not bring the - /// friendship back, in any order. Only a new request does. - #[test] - fn s2_f5_a_dissolved_friendship_is_not_revived_by_its_own_accept() { - let concurrent = [ - request("r0", &[], "ann", "bo"), - remove("x", &["r0"], "ann", "bo", &["r0"]), - accept("a0", &["r0"], "r0", "bo"), - ]; - let p = settled(&concurrent, TEST_CAP); - assert!(p.friendships().is_empty()); - assert_eq!( - p.outcome("a0"), - Some(&Outcome::Refused(Refusal::Dissolved { - request: "r0".into(), - })) - ); - } - - /// F5, the other half: a new request after a dissolve is open, and accepting it is - /// a new friendship. This is the product's rule, and it differs from the S2 group - /// model, where dissolution was terminal. The owner decides which one holds. - #[test] - fn s2_f5_a_new_request_after_a_dissolve_is_the_only_way_back() { - let ops = [ - request("r0", &[], "ann", "bo"), - accept("a0", &["r0"], "r0", "bo"), - remove("x", &["a0"], "ann", "bo", &["r0"]), - request("r2", &["x"], "ann", "bo"), - ]; - let open = settled(&ops, TEST_CAP); - assert!(applied(&open, "r2")); - assert!(!open.are_friends("ann", "bo")); - - let mut again = ops.to_vec(); - again.push(accept("a3", &["r2"], "r2", "bo")); - assert!(settled(&again, TEST_CAP).are_friends("ann", "bo")); - } - - // ----- Properties over random operation sets ----- - - fn script() -> impl Strategy> { - proptest::collection::vec((0u8..4, 0u8..5, 0u8..5, any::(), any::()), 1..=10) - } - - /// Build a set from a script. Each operation sees a subset of the earlier ones, so every - /// generated set is a DAG. - fn build(script: &[(u8, u8, u8, u16, u16)]) -> Vec { - let mut ops: Vec = Vec::new(); - for (i, &(kind, a, b, pick, seen)) in script.iter().enumerate() { - let me = ACCOUNTS[usize::from(a) % ACCOUNTS.len()]; - let other = ACCOUNTS[usize::from(b) % ACCOUNTS.len()]; - let id = format!("{pick:04x}-{i:02}"); - let mut after: BTreeSet = BTreeSet::new(); - for (j, earlier) in ops.iter().enumerate() { - if (seen >> j) & 1 == 1 { - after.insert(earlier.id.clone()); - } - } - let mut open: Vec<(OpId, Account, Account)> = Vec::new(); - for s in &ops { - if let Op::Request { from, to } = &s.op { - open.push((s.id.clone(), from.clone(), to.clone())); - } - } - let op = match kind { - 1 | 2 if !open.is_empty() => { - let (request, _from, to) = open[usize::from(pick) % open.len()].clone(); - after.insert(request.clone()); - // A wrong recipient sometimes, so the static refusal is exercised. - let by = if seen % 7 == 0 { other.to_owned() } else { to }; - if kind == 1 { - Op::Accept { request, by } - } else { - Op::Decline { request, by } - } - } - 3 => { - let mut named = Vec::new(); - for (k, (request, from, to)) in open.iter().enumerate() { - if pair(from, to) == pair(me, other) && (pick >> (k % 16)) & 1 == 1 { - named.push(request.clone()); - } - } - after.extend(named.iter().cloned()); - Op::Remove { - by: me.to_owned(), - other: other.to_owned(), - requests: named, - } - } - _ => Op::Request { - from: me.to_owned(), - to: other.to_owned(), - }, - }; - ops.push(Signed { id, after, op }); - } - ops - } - - /// A random order that respects the `after` sets. `prio` picks among the ready operations. - fn linearize(ops: &[Signed], prio: &[u16]) -> Vec { - let mut rest: Vec<&Signed> = ops.iter().collect(); - let mut done: BTreeSet<&str> = BTreeSet::new(); - let mut out = Vec::new(); - while !rest.is_empty() { - let ready: Vec = (0..rest.len()) - .filter(|&i| rest[i].after.iter().all(|d| done.contains(d.as_str()))) - .collect(); - if ready.is_empty() { - break; - } - let next = rest.remove(ready[usize::from(prio[out.len() % prio.len()]) % ready.len()]); - done.insert(next.id.as_str()); - out.push(next.clone()); - } - out - } - - fn requested_pair(ops: &[Signed], request: &str) -> Option { - ops.iter().find_map(|s| match &s.op { - Op::Request { from, to } if s.id == request => Some(pair(from, to)), - _ => None, - }) - } - - proptest! { - #![proptest_config(ProptestConfig::with_cases(1000))] - - #[test] - fn the_cap_is_never_exceeded(script in script(), cap in 1usize..=3) { - let ops = build(&script); - let p = project(&ops, cap).unwrap(); - for account in ACCOUNTS { - let friends = p.friends_of(account).len(); - prop_assert!(friends <= cap, "{account} has {friends} friends, cap {cap}"); - } - } - - #[test] - fn the_result_does_not_depend_on_the_order( - script in script(), - cap in 1usize..=3, - prio in proptest::collection::vec(any::(), 12), - ) { - let ops = build(&script); - let expected = project(&ops, cap).unwrap(); - let shuffled = linearize(&ops, &prio); - prop_assert_eq!(shuffled.len(), ops.len()); - prop_assert_eq!(project(&shuffled, cap).unwrap(), expected.clone()); - let mut reversed = ops.clone(); - reversed.reverse(); - prop_assert_eq!(project(&reversed, cap).unwrap(), expected); - } - - #[test] - fn every_friendship_is_formed_by_an_applied_accept(script in script(), cap in 1usize..=3) { - let ops = build(&script); - let p = project(&ops, cap).unwrap(); - for (a, b) in p.friendships() { - let formed = ops.iter().any(|s| match &s.op { - Op::Accept { request, .. } => { - applied(&p, &s.id) - && requested_pair(&ops, request) == Some((a.clone(), b.clone())) - } - _ => false, - }); - prop_assert!(formed, "{a} and {b} are friends with no applied accept"); - } - } - } -} diff --git a/pkgs/id/src/groups/fold.rs b/pkgs/id/src/groups/fold.rs new file mode 100644 index 0000000000..47ed23f68e --- /dev/null +++ b/pkgs/id/src/groups/fold.rs @@ -0,0 +1,786 @@ +//! The fold: a group's state from the whole set of its events (design §4.4 and §5). +//! +//! [`fold`] takes every event and puts them in a canonical order: causal order, with ties going to +//! the smaller event ID. It then applies each event in that order. A rule sees the state built by +//! the events before it, so the Admin check, the member cap, and dissolve are all decided against +//! that prefix. The order depends only on the set of events, so the result does not depend on the +//! order they arrived in. +//! +//! Two concurrent events are ordered by ID, so the lower ID wins a contested place. That is the +//! rule for concurrent adds past the cap (design §5.1). The voiding track's rules for removal may +//! refine how a removal meets a concurrent change. +//! +//! Membership operations go to [`crate::membership`], which decides them on p2panda-auth. Each +//! event is handed to it once, so the causal index stays complete. An event this layer refuses is +//! handed over as a no-op. + +use std::cmp::{Ordering, Reverse}; +use std::collections::{BTreeMap, BTreeSet, BinaryHeap}; + +use p2panda_auth::Access; +use p2panda_auth::group::{GroupAction, GroupMember}; +use p2panda_core::Hash; +use thiserror::Error; + +use crate::membership::{ + AuthId, CausalEvent, Membership, MembershipError, Outcome as Decided, Refusal as AuthRefusal, + Role as Placement, +}; + +use super::friendship::{Pair, friendship_id}; +use super::policy::{OnMemberRemoved, Policy, Template}; +use super::{Body, Create, Event, Key, MemberOp, Role}; + +/// Why an event had no effect. A refused event changes no state. It is still decided, so the +/// events after it can be decided too. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Refusal { + /// The event names no group, or a group that does not exist. + NoGroup, + /// The event's group is not the one its kind requires. + WrongGroup, + /// The group has been dissolved and takes no further change. + Dissolved, + /// The author is not an active member. A friendship's requester is not active until the other + /// side has accepted. + NotActive, + /// The author is not an Admin. + NotAdmin, + /// The author may not add or remove members. + NotManager, + /// The account named is not a member. + NotAMember(Key), + /// The account named is already a member. + AlreadyMember(Key), + /// The friendship's ID is not the one its pair and counter give. + WrongFriendshipId, + /// A friendship names exactly one other account, and it must not be the author. + BadFriendship, + /// The template does not admit the policy record. + BadTemplate(Template), + /// The policy record is not usable: its role rule is not Admin, or its cap allows no member. + BadPolicy, + /// The members list repeats an account, or names the author. + BadMembers, + /// The member cap would be exceeded. + OverCap { + /// The cap. + cap: usize, + }, + /// Only a friendship's mutual request takes a join in this version. The other join modes are + /// not built yet. + JoinNotSupported, + /// The account has no invitation to this friendship. + NotInvited, + /// The account has already accepted. + AlreadyPresent, + /// The membership layer refused it at its causal position. + Membership(AuthRefusal), +} + +/// What became of one event. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Outcome { + /// It took effect. + Applied, + /// It had no effect. + Refused(Refusal), +} + +/// The events cannot be used as a set. +#[derive(Clone, Debug, PartialEq, Eq, Error)] +pub enum FoldError { + /// Two events share an ID. + #[error("event {0} appears twice")] + DuplicateId(Hash), + /// An event names an `after` hash that is not in the set. + #[error("event {op} waits for {dependency}")] + MissingDependency { + /// The event that names the missing one. + op: Hash, + /// The missing event. + dependency: Hash, + }, + /// The `after` links form a cycle. + #[error("the events form a cycle")] + Cycle, + /// The membership layer broke an invariant. + #[error(transparent)] + Membership(#[from] MembershipError), +} + +/// One group as the events determine it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct GroupView { + /// The policy record, as last set by an Admin. + pub policy: Policy, + /// Each member and its role. An Admin is listed as Admin, whatever its access level. + pub members: BTreeMap, + /// The friendship pair, for a friendship. + pub friendship: Option, + /// For a friendship, the accounts with an applied event in it. + pub present: BTreeSet, + /// The event that dissolved the group, if it has been dissolved. + pub dissolved_by: Option, +} + +impl GroupView { + /// Whether the group is in effect. A friendship is in effect once both sides are present, and + /// until it dissolves. + pub fn is_active(&self) -> bool { + if self.dissolved_by.is_some() { + return false; + } + match self.friendship { + None => true, + Some(pair) => pair.members().iter().all(|key| self.present.contains(key)), + } + } +} + +/// The state of every group, and what became of each event. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Projection { + groups: BTreeMap, + outcomes: BTreeMap, +} + +impl Projection { + /// The group with this ID. + pub fn group(&self, id: &Hash) -> Option<&GroupView> { + self.groups.get(id) + } + + /// Every group, by ID. + pub fn groups(&self) -> impl Iterator { + self.groups.iter() + } + + /// What became of the event with this ID. + pub fn outcome(&self, id: &Hash) -> Option<&Outcome> { + self.outcomes.get(id) + } + + /// Whether `a` and `b` are friends: an active friendship group names the pair. + pub fn friends(&self, a: &Key, b: &Key) -> bool { + Pair::of(*a, *b).is_some_and(|pair| { + self.groups + .values() + .any(|group| group.friendship == Some(pair) && group.is_active()) + }) + } +} + +/// Computes the state of every group from the whole set of events. The order the events are given +/// in does not change the result. +pub fn fold(events: &[Event]) -> Result { + let by_id = index(events)?; + let order = canonical_order(&by_id)?; + let mut engine = Engine::default(); + let mut outcomes = BTreeMap::new(); + for event in order { + let outcome = engine.apply(event, &by_id)?; + outcomes.insert(event.id, outcome); + } + Ok(engine.into_projection(outcomes)) +} + +/// The events by ID. Every `after` hash must name one of them. +fn index(events: &[Event]) -> Result, FoldError> { + let mut by_id = BTreeMap::new(); + for event in events { + if by_id.insert(event.id, event).is_some() { + return Err(FoldError::DuplicateId(event.id)); + } + } + for event in events { + for dependency in &event.after { + if !by_id.contains_key(dependency) { + return Err(FoldError::MissingDependency { + op: event.id, + dependency: *dependency, + }); + } + } + } + Ok(by_id) +} + +/// The events in causal order, with ties going to the smaller ID. +fn canonical_order<'a>(by_id: &BTreeMap) -> Result, FoldError> { + let mut waiting: BTreeMap = BTreeMap::new(); + let mut children: BTreeMap> = BTreeMap::new(); + let mut ready = BinaryHeap::new(); + for event in by_id.values() { + let dependencies: BTreeSet = event.after.iter().copied().collect(); + for dependency in &dependencies { + children.entry(*dependency).or_default().push(event.id); + } + if dependencies.is_empty() { + ready.push(Reverse(event.id)); + } + waiting.insert(event.id, dependencies.len()); + } + let mut order = Vec::with_capacity(by_id.len()); + while let Some(Reverse(id)) = ready.pop() { + let Some(event) = by_id.get(&id) else { + continue; + }; + order.push(*event); + for child in children.remove(&id).unwrap_or_default() { + if let Some(count) = waiting.get_mut(&child) { + *count -= 1; + if *count == 0 { + ready.push(Reverse(child)); + } + } + } + } + if order.len() == by_id.len() { + Ok(order) + } else { + Err(FoldError::Cycle) + } +} + +/// Every event that the `after` hashes reach through `after` links, the hashes included. +fn causal_past(by_id: &BTreeMap, after: &[Hash]) -> BTreeSet { + let mut past = BTreeSet::new(); + let mut stack: Vec = after.to_vec(); + while let Some(id) = stack.pop() { + if !past.insert(id) { + continue; + } + if let Some(event) = by_id.get(&id) { + stack.extend(event.after.iter().copied()); + } + } + past +} + +/// What a group holds beyond its membership layer state. +#[derive(Clone, Debug, PartialEq, Eq)] +struct Record { + policy: Policy, + admins: BTreeSet, + present: BTreeSet, + friendship: Option, + dissolved_by: Option, +} + +/// The state change an accepted event makes. It is committed once the membership layer accepts +/// the event. +#[derive(Debug)] +enum Effect { + Create(Record), + Present(Key), + Policy(Policy), + Grant { + member: Key, + admin: bool, + }, + Remove { + member: Key, + dissolves: bool, + by: Hash, + }, +} + +/// A rule's decision: the membership operation to hand to the membership layer, and the state +/// change to commit if the layer accepts it. +#[derive(Debug)] +struct Decision { + group: Hash, + action: Option>, + effect: Effect, +} + +/// The state while the events are applied in canonical order. +#[derive(Debug, Default)] +struct Engine { + membership: Membership, + groups: BTreeMap, +} + +impl Engine { + /// Applies one event, and returns what became of it. + fn apply( + &mut self, + event: &Event, + by_id: &BTreeMap, + ) -> Result { + let decided = match &event.body { + Body::Create(create) => self.create(event, create, by_id), + Body::Join => self.join(event), + Body::Policy(policy) => self.policy(event, policy), + Body::Member(op) => self.member(event, *op), + }; + let decision = match decided { + Ok(decision) => decision, + Err(refusal) => { + self.decide(event, Placement::Other)?; + return Ok(Outcome::Refused(refusal)); + } + }; + let role = match &decision.action { + Some(action) => Placement::Auth { + author: event.author, + group: Some(decision.group), + action: action.clone(), + }, + None => Placement::Other, + }; + match self.decide(event, role)? { + Decided::Applied => { + self.commit(decision.group, decision.effect); + Ok(Outcome::Applied) + } + Decided::Refused { reason, .. } => Ok(Outcome::Refused(Refusal::Membership(reason))), + Decided::Held(_) | Decided::Duplicate => Err(FoldError::Membership( + MembershipError::Internal(format!("{} was not decided", event.id)), + )), + } + } + + /// Hands one event to the membership layer. The events are applied in causal order, so it + /// decides at once. + fn decide(&mut self, event: &Event, role: Placement) -> Result { + let decided = self.membership.receive(CausalEvent { + id: event.id, + after: event.after.clone(), + role, + })?; + decided + .into_iter() + .find(|(id, _)| *id == event.id) + .map(|(_, outcome)| outcome) + .ok_or_else(|| { + FoldError::Membership(MembershipError::Internal(format!( + "{} was not decided", + event.id + ))) + }) + } + + fn commit(&mut self, group: Hash, effect: Effect) { + match effect { + Effect::Create(record) => { + self.groups.insert(group, record); + } + other => { + if let Some(record) = self.groups.get_mut(&group) { + apply_to(record, other); + } + } + } + } + + fn create( + &self, + event: &Event, + create: &Create, + by_id: &BTreeMap, + ) -> Result { + if !create.template.admits(&create.policy) { + return Err(Refusal::BadTemplate(create.template)); + } + if !create.policy.is_valid() { + return Err(Refusal::BadPolicy); + } + if create.template == Template::Friendship { + self.friendship_request(event, create, by_id) + } else { + new_group(event, create) + } + } + + /// A friendship request. Its group is the friendship ID for its pair and the number of + /// friendships of that pair that the request has seen dissolve. A request for a friendship + /// that already exists is the other side's acceptance. + fn friendship_request( + &self, + event: &Event, + create: &Create, + by_id: &BTreeMap, + ) -> Result { + let author = event.author; + let [(other, _)] = create.members.as_slice() else { + return Err(Refusal::BadFriendship); + }; + let other = *other; + let pair = Pair::of(author, other).ok_or(Refusal::BadFriendship)?; + let Some(group) = event.group else { + return Err(Refusal::WrongFriendshipId); + }; + if let Some(record) = self.groups.get(&group) { + if record.friendship != Some(pair) { + return Err(Refusal::WrongGroup); + } + return self.accept(group, record, author); + } + let counter = self.dissolved_before(&pair, &causal_past(by_id, &event.after)); + if group != friendship_id(&pair, counter) { + return Err(Refusal::WrongFriendshipId); + } + let admins = if create.admins_on_create { + BTreeSet::from([author, other]) + } else { + BTreeSet::new() + }; + let record = Record { + policy: create.policy.clone(), + admins, + present: BTreeSet::from([author]), + friendship: Some(pair), + dissolved_by: None, + }; + let initial = vec![ + ( + GroupMember::Individual(AuthId::Key(author)), + Access::manage(), + ), + ( + GroupMember::Individual(AuthId::Key(other)), + Access::manage(), + ), + ]; + Ok(Decision { + group, + action: Some(GroupAction::Create { + initial_members: initial, + }), + effect: Effect::Create(record), + }) + } + + /// The other side accepts a friendship request. The accepter must be the invitee who has not + /// yet been present. + fn accept(&self, group: Hash, record: &Record, author: Key) -> Result { + if record.friendship.is_none() { + return Err(Refusal::JoinNotSupported); + } + if record.dissolved_by.is_some() { + return Err(Refusal::Dissolved); + } + if !self.listed(&group, &author) { + return Err(Refusal::NotInvited); + } + if record.present.contains(&author) { + return Err(Refusal::AlreadyPresent); + } + Ok(Decision { + group, + action: None, + effect: Effect::Present(author), + }) + } + + fn join(&self, event: &Event) -> Result { + let group = event.group.ok_or(Refusal::NoGroup)?; + let record = self.record(&group)?; + self.accept(group, record, event.author) + } + + fn policy(&self, event: &Event, policy: &Policy) -> Result { + let group = event.group.ok_or(Refusal::NoGroup)?; + let record = self.record(&group)?; + let author = event.author; + if record.dissolved_by.is_some() { + return Err(Refusal::Dissolved); + } + if !self.is_active(&group, record, &author) { + return Err(Refusal::NotActive); + } + if !record.admins.contains(&author) { + return Err(Refusal::NotAdmin); + } + if !policy.is_valid() { + return Err(Refusal::BadPolicy); + } + if let Some(cap) = policy.member_cap + && self.membership.members(group).len() > cap + { + return Err(Refusal::OverCap { cap }); + } + Ok(Decision { + group, + action: None, + effect: Effect::Policy(policy.clone()), + }) + } + + fn member(&self, event: &Event, op: MemberOp) -> Result { + let group = event.group.ok_or(Refusal::NoGroup)?; + let record = self.record(&group)?; + let author = event.author; + if record.dissolved_by.is_some() { + return Err(Refusal::Dissolved); + } + if !self.is_active(&group, record, &author) { + return Err(Refusal::NotActive); + } + let is_admin = record.admins.contains(&author); + let is_manager = self + .access(&group, &author) + .is_some_and(|role| role >= Role::Manage); + match op { + MemberOp::Add { member, role } => { + if !is_manager { + return Err(Refusal::NotManager); + } + if role == Role::Admin && !is_admin { + return Err(Refusal::NotAdmin); + } + if self.listed(&group, &member) { + return Err(Refusal::AlreadyMember(member)); + } + if let Some(cap) = record.policy.member_cap + && self.membership.members(group).len() >= cap + { + return Err(Refusal::OverCap { cap }); + } + Ok(Decision { + group, + action: Some(GroupAction::Add { + member: GroupMember::Individual(AuthId::Key(member)), + access: access_for(role), + }), + effect: Effect::Grant { + member, + admin: role == Role::Admin, + }, + }) + } + MemberOp::Remove { member } => { + if !self.listed(&group, &member) { + return Err(Refusal::NotAMember(member)); + } + if member != author && !is_manager { + return Err(Refusal::NotManager); + } + Ok(Decision { + group, + action: Some(GroupAction::Remove { + member: GroupMember::Individual(AuthId::Key(member)), + }), + effect: Effect::Remove { + member, + dissolves: record.policy.on_member_removed == OnMemberRemoved::Dissolve, + by: event.id, + }, + }) + } + MemberOp::SetRole { member, role } => { + if !is_admin { + return Err(Refusal::NotAdmin); + } + let Some(current) = self.access(&group, &member) else { + return Err(Refusal::NotAMember(member)); + }; + let target = access_level(role); + let action = match target.cmp(¤t) { + Ordering::Greater => Some(GroupAction::Promote { + member: GroupMember::Individual(AuthId::Key(member)), + access: access_for(target), + }), + Ordering::Less => Some(GroupAction::Demote { + member: GroupMember::Individual(AuthId::Key(member)), + access: access_for(target), + }), + Ordering::Equal => None, + }; + Ok(Decision { + group, + action, + effect: Effect::Grant { + member, + admin: role == Role::Admin, + }, + }) + } + } + } + + fn record(&self, group: &Hash) -> Result<&Record, Refusal> { + self.groups.get(group).ok_or(Refusal::NoGroup) + } + + fn listed(&self, group: &Hash, key: &Key) -> bool { + self.membership + .members(*group) + .iter() + .any(|(id, _)| *id == AuthId::Key(*key)) + } + + /// The member's role as its access level gives it, or `None` when it is not listed. An Admin + /// shows as Manage here, because Admin is recorded apart from the access level. + fn access(&self, group: &Hash, key: &Key) -> Option { + self.membership + .members(*group) + .iter() + .find(|(id, _)| *id == AuthId::Key(*key)) + .map(|(_, access)| access_role(access)) + } + + /// Whether the account may act in the group. A friendship's member must be present too. + fn is_active(&self, group: &Hash, record: &Record, key: &Key) -> bool { + self.listed(group, key) && (record.friendship.is_none() || record.present.contains(key)) + } + + /// How many friendships of `pair` the events in `past` have dissolved. This is the counter a + /// new request for the pair must name. + fn dissolved_before(&self, pair: &Pair, past: &BTreeSet) -> u32 { + let count = self + .groups + .values() + .filter(|record| { + record.friendship == Some(*pair) + && record.dissolved_by.is_some_and(|by| past.contains(&by)) + }) + .count(); + u32::try_from(count).unwrap_or(u32::MAX) + } + + fn into_projection(self, outcomes: BTreeMap) -> Projection { + let membership = &self.membership; + let groups = self + .groups + .into_iter() + .map(|(group, record)| { + let members: BTreeMap = membership + .members(group) + .into_iter() + .filter_map(|(id, access)| match id { + AuthId::Key(key) if record.admins.contains(&key) => { + Some((key, Role::Admin)) + } + AuthId::Key(key) => Some((key, access_role(&access))), + AuthId::Group(_) => None, + }) + .collect(); + let view = GroupView { + policy: record.policy, + members, + friendship: record.friendship, + present: record.present, + dissolved_by: record.dissolved_by, + }; + (group, view) + }) + .collect(); + Projection { groups, outcomes } + } +} + +/// Applies a state change to a group that exists. +fn apply_to(record: &mut Record, effect: Effect) { + match effect { + Effect::Create(_) => {} + Effect::Present(member) => { + record.present.insert(member); + } + Effect::Policy(policy) => { + record.policy = policy; + } + Effect::Grant { member, admin } => { + if admin { + record.admins.insert(member); + } else { + record.admins.remove(&member); + } + } + Effect::Remove { + member, + dissolves, + by, + } => { + record.admins.remove(&member); + record.present.remove(&member); + if dissolves && record.dissolved_by.is_none() { + record.dissolved_by = Some(by); + } + } + } +} + +/// A normal group. Its ID is its create's event ID, and its creator is Admin. +fn new_group(event: &Event, create: &Create) -> Result { + let author = event.author; + if create.admins_on_create { + return Err(Refusal::BadTemplate(create.template)); + } + if event.group.is_some() { + return Err(Refusal::WrongGroup); + } + if create.members.iter().any(|(key, _)| *key == author) || has_repeats(&create.members) { + return Err(Refusal::BadMembers); + } + if let Some(cap) = create.policy.member_cap + && create.members.len() >= cap + { + return Err(Refusal::OverCap { cap }); + } + let mut initial = vec![( + GroupMember::Individual(AuthId::Key(author)), + Access::manage(), + )]; + let mut admins = BTreeSet::from([author]); + for (member, role) in &create.members { + initial.push(( + GroupMember::Individual(AuthId::Key(*member)), + access_for(*role), + )); + if *role == Role::Admin { + admins.insert(*member); + } + } + let record = Record { + policy: create.policy.clone(), + admins, + present: BTreeSet::new(), + friendship: None, + dissolved_by: None, + }; + Ok(Decision { + group: event.id, + action: Some(GroupAction::Create { + initial_members: initial, + }), + effect: Effect::Create(record), + }) +} + +fn has_repeats(members: &[(Key, Role)]) -> bool { + let distinct: BTreeSet = members.iter().map(|(key, _)| *key).collect(); + distinct.len() != members.len() +} + +/// The role a member's access level gives. Admin is never an access level. +fn access_role(access: &Access<()>) -> Role { + if access.is_manage() { + Role::Manage + } else if access.is_write() { + Role::Write + } else if access.is_read() { + Role::Read + } else { + Role::Pull + } +} + +/// The access level a role needs. Admin is a manager that is also recorded as Admin. +const fn access_level(role: Role) -> Role { + match role { + Role::Admin => Role::Manage, + other => other, + } +} + +fn access_for(role: Role) -> Access<()> { + match access_level(role) { + Role::Pull => Access::pull(), + Role::Read => Access::read(), + Role::Write => Access::write(), + Role::Manage | Role::Admin => Access::manage(), + } +} diff --git a/pkgs/id/src/groups/friendship.rs b/pkgs/id/src/groups/friendship.rs new file mode 100644 index 0000000000..0b5c40e1b4 --- /dev/null +++ b/pkgs/id/src/groups/friendship.rs @@ -0,0 +1,65 @@ +//! Friendship as a group (design §5.4). +//! +//! A friendship is a group from the friendship template: two members, mutual request, and dissolve +//! on removal. Its ID is derived from the pair and a counter, so two concurrent requests for one +//! pair name the same group and collapse into one object. The counter increments when a friendship +//! dissolves, so re-friending makes a new group. + +use p2panda_core::Hash; + +use super::Key; + +/// Two accounts, smaller key first. A friendship has exactly one pair. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Pair { + low: Key, + high: Key, +} + +impl Pair { + /// The pair of two accounts, or `None` when they are the same account. + pub fn of(a: Key, b: Key) -> Option { + match a.cmp(&b) { + std::cmp::Ordering::Less => Some(Self { low: a, high: b }), + std::cmp::Ordering::Greater => Some(Self { low: b, high: a }), + std::cmp::Ordering::Equal => None, + } + } + + /// Both accounts, smaller first. + pub const fn members(&self) -> [Key; 2] { + [self.low, self.high] + } +} + +/// The ID of the friendship group for `pair` at `counter` (design §5.4): BLAKE3 over the label +/// "friendship", the sorted pair, and the counter. +pub fn friendship_id(pair: &Pair, counter: u32) -> Hash { + let mut bytes = Vec::with_capacity(b"friendship".len() + 64 + 4); + bytes.extend_from_slice(b"friendship"); + bytes.extend_from_slice(&pair.low); + bytes.extend_from_slice(&pair.high); + bytes.extend_from_slice(&counter.to_be_bytes()); + Hash::digest(bytes) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used)] +mod tests { + use super::*; + + #[test] + fn test_a_pair_is_the_same_in_either_order_and_needs_two_accounts() { + assert_eq!(Pair::of([1; 32], [2; 32]), Pair::of([2; 32], [1; 32])); + assert_eq!(Pair::of([1; 32], [1; 32]), None); + } + + #[test] + fn test_the_friendship_id_depends_on_the_pair_and_the_counter() { + let ann_bo = Pair::of([1; 32], [2; 32]).unwrap(); + let ann_cy = Pair::of([1; 32], [3; 32]).unwrap(); + assert_eq!(friendship_id(&ann_bo, 0), friendship_id(&ann_bo, 0)); + assert_ne!(friendship_id(&ann_bo, 0), friendship_id(&ann_bo, 1)); + assert_ne!(friendship_id(&ann_bo, 0), friendship_id(&ann_cy, 0)); + } +} diff --git a/pkgs/id/src/groups/mod.rs b/pkgs/id/src/groups/mod.rs new file mode 100644 index 0000000000..4611363f65 --- /dev/null +++ b/pkgs/id/src/groups/mod.rs @@ -0,0 +1,114 @@ +//! Groups (Phase 2, P2.4): members and roles, the signed policy record, the templates groups are +//! created from, and friendship as a two-member group (design §5). +//! +//! A group changes only by events. [`fold`] computes its state from the whole set of events, so the +//! result does not depend on the order the events arrived in. Membership operations go through +//! [`crate::membership`], which wraps p2panda-auth. The rules p2panda-auth does not have are ours: +//! the Admin role, the policy record, the member cap, and dissolve. +//! +//! - Anyone may create a group. A normal group makes its creator Admin. +//! - Only an Admin may change a role or the policy, including the member cap. +//! - A friendship has no Admin unless its create asks for one (`admins_on_create`). +//! +//! Authority and the cap are checked against the events that come before each event in the +//! canonical order. See [`fold`]. + +pub mod fold; +pub mod friendship; +pub mod policy; + +#[cfg(test)] +mod tests; + +use p2panda_core::Hash; + +pub use fold::{FoldError, GroupView, Outcome, Projection, Refusal, fold}; +pub use friendship::{Pair, friendship_id}; +pub use policy::{ + Delegation, History, Join, OnMemberRemoved, Policy, Removal, RoleRules, Scheme, Template, +}; + +/// An account's key. Accounts are keys in this layer. +pub type Key = [u8; 32]; + +/// What a member may do, from least to most. `Admin` is a manager that may also change roles and +/// the policy record. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub enum Role { + /// Replicates ciphertext without keys. + Pull, + /// Reads content. + Read, + /// Edits content. + Write, + /// Adds and removes members. + Manage, + /// Manages, and changes roles and the policy record. + Admin, +} + +/// One signed group event, as the group layer sees it. The caller has verified it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Event { + /// The event's ID. + pub id: Hash, + /// The account that signed it. + pub author: Key, + /// The `after` hashes, as signed. + pub after: Vec, + /// The group it names. A normal group's create names none. A friendship's create names the + /// friendship's derived group. + pub group: Option, + /// What it does. + pub body: Body, +} + +/// What a group event does. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Body { + /// Creates a group. Anyone may create one. + Create(Create), + /// Accepts a friendship request, as its other side. + Join, + /// Replaces the policy record. Admin only. + Policy(Policy), + /// Changes one member. + Member(MemberOp), +} + +/// A group's creation. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Create { + /// The template the group is created from. + pub template: Template, + /// The policy record, written out in full. + pub policy: Policy, + /// The members besides the author, with their roles. A friendship lists exactly one. + pub members: Vec<(Key, Role)>, + /// Whether both friends start as Admin. Only a friendship may set it. + pub admins_on_create: bool, +} + +/// A change to one member. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum MemberOp { + /// Adds a member with a role. + Add { + /// The member added. + member: Key, + /// Its role. + role: Role, + }, + /// Removes a member. The author may remove itself, which is leaving. + Remove { + /// The member removed. + member: Key, + }, + /// Sets a member's role. Admin only. + SetRole { + /// The member whose role changes. + member: Key, + /// Its new role. + role: Role, + }, +} diff --git a/pkgs/id/src/groups/policy.rs b/pkgs/id/src/groups/policy.rs new file mode 100644 index 0000000000..1044525e6f --- /dev/null +++ b/pkgs/id/src/groups/policy.rs @@ -0,0 +1,224 @@ +//! Group policy records and templates (design §5.1 and §5.3). +//! +//! A policy record is written in full into the group's create event, and it changes only through +//! a `group.policy` event by an Admin. A template is a named preset that a create event names, and +//! the record must be one that template admits. + +use super::Role; + +/// Who may join a group, and how. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Join { + /// A manager adds members. + ManagerAdd, + /// An invite event admits the joiner (design §10). + Invite, + /// One side asks and the other accepts. Friendship uses this. + MutualRequest, + /// Anyone may join. + Open, +} + +/// What a removal does to the group as a whole. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum OnMemberRemoved { + /// The group goes on without the removed member. + Continue, + /// Removing either side ends the group. Friendship uses this. + Dissolve, +} + +/// How a removal takes effect (design §6). Strong is the default. The rules belong to the voiding +/// track; this module only records the setting. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Removal { + /// Strong remove, the default. + #[default] + Strong, + /// Weak remove. + Weak, +} + +/// What happens to a removed member's delegations (design §7.3). Unset means the default is still +/// open; see [`Policy::delegation`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Delegation { + /// Delegations made before the removal stand. + KeepPrior, + /// Delegations made by the removed member end with it. + Cascade, + /// Delegations pass to the members who remain. + Transfer, +} + +/// What a joiner may see of earlier history (design §8.3). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum History { + /// The whole history. + #[default] + Full, + /// Only what came after the join. + FromJoin, + /// Causal history (deferred). + Causal, +} + +/// A key-agreement scheme and its version (design §8.7). A policy with no scheme has `None`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Scheme { + /// The scheme's name. + pub name: String, + /// The scheme's version. + pub version: u32, +} + +/// Which role may change roles and the policy record. Only Admin may, so the field is a rule and +/// not a choice: [`Policy::is_valid`] refuses any other value. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct RoleRules { + /// The least role that may change roles and policy. + pub change: Role, +} + +/// A group's policy record. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Policy { + /// The most members the group may have. `None` means no cap. Only an Admin may change it. + pub member_cap: Option, + /// How a joiner gets in. + pub join: Join, + /// What removing a member does to the group. + pub on_member_removed: OnMemberRemoved, + /// How removals take effect. + pub removal: Removal, + /// The fate of a removed member's delegations. `None` is the open default (design §7.3). + pub delegation: Option, + /// What a joiner may see of earlier history. + pub history: History, + /// The key-agreement scheme. `None` means no scheme. + pub scheme: Option, + /// Which role may change roles and policy. + pub roles: RoleRules, +} + +impl Default for Policy { + /// A normal group: no cap, managers add members, removal continues the group, strong remove, + /// full history, no scheme, and Admin changes roles and policy. + fn default() -> Self { + Self { + member_cap: None, + join: Join::ManagerAdd, + on_member_removed: OnMemberRemoved::Continue, + removal: Removal::Strong, + delegation: None, + history: History::Full, + scheme: None, + roles: RoleRules { + change: Role::Admin, + }, + } + } +} + +impl Policy { + /// The friendship template (design §5.3): two members, mutual request, dissolve on removal, + /// strong remove, cascade delegation, and full history. + pub const fn friendship() -> Self { + Self { + member_cap: Some(2), + join: Join::MutualRequest, + on_member_removed: OnMemberRemoved::Dissolve, + removal: Removal::Strong, + delegation: Some(Delegation::Cascade), + history: History::Full, + scheme: None, + roles: RoleRules { + change: Role::Admin, + }, + } + } + + /// Whether the record is usable. Only Admin may change roles and policy, and a cap must allow + /// at least one member. + pub fn is_valid(&self) -> bool { + self.roles.change == Role::Admin && self.member_cap.is_none_or(|cap| cap >= 1) + } +} + +/// A named preset that a create event names. The create's policy record is written in full, and +/// [`Template::admits`] checks it against the preset. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Template { + /// Two members who ask and accept each other (design §5.4). + Friendship, + /// Many readers, some writers, few managers. No cap. Joins by manager add, invite, or open. + Channel, + /// Joins by invite only. + Private, + /// Any combination of fields. + Custom, +} + +impl Template { + /// Whether this template admits `policy`. + pub fn admits(self, policy: &Policy) -> bool { + match self { + Self::Friendship => *policy == Policy::friendship(), + Self::Channel => { + policy.member_cap.is_none() + && policy.scheme.is_none() + && matches!(policy.join, Join::ManagerAdd | Join::Invite | Join::Open) + } + Self::Private => policy.join == Join::Invite, + Self::Custom => true, + } + } +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used)] +mod tests { + use super::*; + + #[test] + fn test_the_friendship_template_admits_only_the_friendship_policy() { + assert!(Template::Friendship.admits(&Policy::friendship())); + let wider = Policy { + member_cap: Some(3), + ..Policy::friendship() + }; + assert!(!Template::Friendship.admits(&wider)); + } + + #[test] + fn test_a_channel_has_no_cap_and_a_private_group_joins_by_invite() { + let capped = Policy { + member_cap: Some(2), + ..Policy::default() + }; + assert!(!Template::Channel.admits(&capped)); + let private = Policy { + join: Join::Invite, + ..Policy::default() + }; + assert!(Template::Private.admits(&private)); + assert!(!Template::Private.admits(&Policy::default())); + } + + #[test] + fn test_only_an_admin_rule_and_a_positive_cap_are_valid() { + assert!(Policy::default().is_valid()); + let manager_rule = Policy { + roles: RoleRules { + change: Role::Manage, + }, + ..Policy::default() + }; + assert!(!manager_rule.is_valid()); + let no_members = Policy { + member_cap: Some(0), + ..Policy::default() + }; + assert!(!no_members.is_valid()); + } +} diff --git a/pkgs/id/src/groups/tests.rs b/pkgs/id/src/groups/tests.rs new file mode 100644 index 0000000000..38adff7208 --- /dev/null +++ b/pkgs/id/src/groups/tests.rs @@ -0,0 +1,822 @@ +//! Behaviour of groups and friendship. Each rule has a test. The property tests check that the +//! final state does not depend on the order the events arrive in. + +#![allow(clippy::unwrap_used, clippy::expect_used)] + +use p2panda_core::Hash; +use proptest::prelude::*; + +use super::policy::{Join, OnMemberRemoved, Policy, RoleRules, Template}; +use super::{ + Body, Create, Event, Key, MemberOp, Outcome, Pair, Projection, Refusal, Role, fold, + friendship_id, +}; + +fn key(n: u8) -> Key { + [n; 32] +} + +fn id(name: &str) -> Hash { + Hash::digest(name.as_bytes()) +} + +fn after(names: &[&str]) -> Vec { + names.iter().map(|name| id(name)).collect() +} + +fn event(name: &str, author: u8, after_names: &[&str], group: Option, body: Body) -> Event { + Event { + id: id(name), + author: key(author), + after: after(after_names), + group, + body, + } +} + +/// The friendship group of `a` and `b` at `counter`. +fn pair_group(a: u8, b: u8, counter: u32) -> Hash { + friendship_id(&Pair::of(key(a), key(b)).unwrap(), counter) +} + +/// A group created from `template` by `author`, with `members` besides the author. +fn create( + name: &str, + author: u8, + after_names: &[&str], + template: Template, + policy: Policy, + members: &[(u8, Role)], + admins_on_create: bool, +) -> Event { + let members = members.iter().map(|(n, role)| (key(*n), *role)).collect(); + let body = Body::Create(Create { + template, + policy, + members, + admins_on_create, + }); + event(name, author, after_names, None, body) +} + +/// A normal group of a custom policy, created by `author`. +fn custom(name: &str, author: u8, members: &[(u8, Role)], policy: Policy) -> Event { + create(name, author, &[], Template::Custom, policy, members, false) +} + +/// A friendship request from `from` to `to`, naming the friendship at `counter`. +fn request( + name: &str, + from: u8, + to: u8, + counter: u32, + after_names: &[&str], + admins: bool, +) -> Event { + let pair = Pair::of(key(from), key(to)); + let group = pair.map(|pair| friendship_id(&pair, counter)); + let body = Body::Create(Create { + template: Template::Friendship, + policy: Policy::friendship(), + members: vec![(key(to), Role::Manage)], + admins_on_create: admins, + }); + event(name, from, after_names, group, body) +} + +fn join(name: &str, by: u8, group: Hash, after_names: &[&str]) -> Event { + event(name, by, after_names, Some(group), Body::Join) +} + +fn policy(name: &str, by: u8, group: Hash, record: Policy, after_names: &[&str]) -> Event { + event(name, by, after_names, Some(group), Body::Policy(record)) +} + +fn member(name: &str, by: u8, group: Hash, op: MemberOp, after_names: &[&str]) -> Event { + event(name, by, after_names, Some(group), Body::Member(op)) +} + +fn add(name: &str, by: u8, group: Hash, who: u8, role: Role, after_names: &[&str]) -> Event { + member( + name, + by, + group, + MemberOp::Add { + member: key(who), + role, + }, + after_names, + ) +} + +fn remove(name: &str, by: u8, group: Hash, who: u8, after_names: &[&str]) -> Event { + member( + name, + by, + group, + MemberOp::Remove { member: key(who) }, + after_names, + ) +} + +fn set_role(name: &str, by: u8, group: Hash, who: u8, role: Role, after_names: &[&str]) -> Event { + member( + name, + by, + group, + MemberOp::SetRole { + member: key(who), + role, + }, + after_names, + ) +} + +fn project(events: &[Event]) -> Projection { + fold(events).unwrap() +} + +fn outcome(p: &Projection, name: &str) -> Outcome { + p.outcome(&id(name)).cloned().unwrap() +} + +fn role_of(p: &Projection, group: Hash, n: u8) -> Option { + p.group(&group)?.members.get(&key(n)).copied() +} + +/// A deterministic shuffle, so a failing case can be replayed from its seed. +fn shuffled(items: &[T], mut seed: u64) -> Vec { + let mut out = items.to_vec(); + for i in (1..out.len()).rev() { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + let j = usize::try_from(seed % (i as u64 + 1)).unwrap(); + out.swap(i, j); + } + out +} + +// ----- Creation and roles ----- + +#[test] +fn test_anyone_may_create_a_normal_group_and_the_creator_is_its_admin() { + let events = [custom("g", 3, &[(1, Role::Read)], Policy::default())]; + let p = project(&events); + assert_eq!(outcome(&p, "g"), Outcome::Applied); + assert_eq!(role_of(&p, id("g"), 3), Some(Role::Admin)); + assert_eq!(role_of(&p, id("g"), 1), Some(Role::Read)); +} + +#[test] +fn test_a_friendship_has_no_admin_by_default() { + let g = pair_group(1, 2, 0); + let p = project(&[ + request("r0", 1, 2, 0, &[], false), + join("a0", 2, g, &["r0"]), + ]); + assert_eq!(role_of(&p, g, 1), Some(Role::Manage)); + assert_eq!(role_of(&p, g, 2), Some(Role::Manage)); + assert!(p.friends(&key(1), &key(2))); +} + +#[test] +fn test_admins_on_create_makes_both_friends_admin() { + let g = pair_group(1, 2, 0); + let p = project(&[request("r0", 1, 2, 0, &[], true), join("a0", 2, g, &["r0"])]); + assert_eq!(role_of(&p, g, 1), Some(Role::Admin)); + assert_eq!(role_of(&p, g, 2), Some(Role::Admin)); +} + +#[test] +fn test_either_admin_friend_may_change_the_other_friends_role() { + let g = pair_group(1, 2, 0); + let base = [request("r0", 1, 2, 0, &[], true), join("a0", 2, g, &["r0"])]; + let mut ann_demotes_bo = base.to_vec(); + ann_demotes_bo.push(set_role("s1", 1, g, 2, Role::Read, &["a0"])); + let p = project(&ann_demotes_bo); + assert_eq!(outcome(&p, "s1"), Outcome::Applied); + assert_eq!(role_of(&p, g, 2), Some(Role::Read)); + + let mut bo_demotes_ann = base.to_vec(); + bo_demotes_ann.push(set_role("s2", 2, g, 1, Role::Manage, &["a0"])); + let p = project(&bo_demotes_ann); + assert_eq!(outcome(&p, "s2"), Outcome::Applied); + assert_eq!(role_of(&p, g, 1), Some(Role::Manage)); +} + +#[test] +fn test_a_non_admin_may_not_change_a_role() { + let g = id("g"); + let p = project(&[ + custom( + "g", + 1, + &[(2, Role::Manage), (3, Role::Read)], + Policy::default(), + ), + set_role("s0", 2, g, 3, Role::Write, &["g"]), + ]); + assert_eq!(outcome(&p, "s0"), Outcome::Refused(Refusal::NotAdmin)); + assert_eq!(role_of(&p, g, 3), Some(Role::Read)); +} + +#[test] +fn test_a_rule_other_than_admin_for_roles_is_refused() { + let manager_rule = Policy { + roles: RoleRules { + change: Role::Manage, + }, + ..Policy::default() + }; + let p = project(&[custom("g", 1, &[], manager_rule)]); + assert_eq!(outcome(&p, "g"), Outcome::Refused(Refusal::BadPolicy)); +} + +// ----- Policy ----- + +#[test] +fn test_a_non_admin_may_not_change_the_policy_of_a_normal_group_or_a_friendship() { + let g = id("g"); + let p = project(&[ + custom("g", 1, &[(2, Role::Manage)], Policy::default()), + policy("p0", 2, g, Policy::default(), &["g"]), + ]); + assert_eq!(outcome(&p, "p0"), Outcome::Refused(Refusal::NotAdmin)); + + let f = pair_group(1, 2, 0); + let capped = Policy { + member_cap: Some(3), + ..Policy::friendship() + }; + let p = project(&[ + request("r0", 1, 2, 0, &[], false), + join("a0", 2, f, &["r0"]), + policy("p0", 1, f, capped, &["a0"]), + ]); + assert_eq!(outcome(&p, "p0"), Outcome::Refused(Refusal::NotAdmin)); + assert_eq!(p.group(&f).unwrap().policy, Policy::friendship()); +} + +#[test] +fn test_an_admin_changes_the_member_cap_and_not_below_the_members() { + let g = id("g"); + let raise = Policy { + member_cap: Some(3), + ..Policy::default() + }; + let lower = Policy { + member_cap: Some(1), + ..Policy::default() + }; + let p = project(&[ + custom("g", 1, &[(2, Role::Read)], Policy::default()), + policy("p0", 1, g, raise, &["g"]), + policy("p1", 1, g, lower, &["p0"]), + ]); + assert_eq!(outcome(&p, "p0"), Outcome::Applied); + assert_eq!(p.group(&g).unwrap().policy.member_cap, Some(3)); + assert_eq!( + outcome(&p, "p1"), + Outcome::Refused(Refusal::OverCap { cap: 1 }) + ); +} + +// ----- Member cap ----- + +#[test] +fn test_the_member_cap_refuses_the_add_past_it() { + let g = id("g"); + let capped = Policy { + member_cap: Some(2), + ..Policy::default() + }; + let p = project(&[ + custom("g", 1, &[], capped), + add("a1", 1, g, 2, Role::Read, &["g"]), + add("a2", 1, g, 3, Role::Read, &["a1"]), + ]); + assert_eq!(outcome(&p, "a1"), Outcome::Applied); + assert_eq!( + outcome(&p, "a2"), + Outcome::Refused(Refusal::OverCap { cap: 2 }) + ); + assert_eq!(p.group(&g).unwrap().members.len(), 2); +} + +#[test] +fn test_concurrent_adds_past_the_cap_keep_the_lowest_event_ids() { + // F2 (S2 friendship). Two concurrent adds and one free place: the add with the lower event ID + // wins, in every order. + let g = id("g"); + let capped = Policy { + member_cap: Some(3), + ..Policy::default() + }; + let events = [ + custom("g", 1, &[(2, Role::Read)], capped), + add("a1", 1, g, 3, Role::Read, &["g"]), + add("a2", 1, g, 4, Role::Read, &["g"]), + ]; + let (low, high, low_key) = if id("a1") < id("a2") { + ("a1", "a2", 3) + } else { + ("a2", "a1", 4) + }; + let p = project(&events); + assert_eq!(outcome(&p, low), Outcome::Applied); + assert_eq!( + outcome(&p, high), + Outcome::Refused(Refusal::OverCap { cap: 3 }) + ); + let members: Vec = p.group(&g).unwrap().members.keys().copied().collect(); + assert_eq!(members, vec![key(1), key(2), key(low_key)]); + + let mut reversed = events.to_vec(); + reversed.reverse(); + assert_eq!(project(&reversed), p); +} + +// ----- Templates ----- + +#[test] +fn test_a_template_admits_only_the_policy_it_names() { + let capped = Policy { + member_cap: Some(2), + ..Policy::default() + }; + let p = project(&[ + create("c1", 1, &[], Template::Channel, capped, &[], false), + create( + "c2", + 1, + &[], + Template::Private, + Policy::default(), + &[], + false, + ), + create( + "c3", + 1, + &[], + Template::Friendship, + Policy { + member_cap: Some(3), + ..Policy::friendship() + }, + &[(2, Role::Manage)], + false, + ), + create( + "c4", + 1, + &[], + Template::Private, + Policy { + join: Join::Invite, + ..Policy::default() + }, + &[(2, Role::Read)], + false, + ), + ]); + assert_eq!( + outcome(&p, "c1"), + Outcome::Refused(Refusal::BadTemplate(Template::Channel)) + ); + assert_eq!( + outcome(&p, "c2"), + Outcome::Refused(Refusal::BadTemplate(Template::Private)) + ); + assert_eq!( + outcome(&p, "c3"), + Outcome::Refused(Refusal::BadTemplate(Template::Friendship)) + ); + assert_eq!(outcome(&p, "c4"), Outcome::Applied); +} + +#[test] +fn test_admins_on_create_is_for_friendships_only() { + let p = project(&[create( + "g", + 1, + &[], + Template::Channel, + Policy::default(), + &[(2, Role::Read)], + true, + )]); + assert_eq!( + outcome(&p, "g"), + Outcome::Refused(Refusal::BadTemplate(Template::Channel)) + ); +} + +#[test] +fn test_a_join_is_for_a_friendship_and_a_normal_group_refuses_it() { + let g = id("g"); + let mutual = Policy { + join: Join::MutualRequest, + ..Policy::default() + }; + let p = project(&[ + custom("g", 1, &[(2, Role::Read)], mutual), + join("j0", 2, g, &["g"]), + ]); + assert_eq!( + outcome(&p, "j0"), + Outcome::Refused(Refusal::JoinNotSupported) + ); +} + +#[test] +fn test_a_removal_on_a_policy_that_continues_does_not_dissolve() { + let g = id("g"); + let p = project(&[ + custom("g", 1, &[(2, Role::Read)], Policy::default()), + remove("x0", 1, g, 2, &["g"]), + ]); + assert_eq!(outcome(&p, "x0"), Outcome::Applied); + assert_eq!(p.group(&g).unwrap().dissolved_by, None); + assert_eq!( + Policy::default().on_member_removed, + OnMemberRemoved::Continue + ); +} + +// ----- Membership rules ----- + +#[test] +fn test_a_non_member_may_not_add_and_a_pending_friend_may_not_act() { + let g = id("g"); + let f = pair_group(1, 2, 0); + let p = project(&[ + custom("g", 1, &[], Policy::default()), + add("a0", 3, g, 4, Role::Read, &["g"]), + request("r0", 1, 2, 0, &[], false), + add("a1", 2, f, 3, Role::Read, &["r0"]), + ]); + assert_eq!(outcome(&p, "a0"), Outcome::Refused(Refusal::NotActive)); + assert_eq!(outcome(&p, "a1"), Outcome::Refused(Refusal::NotActive)); +} + +#[test] +fn test_a_non_manager_may_not_add_or_remove_a_member() { + let g = id("g"); + let p = project(&[ + custom( + "g", + 1, + &[(2, Role::Write), (3, Role::Read)], + Policy::default(), + ), + add("a0", 2, g, 4, Role::Read, &["g"]), + remove("x0", 2, g, 3, &["g"]), + ]); + assert_eq!(outcome(&p, "a0"), Outcome::Refused(Refusal::NotManager)); + assert_eq!(outcome(&p, "x0"), Outcome::Refused(Refusal::NotManager)); +} + +#[test] +fn test_only_an_invitee_may_accept_a_friendship_request() { + let g = pair_group(1, 2, 0); + let p = project(&[ + request("r0", 1, 2, 0, &[], false), + join("j0", 3, g, &["r0"]), + ]); + assert_eq!(outcome(&p, "j0"), Outcome::Refused(Refusal::NotInvited)); + assert!(!p.friends(&key(1), &key(2))); +} + +#[test] +fn test_a_friendship_request_must_name_its_pair_and_counter() { + let wrong_group = Event { + id: id("r0"), + author: key(1), + after: vec![], + group: Some(id("not a friendship")), + body: Body::Create(Create { + template: Template::Friendship, + policy: Policy::friendship(), + members: vec![(key(2), Role::Manage)], + admins_on_create: false, + }), + }; + let p = project(&[wrong_group]); + assert_eq!( + outcome(&p, "r0"), + Outcome::Refused(Refusal::WrongFriendshipId) + ); + + // A request for counter 1 that does not see a dissolve is refused. + let g = pair_group(1, 2, 0); + let p = project(&[ + request("r0", 1, 2, 0, &[], false), + join("a0", 2, g, &["r0"]), + request("r9", 1, 2, 1, &["a0"], false), + ]); + assert_eq!( + outcome(&p, "r9"), + Outcome::Refused(Refusal::WrongFriendshipId) + ); +} + +// ----- Friendship ----- + +#[test] +fn test_a_removal_by_either_side_dissolves_the_friendship() { + let g = pair_group(1, 2, 0); + for (by, other) in [(1u8, 2u8), (2, 1)] { + let p = project(&[ + request("r0", 1, 2, 0, &[], false), + join("a0", 2, g, &["r0"]), + remove("x", by, g, other, &["a0"]), + ]); + assert_eq!(outcome(&p, "x"), Outcome::Applied); + assert!(!p.friends(&key(1), &key(2))); + assert_eq!(p.group(&g).unwrap().dissolved_by, Some(id("x"))); + } +} + +#[test] +fn test_a_removal_concurrent_with_the_accept_dissolves_it_in_every_order() { + // F3 (S2 friendship). The removal and the accept are concurrent. In every order the + // friendship ends. + let g = pair_group(1, 2, 0); + let events = [ + request("r0", 1, 2, 0, &[], false), + join("a0", 2, g, &["r0"]), + remove("x", 1, g, 2, &["r0"]), + ]; + let p = project(&events); + assert_eq!(outcome(&p, "x"), Outcome::Applied); + assert!(!p.friends(&key(1), &key(2))); + assert!(p.group(&g).unwrap().dissolved_by.is_some()); + + let mut reversed = events.to_vec(); + reversed.reverse(); + assert_eq!(project(&reversed), p); +} + +#[test] +fn test_mutual_removal_dissolves_the_friendship_once() { + // F4 (S2 friendship). Both sides remove. One removal dissolves the friendship, and the other + // finds it already dissolved. + let g = pair_group(1, 2, 0); + let p = project(&[ + request("r0", 1, 2, 0, &[], false), + join("a0", 2, g, &["r0"]), + remove("x", 1, g, 2, &["a0"]), + remove("y", 2, g, 1, &["a0"]), + ]); + // Which removal comes first is decided by event ID. The other is refused as dissolved. + let applied = ["x", "y"] + .iter() + .filter(|name| outcome(&p, name) == Outcome::Applied) + .count(); + assert_eq!(applied, 1); + for name in ["x", "y"] { + let result = outcome(&p, name); + assert!( + result == Outcome::Applied || result == Outcome::Refused(Refusal::Dissolved), + "{name} was {result:?}" + ); + } + assert!(!p.friends(&key(1), &key(2))); +} + +#[test] +fn test_a_dissolved_friendship_is_not_revived_by_its_own_accept_in_any_order() { + // F5 (S2 friendship). The accept is concurrent with the removal that dissolves the friendship. + // Whichever comes first, the friendship ends. The accept's outcome is decided by the order + // (removal and voiding are the voiding track's rules). + let g = pair_group(1, 2, 0); + let events = [ + request("r0", 1, 2, 0, &[], false), + remove("x", 1, g, 2, &["r0"]), + join("a0", 2, g, &["r0"]), + ]; + let p = project(&events); + assert!(!p.friends(&key(1), &key(2))); + assert!(p.group(&g).unwrap().dissolved_by.is_some()); + let mut reversed = events.to_vec(); + reversed.reverse(); + assert_eq!(project(&reversed), p); +} + +#[test] +fn test_re_friending_creates_a_new_group_with_the_counter_incremented() { + // F5, the other half (S2 friendship). After a dissolve, a new request is open, and accepting + // it makes a new friendship in a new group. + let f0 = pair_group(1, 2, 0); + let f1 = pair_group(1, 2, 1); + assert_ne!(f0, f1); + let p = project(&[ + request("r0", 1, 2, 0, &[], false), + join("a0", 2, f0, &["r0"]), + remove("x", 1, f0, 2, &["a0"]), + request("r2", 1, 2, 1, &["x"], false), + join("a3", 2, f1, &["r2"]), + ]); + assert_eq!(outcome(&p, "r2"), Outcome::Applied); + assert_eq!(outcome(&p, "a3"), Outcome::Applied); + assert!(p.friends(&key(1), &key(2))); + assert_eq!(p.group(&f0).unwrap().dissolved_by, Some(id("x"))); +} + +#[test] +fn test_concurrent_requests_for_one_pair_collapse_into_one_friendship() { + // The design's collapse (§5.4): a request in each direction is one friendship. + let g = pair_group(1, 2, 0); + let events = [ + request("r0", 1, 2, 0, &[], false), + request("r1", 2, 1, 0, &[], false), + ]; + let p = project(&events); + assert_eq!(outcome(&p, "r0"), Outcome::Applied); + assert_eq!(outcome(&p, "r1"), Outcome::Applied); + let friendships = p + .groups() + .filter(|(_, view)| view.friendship == Pair::of(key(1), key(2))) + .count(); + assert_eq!(friendships, 1); + assert!(p.friends(&key(1), &key(2))); + assert_eq!(p.group(&g).unwrap().present.len(), 2); + + let mut reversed = events.to_vec(); + reversed.reverse(); + assert_eq!(project(&reversed), p); +} + +#[test] +fn test_a_friendship_has_no_cap_beyond_its_two_and_no_third_member() { + let g = pair_group(1, 2, 0); + let p = project(&[ + request("r0", 1, 2, 0, &[], false), + join("a0", 2, g, &["r0"]), + add("a1", 1, g, 3, Role::Read, &["a0"]), + ]); + assert_eq!( + outcome(&p, "a1"), + Outcome::Refused(Refusal::OverCap { cap: 2 }) + ); +} + +// ----- Properties over arrival order ----- + +/// A random set of group events. Each step picks a kind, the actors, a group among those +/// already named, and an `after` set drawn from the earlier events. +fn script() -> impl Strategy> { + prop::collection::vec( + (0u8..7, 1u8..=4, 1u8..=4, 0u8..5, 0u8..4, any::()), + 1..16, + ) +} + +fn build(script: &[(u8, u8, u8, u8, u8, u8)]) -> Vec { + const ROLES: [Role; 5] = [ + Role::Pull, + Role::Read, + Role::Write, + Role::Manage, + Role::Admin, + ]; + let mut events: Vec = Vec::new(); + // The groups named so far, so that most events name a group that exists. + let mut groups: Vec = Vec::new(); + for (i, &(kind, author, target, role, pick, mask)) in script.iter().enumerate() { + let name = format!("e{i}"); + let after_hashes: Vec = events + .iter() + .enumerate() + .filter(|(j, _)| (mask >> (j % 8)) & 1 == 1) + .map(|(_, earlier)| earlier.id) + .rev() + .take(3) + .collect(); + let group = groups + .get(usize::from(pick) % groups.len().max(1)) + .copied() + .unwrap_or_else(|| id("none")); + let role = ROLES[usize::from(role)]; + let body_and_group = match kind { + 0 => { + let cap = if target % 2 == 0 { + None + } else { + Some(usize::from(target)) + }; + let policy = Policy { + member_cap: cap, + ..Policy::default() + }; + let members = if target == author { + vec![] + } else { + vec![(key(target), role)] + }; + let body = Body::Create(Create { + template: Template::Custom, + policy, + members, + admins_on_create: false, + }); + (None, body) + } + 1 => { + let counter = u32::from(pick % 4 == 0); + let group = + Pair::of(key(author), key(target)).map(|pair| friendship_id(&pair, counter)); + let body = Body::Create(Create { + template: Template::Friendship, + policy: Policy::friendship(), + members: vec![(key(target), Role::Manage)], + admins_on_create: mask % 2 == 1, + }); + (group, body) + } + 2 => (Some(group), Body::Join), + 3 => { + let policy = Policy { + member_cap: if target % 2 == 0 { + None + } else { + Some(usize::from(target)) + }, + ..Policy::default() + }; + (Some(group), Body::Policy(policy)) + } + 4 => ( + Some(group), + Body::Member(MemberOp::Add { + member: key(target), + role, + }), + ), + 5 => ( + Some(group), + Body::Member(MemberOp::Remove { + member: key(target), + }), + ), + _ => ( + Some(group), + Body::Member(MemberOp::SetRole { + member: key(target), + role, + }), + ), + }; + let (group, body) = body_and_group; + let created = Event { + id: id(&name), + author: key(author), + after: after_hashes, + group, + body, + }; + if matches!(created.body, Body::Create(_)) { + groups.push(created.group.unwrap_or(created.id)); + } + events.push(created); + } + events +} + +proptest! { + #![proptest_config(ProptestConfig::with_cases(256))] + + #[test] + fn prop_the_final_state_does_not_depend_on_the_order_the_events_arrive_in( + script in script(), + seed in any::(), + ) { + let events = build(&script); + let expected = project(&events); + let shuffle = shuffled(&events, seed.max(1)); + let shuffled_state = fold(&shuffle).unwrap(); + prop_assert_eq!(&shuffled_state, &expected); + let mut reversed = events; + reversed.reverse(); + prop_assert_eq!(fold(&reversed).unwrap(), expected); + } + + #[test] + fn prop_no_group_is_ever_over_its_cap_and_a_friendship_is_active_only_when_both_are_present( + script in script(), + ) { + let p = project(&build(&script)); + for (_, view) in p.groups() { + if let Some(cap) = view.policy.member_cap { + prop_assert!(view.members.len() <= cap); + } + if view.is_active() + && let Some(pair) = view.friendship + { + prop_assert!(pair.members().iter().all(|k| view.present.contains(k))); + } + } + } +} diff --git a/pkgs/id/src/lib.rs b/pkgs/id/src/lib.rs index 3c00281c1f..3631c229f8 100644 --- a/pkgs/id/src/lib.rs +++ b/pkgs/id/src/lib.rs @@ -176,7 +176,7 @@ pub mod envelope_net; pub mod envelope_outbox; pub mod event_store; pub mod fileops; -pub mod friendship; +pub mod groups; pub mod helpers; pub mod invite; pub mod local; From 25ef356fd7b6e433b20c6df942240e8d2e67ecc6 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 12 Oct 2026 00:46:19 -0500 Subject: [PATCH 15/40] docs(id): owner decisions on aliases, prefix disambiguation, and P5.7 --- ...6-10-11T11-08-42Z_design_remaining_work.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/doc/2026-10-11T11-08-42Z_design_remaining_work/2026-10-11T11-08-42Z_design_remaining_work.md b/doc/2026-10-11T11-08-42Z_design_remaining_work/2026-10-11T11-08-42Z_design_remaining_work.md index da5c9d38c5..d1e1c25981 100644 --- a/doc/2026-10-11T11-08-42Z_design_remaining_work/2026-10-11T11-08-42Z_design_remaining_work.md +++ b/doc/2026-10-11T11-08-42Z_design_remaining_work/2026-10-11T11-08-42Z_design_remaining_work.md @@ -206,3 +206,22 @@ Open for the owner: 1. User subject for tags: the user's first identity event ID, or the account key itself? 2. Two groups claim the same alias: show both as contested, never pick one silently (recommended). Does a server config key always win locally? 3. Official names unique per server, or not (recommended: not; aliases and config keys disambiguate)? + +## Owner decisions on aliases (2026-10-12) + +- Aliases are tag claims on the object. Each alias shows its text, its creation date, and the account that made it. +- Two or more aliases on one object are shown as contested. Users can inspect the full set. Nothing picks one silently. +- A server config sets a primary alias, separate from the name. Until the server sets one, the server may show its own alias as a fallback (meaning to confirm). +- Later: sort methods (creation time, votes or popularity, a user's chosen perspective). Per-user or per-server preferred and primary aliases. Display shows the name, the preferred alias, and the other aliases. +- Later: users can view aliases and set one as their user alias, which is the same thing as a pet name. Whether the user alias is shown by default is open. +- Later: a group can act through its members. A group can make a tag or upload a document. The acting user is always attached, and a user can act as the group. +- Strong removal of a user does not delete their data. It sets markers that invalidate that user's authority from the removal point. +- No official names and no uniqueness. Only event and object IDs are unique. Users, groups, tags, and aliases may share names. +- Disambiguation uses the shortest unique prefix of an object's ID. + +Open for the owner: + +1. Tag subject for a user: the first identity event ID (recommended), or the account key. Hashing the account key adds no privacy, because keys are already public. +2. Server alias fallback: confirm that it shows only until the server sets its primary alias. +3. Show the user alias by default, or only the name? +4. Prefix or suffix for disambiguation: prefix (recommended), since prefixes sort and match like git short IDs. From fffa8143dc465c32e60e1594ffd8462849472c81 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 12 Oct 2026 00:46:25 -0500 Subject: [PATCH 16/40] docs(id): add P5.7 for aliases as tags --- .../plan-phases.md | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/doc/2026-10-11T11-08-42Z_design_remaining_work/plan-phases.md b/doc/2026-10-11T11-08-42Z_design_remaining_work/plan-phases.md index 41dd0b9309..e88cf47dfa 100644 --- a/doc/2026-10-11T11-08-42Z_design_remaining_work/plan-phases.md +++ b/doc/2026-10-11T11-08-42Z_design_remaining_work/plan-phases.md @@ -154,14 +154,15 @@ Goal: group encryption on DataScheme, with the history modes, the heads rule, wa Goal: observed-remove tags, the tag index, compaction, documents, and search. -| Step | What | Blocked by | Parallel with | Tests | -| ---- | ---------------------------------------------------------------------------------------------------------------------- | ---------- | ------------- | ----------------------------------------------------------------------------- | -| P5.1 | Observed-remove tags (the S8 model) in the store. The clock covers the whole causal past | P1.3, P2.1 | P5.4 | the S8 properties; planted-bug checks | -| P5.2 | Tag index on the fixed tuple encoding: subject, name and value prefixes | P5.1, P0.9 | P5.4 | property over random tags; the `"a"` versus `"a\0b"` regression | -| P5.3 | Compaction: snapshot at a causal cut, then the tail (N33) | P5.1 | P5.2, P5.4 | the S8 counterexample as a regression test; a new device's state is preserved | -| P5.4 | Documents: content events; snapshots from the collab server; save on explicit save and on idle close (task 10, item 6) | P5.1 | P5.2, P5.3 | integration; e2e: edit, save, reload | -| P5.5 | Search over the tag index | P5.2 | P5.3, P5.4 | unit; e2e | -| P5.6 | Content on removal, kept (decision 4) | P2.6 | P5.3, P5.4 | integration | +| Step | What | Blocked by | Parallel with | Tests | +| ---- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | ------------- | ------------------------------------------------------------------------------------------- | +| P5.1 | Observed-remove tags (the S8 model) in the store. The clock covers the whole causal past | P1.3, P2.1 | P5.4 | the S8 properties; planted-bug checks | +| P5.2 | Tag index on the fixed tuple encoding: subject, name and value prefixes | P5.1, P0.9 | P5.4 | property over random tags; the `"a"` versus `"a\0b"` regression | +| P5.3 | Compaction: snapshot at a causal cut, then the tail (N33) | P5.1 | P5.2, P5.4 | the S8 counterexample as a regression test; a new device's state is preserved | +| P5.4 | Documents: content events; snapshots from the collab server; save on explicit save and on idle close (task 10, item 6) | P5.1 | P5.2, P5.3 | integration; e2e: edit, save, reload | +| P5.5 | Search over the tag index | P5.2 | P5.3, P5.4 | unit; e2e | +| P5.7 | Aliases as tags: alias list (text, date, creator), contested sets shown, shortest-unique-prefix disambiguation, server primary alias (decisions 2026-10-12); later preferred and user aliases, sort methods | P5.1, P2.9 | P5.4 | alias contest shown, never picked; prefix disambiguation; user subject decided before merge | +| P5.6 | Content on removal, kept (decision 4) | P2.6 | P5.3, P5.4 | integration | ## 11. Phase 6: invites, pull, and the CLI From df4e841399b50ed4b8cd8a6f12034d0d5454d3be Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 12 Oct 2026 00:46:49 -0500 Subject: [PATCH 17/40] build(rust): enable p2panda-auth's serde feature for group actions [P2.3] The event store keeps each group operation's action, CBOR-encoded, so the resolution can read it again without the event body. The feature adds serialization only. --- pkgs/id/Cargo.lock | 1 + pkgs/id/Cargo.toml | 5 +++-- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/pkgs/id/Cargo.lock b/pkgs/id/Cargo.lock index a3c51da161..dd4e4bb712 100644 --- a/pkgs/id/Cargo.lock +++ b/pkgs/id/Cargo.lock @@ -4227,6 +4227,7 @@ source = "git+https://github.com/p2panda/p2panda?rev=3e84cac48bba05c6857cce2ec43 dependencies = [ "p2panda-core", "petgraph", + "serde", "thiserror 2.0.21", "tracing", ] diff --git a/pkgs/id/Cargo.toml b/pkgs/id/Cargo.toml index 4e63284952..a31b1dd0d1 100644 --- a/pkgs/id/Cargo.toml +++ b/pkgs/id/Cargo.toml @@ -54,9 +54,10 @@ iroh-gossip = { version = "0.101", features = ["net"] } p2panda-core = { git = "https://github.com/p2panda/p2panda", rev = "3e84cac48bba05c6857cce2ec433862b97f8d53c" } # Store traits only. The default features would pull in SQLite (explainers section 14). p2panda-store = { git = "https://github.com/p2panda/p2panda", rev = "3e84cac48bba05c6857cce2ec433862b97f8d53c", default-features = false } -# Group membership and the auth DAG (P2.1). Default features only: `test_utils` turns on +# Group membership and the auth DAG (P2.1). The `serde` feature (P2.3) serializes group actions, +# which the event store keeps with each group operation. `test_utils` is not enabled: it turns on # test-only behaviour in p2panda-core, so the test types come from our own tests. -p2panda-auth = { git = "https://github.com/p2panda/p2panda", rev = "3e84cac48bba05c6857cce2ec433862b97f8d53c" } +p2panda-auth = { git = "https://github.com/p2panda/p2panda", rev = "3e84cac48bba05c6857cce2ec433862b97f8d53c", features = ["serde"] } postcard = { version = "1", features = ["alloc"] } rand = "0.10" redb = "=4.3.0" From 4da53d46daff06b53beb5c2927ef409e8d066d6e Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 12 Oct 2026 00:46:53 -0500 Subject: [PATCH 18/40] feat(rust): membership queries for which group operations take effect [P2.3] Membership::is_effective says whether an accepted operation takes effect in the final state: it must not be refused, the resolver must not filter it, and its author must hold manage access at its dependencies. A mutual removal is exempt from the concurrent filter, since both halves take effect. is_member_at and has_group judge content by its author's membership at its position. --- pkgs/id/src/membership/layer.rs | 70 +++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) diff --git a/pkgs/id/src/membership/layer.rs b/pkgs/id/src/membership/layer.rs index c05db89b1e..efb6021145 100644 --- a/pkgs/id/src/membership/layer.rs +++ b/pkgs/id/src/membership/layer.rs @@ -110,6 +110,8 @@ pub struct Membership { state: GroupState, /// Every operation accepted into the auth graph, in order. A rebuild replays these. accepted: Vec, + /// Membership operations the layer refused. A refused operation takes no effect. + refused: HashSet, } impl Membership { @@ -177,6 +179,7 @@ impl Membership { let group = if action.is_create() { Some(id) } else { group }; let Some(group) = group else { self.index.insert(id, after, None)?; + self.refused.insert(id); return Ok(Outcome::Refused { reason: Refusal::Malformed, placeholder: false, @@ -222,6 +225,7 @@ impl Membership { reason: Refusal, ) -> Result { let id = op.id; + self.refused.insert(id); let placeholder = match self.manager_at(group, &op.dependencies) { Some(target) => { // Promoting a member who already manages changes nothing, and the crate does not @@ -285,6 +289,72 @@ impl Membership { self.dependencies.get(id).map(Vec::as_slice) } + /// Whether the group operation `id` takes effect in the resolved state. It must be accepted at + /// its position and not refused, the resolver must not filter it, and its author must hold + /// manage access at its dependencies. The check reads the final state, so an operation stops + /// taking effect when a later operation makes the resolver filter it. + pub fn is_effective(&self, id: &Hash) -> bool { + if self.refused.contains(id) { + return false; + } + // The resolver filters the concurrent operations of a removed member, which includes the + // other half of a mutual removal. A mutual removal still takes effect, so it is exempt. + let filtered = + self.state.inner.ignore.contains(id) && !self.state.inner.mutual_removes.contains(id); + if filtered { + return false; + } + let Some(op) = self.state.inner.operations.get(id) else { + return false; + }; + if op.action.is_create() { + return true; + } + let deps: HashSet = op.dependencies.iter().copied().collect(); + self.access_at(&deps, op.group_id, op.author) + .is_some_and(|access| access.is_manage()) + } + + /// Whether `author` is a member of `group`, with any access, at the causal position that + /// `after` names. Content is judged by this: it keeps its place while its author holds access. + /// + /// # Errors + /// + /// Returns [`FrontierError`] when an `after` hash is not indexed. + pub fn is_member_at( + &mut self, + author: [u8; 32], + group: Hash, + after: &[Hash], + ) -> Result { + let deps: HashSet = self.index.frontier(after, group)?.into_iter().collect(); + Ok(self + .access_at(&deps, AuthId::Group(group), AuthId::Key(author)) + .is_some()) + } + + /// Whether a create has been decided for `group`. + pub fn has_group(&self, group: Hash) -> bool { + self.state.has_group(AuthId::Group(group)) + } + + /// The access `member` holds in `group` at `dependencies`, in the resolved state. The state at + /// a position is merged from the per-operation states, which the resolver's filter shaped, so + /// a filtered operation gives no access here. + fn access_at( + &self, + dependencies: &HashSet, + group: AuthId, + member: AuthId, + ) -> Option> { + let groups = self.state.inner.state_at(dependencies).ok()?; + let members = groups.get(&group)?; + members + .access_levels() + .into_iter() + .find_map(|(who, access)| (who == GroupMember::Individual(member)).then_some(access)) + } + /// Whether the event is held, waiting for an `after` hash. pub fn is_held(&self, id: &Hash) -> bool { self.held.contains_key(id) From 885745050990744ce2c2af306767ed05c9178bb5 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 12 Oct 2026 00:46:56 -0500 Subject: [PATCH 19/40] feat(rust): authority-based voiding of dependents [P2.3] Which stored events apply is now a function of the stored events and the fork proofs, so every arrival order gives the same applied set (decision 1): - A fork excludes its author's events from the fork point up, and nothing else (the Phase 1 rule). - A group operation applies when the membership layer says it takes effect (is_effective). - Content applies, unless it names an event that does not apply and its author is not a member of the group at its position. A dependent of a voided event is voided only when its author lost authority, so a member who kept authority keeps its content. A voided event stays stored, so its author's later events link to it and do not stall. ingest gains ingest_with_action, which takes the decoded action of a group operation; ingest passes none. The actions table holds an action from the moment its event arrives, held or stored, so a release does not need the caller again. Ingest::Voided reports a stored event that does not apply. The store format moves to v5, so older stores are refused. The waiting rows are unchanged. The Phase 1 waiting fix (p1-crashfix) owns that code. --- pkgs/id/src/event_store/ingest.rs | 282 ++++++++++++++++++----------- pkgs/id/src/event_store/mod.rs | 69 +++++-- pkgs/id/src/event_store/resolve.rs | 280 ++++++++++++++++++++++++++++ pkgs/id/tests/crash/store.rs | 2 + 4 files changed, 518 insertions(+), 115 deletions(-) create mode 100644 pkgs/id/src/event_store/resolve.rs diff --git a/pkgs/id/src/event_store/ingest.rs b/pkgs/id/src/event_store/ingest.rs index f39680a857..ce8c87035b 100644 --- a/pkgs/id/src/event_store/ingest.rs +++ b/pkgs/id/src/event_store/ingest.rs @@ -66,18 +66,21 @@ //! The property tests in `tests/event_store_properties.rs` check the applied state against //! this definition, for every arrival order. -use std::collections::VecDeque; +use std::collections::{BTreeMap, VecDeque}; +use p2panda_auth::group::GroupAction; use p2panda_core::{Hash, SeqNum}; use redb::{ReadableTable, WriteTransaction}; +use super::resolve::{self, decode_action, encode_action}; use super::waiting_rows::{Hold, Mirror}; use super::{ - CHAINS, Chain, EVENTS, EventStore, FORKS, ForkProof, HASHES, PROOF_IDS, StoreError, corrupt, - decode_proof, decode_stored, position_key, split_position, store_chain, store_event, + ACTIONS, APPLIED, CHAINS, Chain, EVENTS, EventStore, FORKS, ForkProof, HASHES, PROOF_IDS, + StoreError, corrupt, decode_proof, decode_stored, position_key, store_chain, store_event, store_fork, }; use crate::chain::{self, Event}; +use crate::membership::AuthId; use crate::waiting::{AuthorKey, WaitingPool}; /// Why an event was refused. A refused event changes nothing. @@ -129,6 +132,16 @@ pub enum Ingest { }, /// The event was refused. Nothing changed. Refused(Refusal), + /// The event is stored but does not apply. It is a group operation the membership layer + /// voids, or content whose author lost authority at a voided event it names. It still counts + /// as present, so events that name it and events after it in its author's chain are not held. + /// `released` lists the waiting events that became applied because of it. + Voided { + /// The event's ID. + id: Hash, + /// The IDs of the waiting events it released that applied, in application order. + released: Vec, + }, } /// What the store decides for one event, before the waiting pool sees it. @@ -161,11 +174,28 @@ impl EventStore { /// [`Ingest::Refused`]. After an error the waiting events are rebuilt from disk. If that /// fails too, the store refuses further calls until it is reopened. pub fn ingest(&mut self, bytes: &[u8], now_ms: u64) -> Result { + self.ingest_with_action(bytes, None, now_ms) + } + + /// Verifies one received event, which may be a group operation, and applies what it allows. + /// `action` is the membership change of a group operation. The caller has read it from the + /// event's body and checked the body against the event's payload hash. The store does not read + /// bodies. Other events take no action. + /// + /// # Errors + /// + /// Returns a redb or corruption error, as [`EventStore::ingest`] does. + pub fn ingest_with_action( + &mut self, + bytes: &[u8], + action: Option<&GroupAction>, + now_ms: u64, + ) -> Result { let event = match chain::decode(bytes) { Ok(event) => event, Err(err) => return Ok(Ingest::Refused(Refusal::Malformed(err.to_string()))), }; - self.transact(now_ms, |mirror| ingest_in(mirror, event, now_ms)) + self.transact(now_ms, |mirror| ingest_in(mirror, event, action, now_ms)) } /// Drops the waiting events due at `now_ms`, with their rows. Returns how many were dropped. @@ -199,16 +229,25 @@ impl EventStore { /// Decides a received event inside the call's transaction, and the events it releases. Returns /// the outcome, and whether the call changed anything. A call that expired events has changed /// something, even if its own event was refused. -fn ingest_in(m: &mut Mirror<'_>, event: Event, now: u64) -> Result<(Ingest, bool), StoreError> { +fn ingest_in( + m: &mut Mirror<'_>, + event: Event, + action: Option<&GroupAction>, + now: u64, +) -> Result<(Ingest, bool), StoreError> { let expired = m.expire(now)?; let id = event.id; let author = author_of(&event); let rivals = held_rivals(m.pool, &event); - let outcome = match settle(m, event, &rivals, now, false)? { - Settled::Accepted { released } => Ingest::Accepted { - id, - released: drain(m, released.into(), now)?, - }, + let outcome = match settle(m, event, action, &rivals, now, false)? { + Settled::Stored { applied, released } => { + let released = drain(m, released.into(), now)?; + if applied { + Ingest::Accepted { id, released } + } else { + Ingest::Voided { id, released } + } + } Settled::Duplicate => Ingest::Duplicate { id }, Settled::Fork { seq, released } => { drain(m, released.into(), now)?; @@ -226,8 +265,9 @@ fn ingest_in(m: &mut Mirror<'_>, event: Event, now: u64) -> Result<(Ingest, bool /// What one decision did, once the pool and the rows agree with it. enum Settled { - /// Applied. `released` are the events that waited only for it, and each is due a decision. - Accepted { released: Vec }, + /// Stored, and applied or voided as the resolution says. `released` are the events that + /// waited only for it, and each is due a decision. + Stored { applied: bool, released: Vec }, /// Already stored, or a fork proof header. Nothing changed. Duplicate, /// A conflict at `seq`. The proof headers are present now, and `released` are the events @@ -248,21 +288,30 @@ enum Settled { fn settle( m: &mut Mirror<'_>, event: Event, + action: Option<&GroupAction>, rivals: &[Event], now: u64, from_pool: bool, ) -> Result { let id = event.id; let settled = match decide_in(m.txn, &event, rivals)? { - Decision::Accept => Settled::Accepted { - released: m.release(&id, now)?, - }, + Decision::Accept => { + if let Some(action) = action { + store_action(m.txn, &id, action)?; + } + refresh(m.txn)?; + Settled::Stored { + applied: is_applied(m.txn, &id)?, + released: m.release(&id, now)?, + } + } Decision::Duplicate => { drop_released(m, &id, from_pool)?; Settled::Duplicate } Decision::Fork { seq, proof } => { drop_released(m, &id, from_pool)?; + refresh(m.txn)?; let mut released = Vec::new(); for header in proof { released.extend(m.release(&header, now)?); @@ -273,12 +322,33 @@ fn settle( drop_released(m, &id, from_pool)?; Settled::Refused(refusal) } - Decision::Wait(deps) => held(m.hold(event, deps, false, now)?), - Decision::Park => held(m.hold(event, Vec::new(), true, now)?), + Decision::Wait(deps) => { + if let Some(action) = action { + store_action(m.txn, &id, action)?; + } + held(m.hold(event, deps, false, now)?) + } + Decision::Park => { + if let Some(action) = action { + store_action(m.txn, &id, action)?; + } + held(m.hold(event, Vec::new(), true, now)?) + } }; Ok(settled) } +/// The action of a held or stored group operation, from the actions table. A held event keeps +/// its action there from the moment it arrives, so a release does not need the caller again. +fn stored_action( + txn: &WriteTransaction, + id: &Hash, +) -> Result>, StoreError> { + let actions = txn.open_table(ACTIONS)?; + let row = actions.get(id.as_bytes().as_slice())?; + row.map(|row| decode_action(row.value())).transpose() +} + fn drop_released(m: &Mirror<'_>, id: &Hash, from_pool: bool) -> Result<(), StoreError> { if from_pool { m.drop_row(id)?; @@ -306,9 +376,15 @@ fn drain( while let Some(event) = queue.pop_front() { let id = event.id; let rivals = held_rivals(m.pool, &event); - match settle(m, event, &rivals, now, true)? { - Settled::Accepted { released } => { - applied.push(id); + let action = stored_action(m.txn, &id)?; + match settle(m, event, action.as_ref(), &rivals, now, true)? { + Settled::Stored { + applied: is_applied, + released, + } => { + if is_applied { + applied.push(id); + } queue.extend(released); } Settled::Fork { released, .. } => queue.extend(released), @@ -369,76 +445,104 @@ fn decide_in( conflicts.push(event.clone()); let (first, second) = two_lowest(conflicts)?; store_fork(txn, &author, seq, &first, &second)?; - freeze_and_void(txn, &author, seq)?; return Ok(Decision::Fork { seq, proof: [first.id, second.id], }); } - let chain = read_chain(txn, &author)?; - if seq < chain.next_seq { - // The applied event at this sequence number is stored, so it would be a conflict. - return Err(corrupt("an applied sequence number has no stored event")); - } - let deps = missing_deps(txn, &event.header.extensions.after)?; - if seq == chain.next_seq { - if seq > 0 && event.header.backlink != chain.head { - return Ok(Decision::Park); - } - if !deps.is_empty() { - return Ok(Decision::Wait(deps)); + // The backlink must be the stored event before this one. Voided events are stored, so a + // backlink does not need to be applied. A backlink that is stored at another position, or + // that is missing where there is no backlink, can never link, so the event is parked. + let mut waits = missing_deps(txn, &event.header.extensions.after)?; + if seq > 0 { + let linked = match event.header.backlink { + Some(backlink) => { + stored_at(txn, &author, seq - 1)?.is_some_and(|before| before.id == backlink) + } + None => false, + }; + if !linked { + match event.header.backlink { + Some(backlink) if !is_stored(txn, &backlink)? => waits.push(backlink), + _ => return Ok(Decision::Park), + } } - return accept(txn, event, chain); - } - // Ahead of the chain. The backlink must be applied first, unless it already is, at - // another position, and then this event can never apply. - let mut waits = deps; - let missing_backlink = match event.header.backlink { - Some(backlink) => (!is_applied(txn, &backlink)?).then_some(backlink), - None => None, - }; - waits.extend(missing_backlink); + } if waits.is_empty() { - Ok(Decision::Park) + accept(txn, event) } else { Ok(Decision::Wait(waits)) } } -/// Stores `event` as the next applied event of its author, and records what it rests on. -fn accept(txn: &WriteTransaction, event: &Event, chain: Chain) -> Result { - let author = author_of(event); - let seq = event.header.seq_num; +/// Stores `event`. Whether it applies is decided by [`refresh`], which the caller runs next. +fn accept(txn: &WriteTransaction, event: &Event) -> Result { store_event(txn, event)?; - let next_seq = seq - .checked_add(1) - .ok_or_else(|| corrupt("a sequence number overflows"))?; - store_chain( - txn, - &author, - Chain { - next_seq, - head: Some(event.id), - frozen: chain.frozen, - }, - )?; Ok(Decision::Accept) } -/// Freezes `author` at `seq`: the applied prefix ends there, and the author's applied events from -/// `seq` up are voided. Nothing else is voided. An event of another author that names a voided -/// event stays applied, because the voided event is still present. -/// -/// This is the Phase 1 rule. With no membership or authority model, a fork cannot void by -/// authority. Authority-based voiding (decision 1) replaces this rule in Phase 2 (P2.3). -fn freeze_and_void( +/// Writes the action of a group operation, so the resolution can read it again. +fn store_action( txn: &WriteTransaction, - author: &AuthorKey, - seq: SeqNum, + id: &Hash, + action: &GroupAction, ) -> Result<(), StoreError> { - let chain = read_chain(txn, author)?; - set_prefix(txn, author, chain.next_seq.min(seq), true) + let encoded = encode_action(action)?; + let mut actions = txn.open_table(ACTIONS)?; + actions.insert(id.as_bytes().as_slice(), encoded.as_slice())?; + Ok(()) +} + +/// Recomputes which stored events apply, and writes the result: the applied table, and each +/// chain row as the leading run of applied events from sequence zero. The result is a function of +/// the stored events and the fork proofs, so every arrival order writes the same rows. +pub(super) fn refresh(txn: &WriteTransaction) -> Result<(), StoreError> { + let (stored, forks, headers) = { + let events = txn.open_table(EVENTS)?; + let actions = txn.open_table(ACTIONS)?; + let forks = txn.open_table(FORKS)?; + resolve::load(&events, &actions, &forks)? + }; + let resolved = resolve::resolve(&stored, &forks, &headers)?; + + let mut applied_table = txn.open_table(APPLIED)?; + let mut previous = Vec::new(); + for entry in applied_table.iter()? { + let (key, _) = entry?; + previous.push(key.value().to_vec()); + } + for key in previous { + applied_table.remove(key.as_slice())?; + } + for id in &resolved.applied { + applied_table.insert(id.as_bytes().as_slice(), [].as_slice())?; + } + drop(applied_table); + + let mut order: Vec<(AuthorKey, SeqNum, bool)> = stored + .iter() + .map(|item| { + let event = &item.event; + ( + author_of(event), + event.header.seq_num, + resolved.applied.contains(&event.id), + ) + }) + .collect(); + order.sort_unstable(); + let mut next: BTreeMap = forks.keys().map(|author| (*author, 0)).collect(); + for (author, seq, applied) in order { + let run = next.entry(author).or_insert(0); + if applied && seq == *run { + *run += 1; + } + } + for (author, prefix) in next { + set_prefix(txn, &author, prefix, forks.contains_key(&author))?; + } + Ok(()) } /// Writes `author`'s chain row for an applied prefix of `next_seq` events. A chain with @@ -507,15 +611,6 @@ fn read_proof(txn: &WriteTransaction, author: &AuthorKey) -> Result Result { - let chains = txn.open_table(CHAINS)?; - let row = chains.get(author.as_slice())?; - match row { - Some(row) => Chain::decode(row.value()), - None => Ok(Chain::default()), - } -} - /// The stored event at `author`'s `seq`, applied or voided, if there is one. fn stored_at( txn: &WriteTransaction, @@ -547,10 +642,11 @@ fn missing_deps(txn: &WriteTransaction, after: &[Hash]) -> Result, Sto Ok(missing) } -/// Whether the event with this ID is applied: stored, at a sequence number below its -/// author's applied prefix. +/// Whether the event with this ID applies, in the resolved state. pub(super) fn is_applied(txn: &WriteTransaction, hash: &Hash) -> Result { - applied_in(&txn.open_table(HASHES)?, &txn.open_table(CHAINS)?, hash) + let applied = txn.open_table(APPLIED)?; + let found = applied.get(hash.as_bytes().as_slice())?.is_some(); + Ok(found) } /// Whether an `after` hash is present: the store holds the event it names, applied or voided, or @@ -572,26 +668,6 @@ pub(super) fn present_in( Ok(proof_ids.get(hash.as_bytes().as_slice())?.is_some()) } -/// [`is_applied`] over the `hashes` and `chains` tables, whether they are read or written. -pub(super) fn applied_in( - hashes: &impl ReadableTable<&'static [u8], &'static [u8]>, - chains: &impl ReadableTable<&'static [u8], &'static [u8]>, - hash: &Hash, -) -> Result { - let position = hashes - .get(hash.as_bytes().as_slice())? - .map(|found| found.value().to_vec()); - let Some(position) = position else { - return Ok(false); - }; - let (author, seq) = split_position(&position)?; - let row = chains.get(author.as_slice())?; - match row { - Some(row) => Ok(Chain::decode(row.value())?.next_seq > seq), - None => Ok(false), - } -} - #[cfg(test)] #[allow(clippy::unwrap_used, clippy::expect_used)] mod tests { diff --git a/pkgs/id/src/event_store/mod.rs b/pkgs/id/src/event_store/mod.rs index 4aff519b2b..81680073f2 100644 --- a/pkgs/id/src/event_store/mod.rs +++ b/pkgs/id/src/event_store/mod.rs @@ -57,6 +57,7 @@ use redb::{ use crate::chain::{self, Event}; mod ingest; +mod resolve; mod waiting_rows; use crate::waiting::{AuthorKey, WaitRefusal, WaitingLimits, WaitingPool}; @@ -72,7 +73,7 @@ pub const FILE_NAME: &str = "events.redb"; pub const TEMP_NAME: &str = "events.redb.tmp"; /// The format row in `meta`. A store with another format is refused. -const FORMAT: &[u8] = b"id.events.store.v4"; +const FORMAT: &[u8] = b"id.events.store.v5"; const FORMAT_KEY: &[u8] = b"format"; const EVENTS: TableDefinition<'static, &'static [u8], &'static [u8]> = @@ -91,6 +92,13 @@ const WAITING: TableDefinition<'static, &'static [u8], &'static [u8]> = const WAITING_BY_DEP: MultimapTableDefinition<'static, &'static [u8], &'static [u8]> = MultimapTableDefinition::new("waiting_by_dep"); const META: TableDefinition<'static, &'static [u8], &'static [u8]> = TableDefinition::new("meta"); +/// Each group operation's encoded action, by event ID. Written when the event arrives, held or +/// stored, so a release reads it back without the caller. The resolution reads it again. +const ACTIONS: TableDefinition<'static, &'static [u8], &'static [u8]> = + TableDefinition::new("actions"); +/// The IDs of the applied events, with an empty value. Written by the resolution. +const APPLIED: TableDefinition<'static, &'static [u8], &'static [u8]> = + TableDefinition::new("applied"); /// Bytes in a position key: the author, then the sequence number. const POSITION_LEN: usize = 40; @@ -397,6 +405,36 @@ impl EventStore { row.map(|row| Chain::decode(row.value())).transpose() } + /// Whether the event with this ID applies, in the resolved state. + /// + /// # Errors + /// + /// Returns a redb error if the read fails. + pub fn event_applied(&self, id: &Hash) -> Result { + let txn = self.db.begin_read()?; + let applied = txn.open_table(APPLIED)?; + let found = applied.get(id.as_bytes().as_slice())?.is_some(); + Ok(found) + } + + /// The keys that are members of `group` in the resolved state, sorted. A member with access + /// at the end of the causal history is listed, and a removed member is not. + /// + /// # Errors + /// + /// Returns a redb error if the read fails, or [`StoreError::Corrupt`]. + pub fn roster(&self, group: &Hash) -> Result, StoreError> { + let txn = self.db.begin_read()?; + let (stored, forks, headers) = { + let events = txn.open_table(EVENTS)?; + let actions = txn.open_table(ACTIONS)?; + let forks = txn.open_table(FORKS)?; + resolve::load(&events, &actions, &forks)? + }; + let resolved = resolve::resolve(&stored, &forks, &headers)?; + Ok(resolve::roster_of(&resolved, group)) + } + /// The stored event at `(author, seq)`, applied or not. /// /// # Errors @@ -779,6 +817,8 @@ fn initialize(db: &Database) -> Result<(), StoreError> { txn.open_table(PROOF_IDS)?; txn.open_table(WAITING)?; txn.open_multimap_table(WAITING_BY_DEP)?; + txn.open_table(ACTIONS)?; + txn.open_table(APPLIED)?; let mut meta = txn.open_table(META)?; meta.insert(FORMAT_KEY, FORMAT)?; drop(meta); @@ -798,6 +838,8 @@ fn verify_schema(db: &Database) -> Result<(), StoreError> { txn.open_table(PROOF_IDS).map_err(missing)?; txn.open_table(WAITING).map_err(missing)?; txn.open_multimap_table(WAITING_BY_DEP).map_err(missing)?; + txn.open_table(ACTIONS).map_err(missing)?; + txn.open_table(APPLIED).map_err(missing)?; let meta = txn.open_table(META).map_err(missing)?; match meta.get(FORMAT_KEY)? { Some(found) if found.value() == FORMAT => Ok(()), @@ -987,27 +1029,30 @@ impl EventStore { limit: usize, ) -> Result, StoreError> { let txn = self.db.begin_read()?; - let chains = txn.open_table(CHAINS)?; - let Some(chain_row) = chains.get(author.as_slice())? else { - return Ok(Vec::new()); - }; - let Some(last) = Chain::decode(chain_row.value())?.next_seq.checked_sub(1) else { - return Ok(Vec::new()); - }; - let last = until.map_or(last, |until| until.min(last)); let first = match after { Some(after) => after.checked_add(1), None => Some(0), }; - let Some(first) = first.filter(|first| *first <= last) else { + let Some(first) = first else { return Ok(Vec::new()); }; + let last = until.unwrap_or(SeqNum::MAX); + if first > last { + return Ok(Vec::new()); + } + let applied = txn.open_table(APPLIED)?; let events = txn.open_table(EVENTS)?; let (start, end) = (position_key(author, first), position_key(author, last)); let mut found = Vec::new(); - for row in events.range(start.as_slice()..=end.as_slice())?.take(limit) { + for row in events.range(start.as_slice()..=end.as_slice())? { + if found.len() >= limit { + break; + } let (_position, bytes) = row?; - found.push(decode_stored(bytes.value())?); + let event = decode_stored(bytes.value())?; + if applied.get(event.id.as_bytes().as_slice())?.is_some() { + found.push(event); + } } Ok(found) } diff --git a/pkgs/id/src/event_store/resolve.rs b/pkgs/id/src/event_store/resolve.rs new file mode 100644 index 0000000000..f6b2199db0 --- /dev/null +++ b/pkgs/id/src/event_store/resolve.rs @@ -0,0 +1,280 @@ +//! The applied state of a store, derived from the events it holds and its fork proofs (P2.3). +//! +//! The store keeps every event that is present: stored, applied or voided, and fork proof headers. +//! Which of them apply is a function of that set, so it does not depend on arrival order. The +//! rules are: +//! +//! 1. **Fork.** An event at or above its author's fork point never applies. This is the fork +//! rule of Phase 1, and it reaches no other author's events. +//! 2. **Group operation.** A membership operation applies when the membership layer says it takes +//! effect: accepted at its position, not filtered by the resolver, and its author holds manage +//! access at its dependencies. The strong-remove rules decide concurrency (see +//! [`Membership::is_effective`]), so a dependent of a voided operation is voided only when its +//! author lost authority at its position. +//! 3. **Content.** Any other event applies, unless it names a voided event and its author is not a +//! member of its group at its position. A group with no create has no authority to lose, so its +//! content always applies. Content is kept on removal, as the content policy says. +//! +//! A voided event stays stored. Its author's later events do not wait on it, and they are judged +//! by the same rules. That is why an honest author never stalls on another author's removal. + +use std::collections::{HashMap, HashSet}; + +use p2panda_auth::group::GroupAction; +use p2panda_core::{Hash, SeqNum}; +use redb::ReadableTable; + +use super::{StoreError, corrupt, decode_proof, decode_stored}; +use crate::chain::Event; +use crate::membership::{AuthId, CausalEvent, Membership, Role}; +use crate::waiting::AuthorKey; + +/// One stored event, with the membership action it carries when it is a group operation. +#[derive(Clone, Debug)] +pub(super) struct Stored { + pub event: Event, + pub action: Option>, +} + +/// The applied state of a set of events. +pub(super) struct Resolved { + /// The IDs of the events that apply. + pub applied: HashSet, + /// The membership layer over the events, or `None` when there is no group operation. + pub membership: Option, +} + +/// One event, or one fork proof header, as the resolution sees it. +struct Node { + id: Hash, + author: AuthorKey, + group: Option, + after: Vec, + action: Option>, + /// True for a fork proof header, and for an event at or above its author's fork point. Such a + /// node never applies. + excluded: bool, +} + +/// The author of an event. +pub(super) fn author_of(event: &Event) -> AuthorKey { + *event.header.verifying_key.as_bytes() +} + +/// Resolves which of `stored` apply, given the fork proofs as `(author, fork point)`. +/// +/// # Errors +/// +/// Returns [`StoreError::Corrupt`] when an event names a dependency that is not present, or when +/// the membership layer cannot keep its invariants. Neither happens for a store written by this +/// code. +pub(super) fn resolve( + stored: &[Stored], + forks: &HashMap, + proof_headers: &[Event], +) -> Result { + let mut nodes: Vec = Vec::new(); + let mut position: HashMap = HashMap::new(); + for item in stored { + let event = &item.event; + let author = author_of(event); + let seq = event.header.seq_num; + let excluded = forks.get(&author).is_some_and(|point| seq >= *point); + position.insert(event.id, nodes.len()); + nodes.push(Node { + id: event.id, + author, + group: event.header.extensions.group, + after: event.header.extensions.after.clone(), + action: item.action.clone(), + excluded, + }); + } + for header in proof_headers { + if position.contains_key(&header.id) { + continue; + } + position.insert(header.id, nodes.len()); + nodes.push(Node { + id: header.id, + author: author_of(header), + group: header.header.extensions.group, + after: header.header.extensions.after.clone(), + action: None, + excluded: true, + }); + } + + let order = causal_order(&nodes, &position)?; + + // Pass one: the membership layer over every node that is not excluded, in causal order. An + // excluded node stays in the index with the dependencies it can name, so a dependent of a + // fork proof header still has a causal past. + let has_actions = nodes.iter().any(|node| node.action.is_some()); + let mut membership = has_actions.then(Membership::new); + if let Some(layer) = membership.as_mut() { + for &index in &order { + let node = &nodes[index]; + let after: Vec = node + .after + .iter() + .filter(|dep| position.contains_key(dep)) + .copied() + .collect(); + let role = match (&node.action, node.excluded) { + (Some(action), false) => Role::Auth { + author: node.author, + group: node.group, + action: action.clone(), + }, + _ => Role::Other, + }; + layer + .receive(CausalEvent { + id: node.id, + after, + role, + }) + .map_err(|err| corrupt(format!("the membership layer: {err}")))?; + } + } + + // Pass two: each node's effect, in causal order, so that a dependency is decided first. + let mut applied = HashSet::new(); + for &index in &order { + let node = &nodes[index]; + if node.excluded { + continue; + } + let takes_effect = match (&node.action, membership.as_mut()) { + (Some(_), Some(layer)) => layer.is_effective(&node.id), + (Some(_), None) => false, + (None, layer) => content_applies(node, &applied, layer)?, + }; + if takes_effect { + applied.insert(node.id); + } + } + + Ok(Resolved { + applied, + membership, + }) +} + +/// Whether content applies. It applies unless it names a voided event and its author is not a +/// member of its group at its position. +fn content_applies( + node: &Node, + applied: &HashSet, + membership: Option<&mut Membership>, +) -> Result { + let names_voided = node.after.iter().any(|dep| !applied.contains(dep)); + let (Some(group), Some(layer), true) = (node.group, membership, names_voided) else { + return Ok(true); + }; + if !layer.has_group(group) { + return Ok(true); + } + layer + .is_member_at(node.author, group, &node.after) + .map_err(|err| corrupt(format!("the membership layer: {err}"))) +} + +/// The node indices in an order where every dependency comes first. A node that names an absent +/// dependency is placed only when it is excluded, since its dependencies are then dropped. +fn causal_order(nodes: &[Node], position: &HashMap) -> Result, StoreError> { + let mut placed = vec![false; nodes.len()]; + let mut order = Vec::with_capacity(nodes.len()); + let mut progress = true; + while progress { + progress = false; + for (index, node) in nodes.iter().enumerate() { + if placed[index] { + continue; + } + let ready = node.after.iter().all(|dep| match position.get(dep) { + Some(&other) => placed[other], + None => node.excluded, + }); + if ready { + placed[index] = true; + order.push(index); + progress = true; + } + } + } + if order.len() != nodes.len() { + return Err(corrupt( + "an event names a dependency that is not stored, or the dependencies form a cycle", + )); + } + Ok(order) +} + +/// What [`load`] reads: the stored events, the fork points, and the fork proof headers. +pub(super) type Loaded = (Vec, HashMap, Vec); + +/// Reads every stored event with its action, and every fork proof, from the tables. +pub(super) fn load(events: &T, actions: &T, forks: &T) -> Result +where + T: ReadableTable<&'static [u8], &'static [u8]>, +{ + let mut stored = Vec::new(); + for entry in events.iter()? { + let (_, value) = entry?; + let event = decode_stored(value.value())?; + let action = match actions.get(event.id.as_bytes().as_slice())? { + Some(row) => Some(decode_action(row.value())?), + None => None, + }; + stored.push(Stored { event, action }); + } + let mut fork_points = HashMap::new(); + let mut headers = Vec::new(); + for entry in forks.iter()? { + let (key, value) = entry?; + let proof = decode_proof(value.value())?; + let author: AuthorKey = key + .value() + .try_into() + .map_err(|_err| corrupt("a fork row has a short author"))?; + fork_points.insert(author, proof.seq); + headers.push(proof.first); + headers.push(proof.second); + } + Ok((stored, fork_points, headers)) +} + +/// Encodes a group action for its table. +pub(super) fn encode_action(action: &GroupAction) -> Result, StoreError> { + let value = cbor_core::Value::serialized(action) + .map_err(|err| corrupt(format!("a group action does not encode: {err}")))?; + Ok(value.encode()) +} + +/// Decodes a group action from its table. +pub(super) fn decode_action(bytes: &[u8]) -> Result, StoreError> { + let value = cbor_core::Value::decode(bytes) + .map_err(|err| corrupt(format!("a group action row is not CBOR: {err}")))?; + value + .deserialized() + .map_err(|err| corrupt(format!("a group action row does not decode: {err}"))) +} + +/// The members of `group` in a resolution, as keys. Empty when there is no membership layer. +pub(super) fn roster_of(resolved: &Resolved, group: &Hash) -> Vec { + let Some(layer) = resolved.membership.as_ref() else { + return Vec::new(); + }; + let mut keys: Vec = layer + .members(*group) + .into_iter() + .filter_map(|(who, _)| match who { + AuthId::Key(key) => Some(key), + AuthId::Group(_) => None, + }) + .collect(); + keys.sort_unstable(); + keys +} diff --git a/pkgs/id/tests/crash/store.rs b/pkgs/id/tests/crash/store.rs index 2c9f833fdf..36cfda2b22 100644 --- a/pkgs/id/tests/crash/store.rs +++ b/pkgs/id/tests/crash/store.rs @@ -527,6 +527,8 @@ fn acknowledged_survive(disk: &Disk, acked: &[(Vec, Ingest)]) -> Result<(), } } Ingest::Waiting { id } => held_ids.push(*id), + // Stored and not applied: it is neither applied nor held, so it is not checked here. + Ingest::Voided { released, .. } => applied_ids.extend(released), Ingest::Refused(_) => {} } } From 21d00659c07cd2b1966a3797ad8b0f6b07107eb0 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 12 Oct 2026 00:47:00 -0500 Subject: [PATCH 20/40] test(rust): S2 voiding scenarios through the event store [P2.3] Each S2 scenario runs in every arrival order: a week-late add, a causally prior add, a transitive dependent by a member who kept authority and by one who lost it, content after a voided add, mutual and three-way removal, concurrent and causal re-adds, and an honest chain beside a removal. A voided predecessor does not stall its author's next event. --- pkgs/id/tests/voiding_scenarios.rs | 376 +++++++++++++++++++++++++++++ 1 file changed, 376 insertions(+) create mode 100644 pkgs/id/tests/voiding_scenarios.rs diff --git a/pkgs/id/tests/voiding_scenarios.rs b/pkgs/id/tests/voiding_scenarios.rs new file mode 100644 index 0000000000..edcf2fd1fd --- /dev/null +++ b/pkgs/id/tests/voiding_scenarios.rs @@ -0,0 +1,376 @@ +//! Authority-based voiding through the event store (P2.3). The S2 scenarios, each delivered in +//! every arrival order. The applied state and the roster must be the same in all of them, and +//! must match the S2 outcomes: an operation is voided when its author lost authority at its +//! position, and a dependent of a voided operation is kept when its author kept authority. + +#![allow(clippy::unwrap_used, clippy::expect_used)] + +use std::collections::BTreeMap; + +use id::chain::{ChainExt, sign}; +use id::event_store::EventStore; +use id::membership::AuthId; +use id::waiting::WaitingLimits; +use p2panda_auth::Access; +use p2panda_auth::group::{GroupAction, GroupMember}; +use p2panda_core::{Hash, SeqNum, SigningKey}; + +/// One event of a scenario: its name in the scenario, its signed bytes, and its action. +#[derive(Clone)] +struct Step { + name: u8, + bytes: Vec, + action: Option>, +} + +/// Signs a scenario. Each author's events form a chain, so the sequence numbers and backlinks +/// are set here. The group is the create event's ID. +#[derive(Default)] +struct Builder { + ids: BTreeMap, + last: BTreeMap, + group: Option, + steps: Vec, +} + +fn key(who: char) -> SigningKey { + SigningKey::from_bytes(&[who as u8; 32]) +} + +fn auth(who: char) -> AuthId { + AuthId::Key(*key(who).verifying_key().as_bytes()) +} + +fn add(who: char, access: Access<()>) -> GroupAction { + GroupAction::Add { + member: GroupMember::Individual(auth(who)), + access, + } +} + +fn remove(who: char) -> GroupAction { + GroupAction::Remove { + member: GroupMember::Individual(auth(who)), + } +} + +fn create(managers: &[char]) -> GroupAction { + GroupAction::Create { + initial_members: managers + .iter() + .map(|who| (GroupMember::Individual(auth(*who)), Access::manage())) + .collect(), + } +} + +impl Builder { + /// Signs one event by `who`, after the events named in `after`. + fn push( + &mut self, + name: u8, + who: char, + after: &[u8], + kind: &str, + action: Option>, + ) { + let (seq, backlink) = match self.last.get(&who) { + Some((seq, hash)) => (seq + 1, Some(*hash)), + None => (0, None), + }; + let ext = ChainExt { + kind: kind.to_owned(), + group: if matches!(action, Some(GroupAction::Create { .. })) { + None + } else { + self.group + }, + after: after.iter().map(|n| self.ids[n]).collect(), + }; + let event = sign(&key(who), seq, backlink, None, ext).unwrap(); + if matches!(action, Some(GroupAction::Create { .. })) { + self.group = Some(event.id); + } + self.ids.insert(name, event.id); + self.last.insert(who, (seq, event.id)); + self.steps.push(Step { + name, + bytes: event.bytes, + action, + }); + } + + /// A membership operation by `who`. + fn op(&mut self, name: u8, who: char, after: &[u8], action: GroupAction) { + self.push(name, who, after, "group.op", Some(action)); + } + + /// Content in the group: an event with no membership effect. + fn content(&mut self, name: u8, who: char, after: &[u8]) { + self.push(name, who, after, "message", None); + } +} + +/// What one delivery order produced: each event's applied flag, and the group's roster. +#[derive(Debug, PartialEq, Eq)] +struct Outcome { + applied: BTreeMap, + roster: Vec, +} + +/// Delivers the steps in `order` to a fresh store, and reports what it applied. +fn deliver(steps: &[Step], order: &[usize]) -> Outcome { + let dir = tempfile::tempdir().unwrap(); + let mut store = EventStore::open(dir.path(), WaitingLimits::default(), 0).unwrap(); + for &index in order { + let step = &steps[index]; + store + .ingest_with_action(&step.bytes, step.action.as_ref(), 0) + .unwrap(); + } + let group = steps + .iter() + .find(|step| matches!(step.action, Some(GroupAction::Create { .. }))) + .map(|step| Hash::digest(&step.bytes)) + .unwrap(); + let applied = steps + .iter() + .map(|step| { + let id = Hash::digest(&step.bytes); + (step.name, store.event_applied(&id).unwrap()) + }) + .collect(); + let mut roster: Vec = store + .roster(&group) + .unwrap() + .into_iter() + .map(AuthId::Key) + .collect(); + roster.sort(); + Outcome { applied, roster } +} + +/// Every permutation of `0..n`. +fn permutations(n: usize) -> Vec> { + fn walk(current: &mut Vec, rest: &mut Vec, out: &mut Vec>) { + if rest.is_empty() { + out.push(current.clone()); + return; + } + for i in 0..rest.len() { + let item = rest.remove(i); + current.push(item); + walk(current, rest, out); + current.pop(); + rest.insert(i, item); + } + } + let mut out = Vec::new(); + walk(&mut Vec::new(), &mut (0..n).collect(), &mut out); + out +} + +/// Checks a scenario in every arrival order: all orders agree, and they match `expected`. +fn check(name: &str, steps: &[Step], expected: &[(u8, bool)], roster: &[char]) { + let expected = Outcome { + applied: expected.iter().copied().collect(), + roster: { + let mut keys: Vec = roster.iter().map(|who| auth(*who)).collect(); + keys.sort(); + keys + }, + }; + for order in permutations(steps.len()) { + let outcome = deliver(steps, &order); + assert_eq!(outcome, expected, "{name}: arrival order {order:?}"); + } +} + +#[test] +fn test_s2_week_late_add_by_a_removed_member_is_voided() { + // Alice removes Bob (R). Bob's add of Dave (X) was made without seeing R. + let mut b = Builder::default(); + b.op(0, 'A', &[], create(&['A', 'B', 'C'])); + b.op(1, 'A', &[0], remove('B')); + b.op(2, 'B', &[0], add('D', Access::manage())); + check( + "1 week-late add", + &b.steps, + &[(0, true), (1, true), (2, false)], + &['A', 'C'], + ); +} + +#[test] +fn test_s2_causally_prior_add_survives() { + // Bob adds Dave (Y). Alice sees Y, then removes Bob (R names Y). + let mut b = Builder::default(); + b.op(0, 'A', &[], create(&['A', 'B', 'C'])); + b.op(1, 'B', &[0], add('D', Access::manage())); + b.op(2, 'A', &[1], remove('B')); + check( + "2 causally prior add", + &b.steps, + &[(0, true), (1, true), (2, true)], + &['A', 'C', 'D'], + ); +} + +#[test] +fn test_s2_transitive_dependent_of_a_voided_add_is_voided_for_a_removed_author() { + // Dave's authority comes from Bob's add Z, which is concurrent with R. Dave adds Eve after Z. + let mut b = Builder::default(); + b.op(0, 'A', &[], create(&['A', 'B', 'C'])); + b.op(1, 'B', &[0], add('D', Access::manage())); + b.op(2, 'A', &[0], remove('B')); + b.op(3, 'D', &[1], add('E', Access::read())); + check( + "3 transitive void by authority", + &b.steps, + &[(0, true), (1, false), (2, true), (3, false)], + &['A', 'C'], + ); +} + +#[test] +fn test_s2_transitive_dependent_of_a_voided_add_is_kept_for_an_independent_author() { + // The same shape, but the add after Z is by Claire, who has her own authority (rule 3b). + let mut b = Builder::default(); + b.op(0, 'A', &[], create(&['A', 'B', 'C'])); + b.op(1, 'B', &[0], add('D', Access::manage())); + b.op(2, 'A', &[0], remove('B')); + b.op(3, 'C', &[1], add('E', Access::read())); + check( + "3b dependent add by an independent author", + &b.steps, + &[(0, true), (1, false), (2, true), (3, true)], + &['A', 'C', 'E'], + ); +} + +#[test] +fn test_s2_content_by_a_removed_author_after_a_voided_add_is_voided() { + // Content is kept on removal, except where its author lost authority at the voided add. + let mut b = Builder::default(); + b.op(0, 'A', &[], create(&['A', 'B', 'C'])); + b.op(1, 'B', &[0], add('D', Access::manage())); + b.op(2, 'A', &[0], remove('B')); + b.content(3, 'D', &[1]); + b.content(4, 'C', &[1]); + check( + "3c content after a voided add", + &b.steps, + &[(0, true), (1, false), (2, true), (3, false), (4, true)], + &['A', 'C'], + ); +} + +#[test] +fn test_s2_mutual_removal_removes_both() { + let mut b = Builder::default(); + b.op(0, 'A', &[], create(&['A', 'B', 'C'])); + b.op(1, 'A', &[0], remove('B')); + b.op(2, 'B', &[0], remove('A')); + check( + "4 mutual removal", + &b.steps, + &[(0, true), (1, true), (2, true)], + &['C'], + ); +} + +#[test] +fn test_s2_three_cycle_removes_every_member() { + let mut b = Builder::default(); + b.op(0, 'A', &[], create(&['A', 'B', 'C'])); + b.op(1, 'A', &[0], remove('B')); + b.op(2, 'B', &[0], remove('C')); + b.op(3, 'C', &[0], remove('A')); + check( + "4b three-cycle", + &b.steps, + &[(0, true), (1, true), (2, true), (3, true)], + &[], + ); +} + +#[test] +fn test_s2_concurrent_re_add_is_voided() { + // Claire removes and re-adds Bob, without seeing Alice's removal of Bob. + let mut b = Builder::default(); + b.op(0, 'A', &[], create(&['A', 'B', 'C'])); + b.op(1, 'C', &[0], remove('B')); + b.op(2, 'C', &[1], add('B', Access::manage())); + b.op(3, 'A', &[0], remove('B')); + check( + "5 concurrent re-add", + &b.steps, + &[(0, true), (1, true), (2, false), (3, true)], + &['A', 'C'], + ); +} + +#[test] +fn test_s2_re_add_concurrent_with_another_managers_removal_is_voided() { + // Alice removes and re-adds Bob. Claire removes Bob concurrently. + let mut b = Builder::default(); + b.op(0, 'A', &[], create(&['A', 'B', 'C'])); + b.op(1, 'A', &[0], remove('B')); + b.op(2, 'A', &[1], add('B', Access::manage())); + b.op(3, 'C', &[0], remove('B')); + check( + "5c re-add beside another manager's removal", + &b.steps, + &[(0, true), (1, true), (2, false), (3, true)], + &['A', 'C'], + ); +} + +#[test] +fn test_s2_causal_re_add_control_stands() { + // Claire re-adds Bob after she has seen Alice's removal. + let mut b = Builder::default(); + b.op(0, 'A', &[], create(&['A', 'B', 'C'])); + b.op(1, 'A', &[0], remove('B')); + b.op(2, 'C', &[1], add('B', Access::manage())); + check( + "5b causal re-add", + &b.steps, + &[(0, true), (1, true), (2, true)], + &['A', 'B', 'C'], + ); +} + +#[test] +fn test_s2_a_fork_free_chain_is_not_voided_by_a_removal_of_another_author() { + // Regression for the Phase 1 cascade: a removal voids only the removed member's concurrent + // operations. Claire's add after Alice's add is honest and stands. + let mut b = Builder::default(); + b.op(0, 'A', &[], create(&['A', 'B', 'C'])); + b.op(1, 'A', &[0], add('D', Access::read())); + b.op(2, 'B', &[0], remove('C')); + b.op(3, 'A', &[1], add('E', Access::read())); + check( + "honest dependents apply", + &b.steps, + &[(0, true), (1, true), (2, true), (3, true)], + &['A', 'B', 'D', 'E'], + ); +} + +#[test] +fn test_a_voided_event_does_not_stall_its_author() { + // Regression: a voided event stays stored, so its author's next event links to it. Bob's add is + // concurrent with Alice's removal of him, so it is voided. Bob's content after it is kept, + // because it names only the create, which applies. + let mut b = Builder::default(); + b.op(0, 'A', &[], create(&['A', 'B', 'C'])); + b.op(1, 'A', &[0], remove('B')); + b.op(2, 'B', &[0], add('D', Access::manage())); + b.content(3, 'B', &[0]); + check( + "a voided predecessor does not hold the author's next event", + &b.steps, + &[(0, true), (1, true), (2, false), (3, true)], + &['A', 'C'], + ); +} From 16cddd7767411fca1701446de864ef93d35e9c3d Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 12 Oct 2026 00:47:00 -0500 Subject: [PATCH 21/40] test(rust): arrival-order property for authority voiding [P2.3] Random scenarios of group creates, adds, removes and content, each naming random earlier events, are delivered in causal order and in shuffled arrival orders. Every order must reach the same applied set and roster, and none may leave an event waiting or refuse one. --- pkgs/id/tests/voiding_properties.rs | 239 ++++++++++++++++++++++++++++ 1 file changed, 239 insertions(+) create mode 100644 pkgs/id/tests/voiding_properties.rs diff --git a/pkgs/id/tests/voiding_properties.rs b/pkgs/id/tests/voiding_properties.rs new file mode 100644 index 0000000000..b11a598065 --- /dev/null +++ b/pkgs/id/tests/voiding_properties.rs @@ -0,0 +1,239 @@ +//! Authority-based voiding over random scenarios (P2.3). +//! +//! A scenario is a seeded set of signed events: a group create, then group operations (adds and +//! removes of random keys) and content, each naming a random set of earlier events in `after`. +//! Each scenario is delivered to a fresh store in its causal order and in several random arrival +//! orders. Every order must reach the same applied set and roster, and no order may leave an event +//! waiting: a voided event stays stored, so its author's later events still link to it. + +#![allow(clippy::unwrap_used, clippy::expect_used)] + +use std::collections::BTreeMap; + +use id::chain::{ChainExt, sign}; +use id::event_store::{EventStore, Ingest}; +use id::membership::AuthId; +use id::waiting::WaitingLimits; +use p2panda_auth::Access; +use p2panda_auth::group::{GroupAction, GroupMember}; +use p2panda_core::{Hash, SeqNum, SigningKey}; +use proptest::prelude::*; +use proptest::test_runner::TestCaseError; + +/// Arrival orders checked per scenario, besides the causal order. +const ORDERS: usize = 4; + +/// The authors of a scenario. The first one creates the group. +const WHO: [char; 4] = ['A', 'B', 'C', 'D']; + +/// `SplitMix64`. A scenario is a pure function of its seed. +struct Rng(u64); + +impl Rng { + const fn next_u64(&mut self) -> u64 { + self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15); + let mut z = self.0; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) + } + + /// A number in `0..n`. + fn below(&mut self, n: usize) -> usize { + let n = u64::try_from(n).expect("a small bound"); + usize::try_from(self.next_u64() % n).expect("an index fits in usize") + } +} + +/// Cases per property. `PROPTEST_CASES` raises it. +fn config() -> ProptestConfig { + let cases = std::env::var("PROPTEST_CASES") + .ok() + .and_then(|value| value.parse().ok()) + .unwrap_or(16); + ProptestConfig { + cases, + failure_persistence: None, + ..ProptestConfig::default() + } +} + +/// One signed event of a scenario, with its membership action when it is a group operation. +#[derive(Clone)] +struct Step { + id: Hash, + bytes: Vec, + action: Option>, +} + +fn key(who: char) -> SigningKey { + SigningKey::from_bytes(&[who as u8; 32]) +} + +fn auth(who: char) -> AuthId { + AuthId::Key(*key(who).verifying_key().as_bytes()) +} + +/// A random scenario of 4 to 10 events. Event 0 creates the group with A, B and C as managers. +/// Each later event is signed by a random author, names up to three random earlier events, and is +/// an add, a remove, or content. Each author's events form a chain, so the sequence numbers and +/// backlinks follow from the order of signing. +fn scenario(seed: u64) -> Vec { + let mut rng = Rng(seed); + let size = 4 + rng.below(7); + let mut steps: Vec = Vec::new(); + let mut group: Option = None; + let mut last: BTreeMap = BTreeMap::new(); + for index in 0..size { + let who = if index == 0 { + 'A' + } else { + WHO[rng.below(WHO.len())] + }; + let action = if index == 0 { + Some(GroupAction::Create { + initial_members: ['A', 'B', 'C'] + .iter() + .map(|m| (GroupMember::Individual(auth(*m)), Access::manage())) + .collect(), + }) + } else { + match rng.below(100) { + 0..35 => { + let access = if rng.below(2) == 0 { + Access::read() + } else { + Access::manage() + }; + Some(GroupAction::Add { + member: GroupMember::Individual(auth(WHO[rng.below(WHO.len())])), + access, + }) + } + 35..70 => Some(GroupAction::Remove { + member: GroupMember::Individual(auth(WHO[rng.below(WHO.len())])), + }), + _ => None, + } + }; + + let mut after = Vec::new(); + let named = if steps.is_empty() { 0 } else { rng.below(4) }; + for _ in 0..named { + let pick = steps[rng.below(steps.len())].id; + if !after.contains(&pick) { + after.push(pick); + } + } + + let (seq, backlink) = match last.get(&who) { + Some((seq, hash)) => (seq + 1, Some(*hash)), + None => (0, None), + }; + let ext = ChainExt { + kind: if action.is_some() { + "group.op" + } else { + "message" + } + .to_owned(), + group: if index == 0 { None } else { group }, + after, + }; + let event = sign(&key(who), seq, backlink, None, ext).unwrap(); + if index == 0 { + group = Some(event.id); + } + last.insert(who, (seq, event.id)); + steps.push(Step { + id: event.id, + bytes: event.bytes, + action, + }); + } + steps +} + +/// The result of one arrival order: which events applied, and the group's roster. +#[derive(Debug, PartialEq, Eq)] +struct Final { + applied: Vec, + roster: Vec, +} + +/// Delivers the scenario in `order` to a fresh store. Every event must be stored and none may be +/// refused or left waiting. +fn deliver(steps: &[Step], order: &[usize]) -> Result { + let dir = tempfile::tempdir().map_err(|err| err.to_string())?; + let mut store = + EventStore::open(dir.path(), WaitingLimits::default(), 0).map_err(|err| err.to_string())?; + for &index in order { + let step = &steps[index]; + let outcome = store + .ingest_with_action(&step.bytes, step.action.as_ref(), 0) + .map_err(|err| err.to_string())?; + if matches!(outcome, Ingest::Refused(_)) { + return Err(format!("event {index} was refused: {outcome:?}")); + } + } + let waiting = store.waiting_ids().map_err(|err| err.to_string())?; + if !waiting.is_empty() { + return Err(format!( + "order {order:?} leaves {} events waiting", + waiting.len() + )); + } + for (index, step) in steps.iter().enumerate() { + let stored = store + .event_by_id(&step.id) + .map_err(|err| err.to_string())? + .is_some(); + if !stored { + return Err(format!("order {order:?} never stored event {index}")); + } + } + let mut applied = Vec::new(); + for step in steps { + applied.push( + store + .event_applied(&step.id) + .map_err(|err| err.to_string())?, + ); + } + let mut roster: Vec = store + .roster(&steps[0].id) + .map_err(|err| err.to_string())? + .into_iter() + .map(AuthId::Key) + .collect(); + roster.sort(); + Ok(Final { applied, roster }) +} + +/// A random permutation of `0..n`, by Fisher-Yates. +fn shuffled(n: usize, rng: &mut Rng) -> Vec { + let mut order: Vec = (0..n).collect(); + for i in (1..n).rev() { + order.swap(i, rng.below(i + 1)); + } + order +} + +proptest! { + #![proptest_config(config())] + + /// Random removals, adds and dependent chains give the same applied set and roster in every + /// arrival order, and no order leaves an event waiting. + #[test] + fn test_authority_voiding_is_the_same_for_every_arrival_order(seed in any::()) { + let steps = scenario(seed); + let causal: Vec = (0..steps.len()).collect(); + let reference = deliver(&steps, &causal).map_err(TestCaseError::fail)?; + let mut rng = Rng(seed ^ 0xA5A5_5A5A_F00D_BEEF); + for _ in 0..ORDERS { + let order = shuffled(steps.len(), &mut rng); + let outcome = deliver(&steps, &order).map_err(TestCaseError::fail)?; + prop_assert_eq!(&outcome, &reference, "arrival order {:?}", order); + } + } +} From 240387806313ed514454388b243f0de0f1298ef8 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 12 Oct 2026 01:07:29 -0500 Subject: [PATCH 22/40] feat(rust): group action body codec [P2.3] A group operation body is the canonical CBOR array ["group.op", 1, kind, args]. Kinds: create, join (Add), remove, promote, demote. A body that does not start with the claim is content; a claimed body must decode or it is refused. --- pkgs/id/src/membership/body.rs | 635 +++++++++++++++++++++++++++++++++ pkgs/id/src/membership/mod.rs | 1 + 2 files changed, 636 insertions(+) create mode 100644 pkgs/id/src/membership/body.rs diff --git a/pkgs/id/src/membership/body.rs b/pkgs/id/src/membership/body.rs new file mode 100644 index 0000000000..9db9cd8591 --- /dev/null +++ b/pkgs/id/src/membership/body.rs @@ -0,0 +1,635 @@ +//! The body of a group operation: how a membership change travels in an event's body (P2.3). +//! +//! An event's header commits to its body through `payload_hash` and `payload_size`. A body is a +//! group operation when it starts with the bytes of [`CLAIM`]. Such a body is the canonical CBOR +//! array +//! +//! ```text +//! ["group.op", version, kind, args] +//! ``` +//! +//! where `version` is [`VERSION`] and `kind` and `args` are: +//! +//! | `kind` | `args` | [`GroupAction`] | +//! |-----------|-----------------------------------|-------------------| +//! | `create` | array of `[member, access]` pairs | `Create` | +//! | `join` | `[member, access]` | `Add` | +//! | `remove` | `[member]` | `Remove` | +//! | `promote` | `[member, access]` | `Promote` | +//! | `demote` | `[member, access]` | `Demote` | +//! +//! A member is `[kind, id]`: kind `0` is an individual and `1` a group. An `id` is a 33-byte +//! string: a tag byte (`0` for a key, `1` for a group hash), then the 32 bytes. An access is its +//! level as an unsigned integer: `0` pull, `1` read, `2` write, `3` manage. Access conditions are +//! not encoded, so [`encode_body`] refuses an access that has them. +//! +//! [`decode_body`] has two outcomes for a body that starts with [`CLAIM`]: it decodes, or it is +//! refused. A body that does not start with it is not a group operation, and it is content. +//! Friendship and group policy have no [`GroupAction`] form, so they are not encoded here. + +use cbor_core::{DecodeOptions, Strictness, Value}; +use p2panda_auth::group::{GroupAction, GroupMember}; +use p2panda_auth::{Access, AccessLevel}; +use p2panda_core::Hash; + +use super::AuthId; + +/// The text that opens a group operation body. It names the format, as an event's kind does. +pub const TAG: &str = "group.op"; + +/// The version of the body format this code writes and reads. +pub const VERSION: u64 = 1; + +/// The most bytes a group operation body may have. +pub const MAX_BODY_BYTES: usize = 16 * 1024; + +/// The most members a `create` may list. +pub const MAX_CREATE_MEMBERS: usize = 256; + +/// The first bytes of every group operation body: an array of four items, then [`TAG`] as a text +/// string. A body that starts with these bytes claims to be a group operation. +pub const CLAIM: &[u8] = b"\x84\x68group.op"; + +/// Nesting limit for a body's CBOR. Matches the limit the header decoder uses. +const RECURSION_LIMIT: u16 = 8; + +/// Declared element limit for one array. Matches the header decoder. +const LENGTH_LIMIT: u64 = 512; + +/// Byte budget for speculative pre-allocation. Matches the header decoder. +const OOM_MITIGATION: usize = 64; + +/// Why a body that claims to be a group operation was refused, or why one could not be encoded. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum BodyError { + /// The body is longer than [`MAX_BODY_BYTES`]. + #[error("a group operation body is {0} bytes, the most allowed is {max}", max = MAX_BODY_BYTES)] + Oversized(usize), + /// The bytes are CBOR that strict decoding refuses. This includes a truncated body. + #[error("the group operation body is not CBOR: {0}")] + Cbor(String), + /// The bytes decode, but they are not the canonical encoding of the value they hold. + #[error("the group operation body is not canonical CBOR")] + NotCanonical, + /// The version is not [`VERSION`]. + #[error("the group operation body has version {0}, this code reads version {v}", v = VERSION)] + Version(u64), + /// The kind is not one of the kinds in the module table. + #[error("the group operation kind {0:?} is unknown")] + Kind(String), + /// The body has the wrong shape for its kind: a missing item, an extra one, or a value of the + /// wrong type or range. + #[error("the group operation body has the wrong shape: {0}")] + Shape(String), + /// The action cannot be encoded: it has access conditions, or too many create members. + #[error("the group action cannot be encoded: {0}")] + Unencodable(String), +} + +/// Encodes a group action as a group operation body. +/// +/// # Errors +/// +/// Returns [`BodyError::Unencodable`] for an access with conditions or a create with more than +/// [`MAX_CREATE_MEMBERS`] members, and [`BodyError::Oversized`] when the encoding is longer than +/// [`MAX_BODY_BYTES`]. +pub fn encode_body(action: &GroupAction) -> Result, BodyError> { + let (kind, args) = match action { + GroupAction::Create { initial_members } => { + if initial_members.len() > MAX_CREATE_MEMBERS { + return Err(BodyError::Unencodable(format!( + "{} members, the most is {MAX_CREATE_MEMBERS}", + initial_members.len() + ))); + } + let pairs = initial_members + .iter() + .map(|(member, access)| member_and_access(member, access)) + .collect::, _>>()?; + ("create", Value::Array(pairs)) + } + GroupAction::Add { member, access } => ("join", member_and_access(member, access)?), + GroupAction::Remove { member } => ("remove", Value::Array(vec![member_value(member)])), + GroupAction::Promote { member, access } => ("promote", member_and_access(member, access)?), + GroupAction::Demote { member, access } => ("demote", member_and_access(member, access)?), + }; + let body = Value::Array(vec![ + Value::TextString(TAG.into()), + Value::Unsigned(VERSION), + Value::TextString(kind.into()), + args, + ]) + .encode(); + if body.len() > MAX_BODY_BYTES { + return Err(BodyError::Oversized(body.len())); + } + Ok(body) +} + +/// Decodes a body as a group action. +/// +/// Returns `Ok(None)` when the body does not start with [`CLAIM`]: it is content, and not a group +/// operation. Returns `Ok(Some(action))` for a body that decodes, and an error for one that claims +/// to be a group operation and does not decode. +/// +/// # Errors +/// +/// Returns the reason a claimed body was refused. See [`BodyError`]. +pub fn decode_body(body: &[u8]) -> Result>, BodyError> { + if !body.starts_with(CLAIM) { + return Ok(None); + } + if body.len() > MAX_BODY_BYTES { + return Err(BodyError::Oversized(body.len())); + } + let value = DecodeOptions::new() + .strictness(Strictness::STRICT) + .recursion_limit(RECURSION_LIMIT) + .length_limit(LENGTH_LIMIT) + .oom_mitigation(OOM_MITIGATION) + .decode_owned(body) + .map_err(|err| BodyError::Cbor(err.to_string()))?; + if value.encode().as_slice() != body { + return Err(BodyError::NotCanonical); + } + let [_tag, version, kind, args] = list(&value, 4)? else { + return Err(BodyError::Shape( + "a group operation has four items".to_owned(), + )); + }; + let version = unsigned(version)?; + if version != VERSION { + return Err(BodyError::Version(version)); + } + let Value::TextString(kind) = kind else { + return Err(BodyError::Shape("the kind is not text".to_owned())); + }; + decode_kind(kind, args).map(Some) +} + +/// The `[member, access]` pair of an action with one member and one access. +fn member_and_access( + member: &GroupMember, + access: &Access<()>, +) -> Result, BodyError> { + Ok(Value::Array(vec![ + member_value(member), + access_value(access)?, + ])) +} + +/// `[kind, id]` for a member: kind `0` is an individual, `1` a group. +fn member_value(member: &GroupMember) -> Value<'static> { + let (kind, id) = match member { + GroupMember::Individual(id) => (0, id), + GroupMember::Group(id) => (1, id), + }; + Value::Array(vec![ + Value::Unsigned(kind), + Value::ByteString(auth_bytes(id).into()), + ]) +} + +/// The 33 bytes of an identity: a tag byte, then the key or the group hash. +fn auth_bytes(id: &AuthId) -> Vec { + let (tag, bytes) = match id { + AuthId::Key(key) => (0, key), + AuthId::Group(hash) => (1, hash.as_bytes()), + }; + let mut out = Vec::with_capacity(33); + out.push(tag); + out.extend_from_slice(bytes); + out +} + +/// The level of an access, as its unsigned integer. Refuses conditions. +fn access_value(access: &Access<()>) -> Result, BodyError> { + if access.conditions.is_some() { + return Err(BodyError::Unencodable( + "an access with conditions".to_owned(), + )); + } + let level = match access.level { + AccessLevel::Pull => 0, + AccessLevel::Read => 1, + AccessLevel::Write => 2, + AccessLevel::Manage => 3, + }; + Ok(Value::Unsigned(level)) +} + +/// Decodes the args of one kind. The kind table is the one in the module docs. +fn decode_kind(kind: &str, args: &Value<'static>) -> Result, BodyError> { + match kind { + "create" => { + let pairs = args + .as_array() + .map_err(|_err| BodyError::Shape("create takes a list of pairs".to_owned()))?; + if pairs.len() > MAX_CREATE_MEMBERS { + return Err(BodyError::Shape(format!( + "{} members, the most is {MAX_CREATE_MEMBERS}", + pairs.len() + ))); + } + let initial_members = pairs + .iter() + .map(|pair| { + let [member, access] = list(pair, 2)? else { + return Err(BodyError::Shape("a member pair has two items".to_owned())); + }; + Ok((decode_member(member)?, decode_access(access)?)) + }) + .collect::, BodyError>>()?; + Ok(GroupAction::Create { initial_members }) + } + "join" | "promote" | "demote" => { + let [member, access] = list(args, 2)? else { + return Err(BodyError::Shape(format!( + "{kind} takes a member and an access" + ))); + }; + let member = decode_member(member)?; + let access = decode_access(access)?; + Ok(match kind { + "join" => GroupAction::Add { member, access }, + "promote" => GroupAction::Promote { member, access }, + _ => GroupAction::Demote { member, access }, + }) + } + "remove" => { + let [member] = list(args, 1)? else { + return Err(BodyError::Shape("remove takes one member".to_owned())); + }; + Ok(GroupAction::Remove { + member: decode_member(member)?, + }) + } + other => Err(BodyError::Kind(other.to_owned())), + } +} + +/// `[kind, id]` back to a member. +fn decode_member(value: &Value<'static>) -> Result, BodyError> { + let [kind, id] = list(value, 2)? else { + return Err(BodyError::Shape("a member has two items".to_owned())); + }; + let id = decode_auth(id)?; + match unsigned(kind)? { + 0 => Ok(GroupMember::Individual(id)), + 1 => Ok(GroupMember::Group(id)), + other => Err(BodyError::Shape(format!("member kind {other}"))), + } +} + +/// A 33-byte identity back to a key or a group. +fn decode_auth(value: &Value<'static>) -> Result { + let Value::ByteString(bytes) = value else { + return Err(BodyError::Shape("an identity is a byte string".to_owned())); + }; + let bytes: &[u8] = bytes; + let Some((&tag, rest)) = bytes.split_first() else { + return Err(BodyError::Shape("an identity is empty".to_owned())); + }; + let Ok(id) = <[u8; 32]>::try_from(rest) else { + return Err(BodyError::Shape(format!( + "an identity is {} bytes, it must be 33", + bytes.len() + ))); + }; + match tag { + 0 => Ok(AuthId::Key(id)), + 1 => Ok(AuthId::Group(Hash::from(id))), + other => Err(BodyError::Shape(format!("identity tag {other}"))), + } +} + +/// An access level back to an access with no conditions. +fn decode_access(value: &Value<'static>) -> Result, BodyError> { + match unsigned(value)? { + 0 => Ok(Access::pull()), + 1 => Ok(Access::read()), + 2 => Ok(Access::write()), + 3 => Ok(Access::manage()), + other => Err(BodyError::Shape(format!("access level {other}"))), + } +} + +/// The items of an array of exactly `len` items. +fn list<'a>(value: &'a Value<'static>, len: usize) -> Result<&'a [Value<'static>], BodyError> { + match value.as_array() { + Ok(items) if items.len() == len => Ok(items), + _ => Err(BodyError::Shape(format!( + "expected an array of {len} items" + ))), + } +} + +/// An unsigned integer. +fn unsigned(value: &Value<'static>) -> Result { + match value { + Value::Unsigned(number) => Ok(*number), + _ => Err(BodyError::Shape("expected an unsigned integer".to_owned())), + } +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used)] +mod tests { + use std::collections::BTreeMap; + + use super::*; + use p2panda_core::SigningKey; + + fn key(who: u8) -> AuthId { + let signing = SigningKey::from_bytes(&[who; 32]); + AuthId::Key(*signing.verifying_key().as_bytes()) + } + + fn individual(who: u8) -> GroupMember { + GroupMember::Individual(key(who)) + } + + /// One action of every kind, with every access level and both member kinds in use. + fn every_kind() -> Vec> { + let group = AuthId::Group(Hash::digest(b"a group")); + vec![ + GroupAction::Create { + initial_members: vec![ + (individual(1), Access::manage()), + (individual(2), Access::write()), + (GroupMember::Group(group), Access::read()), + ], + }, + GroupAction::Create { + initial_members: Vec::new(), + }, + GroupAction::Add { + member: individual(3), + access: Access::pull(), + }, + GroupAction::Remove { + member: individual(4), + }, + GroupAction::Remove { + member: GroupMember::Group(group), + }, + GroupAction::Promote { + member: individual(5), + access: Access::manage(), + }, + GroupAction::Demote { + member: individual(6), + access: Access::read(), + }, + ] + } + + /// The bytes of a valid `remove` body with one key member. + fn remove_body() -> Vec { + encode_body(&GroupAction::Remove { + member: individual(9), + }) + .unwrap() + } + + #[test] + fn test_every_kind_round_trips() { + for action in every_kind() { + let body = encode_body(&action).unwrap(); + assert!(body.starts_with(CLAIM), "the claim opens every body"); + assert_eq!(decode_body(&body).unwrap(), Some(action.clone())); + // Canonical: encoding the decoded action gives the same bytes. + let decoded = decode_body(&body).unwrap().unwrap(); + assert_eq!(encode_body(&decoded).unwrap(), body); + } + } + + #[test] + fn test_the_claim_is_the_encoded_tag() { + let tag = Value::TextString(TAG.into()).encode(); + assert_eq!(&CLAIM[1..], tag.as_slice()); + assert_eq!(CLAIM[0], 0x84, "an array of four items"); + } + + #[test] + fn test_a_body_that_is_not_a_group_operation_is_content() { + let bodies: [&[u8]; 3] = [b"", b"hello", &[0x84, 0x01, 0x02, 0x03, 0x04]]; + for body in bodies { + assert_eq!(decode_body(body).unwrap(), None, "{body:?} is content"); + } + // A map of the same shape as a content body, with no claim. + let content = Value::Map(BTreeMap::from([( + Value::TextString("kind".into()), + Value::TextString("message".into()), + )])) + .encode(); + assert_eq!(decode_body(&content).unwrap(), None); + } + + #[test] + fn test_a_truncated_body_is_refused() { + // Every proper prefix that still carries the claim must be refused, not decoded. + let body = encode_body(&every_kind()[0]).unwrap(); + for cut in CLAIM.len()..body.len() { + assert!( + decode_body(&body[..cut]).is_err(), + "a body cut at {cut} of {} is refused", + body.len() + ); + } + } + + #[test] + fn test_a_wrong_version_is_refused() { + let body = Value::Array(vec![ + Value::TextString(TAG.into()), + Value::Unsigned(VERSION + 1), + Value::TextString("remove".into()), + Value::Array(vec![Value::Array(vec![ + Value::Unsigned(0), + Value::ByteString(auth_bytes(&key(9)).into()), + ])]), + ]) + .encode(); + assert_eq!(decode_body(&body), Err(BodyError::Version(VERSION + 1))); + } + + #[test] + fn test_an_unknown_kind_is_refused() { + let body = Value::Array(vec![ + Value::TextString(TAG.into()), + Value::Unsigned(VERSION), + Value::TextString("friend.request".into()), + Value::Array(Vec::new()), + ]) + .encode(); + assert_eq!( + decode_body(&body), + Err(BodyError::Kind("friend.request".to_owned())) + ); + } + + #[test] + fn test_an_oversized_body_is_refused() { + let body = [CLAIM, &vec![0u8; MAX_BODY_BYTES]].concat(); + assert!(matches!(decode_body(&body), Err(BodyError::Oversized(_)))); + } + + #[test] + fn test_a_create_with_too_many_members_is_refused_both_ways() { + let members: Vec<(GroupMember, Access<()>)> = (0..=MAX_CREATE_MEMBERS) + .map(|who| (individual(u8::try_from(who % 200).unwrap()), Access::read())) + .collect(); + let action = GroupAction::Create { + initial_members: members, + }; + assert!(matches!( + encode_body(&action), + Err(BodyError::Unencodable(_)) + )); + // A body that lists them anyway is refused as a shape. + let pair = Value::Array(vec![ + Value::Array(vec![ + Value::Unsigned(0), + Value::ByteString(auth_bytes(&key(1)).into()), + ]), + Value::Unsigned(1), + ]); + let body = Value::Array(vec![ + Value::TextString(TAG.into()), + Value::Unsigned(VERSION), + Value::TextString("create".into()), + Value::Array(vec![pair; MAX_CREATE_MEMBERS + 1]), + ]) + .encode(); + assert!(matches!(decode_body(&body), Err(BodyError::Shape(_)))); + } + + #[test] + fn test_an_access_with_conditions_is_not_encoded() { + let action = GroupAction::Add { + member: individual(1), + access: Access { + conditions: Some(()), + level: AccessLevel::Read, + }, + }; + assert!(matches!( + encode_body(&action), + Err(BodyError::Unencodable(_)) + )); + } + + #[test] + fn test_a_non_canonical_body_is_refused() { + // The version 1 written as two bytes (0x18 0x01) instead of one. The value is the same, + // so only the canonical check refuses it. + let body = remove_body(); + let mut padded = body[..CLAIM.len()].to_vec(); + padded.extend_from_slice(&[0x18, 0x01]); + padded.extend_from_slice(&body[CLAIM.len() + 1..]); + assert!(decode_body(&padded).is_err()); + } + + #[test] + fn test_a_malformed_member_is_refused() { + let tagged = |tag: u8, len: usize| { + let mut id = vec![tag]; + id.extend(std::iter::repeat_n(7u8, len)); + Value::Array(vec![ + Value::TextString(TAG.into()), + Value::Unsigned(VERSION), + Value::TextString("remove".into()), + Value::Array(vec![Value::Array(vec![ + Value::Unsigned(0), + Value::ByteString(id.into()), + ])]), + ]) + .encode() + }; + // `tagged(tag, len)` is the tag byte plus `len` bytes: 33 bytes is the identity length. + assert!( + decode_body(&tagged(0, 31)).is_err(), + "32 bytes is too short" + ); + assert!( + decode_body(&tagged(0, 32)).is_ok(), + "33 bytes is an identity" + ); + assert!( + decode_body(&tagged(2, 32)).is_err(), + "tag 2 is not an identity" + ); + assert!(decode_body(&tagged(0, 33)).is_err(), "34 bytes is too long"); + } + + #[test] + fn test_a_wrong_shape_is_refused() { + let with_args = |kind: &str, args: Value<'static>| { + Value::Array(vec![ + Value::TextString(TAG.into()), + Value::Unsigned(VERSION), + Value::TextString(kind.into()), + args, + ]) + .encode() + }; + let member = Value::Array(vec![ + Value::Unsigned(0), + Value::ByteString(auth_bytes(&key(1)).into()), + ]); + let read = Value::Unsigned(1); + // A join needs a member and an access, so one item is missing and three is one too many. + assert!(decode_body(&with_args("join", Value::Array(vec![member.clone()]))).is_err()); + assert!( + decode_body(&with_args( + "join", + Value::Array(vec![member.clone(), read.clone(), read.clone()]) + )) + .is_err() + ); + // A remove with an access is one item too many. + assert!( + decode_body(&with_args( + "remove", + Value::Array(vec![member.clone(), read.clone()]) + )) + .is_err() + ); + // An access level outside 0 to 3, and a member kind outside 0 and 1. + assert!( + decode_body(&with_args( + "join", + Value::Array(vec![member.clone(), Value::Unsigned(4)]) + )) + .is_err() + ); + let bad_kind = Value::Array(vec![ + Value::Unsigned(2), + Value::ByteString(auth_bytes(&key(1)).into()), + ]); + assert!(decode_body(&with_args("remove", Value::Array(vec![bad_kind]))).is_err()); + // An array of two has no claim, so it is content, whatever its items are. + let short = Value::Array(vec![ + Value::TextString(TAG.into()), + Value::Unsigned(VERSION), + ]) + .encode(); + assert_eq!(decode_body(&short).unwrap(), None); + } + + #[test] + fn test_no_single_byte_change_panics() { + // Every single-byte change of a valid body decodes or is refused. None panics. + for action in every_kind() { + let body = encode_body(&action).unwrap(); + for index in 0..body.len() { + for flip in [0x01, 0x80, 0xFF] { + let mut changed = body.clone(); + changed[index] ^= flip; + let _ = decode_body(&changed); + } + } + } + } +} diff --git a/pkgs/id/src/membership/mod.rs b/pkgs/id/src/membership/mod.rs index bf744c76da..a13b24fcda 100644 --- a/pkgs/id/src/membership/mod.rs +++ b/pkgs/id/src/membership/mod.rs @@ -17,6 +17,7 @@ //! The layer takes events that the caller has already verified (signature, encoding, and //! `after` closure are the event store's job). It does not read the event store itself. +pub mod body; pub mod frontier; pub mod gate; pub mod layer; From 0af8c45effe85163166d096366c3bb3f17c7a69e Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 12 Oct 2026 01:13:03 -0500 Subject: [PATCH 23/40] docs(id): owner answers on aliases --- .../2026-10-11T11-08-42Z_design_remaining_work.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/doc/2026-10-11T11-08-42Z_design_remaining_work/2026-10-11T11-08-42Z_design_remaining_work.md b/doc/2026-10-11T11-08-42Z_design_remaining_work/2026-10-11T11-08-42Z_design_remaining_work.md index d1e1c25981..b73b0d5b5d 100644 --- a/doc/2026-10-11T11-08-42Z_design_remaining_work/2026-10-11T11-08-42Z_design_remaining_work.md +++ b/doc/2026-10-11T11-08-42Z_design_remaining_work/2026-10-11T11-08-42Z_design_remaining_work.md @@ -225,3 +225,10 @@ Open for the owner: 2. Server alias fallback: confirm that it shows only until the server sets its primary alias. 3. Show the user alias by default, or only the name? 4. Prefix or suffix for disambiguation: prefix (recommended), since prefixes sort and match like git short IDs. + +## Owner answers on aliases (2026-10-12) + +- User tag subject: the user's first identity event ID (decided). +- Server alias: a server alias wins for a single displayed value, unless a user sets their own alias (a pet name). Larger views show the winning primary, plus the server's alias and other aliases sorted or selected, for example the user's or group's chosen alias, or the earliest alias. +- User alias: shown by default, with the name. In many views include the shortest unique prefix of the object's ID, to identify it on that server. +- Disambiguation: prefix, like git short IDs (decided). From 4e308e8a5740698bd55044cec7c3da444aa5cabd Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 12 Oct 2026 01:29:32 -0500 Subject: [PATCH 24/40] fix(rust): group actions reach production ingest [P2.3] SharedEventStore::ingest takes the event's body. The body is checked against the header's payload hash and size, and a group operation body decodes to its action, which goes through the same transaction as ingest_with_action. A body that claims to be a group operation and does not decode is refused. Other bodies, and no body, are content. The S2 scenarios run on the production path as well, and every arrival order of the random scenarios is checked there. --- pkgs/id/src/event_store/ingest.rs | 65 +++++- pkgs/id/src/store_traits.rs | 29 ++- pkgs/id/tests/production_ingest.rs | 326 ++++++++++++++++++++++++++++ pkgs/id/tests/voiding_properties.rs | 65 +++++- pkgs/id/tests/voiding_scenarios.rs | 62 ++++-- 5 files changed, 509 insertions(+), 38 deletions(-) create mode 100644 pkgs/id/tests/production_ingest.rs diff --git a/pkgs/id/src/event_store/ingest.rs b/pkgs/id/src/event_store/ingest.rs index d7ccd50177..ca1d2fcc58 100644 --- a/pkgs/id/src/event_store/ingest.rs +++ b/pkgs/id/src/event_store/ingest.rs @@ -82,6 +82,7 @@ use super::{ }; use crate::chain::{self, Event}; use crate::membership::AuthId; +use crate::membership::body::decode_body; use crate::waiting::{AuthorKey, WaitingPool}; /// Why an event was refused. A refused event changes nothing. @@ -178,10 +179,38 @@ impl EventStore { self.ingest_with_action(bytes, None, now_ms) } + /// Verifies one received event with its body, and applies what it allows. This is the + /// production path. The membership action comes from the body, by the body codec in + /// [`crate::membership::body`]: + /// + /// - A body that is not a group operation, or no body at all, makes the event content. + /// - A body that claims to be a group operation decodes to its action, or it is refused. + /// - A body that is not the one the header commits to, by BLAKE3 hash and size, is refused. + /// + /// # Errors + /// + /// Returns a redb or corruption error, as [`EventStore::ingest`] does. + pub fn ingest_with_body( + &mut self, + bytes: &[u8], + body: Option<&[u8]>, + now_ms: u64, + ) -> Result { + let event = match chain::decode(bytes) { + Ok(event) => event, + Err(err) => return Ok(Ingest::Refused(Refusal::Malformed(err.to_string()))), + }; + let action = match body_action(&event, body) { + Ok(action) => action, + Err(refusal) => return Ok(Ingest::Refused(refusal)), + }; + self.ingest_event(event, action.as_ref(), now_ms) + } + /// Verifies one received event, which may be a group operation, and applies what it allows. - /// `action` is the membership change of a group operation. The caller has read it from the - /// event's body and checked the body against the event's payload hash. The store does not read - /// bodies. Other events take no action. + /// `action` is the membership change of a group operation, handed in by the caller. The store + /// does not read bodies here. Other events take no action. The production path is + /// [`EventStore::ingest_with_body`], and the scenario tests use this one. /// /// # Errors /// @@ -196,6 +225,16 @@ impl EventStore { Ok(event) => event, Err(err) => return Ok(Ingest::Refused(Refusal::Malformed(err.to_string()))), }; + self.ingest_event(event, action, now_ms) + } + + /// Runs a decoded event through the store's transaction, with its action. + fn ingest_event( + &mut self, + event: Event, + action: Option<&GroupAction>, + now_ms: u64, + ) -> Result { self.transact(now_ms, |mirror| ingest_in(mirror, event, action, now_ms)) } @@ -227,6 +266,26 @@ impl EventStore { } } +/// The membership action an event's body carries. `Ok(None)` makes the event content: it has no +/// body, or its body is not a group operation. A body that is not the one the header commits to is +/// refused, and so is a body that claims to be a group operation and does not decode. +fn body_action( + event: &Event, + body: Option<&[u8]>, +) -> Result>, Refusal> { + let Some(body) = body else { + return Ok(None); + }; + let committed = event.header.payload_hash == Some(Hash::digest(body)) + && u32::try_from(body.len()).is_ok_and(|len| len == event.header.payload_size); + if !committed { + return Err(Refusal::Malformed( + "the body is not the one the header commits to, by hash and size".to_owned(), + )); + } + decode_body(body).map_err(|err| Refusal::Malformed(err.to_string())) +} + /// Decides a received event inside the call's transaction, and the events it releases. Returns /// the outcome, and whether the call changed anything. A call that expired events has changed /// something, even if its own event was refused. diff --git a/pkgs/id/src/store_traits.rs b/pkgs/id/src/store_traits.rs index 2cd192cc61..cfca8a87bb 100644 --- a/pkgs/id/src/store_traits.rs +++ b/pkgs/id/src/store_traits.rs @@ -96,18 +96,25 @@ impl SharedEventStore { } } - /// Verifies and applies one received event. See [`EventStore::ingest`]. + /// Verifies and applies one received event, with its body. `body` is the bytes the header + /// commits to, or `None` when the event arrived without one. The action of a group operation + /// comes from the body. See [`EventStore::ingest_with_body`]. /// /// # Errors /// /// Returns [`TraitStoreError::Store`] for a redb or corruption error, and /// [`TraitStoreError::Poisoned`] if another thread panicked while it held the lock. - pub fn ingest(&self, bytes: &[u8], now_ms: u64) -> Result { + pub fn ingest( + &self, + bytes: &[u8], + body: Option<&[u8]>, + now_ms: u64, + ) -> Result { let mut store = self .inner .write() .map_err(|_err| TraitStoreError::Poisoned)?; - Ok(store.ingest(bytes, now_ms)?) + Ok(store.ingest_with_body(bytes, body, now_ms)?) } /// Checks the store's own rows. See [`EventStore::check_invariants`]. @@ -119,8 +126,14 @@ impl SharedEventStore { self.read(|store| Ok(store.check_invariants()?)) } - /// Runs `op` under the read lock. - fn read( + /// Runs `op` under the read lock. It answers the queries the traits do not cover, such as the + /// applied state and the roster of a group. + /// + /// # Errors + /// + /// Returns [`TraitStoreError::Poisoned`] if another thread panicked while it held the lock, or + /// whatever `op` returns. + pub fn read( &self, op: impl FnOnce(&EventStore) -> Result, ) -> Result { @@ -531,7 +544,7 @@ mod tests { fn ingest_all(store: &SharedEventStore, events: &[Event]) { for event in events { - let outcome = store.ingest(&event.bytes, 0).unwrap(); + let outcome = store.ingest(&event.bytes, None, 0).unwrap(); assert_eq!( outcome, Ingest::Accepted { @@ -807,7 +820,7 @@ mod tests { // Alice's rival at seq 1: the same backlink as `second`, so it conflicts with it. let rival = event(&alice, 1, Some(first.id), Some(rival_topic), "rival", None); assert_eq!( - store.ingest(&rival.bytes, 0).unwrap(), + store.ingest(&rival.bytes, None, 0).unwrap(), Ingest::Fork { author: *who.as_bytes(), seq: 1, @@ -916,7 +929,7 @@ mod tests { Err(TraitStoreError::Poisoned) )); assert!(matches!( - store.ingest(&[], 0), + store.ingest(&[], None, 0), Err(TraitStoreError::Poisoned) )); } diff --git a/pkgs/id/tests/production_ingest.rs b/pkgs/id/tests/production_ingest.rs new file mode 100644 index 0000000000..05545d9971 --- /dev/null +++ b/pkgs/id/tests/production_ingest.rs @@ -0,0 +1,326 @@ +//! Group operations through the production ingest path (P2.3). +//! +//! `SharedEventStore::ingest` takes an event's header and its body, and reads the membership +//! action from the body. These tests reach the store only through that call, the path the network +//! takes, and never through `ingest_with_action`. + +#![allow(clippy::unwrap_used, clippy::expect_used)] + +use std::collections::BTreeMap; + +use id::chain::{ChainExt, Event, sign}; +use id::event_store::{EventStore, Ingest, Refusal}; +use id::membership::AuthId; +use id::membership::body::{CLAIM, encode_body}; +use id::store_traits::SharedEventStore; +use id::waiting::WaitingLimits; +use p2panda_auth::Access; +use p2panda_auth::group::{GroupAction, GroupMember}; +use p2panda_core::{Hash, SeqNum, SigningKey}; + +/// The group operation kind in an event's header. +const GROUP_OP: &str = "group.op"; + +fn key(who: char) -> SigningKey { + SigningKey::from_bytes(&[who as u8; 32]) +} + +fn auth(who: char) -> AuthId { + AuthId::Key(*key(who).verifying_key().as_bytes()) +} + +fn open() -> (tempfile::TempDir, SharedEventStore) { + let dir = tempfile::tempdir().unwrap(); + let store = EventStore::open(dir.path(), WaitingLimits::default(), 0).unwrap(); + (dir, SharedEventStore::new(store)) +} + +/// A signed event and the body it commits to, as the network delivers them. +struct Sent { + event: Event, + body: Option>, +} + +impl Sent { + fn ingest(&self, shared: &SharedEventStore) -> Ingest { + shared + .ingest(&self.event.bytes, self.body.as_deref(), 0) + .unwrap() + } +} + +/// Signs each author's events as one chain: the sequence numbers and backlinks follow from the +/// order of signing. +#[derive(Default)] +struct Chains { + last: BTreeMap, +} + +impl Chains { + /// Signs the next event of `who`. It names `after` and, when there is one, its body. + fn sign( + &mut self, + who: char, + group: Option, + after: &[Hash], + kind: &str, + body: Option>, + ) -> Sent { + let (seq, backlink) = match self.last.get(&who) { + Some((seq, hash)) => (seq + 1, Some(*hash)), + None => (0, None), + }; + let ext = ChainExt { + kind: kind.to_owned(), + group, + after: after.to_vec(), + }; + let event = sign(&key(who), seq, backlink, body.as_deref(), ext).unwrap(); + self.last.insert(who, (seq, event.id)); + Sent { event, body } + } + + /// A group operation by `who`, with its action in the body. + fn op( + &mut self, + who: char, + group: Hash, + after: &[Hash], + action: &GroupAction, + ) -> Sent { + let body = encode_body(action).unwrap(); + self.sign(who, Some(group), after, GROUP_OP, Some(body)) + } + + /// The group's create, by A, B and C as managers. The group is the create's ID. + fn create(&mut self) -> Sent { + let action = GroupAction::Create { + initial_members: ['A', 'B', 'C'] + .iter() + .map(|who| (GroupMember::Individual(auth(*who)), Access::manage())) + .collect(), + }; + let body = encode_body(&action).unwrap(); + self.sign('A', None, &[], GROUP_OP, Some(body)) + } +} + +fn add(who: char, access: Access<()>) -> GroupAction { + GroupAction::Add { + member: GroupMember::Individual(auth(who)), + access, + } +} + +fn remove(who: char) -> GroupAction { + GroupAction::Remove { + member: GroupMember::Individual(auth(who)), + } +} + +/// The keys of `who`, sorted as the roster is. +fn members(who: &[char]) -> Vec { + let mut keys: Vec = who.iter().map(|who| auth(*who)).collect(); + keys.sort(); + keys +} + +/// Whether the store applies the event. +fn applied(shared: &SharedEventStore, id: &Hash) -> bool { + shared.read(|store| Ok(store.event_applied(id)?)).unwrap() +} + +/// The keys in the group's roster, sorted. +fn roster(shared: &SharedEventStore, group: &Hash) -> Vec { + let mut keys: Vec = shared + .read(|store| Ok(store.roster(group)?)) + .unwrap() + .into_iter() + .map(AuthId::Key) + .collect(); + keys.sort(); + keys +} + +/// The roster of the group the create made, when the test has one. +fn roster_of(shared: &SharedEventStore, create: &Sent) -> Vec { + roster(shared, &create.event.id) +} + +#[test] +fn test_an_unauthorised_group_operation_is_not_applied() { + let (_dir, shared) = open(); + let mut chains = Chains::default(); + let create = chains.create(); + assert!(matches!(create.ingest(&shared), Ingest::Accepted { .. })); + // D is not a member, so D's add of E does not take effect. + let group = create.event.id; + let attempt = chains.op('D', group, &[group], &add('E', Access::manage())); + assert_eq!( + attempt.ingest(&shared), + Ingest::Voided { + id: attempt.event.id, + released: Vec::new(), + } + ); + assert!(!applied(&shared, &attempt.event.id)); + assert_eq!(roster_of(&shared, &create), members(&['A', 'B', 'C'])); +} + +#[test] +fn test_an_authorised_group_operation_is_applied() { + let (_dir, shared) = open(); + let mut chains = Chains::default(); + let create = chains.create(); + create.ingest(&shared); + let group = create.event.id; + let grant = chains.op('A', group, &[group], &add('D', Access::read())); + assert_eq!( + grant.ingest(&shared), + Ingest::Accepted { + id: grant.event.id, + released: Vec::new(), + } + ); + assert!(applied(&shared, &grant.event.id)); + assert_eq!(roster_of(&shared, &create), members(&['A', 'B', 'C', 'D'])); +} + +#[test] +fn test_a_strong_removal_invalidates_the_removed_members_later_operations() { + let (_dir, shared) = open(); + let mut chains = Chains::default(); + let create = chains.create(); + create.ingest(&shared); + let group = create.event.id; + // A removes B. B's add names the removal, so B had already lost authority when it made it. + let removal = chains.op('A', group, &[group], &remove('B')); + assert!(matches!(removal.ingest(&shared), Ingest::Accepted { .. })); + let late = chains.op('B', group, &[removal.event.id], &add('E', Access::manage())); + assert_eq!( + late.ingest(&shared), + Ingest::Voided { + id: late.event.id, + released: Vec::new(), + } + ); + assert!(!applied(&shared, &late.event.id)); + assert_eq!(roster_of(&shared, &create), members(&['A', 'C'])); +} + +#[test] +fn test_a_truncated_group_operation_body_is_refused() { + let (_dir, shared) = open(); + let mut chains = Chains::default(); + let create = chains.create(); + create.ingest(&shared); + let group = create.event.id; + let body = encode_body(&add('D', Access::read())).unwrap(); + let cut = body[..body.len() - 3].to_vec(); + assert!( + cut.starts_with(CLAIM), + "the cut body still claims a group operation" + ); + let sent = chains.sign('A', Some(group), &[group], GROUP_OP, Some(cut)); + assert!(matches!( + sent.ingest(&shared), + Ingest::Refused(Refusal::Malformed(_)) + )); + assert_eq!( + shared + .read(|store| Ok(store.event_by_id(&sent.event.id)?)) + .unwrap(), + None, + "a refused event is not stored" + ); + assert_eq!(roster_of(&shared, &create), members(&['A', 'B', 'C'])); +} + +#[test] +fn test_a_group_operation_body_of_the_wrong_version_is_refused() { + let (_dir, shared) = open(); + let mut chains = Chains::default(); + let create = chains.create(); + create.ingest(&shared); + let group = create.event.id; + let mut body = encode_body(&add('D', Access::read())).unwrap(); + // The version byte follows the claim: 1 becomes 2. + body[CLAIM.len()] = 2; + let sent = chains.sign('A', Some(group), &[group], GROUP_OP, Some(body)); + assert!(matches!( + sent.ingest(&shared), + Ingest::Refused(Refusal::Malformed(_)) + )); +} + +#[test] +fn test_a_body_that_does_not_match_its_payload_hash_is_refused() { + let (_dir, shared) = open(); + let mut chains = Chains::default(); + let create = chains.create(); + create.ingest(&shared); + let group = create.event.id; + // The header commits to an add, and the body that arrives is a remove. + let committed = encode_body(&add('D', Access::manage())).unwrap(); + let event = sign( + &key('A'), + 1, + Some(create.event.id), + Some(committed.as_slice()), + ChainExt { + kind: GROUP_OP.to_owned(), + group: Some(group), + after: vec![group], + }, + ) + .unwrap(); + let swapped = encode_body(&remove('B')).unwrap(); + let outcome = shared.ingest(&event.bytes, Some(&swapped), 0).unwrap(); + assert!(matches!(outcome, Ingest::Refused(Refusal::Malformed(_)))); + assert!(!applied(&shared, &event.id)); + assert_eq!(roster_of(&shared, &create), members(&['A', 'B', 'C'])); +} + +#[test] +fn test_content_with_a_body_that_is_not_a_group_operation_is_content() { + let (_dir, shared) = open(); + let mut chains = Chains::default(); + let create = chains.create(); + create.ingest(&shared); + let message = chains.sign( + 'B', + None, + &[create.event.id], + "message", + Some(b"hello".to_vec()), + ); + assert_eq!( + message.ingest(&shared), + Ingest::Accepted { + id: message.event.id, + released: Vec::new(), + } + ); + assert!(applied(&shared, &message.event.id)); +} + +#[test] +fn test_a_group_operation_that_arrives_without_its_body_is_content() { + // The body is what makes an event a membership change. Without it the event is content, so it + // applies with no effect on the group. A header that commits to a body is not refused for + // lacking one. + let (_dir, shared) = open(); + let mut chains = Chains::default(); + let create = chains.create(); + create.ingest(&shared); + let group = create.event.id; + let attempt = chains.op('D', group, &[group], &add('E', Access::manage())); + assert_eq!( + shared.ingest(&attempt.event.bytes, None, 0).unwrap(), + Ingest::Accepted { + id: attempt.event.id, + released: Vec::new(), + } + ); + assert_eq!(roster_of(&shared, &create), members(&['A', 'B', 'C'])); +} diff --git a/pkgs/id/tests/voiding_properties.rs b/pkgs/id/tests/voiding_properties.rs index b11a598065..6b00116017 100644 --- a/pkgs/id/tests/voiding_properties.rs +++ b/pkgs/id/tests/voiding_properties.rs @@ -13,6 +13,8 @@ use std::collections::BTreeMap; use id::chain::{ChainExt, sign}; use id::event_store::{EventStore, Ingest}; use id::membership::AuthId; +use id::membership::body::encode_body; +use id::store_traits::SharedEventStore; use id::waiting::WaitingLimits; use p2panda_auth::Access; use p2panda_auth::group::{GroupAction, GroupMember}; @@ -58,12 +60,14 @@ fn config() -> ProptestConfig { } } -/// One signed event of a scenario, with its membership action when it is a group operation. +/// One signed event of a scenario, with its membership action when it is a group operation, and the +/// body that carries the action. #[derive(Clone)] struct Step { id: Hash, bytes: Vec, action: Option>, + body: Option>, } fn key(who: char) -> SigningKey { @@ -140,7 +144,8 @@ fn scenario(seed: u64) -> Vec { group: if index == 0 { None } else { group }, after, }; - let event = sign(&key(who), seq, backlink, None, ext).unwrap(); + let body = action.as_ref().map(|action| encode_body(action).unwrap()); + let event = sign(&key(who), seq, backlink, body.as_deref(), ext).unwrap(); if index == 0 { group = Some(event.id); } @@ -149,6 +154,7 @@ fn scenario(seed: u64) -> Vec { id: event.id, bytes: event.bytes, action, + body, }); } steps @@ -161,8 +167,8 @@ struct Final { roster: Vec, } -/// Delivers the scenario in `order` to a fresh store. Every event must be stored and none may be -/// refused or left waiting. +/// Delivers the scenario in `order` to a fresh store, handing each action in directly: the scenario +/// path. Every event must be stored and none may be refused or left waiting. fn deliver(steps: &[Step], order: &[usize]) -> Result { let dir = tempfile::tempdir().map_err(|err| err.to_string())?; let mut store = @@ -176,12 +182,36 @@ fn deliver(steps: &[Step], order: &[usize]) -> Result { return Err(format!("event {index} was refused: {outcome:?}")); } } + read_final(steps, &store) +} + +/// Delivers the scenario in `order` through the production path: each event with its body, to +/// `SharedEventStore::ingest`, which reads the action from the body. The same checks as [`deliver`]. +fn deliver_production(steps: &[Step], order: &[usize]) -> Result { + let dir = tempfile::tempdir().map_err(|err| err.to_string())?; + let store = + EventStore::open(dir.path(), WaitingLimits::default(), 0).map_err(|err| err.to_string())?; + let shared = SharedEventStore::new(store); + for &index in order { + let step = &steps[index]; + let outcome = shared + .ingest(&step.bytes, step.body.as_deref(), 0) + .map_err(|err| err.to_string())?; + if matches!(outcome, Ingest::Refused(_)) { + return Err(format!("event {index} was refused: {outcome:?}")); + } + } + shared + .read(|store| Ok(read_final(steps, store))) + .map_err(|err| err.to_string())? +} + +/// The applied flag of each step, and the roster, once every step is in. No event may be left +/// waiting, and every event must be stored. +fn read_final(steps: &[Step], store: &EventStore) -> Result { let waiting = store.waiting_ids().map_err(|err| err.to_string())?; if !waiting.is_empty() { - return Err(format!( - "order {order:?} leaves {} events waiting", - waiting.len() - )); + return Err(format!("{} events are left waiting", waiting.len())); } for (index, step) in steps.iter().enumerate() { let stored = store @@ -189,7 +219,7 @@ fn deliver(steps: &[Step], order: &[usize]) -> Result { .map_err(|err| err.to_string())? .is_some(); if !stored { - return Err(format!("order {order:?} never stored event {index}")); + return Err(format!("event {index} was never stored")); } } let mut applied = Vec::new(); @@ -236,4 +266,21 @@ proptest! { prop_assert_eq!(&outcome, &reference, "arrival order {:?}", order); } } + + /// Through the production path, which reads each action from the event's body, every arrival + /// order gives the same applied set and roster as the scenario path in causal order. + #[test] + fn test_production_ingest_is_the_same_for_every_arrival_order(seed in any::()) { + let steps = scenario(seed); + let causal: Vec = (0..steps.len()).collect(); + let reference = deliver(&steps, &causal).map_err(TestCaseError::fail)?; + let mut rng = Rng(seed ^ 0x5EED_1CE0_F00D_CAFE_u64); + let production = deliver_production(&steps, &causal).map_err(TestCaseError::fail)?; + prop_assert_eq!(&production, &reference, "production path in causal order"); + for _ in 0..ORDERS { + let order = shuffled(steps.len(), &mut rng); + let outcome = deliver_production(&steps, &order).map_err(TestCaseError::fail)?; + prop_assert_eq!(&outcome, &reference, "production path, arrival order {:?}", order); + } + } } diff --git a/pkgs/id/tests/voiding_scenarios.rs b/pkgs/id/tests/voiding_scenarios.rs index edcf2fd1fd..179dc62527 100644 --- a/pkgs/id/tests/voiding_scenarios.rs +++ b/pkgs/id/tests/voiding_scenarios.rs @@ -2,25 +2,33 @@ //! every arrival order. The applied state and the roster must be the same in all of them, and //! must match the S2 outcomes: an operation is voided when its author lost authority at its //! position, and a dependent of a voided operation is kept when its author kept authority. +//! +//! Each scenario runs twice. The scenario path hands each action to `ingest_with_action`. The +//! production path sends each event with its body through `SharedEventStore::ingest`, which reads +//! the action from the body. The two must agree. #![allow(clippy::unwrap_used, clippy::expect_used)] use std::collections::BTreeMap; use id::chain::{ChainExt, sign}; -use id::event_store::EventStore; +use id::event_store::{EventStore, StoreError}; use id::membership::AuthId; +use id::membership::body::encode_body; +use id::store_traits::SharedEventStore; use id::waiting::WaitingLimits; use p2panda_auth::Access; use p2panda_auth::group::{GroupAction, GroupMember}; use p2panda_core::{Hash, SeqNum, SigningKey}; -/// One event of a scenario: its name in the scenario, its signed bytes, and its action. +/// One event of a scenario: its name in the scenario, its signed bytes, its action, and the body +/// the header commits to, which carries the action. #[derive(Clone)] struct Step { name: u8, bytes: Vec, action: Option>, + body: Option>, } /// Signs a scenario. Each author's events form a chain, so the sequence numbers and backlinks @@ -86,7 +94,8 @@ impl Builder { }, after: after.iter().map(|n| self.ids[n]).collect(), }; - let event = sign(&key(who), seq, backlink, None, ext).unwrap(); + let body = action.as_ref().map(|action| encode_body(action).unwrap()); + let event = sign(&key(who), seq, backlink, body.as_deref(), ext).unwrap(); if matches!(action, Some(GroupAction::Create { .. })) { self.group = Some(event.id); } @@ -96,6 +105,7 @@ impl Builder { name, bytes: event.bytes, action, + body, }); } @@ -117,7 +127,8 @@ struct Outcome { roster: Vec, } -/// Delivers the steps in `order` to a fresh store, and reports what it applied. +/// Delivers the steps in `order` to a fresh store, and reports what it applied. The actions are +/// handed in directly, as `ingest_with_action` takes them: the scenario path. fn deliver(steps: &[Step], order: &[usize]) -> Outcome { let dir = tempfile::tempdir().unwrap(); let mut store = EventStore::open(dir.path(), WaitingLimits::default(), 0).unwrap(); @@ -127,26 +138,36 @@ fn deliver(steps: &[Step], order: &[usize]) -> Outcome { .ingest_with_action(&step.bytes, step.action.as_ref(), 0) .unwrap(); } + outcome_of(&store, steps).unwrap() +} + +/// Delivers the steps in `order` through the production path: each event with its body, to +/// `SharedEventStore::ingest`, which reads the action from the body. +fn deliver_production(steps: &[Step], order: &[usize]) -> Outcome { + let dir = tempfile::tempdir().unwrap(); + let store = EventStore::open(dir.path(), WaitingLimits::default(), 0).unwrap(); + let shared = SharedEventStore::new(store); + for &index in order { + let step = &steps[index]; + shared.ingest(&step.bytes, step.body.as_deref(), 0).unwrap(); + } + shared.read(|store| Ok(outcome_of(store, steps)?)).unwrap() +} + +/// What the store applied to each step, and the roster of the group the create made. +fn outcome_of(store: &EventStore, steps: &[Step]) -> Result { let group = steps .iter() .find(|step| matches!(step.action, Some(GroupAction::Create { .. }))) .map(|step| Hash::digest(&step.bytes)) .unwrap(); - let applied = steps - .iter() - .map(|step| { - let id = Hash::digest(&step.bytes); - (step.name, store.event_applied(&id).unwrap()) - }) - .collect(); - let mut roster: Vec = store - .roster(&group) - .unwrap() - .into_iter() - .map(AuthId::Key) - .collect(); + let mut applied = BTreeMap::new(); + for step in steps { + applied.insert(step.name, store.event_applied(&Hash::digest(&step.bytes))?); + } + let mut roster: Vec = store.roster(&group)?.into_iter().map(AuthId::Key).collect(); roster.sort(); - Outcome { applied, roster } + Ok(Outcome { applied, roster }) } /// Every permutation of `0..n`. @@ -182,6 +203,11 @@ fn check(name: &str, steps: &[Step], expected: &[(u8, bool)], roster: &[char]) { for order in permutations(steps.len()) { let outcome = deliver(steps, &order); assert_eq!(outcome, expected, "{name}: arrival order {order:?}"); + let production = deliver_production(steps, &order); + assert_eq!( + production, outcome, + "{name}: production path, arrival order {order:?}" + ); } } From 6503f94b604d97b0a98ed7994ba2790ce10968f3 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 12 Oct 2026 01:56:16 -0500 Subject: [PATCH 25/40] feat(rust): server config for group creation limits and provisioning [P2.9] A TOML server config (src/server_config/) with [create] allow rules, [[users]] and [[groups]] tables keyed by local names, and an optional primary alias per user or group. Parsing refuses duplicate keys, unknown or wrong-kind references, malformed user IDs, unknown roles, blank names, and groups that list their creator or a member twice. Provisioning creates users through Directory::sign_up_keyed and groups through the group fold, with the create rule checked before each group. Each group is provisioned once, so a second run changes nothing. New dependency: toml 1 (TOML parser for the config). Cargo.lock also moved tempfile to getrandom 0.4.3 and data-encoding-macro-internal to syn 3.0.8, which cargo chose when resolving toml. --- pkgs/id/Cargo.lock | 35 +- pkgs/id/Cargo.toml | 2 + pkgs/id/src/lib.rs | 2 + pkgs/id/src/server_config/mod.rs | 196 ++++++++ pkgs/id/src/server_config/parse.rs | 658 +++++++++++++++++++++++++ pkgs/id/src/server_config/provision.rs | 536 ++++++++++++++++++++ 6 files changed, 1427 insertions(+), 2 deletions(-) create mode 100644 pkgs/id/src/server_config/mod.rs create mode 100644 pkgs/id/src/server_config/parse.rs create mode 100644 pkgs/id/src/server_config/provision.rs diff --git a/pkgs/id/Cargo.lock b/pkgs/id/Cargo.lock index a3c51da161..e58afdb7f3 100644 --- a/pkgs/id/Cargo.lock +++ b/pkgs/id/Cargo.lock @@ -1365,7 +1365,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c54e03a951783e8b327515db3f2a2fd0e3bed362a96b066f341ce66ed49b4ead" dependencies = [ "data-encoding", - "syn 1.0.109", + "syn 3.0.8", ] [[package]] @@ -2738,6 +2738,7 @@ dependencies = [ "thiserror 2.0.21", "tokio", "tokio-tungstenite", + "toml", "tower", "tower-http 0.7.1", "tracing", @@ -5699,6 +5700,15 @@ dependencies = [ "serde_core", ] +[[package]] +name = "serde_spanned" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7523beb55eece201a2356bee0bbca0d1ab466c14c07703b2e0ee6d42cb0c2c" +dependencies = [ + "serde_core", +] + [[package]] name = "serde_urlencoded" version = "0.7.1" @@ -6184,7 +6194,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.3.4", + "getrandom 0.4.3", "once_cell", "rustix", "windows-sys 0.61.2", @@ -6395,6 +6405,21 @@ dependencies = [ "tokio-util", ] +[[package]] +name = "toml" +version = "1.1.8+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20489e00e4d8741d6be680764cc12e270655e375a20d1011e844a9c3379e678d" +dependencies = [ + "indexmap", + "serde_core", + "serde_spanned", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow", +] + [[package]] name = "toml_datetime" version = "1.1.2+spec-1.1.0" @@ -6425,6 +6450,12 @@ dependencies = [ "winnow", ] +[[package]] +name = "toml_writer" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06bdbd8cfc056b8d2e2e85f29b56a3bdbecb527cef81eb39e3e7b98af4652770" + [[package]] name = "tower" version = "0.5.3" diff --git a/pkgs/id/Cargo.toml b/pkgs/id/Cargo.toml index 4e63284952..66c5d293f1 100644 --- a/pkgs/id/Cargo.toml +++ b/pkgs/id/Cargo.toml @@ -65,6 +65,8 @@ serde = { version = "1", features = ["derive"] } serde_json = "1" tempfile = "3" tokio = { version = "1", features = ["full"] } +# TOML parser for the server config (P2.9). +toml = "1" thiserror = "2" tracing = "0.1" tracing-subscriber = { version = "0.3", features = ["env-filter"] } diff --git a/pkgs/id/src/lib.rs b/pkgs/id/src/lib.rs index 3631c229f8..e2292633da 100644 --- a/pkgs/id/src/lib.rs +++ b/pkgs/id/src/lib.rs @@ -184,6 +184,8 @@ pub mod membership; pub mod meta_client; #[cfg(feature = "world")] pub mod petname; +#[cfg(feature = "world")] +pub mod server_config; pub mod protocol; pub mod repl; #[cfg(feature = "sandbox")] diff --git a/pkgs/id/src/server_config/mod.rs b/pkgs/id/src/server_config/mod.rs new file mode 100644 index 0000000000..b1c76d6533 --- /dev/null +++ b/pkgs/id/src/server_config/mod.rs @@ -0,0 +1,196 @@ +//! Server config (Phase 2, P2.9): who may create groups, what the server provisions at startup, and +//! each object's primary alias. +//! +//! The config is a TOML file. Every table is optional. An empty file is valid: anyone may create a +//! group, and nothing is provisioned. +//! +//! ```toml +//! [create] # absent: anyone may create a group +//! users = ["ann"] # these users may create +//! groups = ["staff"] # members of these groups may create +//! min_role = "write" # the least role a member of a listed group may have +//! +//! [[users]] +//! key = "ann" # a local name, unique within the config +//! id = "<64 hex digits>" # the user's Ed25519 public key +//! alias = "Ann" # optional primary alias +//! +//! [[groups]] +//! key = "staff" +//! name = "Staff" +//! creator = "ann" # a user, who becomes the group's Admin +//! alias = "staff" # optional primary alias +//! +//! [[groups.members]] +//! user = "bo" +//! role = "write" # pull, read, write, manage, or admin +//! ``` +//! +//! [`ServerConfig::parse`] checks the whole file and translates every key to its ID, so a bad file +//! fails at startup. [`Provisioned::apply`] creates what the config names through the same paths a +//! user action takes, and a second run creates nothing. + +mod parse; +pub mod provision; + +use std::collections::{BTreeMap, BTreeSet}; +use std::path::Path; + +use p2panda_core::Hash; + +use crate::groups::{Key, Projection, Role}; + +pub use parse::ConfigError; +pub use provision::{ProvisionError, Provisioned, Report}; + +/// The server config, checked, with every key translated to its ID. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ServerConfig { + users: Vec, + groups: Vec, + create: CreateRule, + /// Every local key, for users and groups alike. Keys are unique within the config. + names: BTreeMap, + /// The primary alias of each object that has one. + aliases: BTreeMap, +} + +/// Something the config names: a user by its public key, or a group by its ID. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub enum Object { + /// A user, by its account key. + User(Key), + /// A group, by its ID. + Group(Hash), +} + +/// A user the config creates. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct UserSpec { + /// The local key. + pub key: String, + /// The user's public key. + pub id: Key, +} + +/// A group the config creates. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct GroupSpec { + /// The local key. + pub key: String, + /// The official name the group starts with. An Admin may change it later. + pub name: String, + /// The group's ID, which is the ID of its create event. + pub id: Hash, + /// The user who creates the group and is its Admin. + pub creator: Key, + /// The other members, in the order the config lists them, with their roles. + pub members: Vec<(Key, Role)>, +} + +/// Who may create a group. Anyone may by default. A config may list who may. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum CreateRule { + /// Anyone may create a group. + Anyone, + /// Only the listed users, and members of the listed groups at or above `floor`. + Listed { + /// Users who may create. + users: BTreeSet, + /// Groups whose members may create. + groups: BTreeSet, + /// The least role a member of a listed group may have. Unset in the file means any member. + floor: Role, + }, +} + +impl CreateRule { + /// Whether `creator` may create a group, given the groups as they stand now. An inactive group + /// grants nothing. + #[must_use] + pub fn allows(&self, creator: &Key, groups: &Projection) -> bool { + match self { + Self::Anyone => true, + Self::Listed { + users, + groups: listed, + floor, + } => { + users.contains(creator) + || listed.iter().any(|id| { + groups.group(id).is_some_and(|view| { + view.is_active() + && view.members.get(creator).is_some_and(|role| role >= floor) + }) + }) + } + } + } +} + +impl ServerConfig { + /// Parses and checks a config. Every refusal names the key it is about. + /// + /// # Errors + /// + /// Fails on invalid TOML or an unknown field, a key declared twice, a reference to an unknown + /// key, a malformed user ID, an unknown role, an empty name, alias, or `[create]`, and a group + /// that lists its creator or a member twice. + pub fn parse(text: &str) -> Result { + parse::parse(text) + } + + /// Reads and parses the config at `path`. + /// + /// # Errors + /// + /// Fails if the file cannot be read, or on any error from [`ServerConfig::parse`]. + pub fn load(path: &Path) -> Result { + let text = std::fs::read_to_string(path) + .map_err(|error| ConfigError::Read(format!("{}: {error}", path.display())))?; + Self::parse(&text) + } + + /// The users the config creates, in file order. + #[must_use] + pub fn users(&self) -> &[UserSpec] { + &self.users + } + + /// The groups the config creates, in file order. A group may only admit a creator from groups + /// listed before it. + #[must_use] + pub fn groups(&self) -> &[GroupSpec] { + &self.groups + } + + /// Who may create a group. + #[must_use] + pub const fn create_rule(&self) -> &CreateRule { + &self.create + } + + /// The public key a user key names. + #[must_use] + pub fn user_id(&self, key: &str) -> Option { + match self.names.get(key)? { + Object::User(id) => Some(*id), + Object::Group(_) => None, + } + } + + /// The ID a group key names. + #[must_use] + pub fn group_id(&self, key: &str) -> Option { + match self.names.get(key)? { + Object::Group(id) => Some(*id), + Object::User(_) => None, + } + } + + /// The primary alias the config sets for an object, if any. The alias display is P5.7. + #[must_use] + pub fn primary_alias(&self, object: &Object) -> Option<&str> { + self.aliases.get(object).map(String::as_str) + } +} diff --git a/pkgs/id/src/server_config/parse.rs b/pkgs/id/src/server_config/parse.rs new file mode 100644 index 0000000000..f4f114f5c0 --- /dev/null +++ b/pkgs/id/src/server_config/parse.rs @@ -0,0 +1,658 @@ +//! Parsing and checking a server config (P2.9). Every refusal names the key it is about. +//! +//! A file is read in three passes. The users come first, so a group can name its creator. Each +//! group is then claimed with its ID. Last, members and the create rule are resolved against every +//! key. A key is claimed once across users and groups, so it names one object. + +use std::collections::{BTreeMap, BTreeSet}; + +use p2panda_core::Hash; +use serde::Deserialize; +use thiserror::Error; + +use super::{CreateRule, GroupSpec, Object, ServerConfig, UserSpec}; +use crate::directory::{hex_to_array, normalize_key}; +use crate::groups::{Key, Role}; + +/// Why a config was refused. +#[derive(Clone, Debug, PartialEq, Eq, Error)] +pub enum ConfigError { + /// The file could not be read. + #[error("cannot read the server config: {0}")] + Read(String), + /// The text is not valid TOML, or it has a field the format does not have. + #[error("the server config is not valid: {0}")] + Parse(String), + /// A key names two users, two groups, or a user and a group. + #[error("key `{0}` is declared more than once; keys are unique within the config")] + DuplicateKey(String), + /// A reference names no key of the kind it needs. + #[error("unknown {kind} key `{key}` in {place}")] + UnknownKey { + /// The kind the reference needs. + kind: &'static str, + /// The key named. + key: String, + /// Where the reference is. + place: String, + }, + /// A reference names a key of the other kind. + #[error("`{key}` names a {found}, not a {expected}, in {place}")] + WrongKind { + /// The key named. + key: String, + /// The kind the reference needs. + expected: &'static str, + /// The kind the key names. + found: &'static str, + /// Where the reference is. + place: String, + }, + /// A user's ID is not an Ed25519 public key written as 64 hex digits. + #[error("user `{key}` has a malformed id: {reason}")] + MalformedId { + /// The user's key. + key: String, + /// What is wrong with the ID. + reason: String, + }, + /// A role name is none of the five roles. + #[error("`{role}` in {place} is not a role; use pull, read, write, manage, or admin")] + UnknownRole { + /// The name given. + role: String, + /// Where it is. + place: String, + }, + /// A name or alias is blank. + #[error("`{key}` has an empty {field}")] + Empty { + /// The key of the object. + key: String, + /// Which field is blank. + field: &'static str, + }, + /// `[create]` lists no user and no group, so no one could create a group. + #[error("[create] lists no user and no group, so no one could create a group")] + EmptyCreate, + /// A group lists its creator as a member. The creator is its Admin already. + #[error( + "group `{group}` lists its creator `{creator}` as a member; the creator is its Admin already" + )] + CreatorListed { + /// The group's key. + group: String, + /// The creator's key. + creator: String, + }, + /// A group lists one member twice. + #[error("group `{group}` lists member `{member}` more than once")] + DuplicateMember { + /// The group's key. + group: String, + /// The member's key. + member: String, + }, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Raw { + create: Option, + #[serde(default)] + users: Vec, + #[serde(default)] + groups: Vec, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct RawCreate { + #[serde(default)] + users: Vec, + #[serde(default)] + groups: Vec, + min_role: Option, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct RawUser { + key: String, + id: String, + alias: Option, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct RawGroup { + key: String, + name: String, + creator: String, + alias: Option, + #[serde(default)] + members: Vec, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct RawMember { + user: String, + role: String, +} + +/// Parses and checks `text`. See the module doc for the passes. +pub(super) fn parse(text: &str) -> Result { + let raw: Raw = toml::from_str(text).map_err(|error| ConfigError::Parse(error.to_string()))?; + let mut names = BTreeMap::new(); + let mut aliases = BTreeMap::new(); + + let mut users = Vec::with_capacity(raw.users.len()); + for user in &raw.users { + let id = parse_id(&user.key, &user.id)?; + claim(&mut names, &user.key, Object::User(id))?; + record_alias( + &mut aliases, + &user.key, + Object::User(id), + user.alias.as_deref(), + )?; + users.push(UserSpec { + key: user.key.clone(), + id, + }); + } + + let mut pending = Vec::with_capacity(raw.groups.len()); + for group in &raw.groups { + let creator = user_of(&names, &group.creator, &format!("group `{}`", group.key))?; + let id = group_id(&creator, &group.key); + claim(&mut names, &group.key, Object::Group(id))?; + if group.name.trim().is_empty() { + return Err(ConfigError::Empty { + key: group.key.clone(), + field: "name", + }); + } + record_alias( + &mut aliases, + &group.key, + Object::Group(id), + group.alias.as_deref(), + )?; + pending.push((group, creator, id)); + } + + let mut groups = Vec::with_capacity(pending.len()); + for (group, creator, id) in pending { + let place = format!("the members of group `{}`", group.key); + let mut members: Vec<(Key, Role)> = Vec::with_capacity(group.members.len()); + for member in &group.members { + let key = user_of(&names, &member.user, &place)?; + let role = parse_role(&member.role, &place)?; + if key == creator { + return Err(ConfigError::CreatorListed { + group: group.key.clone(), + creator: group.creator.clone(), + }); + } + if members.iter().any(|(listed, _)| *listed == key) { + return Err(ConfigError::DuplicateMember { + group: group.key.clone(), + member: member.user.clone(), + }); + } + members.push((key, role)); + } + groups.push(GroupSpec { + key: group.key.clone(), + name: group.name.trim().to_owned(), + id, + creator, + members, + }); + } + + let create = match &raw.create { + None => CreateRule::Anyone, + Some(rule) => create_rule(rule, &names)?, + }; + Ok(ServerConfig { + users, + groups, + create, + names, + aliases, + }) +} + +/// The create rule from its `[create]` table, with every name resolved. +fn create_rule( + rule: &RawCreate, + names: &BTreeMap, +) -> Result { + if rule.users.is_empty() && rule.groups.is_empty() { + return Err(ConfigError::EmptyCreate); + } + let mut users = BTreeSet::new(); + for key in &rule.users { + users.insert(user_of(names, key, "[create].users")?); + } + let mut groups = BTreeSet::new(); + for key in &rule.groups { + groups.insert(group_of(names, key, "[create].groups")?); + } + let floor = match &rule.min_role { + None => Role::Pull, + Some(name) => parse_role(name, "[create].min_role")?, + }; + Ok(CreateRule::Listed { + users, + groups, + floor, + }) +} + +/// Records that `key` names `object`. Keys are unique across users and groups. +fn claim( + names: &mut BTreeMap, + key: &str, + object: Object, +) -> Result<(), ConfigError> { + if names.contains_key(key) { + return Err(ConfigError::DuplicateKey(key.to_owned())); + } + names.insert(key.to_owned(), object); + Ok(()) +} + +/// Stores the object's primary alias, if the file sets one. A blank alias is refused. +fn record_alias( + aliases: &mut BTreeMap, + key: &str, + object: Object, + alias: Option<&str>, +) -> Result<(), ConfigError> { + let Some(alias) = alias else { + return Ok(()); + }; + let alias = alias.trim(); + if alias.is_empty() { + return Err(ConfigError::Empty { + key: key.to_owned(), + field: "alias", + }); + } + aliases.insert(object, alias.to_owned()); + Ok(()) +} + +/// The public key a user key names. +fn user_of(names: &BTreeMap, key: &str, place: &str) -> Result { + match names.get(key) { + Some(Object::User(id)) => Ok(*id), + Some(Object::Group(_)) => Err(ConfigError::WrongKind { + key: key.to_owned(), + expected: "user", + found: "group", + place: place.to_owned(), + }), + None => Err(ConfigError::UnknownKey { + kind: "user", + key: key.to_owned(), + place: place.to_owned(), + }), + } +} + +/// The ID a group key names. +fn group_of(names: &BTreeMap, key: &str, place: &str) -> Result { + match names.get(key) { + Some(Object::Group(id)) => Ok(*id), + Some(Object::User(_)) => Err(ConfigError::WrongKind { + key: key.to_owned(), + expected: "group", + found: "user", + place: place.to_owned(), + }), + None => Err(ConfigError::UnknownKey { + kind: "group", + key: key.to_owned(), + place: place.to_owned(), + }), + } +} + +/// The public key a user's ID names. It is written as 64 hex digits, in either case. +fn parse_id(key: &str, id: &str) -> Result { + let malformed = |reason: String| ConfigError::MalformedId { + key: key.to_owned(), + reason, + }; + let normalized = normalize_key(id).map_err(|error| malformed(format!("{error:#}")))?; + hex_to_array::<32>(&normalized).ok_or_else(|| malformed("not 64 hex digits".to_owned())) +} + +fn parse_role(role: &str, place: &str) -> Result { + match role.trim().to_ascii_lowercase().as_str() { + "pull" => Ok(Role::Pull), + "read" => Ok(Role::Read), + "write" => Ok(Role::Write), + "manage" => Ok(Role::Manage), + "admin" => Ok(Role::Admin), + _ => Err(ConfigError::UnknownRole { + role: role.to_owned(), + place: place.to_owned(), + }), + } +} + +/// The ID of the group a creator makes under `key`. It is the same on every start, so a restart +/// finds the group it made before. +fn group_id(creator: &Key, key: &str) -> Hash { + let mut bytes = b"id-config-group-v1".to_vec(); + bytes.extend_from_slice(creator); + bytes.extend_from_slice(key.as_bytes()); + Hash::digest(bytes) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used)] +mod tests { + use std::path::Path; + + use ed25519_dalek::SigningKey; + + use crate::groups::{Key, Role}; + use crate::server_config::{ConfigError, CreateRule, Object, ServerConfig}; + use crate::world::hex_encode; + + /// The public key of the account that the test calls `n`. + fn key(n: u8) -> Key { + SigningKey::from_bytes(&[n; 32]).verifying_key().to_bytes() + } + + fn hex(n: u8) -> String { + hex_encode(&key(n)) + } + + /// Four users: ann (1), bo (2), cy (3), and dee (4). + fn users() -> String { + format!( + "[[users]]\nkey = \"ann\"\nid = \"{}\"\n\n[[users]]\nkey = \"bo\"\nid = \"{}\"\n\n\ + [[users]]\nkey = \"cy\"\nid = \"{}\"\n\n[[users]]\nkey = \"dee\"\nid = \"{}\"\n", + hex(1), + hex(2), + hex(3), + hex(4) + ) + } + + /// The four users, then `extra`. + fn config(extra: &str) -> Result { + ServerConfig::parse(&format!("{}{extra}", users())) + } + + /// A group named `team`, created by ann, with bo as a writer. + const TEAM: &str = "\n[[groups]]\nkey = \"team\"\nname = \"Team\"\ncreator = \"ann\"\n\n\ + [[groups.members]]\nuser = \"bo\"\nrole = \"write\"\n"; + + #[test] + fn test_a_config_translates_every_key_to_its_id() { + let config = config(TEAM).unwrap(); + assert_eq!(config.user_id("ann"), Some(key(1))); + assert_eq!(config.user_id("bo"), Some(key(2))); + let team = config.group_id("team").unwrap(); + let group = &config.groups()[0]; + assert_eq!(group.id, team); + assert_eq!(group.name, "Team"); + assert_eq!(group.creator, key(1)); + assert_eq!(group.members, vec![(key(2), Role::Write)]); + assert_eq!(config.user_id("team"), None, "a group key is not a user"); + assert_eq!(config.group_id("ann"), None, "a user key is not a group"); + } + + #[test] + fn test_the_same_text_parses_to_the_same_config() { + assert_eq!(config(TEAM).unwrap(), config(TEAM).unwrap()); + } + + #[test] + fn test_a_user_key_declared_twice_is_refused_naming_it() { + let again = format!("\n[[users]]\nkey = \"ann\"\nid = \"{}\"\n", hex(9)); + assert_eq!( + config(&again), + Err(ConfigError::DuplicateKey("ann".to_owned())) + ); + } + + #[test] + fn test_a_group_key_that_reuses_a_user_key_is_refused_naming_it() { + let extra = "\n[[groups]]\nkey = \"bo\"\nname = \"Bo\"\ncreator = \"ann\"\n"; + assert_eq!( + config(extra), + Err(ConfigError::DuplicateKey("bo".to_owned())) + ); + } + + #[test] + fn test_two_groups_with_one_key_are_refused_naming_it() { + let extra = format!("{TEAM}{TEAM}"); + assert_eq!( + config(&extra), + Err(ConfigError::DuplicateKey("team".to_owned())) + ); + } + + #[test] + fn test_an_unknown_creator_is_refused_naming_the_key() { + let extra = "\n[[groups]]\nkey = \"team\"\nname = \"Team\"\ncreator = \"zed\"\n"; + assert!(matches!( + config(extra), + Err(ConfigError::UnknownKey { ref key, kind: "user", .. }) if key == "zed" + )); + } + + #[test] + fn test_an_unknown_member_is_refused_naming_the_key() { + let extra = "\n[[groups]]\nkey = \"team\"\nname = \"Team\"\ncreator = \"ann\"\n\n\ + [[groups.members]]\nuser = \"zed\"\nrole = \"read\"\n"; + assert!(matches!( + config(extra), + Err(ConfigError::UnknownKey { ref key, kind: "user", .. }) if key == "zed" + )); + } + + #[test] + fn test_an_unknown_name_in_the_create_rule_is_refused_naming_it() { + assert!(matches!( + config("\n[create]\nusers = [\"zed\"]\n"), + Err(ConfigError::UnknownKey { ref key, kind: "user", .. }) if key == "zed" + )); + assert!(matches!( + config(&format!("{TEAM}\n[create]\ngroups = [\"nope\"]\n")), + Err(ConfigError::UnknownKey { ref key, kind: "group", .. }) if key == "nope" + )); + } + + #[test] + fn test_a_key_of_the_wrong_kind_is_refused_naming_it() { + // A group named where a user belongs, and a user named where a group belongs. + assert!(matches!( + config(&format!("{TEAM}\n[create]\ngroups = [\"ann\"]\n")), + Err(ConfigError::WrongKind { ref key, expected: "group", .. }) if key == "ann" + )); + let extra = "\n[[groups]]\nkey = \"team\"\nname = \"Team\"\ncreator = \"ann\"\n\n\ + [[groups.members]]\nuser = \"team\"\nrole = \"read\"\n"; + assert!(matches!( + config(extra), + Err(ConfigError::WrongKind { ref key, expected: "user", .. }) if key == "team" + )); + } + + #[test] + fn test_an_unknown_role_is_refused_naming_it() { + let member = TEAM.replace("\"write\"", "\"owner\""); + assert!(matches!( + config(&member), + Err(ConfigError::UnknownRole { ref role, .. }) if role == "owner" + )); + assert!(matches!( + config(&format!("{TEAM}\n[create]\ngroups = [\"team\"]\nmin_role = \"owner\"\n")), + Err(ConfigError::UnknownRole { ref role, .. }) if role == "owner" + )); + } + + #[test] + fn test_every_role_name_is_accepted_and_case_is_ignored() { + for (name, role) in [ + ("pull", Role::Pull), + ("read", Role::Read), + ("write", Role::Write), + ("manage", Role::Manage), + ("Admin", Role::Admin), + ] { + let member = TEAM.replace("\"write\"", &format!("\"{name}\"")); + let config = config(&member).unwrap(); + assert_eq!(config.groups()[0].members, vec![(key(2), role)], "{name}"); + } + } + + #[test] + fn test_a_malformed_user_id_is_refused_naming_the_user() { + let short = users().replace(&hex(1), "abc"); + assert!(matches!( + ServerConfig::parse(&short), + Err(ConfigError::MalformedId { ref key, .. }) if key == "ann" + )); + let not_hex = users().replace(&hex(1), &"zz".repeat(32)); + assert!(matches!( + ServerConfig::parse(¬_hex), + Err(ConfigError::MalformedId { ref key, .. }) if key == "ann" + )); + } + + #[test] + fn test_an_uppercase_user_id_is_the_same_user() { + let upper = users().replace(&hex(1), &hex(1).to_ascii_uppercase()); + let config = ServerConfig::parse(&upper).unwrap(); + assert_eq!(config.user_id("ann"), Some(key(1))); + } + + #[test] + fn test_a_creator_listed_as_a_member_is_refused() { + let member = TEAM.replace("user = \"bo\"", "user = \"ann\""); + assert_eq!( + config(&member), + Err(ConfigError::CreatorListed { + group: "team".to_owned(), + creator: "ann".to_owned(), + }) + ); + } + + #[test] + fn test_a_member_listed_twice_is_refused_naming_it() { + let twice = format!("{TEAM}\n[[groups.members]]\nuser = \"bo\"\nrole = \"read\"\n"); + assert_eq!( + config(&twice), + Err(ConfigError::DuplicateMember { + group: "team".to_owned(), + member: "bo".to_owned(), + }) + ); + } + + #[test] + fn test_an_empty_create_table_is_refused() { + assert_eq!(config("\n[create]\n"), Err(ConfigError::EmptyCreate)); + } + + #[test] + fn test_an_empty_name_or_alias_is_refused_naming_its_key() { + let blank_name = TEAM.replace("name = \"Team\"", "name = \" \""); + assert_eq!( + config(&blank_name), + Err(ConfigError::Empty { + key: "team".to_owned(), + field: "name", + }) + ); + let blank_alias = users().replace( + &format!("id = \"{}\"", hex(2)), + &format!("id = \"{}\"\nalias = \"\"", hex(2)), + ); + assert_eq!( + ServerConfig::parse(&blank_alias), + Err(ConfigError::Empty { + key: "bo".to_owned(), + field: "alias", + }) + ); + } + + #[test] + fn test_an_unknown_field_is_refused() { + let extra = format!("{}\nhue = \"red\"\n", users()); + assert!(matches!( + ServerConfig::parse(&extra), + Err(ConfigError::Parse(_)) + )); + } + + #[test] + fn test_a_primary_alias_is_stored_and_read_back() { + let text = format!( + "{}\n[[groups]]\nkey = \"team\"\nname = \"Team\"\ncreator = \"ann\"\nalias = \"team\"\n", + users().replacen("key = \"ann\"", "key = \"ann\"\nalias = \"Ann\"", 1) + ); + let config = ServerConfig::parse(&text).unwrap(); + let team = config.group_id("team").unwrap(); + assert_eq!( + config.primary_alias(&Object::Group(team)), + Some("team"), + "the group's alias is read back" + ); + assert_eq!( + config.primary_alias(&Object::User(key(1))), + Some("Ann"), + "the user's alias is read back" + ); + assert_eq!( + config.primary_alias(&Object::User(key(2))), + None, + "an object with no alias has none" + ); + } + + #[test] + fn test_without_a_create_table_anyone_may_create() { + assert_eq!(config(TEAM).unwrap().create_rule(), &CreateRule::Anyone); + } + + #[test] + fn test_the_create_rule_keeps_its_listed_users_groups_and_floor() { + let parsed = config(&format!( + "{TEAM}\n[create]\nusers = [\"ann\"]\ngroups = [\"team\"]\nmin_role = \"write\"\n" + )) + .unwrap(); + let team = parsed.group_id("team").unwrap(); + assert_eq!( + parsed.create_rule(), + &CreateRule::Listed { + users: std::iter::once(key(1)).collect(), + groups: std::iter::once(team).collect(), + floor: Role::Write, + } + ); + } + + #[test] + fn test_a_missing_config_file_is_refused() { + let missing = Path::new("/nonexistent/id-server-config.toml"); + assert!(matches!( + ServerConfig::load(missing), + Err(ConfigError::Read(_)) + )); + } +} diff --git a/pkgs/id/src/server_config/provision.rs b/pkgs/id/src/server_config/provision.rs new file mode 100644 index 0000000000..a08f897414 --- /dev/null +++ b/pkgs/id/src/server_config/provision.rs @@ -0,0 +1,536 @@ +//! Provisioning: applying a server config to one server's accounts and groups (P2.9). +//! +//! Provisioning goes through the paths a user action takes. A user is created with +//! [`Directory::sign_up_keyed`], the call a user makes to sign up with a key. A group is a create +//! event, and each member is an add event by the creator. Both are folded by [`fold`], so the Admin +//! check, the member cap, and the rest apply. The creator must pass the config's [`CreateRule`], +//! which is the limit a user's create meets. +//! +//! The events are derived from the config and are not signed. The config holds public keys only, +//! so there is no key to sign with. Each group is provisioned once: a second run skips a group that +//! exists, so a restart changes nothing and an Admin's later change is not undone. + +use p2panda_core::Hash; +use thiserror::Error; + +use super::{GroupSpec, ServerConfig}; +use crate::directory::Directory; +use crate::groups::{ + Body, Create, Event, FoldError, Key, MemberOp, Outcome, Policy, Projection, Refusal, Template, + fold, +}; +use crate::world::hex_encode; + +/// The accounts and group events of one server, as provisioning leaves them. +#[derive(Debug)] +pub struct Provisioned { + directory: Directory, + events: Vec, +} + +/// What one [`Provisioned::apply`] created. All zero means the config was already in effect. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Report { + /// Users whose accounts were created. + pub users_created: usize, + /// Groups created. + pub groups_created: usize, + /// Members added to the groups created. + pub members_added: usize, +} + +/// Why a config could not be applied. +#[derive(Clone, Debug, PartialEq, Eq, Error)] +pub enum ProvisionError { + /// The directory refused a user's account. + #[error("the directory refused user `{key}`: {message}")] + User { + /// The user's key. + key: String, + /// The directory's reason. + message: String, + }, + /// The config's create rule does not allow the group's creator. + #[error("group `{group}` is not allowed: its creator {creator} may not create groups")] + NotAllowed { + /// The group's key. + group: String, + /// The creator's public key, in hex. + creator: String, + }, + /// The group fold refused one of the group's events. + #[error("provisioning group `{group}` was refused: {refusal:?}")] + Refused { + /// The group's key. + group: String, + /// The fold's reason. + refusal: Refusal, + }, + /// The events cannot be folded. This means an invariant broke. + #[error(transparent)] + Fold(#[from] FoldError), +} + +impl Default for Provisioned { + fn default() -> Self { + Self::new() + } +} + +impl Provisioned { + /// Nothing provisioned yet: no accounts and no events. + #[must_use] + pub fn new() -> Self { + Self { + directory: Directory::new(), + events: Vec::new(), + } + } + + /// The accounts. + #[must_use] + pub const fn directory(&self) -> &Directory { + &self.directory + } + + /// Every group event, in the order it was recorded. + #[must_use] + pub fn events(&self) -> &[Event] { + &self.events + } + + /// The groups as the events determine them. + /// + /// # Errors + /// + /// Fails if the events cannot be folded. + pub fn projection(&self) -> Result { + fold(&self.events) + } + + /// Records one event, as a user action does. A refused event is kept in the log with no effect, + /// as the fold decides. Read its outcome from the returned groups. + /// + /// # Errors + /// + /// Fails if the events cannot be folded. + pub fn record(&mut self, event: Event) -> Result { + self.events.push(event); + self.projection() + } + + /// Creates the accounts and groups the config names, and adds their members. What already + /// exists is skipped, so a second run of the same config changes nothing. + /// + /// # Errors + /// + /// Fails on the first user the directory refuses, the first group whose creator the create rule + /// does not allow, or the first group event the fold refuses. A group that fails commits no + /// events. Users created before the failure stay, but the config is refused at startup, so no + /// server runs on that partial state. + pub fn apply(&mut self, config: &ServerConfig) -> Result { + let mut report = Report::default(); + for user in config.users() { + let id = hex_encode(&user.id); + if self.directory.account(&id).is_some() { + continue; + } + self.directory + .sign_up_keyed(&id, &user.key) + .map_err(|error| ProvisionError::User { + key: user.key.clone(), + message: format!("{error:#}"), + })?; + report.users_created += 1; + } + for group in config.groups() { + if self.events.iter().any(|event| event.id == group.id) { + continue; + } + if !config + .create_rule() + .allows(&group.creator, &self.projection()?) + { + return Err(ProvisionError::NotAllowed { + group: group.key.clone(), + creator: hex_encode(&group.creator), + }); + } + let batch = group_events(group); + let mut next = self.events.clone(); + next.extend(batch.iter().cloned()); + let projection = fold(&next)?; + for event in &batch { + if let Some(Outcome::Refused(refusal)) = projection.outcome(&event.id) { + return Err(ProvisionError::Refused { + group: group.key.clone(), + refusal: refusal.clone(), + }); + } + } + self.events = next; + report.groups_created += 1; + report.members_added += group.members.len(); + } + Ok(report) + } +} + +/// The events that create `group` and add its members. The create comes first, and each add follows +/// the one before it, so the group's events form one chain. +fn group_events(group: &GroupSpec) -> Vec { + let mut events = vec![Event { + id: group.id, + author: group.creator, + after: Vec::new(), + group: None, + body: Body::Create(Create { + template: Template::Custom, + policy: Policy::default(), + members: Vec::new(), + admins_on_create: false, + }), + }]; + for (member, role) in &group.members { + let after = events.last().map_or(group.id, |event| event.id); + events.push(Event { + id: add_id(&group.id, member), + author: group.creator, + after: vec![after], + group: Some(group.id), + body: Body::Member(MemberOp::Add { + member: *member, + role: *role, + }), + }); + } + events +} + +/// The ID of the event that adds `member` to `group`. Each member is added once, so the ID is the +/// same on every start. +fn add_id(group: &Hash, member: &Key) -> Hash { + let mut bytes = b"id-config-add-v1".to_vec(); + bytes.extend_from_slice(group.as_bytes()); + bytes.extend_from_slice(member); + Hash::digest(bytes) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used)] +mod tests { + use std::fmt::Write as _; + + use ed25519_dalek::SigningKey; + use p2panda_core::Hash; + use proptest::prelude::*; + + use super::{ProvisionError, Provisioned, Report}; + use crate::groups::{Body, Event, Key, MemberOp, Outcome, Role}; + use crate::server_config::ServerConfig; + use crate::world::hex_encode; + + fn key(n: u8) -> Key { + SigningKey::from_bytes(&[n; 32]).verifying_key().to_bytes() + } + + fn hex(n: u8) -> String { + hex_encode(&key(n)) + } + + /// Four users: ann (1), bo (2), cy (3), and dee (4). + fn users() -> String { + format!( + "[[users]]\nkey = \"ann\"\nid = \"{}\"\n\n[[users]]\nkey = \"bo\"\nid = \"{}\"\n\n\ + [[users]]\nkey = \"cy\"\nid = \"{}\"\n\n[[users]]\nkey = \"dee\"\nid = \"{}\"\n", + hex(1), + hex(2), + hex(3), + hex(4) + ) + } + + fn config(extra: &str) -> String { + format!("{}{extra}", users()) + } + + /// A group `team`, created by ann, with bo as a writer and cy as a reader. + const TEAM: &str = "\n[[groups]]\nkey = \"team\"\nname = \"Team\"\ncreator = \"ann\"\n\n\ + [[groups.members]]\nuser = \"bo\"\nrole = \"write\"\n\n\ + [[groups.members]]\nuser = \"cy\"\nrole = \"read\"\n"; + + /// The group `staff`, created by ann, with bo as a writer, cy as a reader, and dee as a manager. + const STAFF: &str = "\n[[groups]]\nkey = \"staff\"\nname = \"Staff\"\ncreator = \"ann\"\n\n\ + [[groups.members]]\nuser = \"bo\"\nrole = \"write\"\n\n\ + [[groups.members]]\nuser = \"cy\"\nrole = \"read\"\n\n\ + [[groups.members]]\nuser = \"dee\"\nrole = \"manage\"\n"; + + /// Ann may create, and so may members of `staff` at or above write. + fn floor_config(creator: &str) -> String { + config(&format!( + "\n[create]\nusers = [\"ann\"]\ngroups = [\"staff\"]\nmin_role = \"write\"\n{STAFF}\n\ + [[groups]]\nkey = \"new\"\nname = \"New\"\ncreator = \"{creator}\"\n" + )) + } + + fn apply(text: &str) -> (Provisioned, Result) { + let config = ServerConfig::parse(text).unwrap(); + let mut state = Provisioned::new(); + let result = state.apply(&config); + (state, result) + } + + fn view_of( + state: &Provisioned, + config: &ServerConfig, + group: &str, + ) -> crate::groups::GroupView { + let id = config.group_id(group).unwrap(); + state.projection().unwrap().group(&id).cloned().unwrap() + } + + #[test] + fn test_a_config_creates_its_users_groups_and_members() { + let (state, result) = apply(&config(TEAM)); + assert_eq!( + result.unwrap(), + Report { + users_created: 4, + groups_created: 1, + members_added: 2, + } + ); + assert!(state.directory().account(&hex(1)).is_some()); + assert!(state.directory().account(&hex(4)).is_some()); + + let config = ServerConfig::parse(&config(TEAM)).unwrap(); + let view = view_of(&state, &config, "team"); + assert_eq!( + view.members.get(&key(1)), + Some(&Role::Admin), + "the creator is Admin" + ); + assert_eq!(view.members.get(&key(2)), Some(&Role::Write)); + assert_eq!(view.members.get(&key(3)), Some(&Role::Read)); + assert_eq!(view.members.get(&key(4)), None, "dee is not listed in team"); + } + + #[test] + fn test_a_restart_with_the_same_config_creates_nothing() { + let text = config(TEAM); + let (mut state, first) = apply(&text); + first.unwrap(); + let events = state.events().to_vec(); + let accounts = state.directory().accounts().count(); + + // A restart reads the same file again, into a new config. + let restarted = ServerConfig::parse(&text).unwrap(); + assert_eq!(state.apply(&restarted), Ok(Report::default())); + assert_eq!(state.events(), events.as_slice()); + assert_eq!(state.directory().accounts().count(), accounts); + } + + #[test] + fn test_a_fresh_start_with_the_same_config_gives_the_same_state() { + let text = config(TEAM); + let (first, _) = apply(&text); + let (second, _) = apply(&text); + assert_eq!(first.events(), second.events()); + let ids = |state: &Provisioned| -> Vec { + state + .directory() + .accounts() + .map(|account| account.id.clone()) + .collect() + }; + assert_eq!(ids(&first), ids(&second)); + } + + #[test] + fn test_a_member_an_admin_removed_is_not_added_again_on_restart() { + // Provisioning runs once per group. An Admin's later change is a user action, and a + // restart must not undo it. + let text = config(TEAM); + let config = ServerConfig::parse(&text).unwrap(); + let (mut state, first) = apply(&text); + first.unwrap(); + let team = config.group_id("team").unwrap(); + let last = state.events().last().unwrap().id; + let remove_id = Hash::digest(b"ann removes bo"); + let remove_bo = Event { + id: remove_id, + author: key(1), + after: vec![last], + group: Some(team), + body: Body::Member(MemberOp::Remove { member: key(2) }), + }; + let projection = state.record(remove_bo).unwrap(); + assert_eq!(projection.outcome(&remove_id), Some(&Outcome::Applied)); + + assert_eq!(state.apply(&config), Ok(Report::default())); + let view = view_of(&state, &config, "team"); + assert_eq!(view.members.get(&key(2)), None, "bo stays removed"); + assert_eq!(view.members.get(&key(3)), Some(&Role::Read)); + } + + #[test] + fn test_a_listed_user_may_create_a_group() { + let text = config( + "\n[create]\nusers = [\"ann\"]\n\n[[groups]]\nkey = \"team\"\nname = \"Team\"\ncreator = \"ann\"\n", + ); + let (state, result) = apply(&text); + assert_eq!(result.unwrap().groups_created, 1); + assert!(!state.events().is_empty()); + } + + #[test] + fn test_an_unlisted_user_may_not_create_a_group_and_nothing_is_committed() { + let text = config( + "\n[create]\nusers = [\"ann\"]\n\n[[groups]]\nkey = \"team\"\nname = \"Team\"\ncreator = \"bo\"\n", + ); + let (state, result) = apply(&text); + assert!(matches!(result, Err(ProvisionError::NotAllowed { .. }))); + assert!(state.events().is_empty(), "a refused group leaves no event"); + } + + #[test] + fn test_a_member_of_a_listed_group_at_the_floor_may_create() { + let (_, result) = apply(&floor_config("bo")); + assert!(result.is_ok(), "bo is a writer, the floor: {result:?}"); + } + + #[test] + fn test_a_member_of_a_listed_group_above_the_floor_may_create() { + let (_, result) = apply(&floor_config("dee")); + assert!( + result.is_ok(), + "dee is a manager, above the floor: {result:?}" + ); + } + + #[test] + fn test_a_member_of_a_listed_group_below_the_floor_may_not_create() { + let (_, result) = apply(&floor_config("cy")); + assert!( + matches!(result, Err(ProvisionError::NotAllowed { .. })), + "cy is a reader, below the floor: {result:?}" + ); + } + + #[test] + fn test_with_no_floor_any_member_of_a_listed_group_may_create() { + let text = config(&format!( + "\n[create]\nusers = [\"ann\"]\ngroups = [\"staff\"]\n{STAFF}\n\ + [[groups]]\nkey = \"new\"\nname = \"New\"\ncreator = \"cy\"\n" + )); + let (_, result) = apply(&text); + assert!( + result.is_ok(), + "any member may create with no floor: {result:?}" + ); + } + + #[test] + fn test_a_group_admitted_by_a_group_declared_later_is_refused() { + // The config's order decides: `new` is checked before `staff` exists. + let text = config(&format!( + "\n[create]\nusers = [\"ann\"]\ngroups = [\"staff\"]\nmin_role = \"write\"\n\n\ + [[groups]]\nkey = \"new\"\nname = \"New\"\ncreator = \"bo\"\n{STAFF}" + )); + let (_, result) = apply(&text); + assert!(matches!(result, Err(ProvisionError::NotAllowed { .. }))); + } + + /// A random config: `users` users, groups with random creators and members, and one of three + /// create rules. Each rule may refuse some creators, and the property holds either way. + #[derive(Debug, Clone)] + struct Spec { + users: usize, + /// 0: anyone. 1: every user is listed. 2: only u0 is listed. + rule: u8, + /// Each group: a creator index, and members as (index, role) pairs. + groups: Vec<(usize, Vec<(usize, u8)>)>, + } + + impl Spec { + fn render(&self) -> String { + let mut text = String::new(); + for user in 0..self.users { + let id = hex(u8::try_from(user + 1).unwrap()); + write!(text, "[[users]]\nkey = \"u{user}\"\nid = \"{id}\"\n\n").unwrap(); + } + match self.rule { + 0 => {} + 1 => { + let all: Vec = + (0..self.users).map(|user| format!("\"u{user}\"")).collect(); + write!(text, "[create]\nusers = [{}]\n\n", all.join(", ")).unwrap(); + } + _ => text.push_str("[create]\nusers = [\"u0\"]\n\n"), + } + let roles = ["pull", "read", "write", "manage", "admin"]; + for (group, (creator, members)) in self.groups.iter().enumerate() { + let creator = creator % self.users; + write!( + text, + "[[groups]]\nkey = \"g{group}\"\nname = \"G{group}\"\ncreator = \"u{creator}\"\n\n" + ) + .unwrap(); + let mut seen = std::collections::BTreeSet::from([creator]); + for (member, role) in members { + let member = member % self.users; + if !seen.insert(member) { + continue; + } + let role = roles[usize::from(*role)]; + write!( + text, + "[[groups.members]]\nuser = \"u{member}\"\nrole = \"{role}\"\n\n" + ) + .unwrap(); + } + } + text + } + } + + fn spec() -> impl Strategy { + ( + 1usize..=4, + 0u8..3, + prop::collection::vec( + (0usize..4, prop::collection::vec((0usize..4, 0u8..5), 0..4)), + 0..4, + ), + ) + .prop_map(|(users, rule, groups)| Spec { + users, + rule, + groups, + }) + } + + proptest! { + #![proptest_config(ProptestConfig::with_cases(64))] + + #[test] + fn prop_the_same_config_applied_twice_gives_the_same_state(spec in spec()) { + let text = spec.render(); + let config = ServerConfig::parse(&text).unwrap(); + + // A fresh start gives the same answer as the first run, success or refusal. + let mut once = Provisioned::new(); + let first = once.apply(&config); + let fresh = Provisioned::new().apply(&config); + prop_assert_eq!(&first, &fresh); + + if first.is_ok() { + let events = once.events().to_vec(); + let accounts = once.directory().accounts().count(); + prop_assert_eq!(once.apply(&config), Ok(Report::default())); + prop_assert_eq!(once.events(), events.as_slice()); + prop_assert_eq!(once.directory().accounts().count(), accounts); + } + } + } +} From d5ec38286794a3116ae52d53ee00a1874b51e060 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 12 Oct 2026 02:30:37 -0500 Subject: [PATCH 26/40] fix(rust): a create may not take over an existing group [P2.3] A create names its group since P2.4, and before that it always took its own ID. Merging phase-2 let a create name any group. The gate admitted every create, so a stranger's create naming an existing group added its members to that group, with manage access. The gate now refuses a create for a group that a create has already made (GroupExists). The first create stands. --- pkgs/id/src/membership/gate.rs | 14 +++++++++++- pkgs/id/src/membership/layer.rs | 39 +++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 1 deletion(-) diff --git a/pkgs/id/src/membership/gate.rs b/pkgs/id/src/membership/gate.rs index 92cac8c3e0..dc6ce74bb4 100644 --- a/pkgs/id/src/membership/gate.rs +++ b/pkgs/id/src/membership/gate.rs @@ -23,6 +23,9 @@ pub enum Rejection { NoDependencies, /// The operation's group does not exist at its dependencies. The crate would panic on it. GroupAbsent, + /// A create for a group that a create has already made. A create may name its group (P2.4), + /// so a second one could add members to a group it did not make. The first create stands. + GroupExists, } /// What the gate decides for one operation. @@ -48,7 +51,16 @@ pub fn admit(state: &GroupState, op: &AuthOperation) -> Admission { return Admission::Wait(missing); } if op.action.is_create() { - return Admission::Admit; + let made = state + .inner + .operations + .values() + .any(|applied| applied.action.is_create() && applied.group_id == op.group_id); + return if made { + Admission::Reject(Rejection::GroupExists) + } else { + Admission::Admit + }; } if op.dependencies.is_empty() { return Admission::Reject(Rejection::NoDependencies); diff --git a/pkgs/id/src/membership/layer.rs b/pkgs/id/src/membership/layer.rs index 361751a45a..312a36cc4b 100644 --- a/pkgs/id/src/membership/layer.rs +++ b/pkgs/id/src/membership/layer.rs @@ -672,6 +672,45 @@ mod tests { assert!(layer.members(id(10)).is_empty()); } + #[test] + fn test_a_create_naming_a_group_that_exists_adds_no_members() { + // Before P2.4 a create's group was its own ID, so no create could reach a group another + // had made. Now a create names its group, and a stranger's create that names it must not + // give the stranger access to it. + let mut layer = Membership::new(); + let made = GroupAction::Create { + initial_members: vec![ + ( + GroupMember::Individual(AuthId::Key(key(1))), + Access::manage(), + ), + ( + GroupMember::Individual(AuthId::Key(key(2))), + Access::manage(), + ), + ], + }; + layer.receive(auth(10, 1, Some(30), &[], made)).unwrap(); + let stranger = GroupAction::Create { + initial_members: vec![( + GroupMember::Individual(AuthId::Key(key(9))), + Access::manage(), + )], + }; + let outcomes = layer.receive(auth(11, 9, Some(30), &[], stranger)).unwrap(); + assert!(matches!( + outcome_of(&outcomes, 11), + Outcome::Refused { + reason: Refusal::Gate(Rejection::GroupExists), + .. + } + )); + assert_eq!( + member_keys(&layer, 30), + vec![AuthId::Key(key(1)), AuthId::Key(key(2))] + ); + } + #[test] fn test_a_non_create_with_no_group_is_refused_as_malformed() { let mut layer = Membership::new(); From e1b9571b24ce5dffe238221930ed18626f684597 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 12 Oct 2026 02:30:37 -0500 Subject: [PATCH 27/40] fix(rust): a backlink that is a fork proof header parks [P2.3] A released event whose backlink was another author's fork proof header was held to wait for that header. The header is present but never stored, so the stored row waited on a present dependency and the store reported corruption on its next open. The backlink check now asks whether the hash is present, as the after check does. Such an event can never link, so it parks. --- pkgs/id/src/event_store/ingest.rs | 38 ++++++++++++++++++++++++++++--- 1 file changed, 35 insertions(+), 3 deletions(-) diff --git a/pkgs/id/src/event_store/ingest.rs b/pkgs/id/src/event_store/ingest.rs index ca1d2fcc58..2efd0b18de 100644 --- a/pkgs/id/src/event_store/ingest.rs +++ b/pkgs/id/src/event_store/ingest.rs @@ -518,8 +518,10 @@ fn decide_in( } // The backlink must be the stored event before this one. Voided events are stored, so a - // backlink does not need to be applied. A backlink that is stored at another position, or - // that is missing where there is no backlink, can never link, so the event is parked. + // backlink does not need to be applied. A backlink that is present at another position, or + // that is missing where there is no backlink, can never link, so the event is parked. A fork + // proof header is present but never stored, so it is parked too: waiting for it would wait on + // a dependency that is already present. let mut waits = missing_deps(txn, &event.header.extensions.after)?; if seq > 0 { let linked = match event.header.backlink { @@ -530,7 +532,7 @@ fn decide_in( }; if !linked { match event.header.backlink { - Some(backlink) if !is_stored(txn, &backlink)? => waits.push(backlink), + Some(backlink) if !is_present(txn, &backlink)? => waits.push(backlink), _ => return Ok(Decision::Park), } } @@ -1089,6 +1091,36 @@ mod tests { store.check_invariants().unwrap(); } + #[test] + fn test_a_released_event_whose_backlink_is_a_fork_proof_header_is_parked() { + // R, by another author, names H2 as its backlink and waits for it. H2 is a rival of the + // applied H1 by the first author, so its arrival forks that chain, and H2 becomes a proof + // header: present, but never stored. R is released by that. It cannot link to H2, so it + // must park. Holding it to wait for H2 would wait on a dependency that is already present. + // R is not the forking author's event: an event above the fork point is refused as frozen + // before the backlink is read, so only another author's backlink reaches this path. + let (_dir, mut store) = open(); + let forker = key(15); + let other = key(16); + let applied = event(&forker, 0, None, Vec::new(), "first"); + let rival = event(&forker, 0, None, Vec::new(), "rival"); + let after = event(&other, 1, Some(rival.id), Vec::new(), "after"); + assert!(matches!( + ingest(&mut store, &applied), + Ingest::Accepted { .. } + )); + assert_eq!(ingest(&mut store, &after), Ingest::Waiting { id: after.id }); + assert!(matches!( + ingest(&mut store, &rival), + Ingest::Fork { seq: 0, .. } + )); + store.check_invariants().unwrap(); + assert!( + store.event(&author(&other), 1).unwrap().is_none(), + "a parked event is not stored" + ); + } + #[test] fn test_bytes_that_do_not_verify_are_refused_and_change_nothing() { let (_dir, mut store) = open(); From 0970ee94cebda97e67e98ea63a5842d1d542b889 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 12 Oct 2026 03:09:20 -0500 Subject: [PATCH 28/40] feat(rust): delegation modes keep_prior, cascade, transfer [P2.5] A delegation is a grant from a member to an account inside a group, with a scope (Pull to Manage) and a redelegate flag. A grant may not be wider than the grantor's scope at its position. An account acts through a chain of grants that starts at an owner (a root the create named). A manager added by someone else has membership but no authority until a grant reaches it, as S2 chose. - Body::Delegate and Body::Veto. A veto is a Manage member's act that cuts a grant the veto has seen, and what depends on it, from its position on. - MemberOp::Remove names an optional successor, used by transfer. - A manager's add, remove or role change needs a chain (NoChain). - Modes, read from the group policy (unset means cascade): keep_prior keeps grants made before the removal; cascade keeps a grant only while its grantor still holds the scope; transfer supersedes the removed member's grants and reissues them from the successor, judged at the removal's `after`. - Strong remove voids a grant made concurrently with a removal of its grantor. The removal set is settled over rounds, because a removal can be filtered or vetoed; the fold stops when a round reproduces its own set, or returns FoldError::Unsettled. - Projection::takes_effect and Projection::grant_in_force. Tests: unit per mode, attenuation, redelegation, chain search, veto, the S2 delegation table as a regression, and two properties over random scripts (arrival order; no grant outlives its grantor's removal unless its mode keeps it). --- pkgs/id/src/groups/delegation.rs | 369 +++++++++++++++++++ pkgs/id/src/groups/fold.rs | 302 +++++++++++++--- pkgs/id/src/groups/mod.rs | 25 ++ pkgs/id/src/groups/policy.rs | 18 +- pkgs/id/src/groups/tests.rs | 602 ++++++++++++++++++++++++++++++- pkgs/id/src/membership/layer.rs | 16 + 6 files changed, 1282 insertions(+), 50 deletions(-) create mode 100644 pkgs/id/src/groups/delegation.rs diff --git a/pkgs/id/src/groups/delegation.rs b/pkgs/id/src/groups/delegation.rs new file mode 100644 index 0000000000..1041f335f6 --- /dev/null +++ b/pkgs/id/src/groups/delegation.rs @@ -0,0 +1,369 @@ +//! Delegation (P2.5, design §7): grants between accounts inside a group, the chain search that +//! decides whether an account may act at a causal position, the three removal modes, and vetoes. +//! +//! A grant is an event by a grantor who holds the scope there. An account may exercise a scope +//! only through a chain of grants that starts at a root. The roots are the accounts a group's +//! create named, its creator included. A manager added by someone else has membership, but no +//! authority until a grant reaches it. This is S2's choice: the owner is the only root. +//! +//! Each link attenuates: a grantor passes on no more than it holds. A link carries authority at a +//! position when its grantor was valid where it was made, the grant is not voided by a concurrent +//! removal of its grantor, no veto in the position's past cuts it, and the group's mode lets it +//! stand there (design §7.3). +//! +//! The mode decides a removed member's grants. Under `keep_prior` they stand. Under `cascade` they +//! stand only while the grantor still holds the scope. Under `transfer` the removal's successor +//! reissues them, from the removal on, if it holds the scope then and now. + +use std::collections::{BTreeMap, BTreeSet}; + +use p2panda_core::Hash; + +use super::fold::{Decision, Effect, Engine, FoldError, Judged, Refusal, access_role, causal_past}; +use super::policy::Delegation; +use super::{Body, Delegate, Event, Key, MemberOp, Role}; + +/// A grant that took effect: `from` gave `to` the scope `scope` in `group`, as event `id`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(super) struct Grant { + pub(super) id: Hash, + pub(super) group: Hash, + pub(super) from: Key, + pub(super) to: Key, + pub(super) scope: Role, + pub(super) redelegate: bool, +} + +/// A removal that took effect. Its successor takes over the removed member's grants under +/// `transfer`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(super) struct Removal { + pub(super) id: Hash, + pub(super) group: Hash, + pub(super) member: Key, + pub(super) successor: Option, + /// The removal's `after`. A successor is judged there, not at the removal itself: the removal's + /// own position already contains the reissue, so judging it there would recurse. + pub(super) after: Vec, +} + +/// The account a removal event removes, if the event is one. +const fn removed_member(event: &Event) -> Option { + match &event.body { + Body::Member(MemberOp::Remove { member, .. }) => Some(*member), + _ => None, + } +} + +/// One link of a chain at a position: `from` may give `scope` to `to`. A reissued link is a grant +/// from a successor. It stands for the removed member's grant `origin`. +#[derive(Clone, Debug)] +struct Link { + origin: Hash, + from: Key, + to: Key, + scope: Role, + redelegate: bool, + reissued: bool, +} + +impl Engine { + /// Judges a grant. The author must be an active member who holds the scope at the event's + /// position, and must reach it through a chain that can be passed on. + pub(super) fn delegate( + &mut self, + by_id: &BTreeMap, + event: &Event, + delegate: Delegate, + ) -> Result { + let group = match self.acting_in(event) { + Ok(group) => group, + Err(refusal) => return Ok(Err(refusal)), + }; + if delegate.scope == Role::Admin { + return Ok(Err(Refusal::BadScope)); + } + if delegate.grantee == event.author { + return Ok(Err(Refusal::BadGrantee)); + } + if !self.holds(group, event.author, delegate.scope, &event.after)? { + return Ok(Err(Refusal::Attenuated)); + } + if !self.authorized( + by_id, + group, + event.author, + delegate.scope, + &event.after, + true, + )? { + return Ok(Err(Refusal::NoChain)); + } + Ok(Ok(Decision { + group, + action: None, + effect: Effect::Delegation(delegate), + })) + } + + /// Judges a veto. The author must hold Manage and a chain, and the grant must be one the veto + /// has seen. + pub(super) fn veto( + &mut self, + by_id: &BTreeMap, + event: &Event, + grant: Hash, + ) -> Result { + let group = match self.acting_in(event) { + Ok(group) => group, + Err(refusal) => return Ok(Err(refusal)), + }; + let seen = causal_past(by_id, &event.after); + let known = self + .grants + .get(&grant) + .is_some_and(|target| target.group == group) + && seen.contains(&grant); + if !known { + return Ok(Err(Refusal::UnknownGrant)); + } + if !self.holds(group, event.author, Role::Manage, &event.after)? { + return Ok(Err(Refusal::NotManager)); + } + if !self.authorized( + by_id, + group, + event.author, + Role::Manage, + &event.after, + false, + )? { + return Ok(Err(Refusal::NoChain)); + } + Ok(Ok(Decision { + group, + action: None, + effect: Effect::Veto(grant), + })) + } + + /// Judges a manager's membership change, which the membership layer would otherwise accept. A + /// manager needs a chain from an owner. Removing oneself is leaving, and needs none. + pub(super) fn manage_chain( + &mut self, + by_id: &BTreeMap, + event: &Event, + op: MemberOp, + decision: Decision, + ) -> Result { + if let MemberOp::Remove { member, .. } = op + && member == event.author + { + return Ok(Ok(decision)); + } + let manages = self.authorized( + by_id, + decision.group, + event.author, + Role::Manage, + &event.after, + false, + )?; + if manages { + Ok(Ok(decision)) + } else { + Ok(Err(Refusal::NoChain)) + } + } + + /// The grants in force at the head of the events: every grant that its own link carries when + /// every event is in the past. Each is reported once, under its own event ID. + pub(super) fn in_force( + &mut self, + by_id: &BTreeMap, + ) -> Result, FoldError> { + let head: Vec = by_id.keys().copied().collect(); + let groups: Vec = self.groups.keys().copied().collect(); + let mut in_force = BTreeSet::new(); + for group in groups { + for link in self.links(by_id, group, &head)? { + if !link.reissued { + in_force.insert(link.origin); + } + } + } + Ok(in_force) + } + + /// Whether `actor` may exercise `scope` in `group` at the causal position `after` (design + /// §7.2). A root that holds the scope there is authorized. Otherwise a chain of links leads + /// from a root holding the scope to the actor, every link attenuating. With `need_redelegate`, + /// the last link into the actor must allow the actor to grant on. The actor's own membership + /// is not checked here: a grant may reach an account that is not a member. + pub(super) fn authorized( + &mut self, + by_id: &BTreeMap, + group: Hash, + actor: Key, + scope: Role, + after: &[Hash], + need_redelegate: bool, + ) -> Result { + let Some(record) = self.groups.get(&group) else { + return Ok(false); + }; + let roots = record.roots.clone(); + if roots.contains(&actor) && self.holds(group, actor, scope, after)? { + return Ok(true); + } + let links = self.links(by_id, group, after)?; + let mut reached = BTreeSet::new(); + for root in roots { + if self.holds(group, root, scope, after)? { + reached.insert(root); + } + } + let mut stack: Vec = reached.iter().copied().collect(); + while let Some(holder) = stack.pop() { + for link in links + .iter() + .filter(|link| link.from == holder && link.scope >= scope) + { + if link.to == actor && (!need_redelegate || link.redelegate) { + return Ok(true); + } + if link.redelegate && reached.insert(link.to) { + stack.push(link.to); + } + } + } + Ok(false) + } + + /// Whether `who` holds `scope` in `group` at the causal position `after`, by membership. + fn holds( + &mut self, + group: Hash, + who: Key, + scope: Role, + after: &[Hash], + ) -> Result { + let access = self.membership.access_at_position(after, group, who)?; + Ok(access.is_some_and(|access| access_role(&access) >= scope)) + } + + /// The links that carry authority at `after`, in the group's mode (design §7.3). + fn links( + &mut self, + by_id: &BTreeMap, + group: Hash, + after: &[Hash], + ) -> Result, FoldError> { + let Some(mode) = self + .groups + .get(&group) + .map(|record| record.policy.delegation_mode()) + else { + return Ok(Vec::new()); + }; + let past = causal_past(by_id, after); + let grants: Vec = self + .grants + .values() + .filter(|grant| { + grant.group == group && past.contains(&grant.id) && self.settled.contains(&grant.id) + }) + .cloned() + .collect(); + let removals: Vec = self + .removals + .values() + .filter(|removal| { + removal.group == group + && past.contains(&removal.id) + && self.settled.contains(&removal.id) + }) + .cloned() + .collect(); + let mut links = Vec::new(); + for grant in grants { + if self.void(by_id, &grant) || self.vetoed(grant.id, &past) { + continue; + } + let removed: Vec<&Removal> = removals + .iter() + .filter(|removal| removal.member == grant.from) + .collect(); + if mode == Delegation::Transfer && !removed.is_empty() { + // The removed grantor's own link is superseded. Each successor the removals name + // reissues it from the removal on, if it held the scope then and holds it here. + for removal in removed { + let Some(successor) = removal.successor else { + continue; + }; + if !causal_past(by_id, &[removal.id]).contains(&grant.id) { + continue; + } + let holds_now = self.holds(group, successor, grant.scope, after)?; + if holds_now + && self.authorized( + by_id, + group, + successor, + grant.scope, + &removal.after, + true, + )? + { + links.push(Link { + origin: grant.id, + from: successor, + to: grant.to, + scope: grant.scope, + redelegate: grant.redelegate, + reissued: true, + }); + } + } + continue; + } + if mode == Delegation::Cascade && !self.holds(group, grant.from, grant.scope, after)? { + continue; + } + links.push(Link { + origin: grant.id, + from: grant.from, + to: grant.to, + scope: grant.scope, + redelegate: grant.redelegate, + reissued: false, + }); + } + Ok(links) + } + + /// Whether a settled removal of the grantor is concurrent with the grant: neither is in the + /// other's causal past. Strong remove voids such a grant (design §6.2 and §7.3). The removals + /// are read from the events, not from the round's state: a concurrent removal may be judged + /// after the grant in canonical order. + fn void(&self, by_id: &BTreeMap, grant: &Grant) -> bool { + let past_grant = causal_past(by_id, &[grant.id]); + self.settled + .iter() + .filter_map(|id| by_id.get(id).copied()) + .filter(|event| { + event.group == Some(grant.group) && removed_member(event) == Some(grant.from) + }) + .any(|removal| { + !past_grant.contains(&removal.id) + && !causal_past(by_id, &[removal.id]).contains(&grant.id) + }) + } + + /// Whether a veto of the grant is in `past`. + fn vetoed(&self, grant: Hash, past: &BTreeSet) -> bool { + self.vetoes.iter().any(|(veto, target)| { + *target == grant && past.contains(veto) && self.settled.contains(veto) + }) + } +} diff --git a/pkgs/id/src/groups/fold.rs b/pkgs/id/src/groups/fold.rs index 47ed23f68e..d2f1805ffb 100644 --- a/pkgs/id/src/groups/fold.rs +++ b/pkgs/id/src/groups/fold.rs @@ -13,6 +13,11 @@ //! Membership operations go to [`crate::membership`], which decides them on p2panda-auth. Each //! event is handed to it once, so the causal index stays complete. An event this layer refuses is //! handed over as a no-op. +//! +//! Delegation (P2.5) is judged in [`super::delegation`]. Whether a grant or a removal takes effect +//! can depend on a concurrent event (strong remove), so the fold runs in rounds. Each round judges +//! the events against the set that took effect in the round before, and the fold stops when a +//! round reproduces its own set. The set depends only on the events, so the result does too. use std::cmp::{Ordering, Reverse}; use std::collections::{BTreeMap, BTreeSet, BinaryHeap}; @@ -27,9 +32,10 @@ use crate::membership::{ Role as Placement, }; +use super::delegation::{Grant, Removal}; use super::friendship::{Pair, friendship_id}; use super::policy::{OnMemberRemoved, Policy, Template}; -use super::{Body, Create, Event, Key, MemberOp, Role}; +use super::{Body, Create, Delegate, Event, Key, MemberOp, Role}; /// Why an event had no effect. A refused event changes no state. It is still decided, so the /// events after it can be decided too. @@ -76,6 +82,18 @@ pub enum Refusal { AlreadyPresent, /// The membership layer refused it at its causal position. Membership(AuthRefusal), + /// The author does not hold the scope at the grant's position, so it may not grant it + /// (design §7.2, attenuation). + Attenuated, + /// The author holds no chain of grants to the scope it needs (design §7.2). A manager acts + /// only through a grant that reaches it from an owner. + NoChain, + /// A grant may not name Admin. Admin is a policy right, not a scope. + BadScope, + /// A grant may not name its own author. + BadGrantee, + /// A veto names no grant of this group that the veto has seen. + UnknownGrant, } /// What became of one event. @@ -107,6 +125,10 @@ pub enum FoldError { /// The membership layer broke an invariant. #[error(transparent)] Membership(#[from] MembershipError), + /// The grants, vetoes and removals that take effect do not settle on one set. Each round + /// judges the events against the set of the round before, and the sets keep changing. + #[error("the events that take effect do not settle")] + Unsettled, } /// One group as the events determine it. @@ -143,6 +165,8 @@ impl GroupView { pub struct Projection { groups: BTreeMap, outcomes: BTreeMap, + effective: BTreeSet, + in_force: BTreeSet, } impl Projection { @@ -169,6 +193,21 @@ impl Projection { .any(|group| group.friendship == Some(pair) && group.is_active()) }) } + + /// Whether the event takes effect in the settled state. A grant, a veto or a membership + /// operation takes effect when it was applied and p2panda-auth's resolver does not filter it. + /// An event that was applied but filtered does not take effect. + pub fn takes_effect(&self, id: &Hash) -> bool { + self.effective.contains(id) + } + + /// Whether the grant with this event ID is in force at the head of the events (design §7.3). + /// A concurrent removal of its grantor voids it, a veto cuts it, and the group's mode decides + /// the rest. The chain above the grant is not checked here. Use the outcomes of the actions + /// it was meant to allow for that. + pub fn grant_in_force(&self, id: &Hash) -> bool { + self.in_force.contains(id) + } } /// Computes the state of every group from the whole set of events. The order the events are given @@ -176,13 +215,49 @@ impl Projection { pub fn fold(events: &[Event]) -> Result { let by_id = index(events)?; let order = canonical_order(&by_id)?; - let mut engine = Engine::default(); + // The events whose effect depends on the settled set: grants, vetoes, and membership changes. + let candidates: BTreeSet = by_id + .values() + .filter(|event| is_candidate(event)) + .map(|event| event.id) + .collect(); + let rounds = candidates.len() + 1; + let mut settled = candidates; + for _ in 0..=rounds { + let (projection, next) = run(&order, &by_id, &settled)?; + if next == settled { + return Ok(projection); + } + settled = next; + } + Err(FoldError::Unsettled) +} + +/// One round: every event judged against `settled`. Returns the projection and the set of +/// candidate events that took effect in this round. +fn run( + order: &[&Event], + by_id: &BTreeMap, + settled: &BTreeSet, +) -> Result<(Projection, BTreeSet), FoldError> { + let mut engine = Engine::new(settled.clone()); let mut outcomes = BTreeMap::new(); - for event in order { - let outcome = engine.apply(event, &by_id)?; + for &event in order { + let outcome = engine.apply(event, by_id)?; outcomes.insert(event.id, outcome); } - Ok(engine.into_projection(outcomes)) + let effective = engine.effective(); + let in_force = engine.in_force(by_id)?; + let projection = engine.into_projection(outcomes, effective.clone(), in_force); + Ok((projection, effective)) +} + +/// Whether the event's effect depends on the settled set. +const fn is_candidate(event: &Event) -> bool { + matches!( + event.body, + Body::Delegate(_) | Body::Veto { .. } | Body::Member(_) + ) } /// The events by ID. Every `after` hash must name one of them. @@ -244,7 +319,7 @@ fn canonical_order<'a>(by_id: &BTreeMap) -> Result, after: &[Hash]) -> BTreeSet { +pub(super) fn causal_past(by_id: &BTreeMap, after: &[Hash]) -> BTreeSet { let mut past = BTreeSet::new(); let mut stack: Vec = after.to_vec(); while let Some(id) = stack.pop() { @@ -260,18 +335,21 @@ fn causal_past(by_id: &BTreeMap, after: &[Hash]) -> BTreeSet /// What a group holds beyond its membership layer state. #[derive(Clone, Debug, PartialEq, Eq)] -struct Record { - policy: Policy, - admins: BTreeSet, - present: BTreeSet, - friendship: Option, - dissolved_by: Option, +pub(super) struct Record { + pub(super) policy: Policy, + pub(super) admins: BTreeSet, + pub(super) present: BTreeSet, + pub(super) friendship: Option, + pub(super) dissolved_by: Option, + /// The accounts the create named, its author included. They are the owners: the roots of + /// every delegation chain (design §7.2, as S2 chose it). + pub(super) roots: BTreeSet, } /// The state change an accepted event makes. It is committed once the membership layer accepts /// the event. #[derive(Debug)] -enum Effect { +pub(super) enum Effect { Create(Record), Present(Key), Policy(Policy), @@ -282,57 +360,85 @@ enum Effect { Remove { member: Key, dissolves: bool, + successor: Option, by: Hash, }, + Delegation(Delegate), + Veto(Hash), } /// A rule's decision: the membership operation to hand to the membership layer, and the state /// change to commit if the layer accepts it. #[derive(Debug)] -struct Decision { - group: Hash, - action: Option>, - effect: Effect, +pub(super) struct Decision { + pub(super) group: Hash, + pub(super) action: Option>, + pub(super) effect: Effect, } +/// A rule's verdict: a decision, or the reason it has no effect. +pub(super) type Judged = Result; + +/// Placement of an event in the membership layer, as a label for the layer. +type Placed = Placement; + /// The state while the events are applied in canonical order. #[derive(Debug, Default)] -struct Engine { - membership: Membership, - groups: BTreeMap, +pub(super) struct Engine { + pub(super) membership: Membership, + pub(super) groups: BTreeMap, + /// The candidate events that took effect in the previous round. + pub(super) settled: BTreeSet, + /// The candidate events applied in this round. + applied: BTreeSet, + /// The applied candidates that are membership operations in the auth graph. + placed: BTreeSet, + /// The grants applied in this round, by event ID. + pub(super) grants: BTreeMap, + /// The vetoes applied in this round, each with the grant it vetoes. + pub(super) vetoes: BTreeMap, + /// The removals applied in this round, by event ID. + pub(super) removals: BTreeMap, } impl Engine { + fn new(settled: BTreeSet) -> Self { + Self { + settled, + ..Self::default() + } + } + /// Applies one event, and returns what became of it. fn apply( &mut self, event: &Event, by_id: &BTreeMap, ) -> Result { - let decided = match &event.body { - Body::Create(create) => self.create(event, create, by_id), - Body::Join => self.join(event), - Body::Policy(policy) => self.policy(event, policy), - Body::Member(op) => self.member(event, *op), - }; - let decision = match decided { + let decision = match self.judge(event, by_id)? { Ok(decision) => decision, Err(refusal) => { - self.decide(event, Placement::Other)?; + self.decide(event, Placed::Other)?; return Ok(Outcome::Refused(refusal)); } }; let role = match &decision.action { - Some(action) => Placement::Auth { + Some(action) => Placed::Auth { author: event.author, group: Some(decision.group), action: action.clone(), }, - None => Placement::Other, + None => Placed::Other, }; match self.decide(event, role)? { Decided::Applied => { - self.commit(decision.group, decision.effect); + if is_candidate(event) { + self.applied.insert(event.id); + if decision.action.is_some() { + self.placed.insert(event.id); + } + } + self.commit(event, decision.group, decision.effect); Ok(Outcome::Applied) } Decided::Refused { reason, .. } => Ok(Outcome::Refused(Refusal::Membership(reason))), @@ -342,9 +448,28 @@ impl Engine { } } + /// The verdict on one event, before the membership layer sees it. + fn judge( + &mut self, + event: &Event, + by_id: &BTreeMap, + ) -> Result { + match &event.body { + Body::Create(create) => Ok(self.create(event, create, by_id)), + Body::Join => Ok(self.join(event)), + Body::Policy(policy) => Ok(self.policy(event, policy)), + Body::Member(op) => match self.member(event, *op) { + Ok(decision) => self.manage_chain(by_id, event, *op, decision), + Err(refusal) => Ok(Err(refusal)), + }, + Body::Delegate(delegate) => self.delegate(by_id, event, *delegate), + Body::Veto { grant } => self.veto(by_id, event, *grant), + } + } + /// Hands one event to the membership layer. The events are applied in causal order, so it /// decides at once. - fn decide(&mut self, event: &Event, role: Placement) -> Result { + fn decide(&mut self, event: &Event, role: Placed) -> Result { let decided = self.membership.receive(CausalEvent { id: event.id, after: event.after.clone(), @@ -362,11 +487,51 @@ impl Engine { }) } - fn commit(&mut self, group: Hash, effect: Effect) { + fn commit(&mut self, event: &Event, group: Hash, effect: Effect) { match effect { Effect::Create(record) => { self.groups.insert(group, record); } + Effect::Delegation(delegate) => { + let grant = Grant { + id: event.id, + group, + from: event.author, + to: delegate.grantee, + scope: delegate.scope, + redelegate: delegate.can_redelegate, + }; + self.grants.insert(event.id, grant); + } + Effect::Veto(grant) => { + self.vetoes.insert(event.id, grant); + } + Effect::Remove { + member, + dissolves, + successor, + by, + } => { + let removal = Removal { + id: by, + group, + member, + successor, + after: event.after.clone(), + }; + self.removals.insert(by, removal); + if let Some(record) = self.groups.get_mut(&group) { + apply_to( + record, + Effect::Remove { + member, + dissolves, + successor, + by, + }, + ); + } + } other => { if let Some(record) = self.groups.get_mut(&group) { apply_to(record, other); @@ -375,6 +540,16 @@ impl Engine { } } + /// The candidate events that took effect: applied, and for a membership operation not filtered + /// by p2panda-auth's resolver in the final state. + fn effective(&self) -> BTreeSet { + self.applied + .iter() + .copied() + .filter(|id| !self.placed.contains(id) || self.membership.is_effective(id)) + .collect() + } + fn create( &self, event: &Event, @@ -433,6 +608,7 @@ impl Engine { present: BTreeSet::from([author]), friendship: Some(pair), dissolved_by: None, + roots: BTreeSet::from([author, other]), }; let initial = vec![ ( @@ -551,7 +727,7 @@ impl Engine { }, }) } - MemberOp::Remove { member } => { + MemberOp::Remove { member, successor } => { if !self.listed(&group, &member) { return Err(Refusal::NotAMember(member)); } @@ -566,6 +742,7 @@ impl Engine { effect: Effect::Remove { member, dissolves: record.policy.on_member_removed == OnMemberRemoved::Dissolve, + successor, by: event.id, }, }) @@ -601,7 +778,7 @@ impl Engine { } } - fn record(&self, group: &Hash) -> Result<&Record, Refusal> { + pub(super) fn record(&self, group: &Hash) -> Result<&Record, Refusal> { self.groups.get(group).ok_or(Refusal::NoGroup) } @@ -614,7 +791,7 @@ impl Engine { /// The member's role as its access level gives it, or `None` when it is not listed. An Admin /// shows as Manage here, because Admin is recorded apart from the access level. - fn access(&self, group: &Hash, key: &Key) -> Option { + pub(super) fn access(&self, group: &Hash, key: &Key) -> Option { self.membership .members(*group) .iter() @@ -623,10 +800,24 @@ impl Engine { } /// Whether the account may act in the group. A friendship's member must be present too. - fn is_active(&self, group: &Hash, record: &Record, key: &Key) -> bool { + pub(super) fn is_active(&self, group: &Hash, record: &Record, key: &Key) -> bool { self.listed(group, key) && (record.friendship.is_none() || record.present.contains(key)) } + /// The group an event names, when the group is live and the event's author is an active member + /// of it. Otherwise the refusal. + pub(super) fn acting_in(&self, event: &Event) -> Result { + let group = event.group.ok_or(Refusal::NoGroup)?; + let record = self.record(&group)?; + if record.dissolved_by.is_some() { + return Err(Refusal::Dissolved); + } + if !self.is_active(&group, record, &event.author) { + return Err(Refusal::NotActive); + } + Ok(group) + } + /// How many friendships of `pair` the events in `past` have dissolved. This is the counter a /// new request for the pair must name. fn dissolved_before(&self, pair: &Pair, past: &BTreeSet) -> u32 { @@ -641,7 +832,13 @@ impl Engine { u32::try_from(count).unwrap_or(u32::MAX) } - fn into_projection(self, outcomes: BTreeMap) -> Projection { + /// Builds the projection from the final state of the round. + fn into_projection( + self, + outcomes: BTreeMap, + effective: BTreeSet, + in_force: BTreeSet, + ) -> Projection { let membership = &self.membership; let groups = self .groups @@ -668,14 +865,19 @@ impl Engine { (group, view) }) .collect(); - Projection { groups, outcomes } + Projection { + groups, + outcomes, + effective, + in_force, + } } } /// Applies a state change to a group that exists. fn apply_to(record: &mut Record, effect: Effect) { match effect { - Effect::Create(_) => {} + Effect::Create(_) | Effect::Delegation(_) | Effect::Veto(_) => {} Effect::Present(member) => { record.present.insert(member); } @@ -693,6 +895,7 @@ fn apply_to(record: &mut Record, effect: Effect) { member, dissolves, by, + .. } => { record.admins.remove(&member); record.present.remove(&member); @@ -725,11 +928,13 @@ fn new_group(event: &Event, create: &Create) -> Result { Access::manage(), )]; let mut admins = BTreeSet::from([author]); + let mut roots = BTreeSet::from([author]); for (member, role) in &create.members { initial.push(( GroupMember::Individual(AuthId::Key(*member)), access_for(*role), )); + roots.insert(*member); if *role == Role::Admin { admins.insert(*member); } @@ -740,6 +945,7 @@ fn new_group(event: &Event, create: &Create) -> Result { present: BTreeSet::new(), friendship: None, dissolved_by: None, + roots, }; Ok(Decision { group: event.id, @@ -756,7 +962,7 @@ fn has_repeats(members: &[(Key, Role)]) -> bool { } /// The role a member's access level gives. Admin is never an access level. -fn access_role(access: &Access<()>) -> Role { +pub(super) fn access_role(access: &Access<()>) -> Role { if access.is_manage() { Role::Manage } else if access.is_write() { @@ -784,3 +990,17 @@ fn access_for(role: Role) -> Access<()> { Role::Manage | Role::Admin => Access::manage(), } } + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used)] +mod tests { + use super::*; + + #[test] + fn test_an_empty_set_folds_to_nothing() { + let p = fold(&[]).unwrap(); + assert_eq!(p.groups().count(), 0); + assert!(!p.takes_effect(&Hash::digest(b"none"))); + assert!(!p.grant_in_force(&Hash::digest(b"none"))); + } +} diff --git a/pkgs/id/src/groups/mod.rs b/pkgs/id/src/groups/mod.rs index 4611363f65..145fdb27a9 100644 --- a/pkgs/id/src/groups/mod.rs +++ b/pkgs/id/src/groups/mod.rs @@ -17,6 +17,8 @@ pub mod fold; pub mod friendship; pub mod policy; +mod delegation; + #[cfg(test)] mod tests; @@ -28,6 +30,17 @@ pub use policy::{ Delegation, History, Join, OnMemberRemoved, Policy, Removal, RoleRules, Scheme, Template, }; +/// A grant of a scope from the event's author to another account (design §7.1). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Delegate { + /// The account granted the scope. + pub grantee: Key, + /// The access the grantee may exercise. Admin is a policy right and is not delegable. + pub scope: Role, + /// Whether the grantee may grant the scope on. Only a redelegatable grant extends a chain. + pub can_redelegate: bool, +} + /// An account's key. Accounts are keys in this layer. pub type Key = [u8; 32]; @@ -74,6 +87,15 @@ pub enum Body { Policy(Policy), /// Changes one member. Member(MemberOp), + /// Grants a scope to an account. The author must hold the scope, and must reach it through a + /// chain of grants that can be passed on (design §7.2). + Delegate(Delegate), + /// Vetoes a grant the event has seen. The author must hold Manage and a chain (design §7). + /// From this event's causal position on, the grant and what depends on it fail. + Veto { + /// The grant's event ID. + grant: Hash, + }, } /// A group's creation. @@ -103,6 +125,9 @@ pub enum MemberOp { Remove { /// The member removed. member: Key, + /// Under the `transfer` delegation mode, the account that takes over the member's grants + /// (design §7.3). Ignored by the other modes. + successor: Option, }, /// Sets a member's role. Admin only. SetRole { diff --git a/pkgs/id/src/groups/policy.rs b/pkgs/id/src/groups/policy.rs index 1044525e6f..25e5552ad9 100644 --- a/pkgs/id/src/groups/policy.rs +++ b/pkgs/id/src/groups/policy.rs @@ -39,15 +39,15 @@ pub enum Removal { Weak, } -/// What happens to a removed member's delegations (design §7.3). Unset means the default is still -/// open; see [`Policy::delegation`]. +/// What happens to a removed member's grants (design §7.3). #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Delegation { - /// Delegations made before the removal stand. + /// Grants made before the removal stand. Grants made concurrently with it are void. KeepPrior, - /// Delegations made by the removed member end with it. + /// A grant stands only while its grantor still holds the scope. The default. Cascade, - /// Delegations pass to the members who remain. + /// The removal names a successor, who takes over the removed member's grants from the removal + /// on. Without a successor the grants end. Transfer, } @@ -91,7 +91,8 @@ pub struct Policy { pub on_member_removed: OnMemberRemoved, /// How removals take effect. pub removal: Removal, - /// The fate of a removed member's delegations. `None` is the open default (design §7.3). + /// The fate of a removed member's grants. `None` means cascade (design §7.3). Read it through + /// [`Policy::delegation_mode`]. pub delegation: Option, /// What a joiner may see of earlier history. pub history: History, @@ -138,6 +139,11 @@ impl Policy { } } + /// The delegation mode in effect: the record's, or cascade when it names none. + pub fn delegation_mode(&self) -> Delegation { + self.delegation.unwrap_or(Delegation::Cascade) + } + /// Whether the record is usable. Only Admin may change roles and policy, and a cap must allow /// at least one member. pub fn is_valid(&self) -> bool { diff --git a/pkgs/id/src/groups/tests.rs b/pkgs/id/src/groups/tests.rs index 38adff7208..7f4a2d7ddf 100644 --- a/pkgs/id/src/groups/tests.rs +++ b/pkgs/id/src/groups/tests.rs @@ -3,12 +3,14 @@ #![allow(clippy::unwrap_used, clippy::expect_used)] +use std::collections::{BTreeMap, BTreeSet}; + use p2panda_core::Hash; use proptest::prelude::*; -use super::policy::{Join, OnMemberRemoved, Policy, RoleRules, Template}; +use super::policy::{Delegation, Join, OnMemberRemoved, Policy, RoleRules, Template}; use super::{ - Body, Create, Event, Key, MemberOp, Outcome, Pair, Projection, Refusal, Role, fold, + Body, Create, Delegate, Event, Key, MemberOp, Outcome, Pair, Projection, Refusal, Role, fold, friendship_id, }; @@ -114,7 +116,10 @@ fn remove(name: &str, by: u8, group: Hash, who: u8, after_names: &[&str]) -> Eve name, by, group, - MemberOp::Remove { member: key(who) }, + MemberOp::Remove { + member: key(who), + successor: None, + }, after_names, ) } @@ -663,6 +668,596 @@ fn test_a_friendship_has_no_cap_beyond_its_two_and_no_third_member() { ); } +// ----- Delegation (P2.5, design §7) ----- + +fn delegate( + name: &str, + by: u8, + group: Hash, + to: u8, + scope: Role, + redelegate: bool, + after_names: &[&str], +) -> Event { + let body = Body::Delegate(Delegate { + grantee: key(to), + scope, + can_redelegate: redelegate, + }); + event(name, by, after_names, Some(group), body) +} + +fn veto(name: &str, by: u8, group: Hash, grant: &str, after_names: &[&str]) -> Event { + event( + name, + by, + after_names, + Some(group), + Body::Veto { grant: id(grant) }, + ) +} + +fn remove_to( + name: &str, + by: u8, + group: Hash, + who: u8, + successor: Option, + after_names: &[&str], +) -> Event { + member( + name, + by, + group, + MemberOp::Remove { + member: key(who), + successor: successor.map(key), + }, + after_names, + ) +} + +fn with_mode(mode: Option) -> Policy { + Policy { + delegation: mode, + ..Policy::default() + } +} + +/// A group by 1 with 2 and 3 as managers added by 1, and 2 granted Manage by 1 and 3 by 2. Joe +/// (2) is the grantor the removal tests take away. +fn chain_base(mode: Option) -> Vec { + let g = id("g"); + vec![ + custom("g", 1, &[], with_mode(mode)), + add("a0", 1, g, 2, Role::Manage, &["g"]), + add("a1", 1, g, 3, Role::Manage, &["a0"]), + delegate("d0", 1, g, 2, Role::Manage, true, &["a1"]), + delegate("d1", 2, g, 3, Role::Manage, true, &["d0"]), + ] +} + +#[test] +fn test_a_group_without_a_delegation_setting_cascades() { + assert_eq!( + Policy::default().delegation_mode(), + Delegation::Cascade, + "cascade is the default" + ); + assert_eq!( + with_mode(Some(Delegation::KeepPrior)).delegation_mode(), + Delegation::KeepPrior + ); +} + +#[test] +fn test_keep_prior_lets_a_grant_made_before_the_removal_stand() { + let g = id("g"); + let mut events = chain_base(Some(Delegation::KeepPrior)); + events.push(remove_to("x0", 1, g, 2, None, &["d1"])); + events.push(add("a2", 3, g, 4, Role::Read, &["x0"])); + let p = project(&events); + assert_eq!(outcome(&p, "x0"), Outcome::Applied); + assert_eq!(outcome(&p, "a2"), Outcome::Applied, "d1 was made before x0"); + assert!(p.grant_in_force(&id("d1"))); +} + +#[test] +fn test_cascade_removes_the_grants_the_removed_member_made() { + let g = id("g"); + let mut events = chain_base(None); + events.push(remove_to("x0", 1, g, 2, None, &["d1"])); + events.push(add("a2", 3, g, 4, Role::Read, &["x0"])); + let p = project(&events); + assert_eq!(outcome(&p, "x0"), Outcome::Applied); + assert_eq!(outcome(&p, "a2"), Outcome::Refused(Refusal::NoChain)); + assert!(!p.grant_in_force(&id("d1"))); + assert!(p.grant_in_force(&id("d0")), "the owner's grant to 2 stands"); +} + +#[test] +fn test_cascade_keeps_a_grant_for_an_action_concurrent_with_the_removal() { + // a2 names only d1, so it is concurrent with x0. At its position 2 still holds Manage. + let g = id("g"); + let mut events = chain_base(None); + events.push(remove_to("x0", 1, g, 2, None, &["d1"])); + events.push(add("a2", 3, g, 4, Role::Read, &["d1"])); + let p = project(&events); + assert_eq!(outcome(&p, "a2"), Outcome::Applied); +} + +#[test] +fn test_transfer_hands_the_removed_members_grants_to_the_successor() { + let g = id("g"); + let mut events = chain_base(Some(Delegation::Transfer)); + events.push(add("a3", 1, g, 5, Role::Manage, &["a1"])); + events.push(delegate("d2", 1, g, 5, Role::Manage, true, &["a3"])); + events.push(remove_to("x0", 1, g, 2, Some(5), &["d1", "d2"])); + events.push(add("a2", 3, g, 4, Role::Read, &["x0"])); + let p = project(&events); + assert_eq!(outcome(&p, "a2"), Outcome::Applied, "5 reissues d1"); + assert!( + !p.grant_in_force(&id("d1")), + "the original grant is superseded" + ); +} + +#[test] +fn test_transfer_without_a_successor_ends_the_grants() { + let g = id("g"); + let mut events = chain_base(Some(Delegation::Transfer)); + events.push(remove_to("x0", 1, g, 2, None, &["d1"])); + events.push(add("a2", 3, g, 4, Role::Read, &["x0"])); + let p = project(&events); + assert_eq!(outcome(&p, "a2"), Outcome::Refused(Refusal::NoChain)); +} + +#[test] +fn test_a_successor_must_hold_the_scope_to_take_over() { + // 5 is granted Manage by the owner, but its membership is Read, so it cannot hold Manage. + let g = id("g"); + let mut events = chain_base(Some(Delegation::Transfer)); + events.push(add("a3", 1, g, 5, Role::Read, &["a1"])); + events.push(delegate("d2", 1, g, 5, Role::Manage, true, &["a3"])); + events.push(remove_to("x0", 1, g, 2, Some(5), &["d1", "d2"])); + events.push(add("a2", 3, g, 4, Role::Read, &["x0"])); + let p = project(&events); + assert_eq!(outcome(&p, "a2"), Outcome::Refused(Refusal::NoChain)); +} + +#[test] +fn test_a_removed_member_may_not_grant_after_its_removal() { + let g = id("g"); + let mut events = chain_base(None); + events.push(remove_to("x0", 1, g, 2, None, &["d1"])); + events.push(delegate("d2", 2, g, 4, Role::Read, false, &["x0"])); + let p = project(&events); + assert!(matches!(outcome(&p, "d2"), Outcome::Refused(_))); + assert!(!p.grant_in_force(&id("d2"))); +} + +#[test] +fn test_a_grant_may_not_be_wider_than_the_grantors_scope() { + let g = id("g"); + let p = project(&[ + custom("g", 1, &[], Policy::default()), + add("a0", 1, g, 2, Role::Write, &["g"]), + delegate("d0", 1, g, 2, Role::Write, true, &["a0"]), + delegate("d1", 2, g, 3, Role::Manage, true, &["d0"]), + delegate("d2", 2, g, 3, Role::Read, false, &["d0"]), + ]); + assert_eq!(outcome(&p, "d1"), Outcome::Refused(Refusal::Attenuated)); + assert_eq!(outcome(&p, "d2"), Outcome::Applied, "Read is within Write"); +} + +#[test] +fn test_a_grant_that_cannot_be_redelegated_ends_the_chain() { + let g = id("g"); + let p = project(&[ + custom("g", 1, &[], Policy::default()), + add("a0", 1, g, 2, Role::Manage, &["g"]), + delegate("d0", 1, g, 2, Role::Manage, false, &["a0"]), + add("a1", 2, g, 4, Role::Read, &["d0"]), + delegate("d1", 2, g, 3, Role::Read, false, &["d0"]), + ]); + assert_eq!( + outcome(&p, "a1"), + Outcome::Applied, + "a grantee acts without redelegating" + ); + assert_eq!(outcome(&p, "d1"), Outcome::Refused(Refusal::NoChain)); +} + +#[test] +fn test_chain_search_accepts_a_valid_chain_and_refuses_a_broken_one() { + let g = id("g"); + // 1 -> 2 -> 3 -> 4. Every link may be passed on except the last. + let valid = project(&[ + custom("g", 1, &[], Policy::default()), + add("a0", 1, g, 2, Role::Manage, &["g"]), + add("a1", 1, g, 3, Role::Manage, &["a0"]), + add("a2", 1, g, 4, Role::Manage, &["a1"]), + delegate("d0", 1, g, 2, Role::Manage, true, &["a2"]), + delegate("d1", 2, g, 3, Role::Manage, true, &["d0"]), + delegate("d2", 3, g, 4, Role::Manage, false, &["d1"]), + add("a3", 4, g, 5, Role::Read, &["d2"]), + delegate("d3", 4, g, 5, Role::Read, false, &["d2"]), + ]); + assert_eq!(outcome(&valid, "a3"), Outcome::Applied, "the chain holds"); + assert_eq!(outcome(&valid, "d3"), Outcome::Refused(Refusal::NoChain)); + + // The same chain with 2 -> 3 not redelegatable: 3 cannot grant on, and 4 has no chain. + let broken = project(&[ + custom("g", 1, &[], Policy::default()), + add("a0", 1, g, 2, Role::Manage, &["g"]), + add("a1", 1, g, 3, Role::Manage, &["a0"]), + add("a2", 1, g, 4, Role::Manage, &["a1"]), + delegate("d0", 1, g, 2, Role::Manage, true, &["a2"]), + delegate("d1", 2, g, 3, Role::Manage, false, &["d0"]), + delegate("d2", 3, g, 4, Role::Manage, false, &["d1"]), + add("a3", 4, g, 5, Role::Read, &["d2"]), + ]); + assert_eq!(outcome(&broken, "d2"), Outcome::Refused(Refusal::NoChain)); + assert_eq!(outcome(&broken, "a3"), Outcome::Refused(Refusal::NoChain)); +} + +#[test] +fn test_a_manager_acts_only_through_a_grant_from_an_owner() { + // 3 is a Manage member added by the owner, but no grant reaches it, so it cannot add. + let g = id("g"); + let p = project(&[ + custom("g", 1, &[], Policy::default()), + add("a0", 1, g, 2, Role::Manage, &["g"]), + add("a1", 2, g, 3, Role::Manage, &["a0"]), + add("a2", 2, g, 4, Role::Read, &["a1"]), + ]); + assert_eq!( + outcome(&p, "a0"), + Outcome::Applied, + "the owner adds directly" + ); + assert_eq!(outcome(&p, "a1"), Outcome::Refused(Refusal::NoChain)); + assert_eq!(outcome(&p, "a2"), Outcome::Refused(Refusal::NoChain)); +} + +#[test] +fn test_a_manager_may_veto_a_grant_and_the_grants_below_it_fall() { + let g = id("g"); + let mut events = chain_base(None); + events.push(add("a2", 1, g, 4, Role::Manage, &["a1"])); + events.push(delegate("d2", 1, g, 4, Role::Manage, true, &["a2"])); + events.push(veto("v0", 4, g, "d0", &["d2", "d0"])); + events.push(add("a3", 3, g, 5, Role::Read, &["v0"])); + events.push(add("a4", 3, g, 6, Role::Read, &["d1"])); + let p = project(&events); + assert_eq!(outcome(&p, "v0"), Outcome::Applied); + assert_eq!( + outcome(&p, "a3"), + Outcome::Refused(Refusal::NoChain), + "3 reaches the owner only through d0" + ); + assert_eq!( + outcome(&p, "a4"), + Outcome::Applied, + "before the veto, d0 stood" + ); + assert!(!p.grant_in_force(&id("d0"))); + assert!(p.grant_in_force(&id("d2"))); +} + +#[test] +fn test_a_veto_needs_manage_access_a_chain_and_a_grant_it_has_seen() { + let g = id("g"); + let p = project(&[ + custom("g", 1, &[], Policy::default()), + add("a0", 1, g, 2, Role::Manage, &["g"]), + add("a1", 1, g, 3, Role::Read, &["a0"]), + add("a2", 1, g, 4, Role::Manage, &["a1"]), + delegate("d0", 1, g, 2, Role::Manage, true, &["a2"]), + veto("v0", 3, g, "d0", &["d0"]), + veto("v1", 4, g, "d0", &["d0"]), + veto("v2", 2, g, "d0", &["d0"]), + ]); + assert_eq!(outcome(&p, "v0"), Outcome::Refused(Refusal::NotManager)); + assert_eq!( + outcome(&p, "v1"), + Outcome::Refused(Refusal::NoChain), + "4 manages without a chain" + ); + assert_eq!( + outcome(&p, "v2"), + Outcome::Applied, + "2 manages through the owner's grant" + ); + let unseen = project(&[ + custom("g", 1, &[], Policy::default()), + add("a0", 1, g, 2, Role::Manage, &["g"]), + delegate("d0", 1, g, 2, Role::Manage, true, &["a0"]), + veto("v0", 2, g, "d1", &["d0"]), + ]); + assert_eq!( + outcome(&unseen, "v0"), + Outcome::Refused(Refusal::UnknownGrant), + "d1 does not exist" + ); +} + +/// The S2 spike's delegation DAG (`spikes/shared/s2-auth/src/delegation.rs`), with the owner 1, +/// Joe 2, Dan 3, Jim 4, Zed 5, Yan 6, Quinn 7, Eve 8, Kim 9, Lou 10 and Xav 11. Joe is removed by +/// s9. `alt` adds Dan's grant to Jim (s16). `successor` is named by the removal. +fn s2_events(alt: bool, mode: Option, successor: Option) -> Vec { + let g = id("s0"); + let mut events = vec![ + custom("s0", 1, &[], with_mode(mode)), + add("s1", 1, g, 2, Role::Manage, &["s0"]), + add("s2", 1, g, 3, Role::Manage, &["s1"]), + delegate("s3", 1, g, 2, Role::Manage, true, &["s1"]), + delegate("s4", 1, g, 3, Role::Manage, true, &["s2"]), + add("s5", 2, g, 4, Role::Manage, &["s3"]), + delegate("s6", 2, g, 4, Role::Manage, true, &["s5"]), + add("s7", 1, g, 7, Role::Manage, &["s2"]), + delegate("s8", 2, g, 7, Role::Manage, true, &["s5"]), + ]; + let mut removal_after = vec!["s6", "s4"]; + if alt { + events.push(delegate("s16", 3, g, 4, Role::Manage, true, &["s4"])); + removal_after.push("s16"); + } + events.push(remove_to("s9", 1, g, 2, successor, &removal_after)); + events.push(add("s10", 4, g, 5, Role::Manage, &["s9"])); + events.push(add("s11", 4, g, 6, Role::Manage, &["s6"])); + events.push(add("s12", 7, g, 8, Role::Read, &["s7", "s8"])); + events.push(add("s13", 1, g, 9, Role::Write, &["s2"])); + events.push(delegate("s14", 9, g, 10, Role::Manage, true, &["s13"])); + events.push(delegate("s15", 2, g, 11, Role::Manage, true, &["s9"])); + events +} + +#[test] +fn test_s2_delegation_scenarios_keep_their_results() { + let g = id("s0"); + // (alt chain, mode, successor, Jim's later action applies, the grant Joe to Jim stands). + let runs = [ + (false, None, None, false, false), + (true, None, None, true, false), + (false, Some(Delegation::KeepPrior), None, true, true), + (false, Some(Delegation::Transfer), Some(3), true, false), + ]; + for (alt, mode, successor, jim_later, joe_to_jim_stands) in runs { + let name = format!("alt {alt}, mode {mode:?}, successor {successor:?}"); + let p = project(&s2_events(alt, mode, successor)); + let expected = if jim_later { + Outcome::Applied + } else { + Outcome::Refused(Refusal::NoChain) + }; + assert_eq!(outcome(&p, "s10"), expected, "{name}: Jim's later add"); + assert_eq!(outcome(&p, "s11"), Outcome::Applied, "{name}: concurrent"); + assert_eq!( + outcome(&p, "s12"), + Outcome::Refused(Refusal::NoChain), + "{name}: Quinn's only chain is void" + ); + assert!(!p.grant_in_force(&id("s8")), "{name}: void"); + assert_eq!( + p.grant_in_force(&id("s6")), + joe_to_jim_stands, + "{name}: Joe to Jim" + ); + let members = &p.group(&g).unwrap().members; + assert!(!members.contains_key(&key(2)), "{name}: Joe is removed"); + assert_eq!(members.contains_key(&key(5)), jim_later, "{name}: Zed"); + } + let p = project(&s2_events(false, None, None)); + assert_eq!(outcome(&p, "s14"), Outcome::Refused(Refusal::Attenuated)); + assert!(matches!(outcome(&p, "s15"), Outcome::Refused(_))); + assert!(p.grant_in_force(&id("s3"))); +} + +/// The causal past of each event, the event included, from the `after` links. +fn pasts(events: &[Event]) -> BTreeMap> { + let by_id: BTreeMap = events.iter().map(|e| (e.id, e)).collect(); + events + .iter() + .map(|e| { + let mut past = BTreeSet::new(); + let mut stack = vec![e.id]; + while let Some(next) = stack.pop() { + if past.insert(next) + && let Some(event) = by_id.get(&next) + { + stack.extend(event.after.iter().copied()); + } + } + (e.id, past) + }) + .collect() +} + +/// Random delegation scripts: groups in four modes, managers, grants, removals with an optional +/// successor, and vetoes. Each step is (kind, author, target, scope, pick, mask). +fn delegation_script() -> impl Strategy> { + prop::collection::vec( + (0u8..8, 1u8..=4, 1u8..=4, 0u8..4, any::(), any::()), + 1..24, + ) +} + +fn delegation_build(script: &[(u8, u8, u8, u8, u8, u8)]) -> Vec { + const ROLES: [Role; 4] = [Role::Pull, Role::Read, Role::Write, Role::Manage]; + const MODES: [Option; 4] = [ + None, + Some(Delegation::Cascade), + Some(Delegation::KeepPrior), + Some(Delegation::Transfer), + ]; + let mut events: Vec = Vec::new(); + let mut groups: Vec = Vec::new(); + for (i, &(raw, author, target, scope, pick, mask)) in script.iter().enumerate() { + // The first event creates a group. After it, adds and grants are the common steps. + let kind = match raw { + _ if i == 0 => 0, + 0 => 0, + 1 | 2 => 1, + 3..=5 => 2, + 6 => 3, + _ => 4, + }; + let name = format!("e{i}"); + let after_hashes: Vec = events + .iter() + .enumerate() + .filter(|(j, _)| (mask >> (j % 8)) & 1 == 1) + .map(|(_, earlier)| earlier.id) + .rev() + .take(3) + .collect(); + let group = groups + .get(usize::from(pick) % groups.len().max(1)) + .copied() + .unwrap_or_else(|| id("none")); + let grants: Vec = events + .iter() + .filter(|e| matches!(e.body, Body::Delegate(_))) + .map(|e| e.id) + .collect(); + let grant = grants + .get(usize::from(pick) % grants.len().max(1)) + .copied() + .unwrap_or_else(|| id("none")); + let role = ROLES[usize::from(scope)]; + let (group, body) = match kind { + 0 => { + let policy = with_mode(MODES[usize::from(pick % 4)]); + let body = Body::Create(Create { + template: Template::Custom, + policy, + members: Vec::new(), + admins_on_create: false, + }); + (None, body) + } + 1 => ( + Some(group), + Body::Member(MemberOp::Add { + member: key(target), + role, + }), + ), + 2 => ( + Some(group), + Body::Delegate(Delegate { + grantee: key(target), + scope: role, + can_redelegate: mask % 2 == 0, + }), + ), + 3 => ( + Some(group), + Body::Member(MemberOp::Remove { + member: key(target), + successor: (mask % 3 == 0).then(|| key(pick % 5 + 1)), + }), + ), + _ => (Some(group), Body::Veto { grant }), + }; + let created = Event { + id: id(&name), + author: key(author), + after: after_hashes, + group, + body, + }; + if matches!(created.body, Body::Create(_)) { + groups.push(created.id); + } + events.push(created); + } + events +} + +proptest! { + #![proptest_config(ProptestConfig::with_cases(256))] + + #[test] + fn prop_delegation_outcomes_do_not_depend_on_the_arrival_order( + script in delegation_script(), + seed in any::(), + ) { + let events = delegation_build(&script); + let expected = project(&events); + let shuffled_state = fold(&shuffled(&events, seed.max(1))).unwrap(); + prop_assert_eq!(&shuffled_state, &expected); + let mut reversed = events; + reversed.reverse(); + prop_assert_eq!(&fold(&reversed).unwrap(), &expected); + } + + #[test] + fn prop_no_grant_survives_its_grantors_strong_removal_unless_the_mode_keeps_it( + script in delegation_script(), + ) { + let events = delegation_build(&script); + let p = project(&events); + let pasts = pasts(&events); + let grants = events.iter().filter(|e| { + matches!(e.body, Body::Delegate(_)) && p.outcome(&e.id) == Some(&Outcome::Applied) + }); + for grant in grants { + let (Some(group), Body::Delegate(delegate)) = (grant.group, &grant.body) else { + continue; + }; + let view = p.group(&group).unwrap(); + let grantor = grant.author; + let removals: Vec<&Event> = events + .iter() + .filter(|e| { + e.group == Some(group) + && matches!(e.body, Body::Member(MemberOp::Remove { member, .. }) if member == grantor) + && p.takes_effect(&e.id) + }) + .collect(); + let vetoed = events.iter().any(|v| { + matches!(v.body, Body::Veto { grant: target } if target == grant.id) + && p.takes_effect(&v.id) + }); + let in_force = p.grant_in_force(&grant.id); + if vetoed { + prop_assert!(!in_force, "a vetoed grant is not in force"); + } + let concurrent = removals.iter().any(|r| { + !pasts[&grant.id].contains(&r.id) && !pasts[&r.id].contains(&grant.id) + }); + if concurrent { + prop_assert!(!in_force, "a grant concurrent with its grantor's removal is void"); + } + match view.policy.delegation_mode() { + Delegation::Cascade => { + let holds_at_head = view + .members + .get(&grantor) + .is_some_and(|role| *role >= delegate.scope); + if !removals.is_empty() && !holds_at_head { + prop_assert!(!in_force, "cascade ends a grant its grantor no longer holds"); + } + } + Delegation::Transfer => { + if !removals.is_empty() { + prop_assert!(!in_force, "transfer supersedes the grantor's grants"); + } + } + Delegation::KeepPrior => { + let before_every_removal = + removals.iter().all(|r| pasts[&r.id].contains(&grant.id)); + if !vetoed && before_every_removal { + prop_assert!(in_force, "keep_prior keeps a grant made before the removal"); + } + } + } + } + } +} + // ----- Properties over arrival order ----- /// A random set of group events. Each step picks a kind, the actors, a group among those @@ -759,6 +1354,7 @@ fn build(script: &[(u8, u8, u8, u8, u8, u8)]) -> Vec { Some(group), Body::Member(MemberOp::Remove { member: key(target), + successor: None, }), ), _ => ( diff --git a/pkgs/id/src/membership/layer.rs b/pkgs/id/src/membership/layer.rs index 312a36cc4b..03454f54a1 100644 --- a/pkgs/id/src/membership/layer.rs +++ b/pkgs/id/src/membership/layer.rs @@ -338,6 +338,22 @@ impl Membership { .is_some()) } + /// The access `member` holds in `group` at the causal position that `after` names, or `None` + /// when it holds none there. Delegation judges grants by this (design §7.2). + /// + /// # Errors + /// + /// Returns [`MembershipError`] when an `after` hash is not indexed. + pub fn access_at_position( + &mut self, + after: &[Hash], + group: Hash, + member: [u8; 32], + ) -> Result>, MembershipError> { + let deps: HashSet = self.index.frontier(after, group)?.into_iter().collect(); + Ok(self.access_at(&deps, AuthId::Group(group), AuthId::Key(member))) + } + /// Whether a create has been decided for `group`. pub fn has_group(&self, group: Hash) -> bool { self.state.has_group(AuthId::Group(group)) From 6ed7ddb327a0d68cfc6411c99189694d260b1ae6 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 12 Oct 2026 03:26:24 -0500 Subject: [PATCH 29/40] fix(rust): managers are roots at their position, as design 7.2 says [P2.5] Roots are the owners and managers at the action's position, read from the membership layer (managers_at_position). A manager added by another member is a root there, so its grants and its manage actions are valid without a grant reaching it. The owner-only roots of S2 and the Record.roots field are gone. Consequence: a grantee that is a manager is not limited by a removed grantor's chain. The mode tests and the veto and transfer tests now probe with Write-level grantees, which are not managers and still need a chain. S2 expectations that changed: Jim's later add (s10) applies in every mode, including cascade, and Quinn's add (s12) applies in every mode. Both were vetoed under S2's owner-only roots. The void of s8, the grant from Joe to Jim at the head (keep_prior only), and the attenuation and not-active refusals are unchanged. --- pkgs/id/src/groups/delegation.rs | 30 ++-- pkgs/id/src/groups/fold.rs | 7 - pkgs/id/src/groups/tests.rs | 228 +++++++++++++++---------------- pkgs/id/src/membership/layer.rs | 24 ++++ 4 files changed, 147 insertions(+), 142 deletions(-) diff --git a/pkgs/id/src/groups/delegation.rs b/pkgs/id/src/groups/delegation.rs index 1041f335f6..deb9de3ee5 100644 --- a/pkgs/id/src/groups/delegation.rs +++ b/pkgs/id/src/groups/delegation.rs @@ -2,9 +2,9 @@ //! decides whether an account may act at a causal position, the three removal modes, and vetoes. //! //! A grant is an event by a grantor who holds the scope there. An account may exercise a scope -//! only through a chain of grants that starts at a root. The roots are the accounts a group's -//! create named, its creator included. A manager added by someone else has membership, but no -//! authority until a grant reaches it. This is S2's choice: the owner is the only root. +//! through a chain of grants that starts at a root. The roots are the owners and managers at the +//! action's position (design §7.2): a member holding Manage there is a root, so a manager's own +//! grants and actions are valid without a grant reaching it. A grant reaches the others. //! //! Each link attenuates: a grantor passes on no more than it holds. A link carries authority at a //! position when its grantor was valid where it was made, the grant is not voided by a concurrent @@ -196,10 +196,11 @@ impl Engine { } /// Whether `actor` may exercise `scope` in `group` at the causal position `after` (design - /// §7.2). A root that holds the scope there is authorized. Otherwise a chain of links leads - /// from a root holding the scope to the actor, every link attenuating. With `need_redelegate`, - /// the last link into the actor must allow the actor to grant on. The actor's own membership - /// is not checked here: a grant may reach an account that is not a member. + /// §7.2). The roots are the owners and managers at that position: a root holds Manage there, + /// so it holds every scope. An actor that is a root is authorized. Otherwise a chain of links + /// leads from a root to the actor, every link attenuating. With `need_redelegate`, the last + /// link into the actor must allow the actor to grant on. The actor's own membership is not + /// checked here: a grant may reach an account that is not a member. pub(super) fn authorized( &mut self, by_id: &BTreeMap, @@ -209,20 +210,15 @@ impl Engine { after: &[Hash], need_redelegate: bool, ) -> Result { - let Some(record) = self.groups.get(&group) else { + if !self.groups.contains_key(&group) { return Ok(false); - }; - let roots = record.roots.clone(); - if roots.contains(&actor) && self.holds(group, actor, scope, after)? { + } + let roots = self.membership.managers_at_position(after, group)?; + if roots.contains(&actor) { return Ok(true); } let links = self.links(by_id, group, after)?; - let mut reached = BTreeSet::new(); - for root in roots { - if self.holds(group, root, scope, after)? { - reached.insert(root); - } - } + let mut reached: BTreeSet = roots.iter().copied().collect(); let mut stack: Vec = reached.iter().copied().collect(); while let Some(holder) = stack.pop() { for link in links diff --git a/pkgs/id/src/groups/fold.rs b/pkgs/id/src/groups/fold.rs index d2f1805ffb..756599efcd 100644 --- a/pkgs/id/src/groups/fold.rs +++ b/pkgs/id/src/groups/fold.rs @@ -341,9 +341,6 @@ pub(super) struct Record { pub(super) present: BTreeSet, pub(super) friendship: Option, pub(super) dissolved_by: Option, - /// The accounts the create named, its author included. They are the owners: the roots of - /// every delegation chain (design §7.2, as S2 chose it). - pub(super) roots: BTreeSet, } /// The state change an accepted event makes. It is committed once the membership layer accepts @@ -608,7 +605,6 @@ impl Engine { present: BTreeSet::from([author]), friendship: Some(pair), dissolved_by: None, - roots: BTreeSet::from([author, other]), }; let initial = vec![ ( @@ -928,13 +924,11 @@ fn new_group(event: &Event, create: &Create) -> Result { Access::manage(), )]; let mut admins = BTreeSet::from([author]); - let mut roots = BTreeSet::from([author]); for (member, role) in &create.members { initial.push(( GroupMember::Individual(AuthId::Key(*member)), access_for(*role), )); - roots.insert(*member); if *role == Role::Admin { admins.insert(*member); } @@ -945,7 +939,6 @@ fn new_group(event: &Event, create: &Create) -> Result { present: BTreeSet::new(), friendship: None, dissolved_by: None, - roots, }; Ok(Decision { group: event.id, diff --git a/pkgs/id/src/groups/tests.rs b/pkgs/id/src/groups/tests.rs index 7f4a2d7ddf..49b0111231 100644 --- a/pkgs/id/src/groups/tests.rs +++ b/pkgs/id/src/groups/tests.rs @@ -724,16 +724,17 @@ fn with_mode(mode: Option) -> Policy { } } -/// A group by 1 with 2 and 3 as managers added by 1, and 2 granted Manage by 1 and 3 by 2. Joe -/// (2) is the grantor the removal tests take away. +/// A group by 1, with 2 and 3 as Write members and a chain 1 -> 2 -> 3 of grants that may be +/// passed on. A Write member is not a manager, so its own grants need the chain. The mode tests +/// probe with a grant from 3 to 4, and the grants from 2 are the ones a removal of 2 touches. fn chain_base(mode: Option) -> Vec { let g = id("g"); vec![ custom("g", 1, &[], with_mode(mode)), - add("a0", 1, g, 2, Role::Manage, &["g"]), - add("a1", 1, g, 3, Role::Manage, &["a0"]), - delegate("d0", 1, g, 2, Role::Manage, true, &["a1"]), - delegate("d1", 2, g, 3, Role::Manage, true, &["d0"]), + add("a0", 1, g, 2, Role::Write, &["g"]), + add("a1", 1, g, 3, Role::Write, &["a0"]), + delegate("d0", 1, g, 2, Role::Write, true, &["a1"]), + delegate("d1", 2, g, 3, Role::Write, true, &["d0"]), ] } @@ -755,10 +756,10 @@ fn test_keep_prior_lets_a_grant_made_before_the_removal_stand() { let g = id("g"); let mut events = chain_base(Some(Delegation::KeepPrior)); events.push(remove_to("x0", 1, g, 2, None, &["d1"])); - events.push(add("a2", 3, g, 4, Role::Read, &["x0"])); + events.push(delegate("d2", 3, g, 4, Role::Read, false, &["x0"])); let p = project(&events); assert_eq!(outcome(&p, "x0"), Outcome::Applied); - assert_eq!(outcome(&p, "a2"), Outcome::Applied, "d1 was made before x0"); + assert_eq!(outcome(&p, "d2"), Outcome::Applied, "d1 was made before x0"); assert!(p.grant_in_force(&id("d1"))); } @@ -767,35 +768,35 @@ fn test_cascade_removes_the_grants_the_removed_member_made() { let g = id("g"); let mut events = chain_base(None); events.push(remove_to("x0", 1, g, 2, None, &["d1"])); - events.push(add("a2", 3, g, 4, Role::Read, &["x0"])); + events.push(delegate("d2", 3, g, 4, Role::Read, false, &["x0"])); let p = project(&events); assert_eq!(outcome(&p, "x0"), Outcome::Applied); - assert_eq!(outcome(&p, "a2"), Outcome::Refused(Refusal::NoChain)); + assert_eq!(outcome(&p, "d2"), Outcome::Refused(Refusal::NoChain)); assert!(!p.grant_in_force(&id("d1"))); assert!(p.grant_in_force(&id("d0")), "the owner's grant to 2 stands"); } #[test] fn test_cascade_keeps_a_grant_for_an_action_concurrent_with_the_removal() { - // a2 names only d1, so it is concurrent with x0. At its position 2 still holds Manage. + // d2 names only d1, so it is concurrent with x0. At its position 2 still holds Write. let g = id("g"); let mut events = chain_base(None); events.push(remove_to("x0", 1, g, 2, None, &["d1"])); - events.push(add("a2", 3, g, 4, Role::Read, &["d1"])); + events.push(delegate("d2", 3, g, 4, Role::Read, false, &["d1"])); let p = project(&events); - assert_eq!(outcome(&p, "a2"), Outcome::Applied); + assert_eq!(outcome(&p, "d2"), Outcome::Applied); } #[test] fn test_transfer_hands_the_removed_members_grants_to_the_successor() { let g = id("g"); let mut events = chain_base(Some(Delegation::Transfer)); - events.push(add("a3", 1, g, 5, Role::Manage, &["a1"])); - events.push(delegate("d2", 1, g, 5, Role::Manage, true, &["a3"])); + events.push(add("a2", 1, g, 5, Role::Write, &["a1"])); + events.push(delegate("d2", 1, g, 5, Role::Write, true, &["a2"])); events.push(remove_to("x0", 1, g, 2, Some(5), &["d1", "d2"])); - events.push(add("a2", 3, g, 4, Role::Read, &["x0"])); + events.push(delegate("d3", 3, g, 4, Role::Read, false, &["x0"])); let p = project(&events); - assert_eq!(outcome(&p, "a2"), Outcome::Applied, "5 reissues d1"); + assert_eq!(outcome(&p, "d3"), Outcome::Applied, "5 reissues d1"); assert!( !p.grant_in_force(&id("d1")), "the original grant is superseded" @@ -807,22 +808,22 @@ fn test_transfer_without_a_successor_ends_the_grants() { let g = id("g"); let mut events = chain_base(Some(Delegation::Transfer)); events.push(remove_to("x0", 1, g, 2, None, &["d1"])); - events.push(add("a2", 3, g, 4, Role::Read, &["x0"])); + events.push(delegate("d2", 3, g, 4, Role::Read, false, &["x0"])); let p = project(&events); - assert_eq!(outcome(&p, "a2"), Outcome::Refused(Refusal::NoChain)); + assert_eq!(outcome(&p, "d2"), Outcome::Refused(Refusal::NoChain)); } #[test] fn test_a_successor_must_hold_the_scope_to_take_over() { - // 5 is granted Manage by the owner, but its membership is Read, so it cannot hold Manage. + // 5 is granted Write by the owner, but its membership is Read, so it cannot hold Write. let g = id("g"); let mut events = chain_base(Some(Delegation::Transfer)); - events.push(add("a3", 1, g, 5, Role::Read, &["a1"])); - events.push(delegate("d2", 1, g, 5, Role::Manage, true, &["a3"])); + events.push(add("a2", 1, g, 5, Role::Read, &["a1"])); + events.push(delegate("d2", 1, g, 5, Role::Write, true, &["a2"])); events.push(remove_to("x0", 1, g, 2, Some(5), &["d1", "d2"])); - events.push(add("a2", 3, g, 4, Role::Read, &["x0"])); + events.push(delegate("d3", 3, g, 4, Role::Read, false, &["x0"])); let p = project(&events); - assert_eq!(outcome(&p, "a2"), Outcome::Refused(Refusal::NoChain)); + assert_eq!(outcome(&p, "d3"), Outcome::Refused(Refusal::NoChain)); } #[test] @@ -855,69 +856,67 @@ fn test_a_grant_that_cannot_be_redelegated_ends_the_chain() { let g = id("g"); let p = project(&[ custom("g", 1, &[], Policy::default()), - add("a0", 1, g, 2, Role::Manage, &["g"]), - delegate("d0", 1, g, 2, Role::Manage, false, &["a0"]), - add("a1", 2, g, 4, Role::Read, &["d0"]), + add("a0", 1, g, 2, Role::Write, &["g"]), + delegate("d0", 1, g, 2, Role::Write, false, &["a0"]), delegate("d1", 2, g, 3, Role::Read, false, &["d0"]), ]); - assert_eq!( - outcome(&p, "a1"), - Outcome::Applied, - "a grantee acts without redelegating" - ); assert_eq!(outcome(&p, "d1"), Outcome::Refused(Refusal::NoChain)); + assert!(p.grant_in_force(&id("d0"))); } #[test] fn test_chain_search_accepts_a_valid_chain_and_refuses_a_broken_one() { let g = id("g"); - // 1 -> 2 -> 3 -> 4. Every link may be passed on except the last. - let valid = project(&[ - custom("g", 1, &[], Policy::default()), - add("a0", 1, g, 2, Role::Manage, &["g"]), - add("a1", 1, g, 3, Role::Manage, &["a0"]), - add("a2", 1, g, 4, Role::Manage, &["a1"]), - delegate("d0", 1, g, 2, Role::Manage, true, &["a2"]), - delegate("d1", 2, g, 3, Role::Manage, true, &["d0"]), - delegate("d2", 3, g, 4, Role::Manage, false, &["d1"]), - add("a3", 4, g, 5, Role::Read, &["d2"]), - delegate("d3", 4, g, 5, Role::Read, false, &["d2"]), - ]); - assert_eq!(outcome(&valid, "a3"), Outcome::Applied, "the chain holds"); - assert_eq!(outcome(&valid, "d3"), Outcome::Refused(Refusal::NoChain)); - - // The same chain with 2 -> 3 not redelegatable: 3 cannot grant on, and 4 has no chain. - let broken = project(&[ - custom("g", 1, &[], Policy::default()), - add("a0", 1, g, 2, Role::Manage, &["g"]), - add("a1", 1, g, 3, Role::Manage, &["a0"]), - add("a2", 1, g, 4, Role::Manage, &["a1"]), - delegate("d0", 1, g, 2, Role::Manage, true, &["a2"]), - delegate("d1", 2, g, 3, Role::Manage, false, &["d0"]), - delegate("d2", 3, g, 4, Role::Manage, false, &["d1"]), - add("a3", 4, g, 5, Role::Read, &["d2"]), - ]); - assert_eq!(outcome(&broken, "d2"), Outcome::Refused(Refusal::NoChain)); - assert_eq!(outcome(&broken, "a3"), Outcome::Refused(Refusal::NoChain)); + let members = |events: &mut Vec| { + events.push(custom("g", 1, &[], Policy::default())); + events.push(add("a0", 1, g, 2, Role::Write, &["g"])); + events.push(add("a1", 1, g, 3, Role::Write, &["a0"])); + events.push(add("a2", 1, g, 4, Role::Write, &["a1"])); + }; + // 1 -> 2 -> 3 -> 4 -> 5. Every link may be passed on, so 4 can grant to 5. + let mut valid = Vec::new(); + members(&mut valid); + valid.push(delegate("d0", 1, g, 2, Role::Write, true, &["a2"])); + valid.push(delegate("d1", 2, g, 3, Role::Write, true, &["d0"])); + valid.push(delegate("d2", 3, g, 4, Role::Write, true, &["d1"])); + valid.push(delegate("d3", 4, g, 5, Role::Read, false, &["d2"])); + let p = project(&valid); + assert_eq!(outcome(&p, "d3"), Outcome::Applied, "the chain holds"); + + // The last link cannot be passed on, so 4 cannot grant. + let mut last = Vec::new(); + members(&mut last); + last.push(delegate("d0", 1, g, 2, Role::Write, true, &["a2"])); + last.push(delegate("d1", 2, g, 3, Role::Write, true, &["d0"])); + last.push(delegate("d2", 3, g, 4, Role::Write, false, &["d1"])); + last.push(delegate("d3", 4, g, 5, Role::Read, false, &["d2"])); + let p = project(&last); + assert_eq!(outcome(&p, "d3"), Outcome::Refused(Refusal::NoChain)); + + // The middle link cannot be passed on: 3 cannot grant, so 4 has no chain. + let mut middle = Vec::new(); + members(&mut middle); + middle.push(delegate("d0", 1, g, 2, Role::Write, true, &["a2"])); + middle.push(delegate("d1", 2, g, 3, Role::Write, false, &["d0"])); + middle.push(delegate("d2", 3, g, 4, Role::Write, true, &["d1"])); + let p = project(&middle); + assert_eq!(outcome(&p, "d2"), Outcome::Refused(Refusal::NoChain)); } #[test] -fn test_a_manager_acts_only_through_a_grant_from_an_owner() { - // 3 is a Manage member added by the owner, but no grant reaches it, so it cannot add. +fn test_a_manager_added_by_another_member_is_a_root_and_its_grants_are_valid() { + // Design §7.2: roots are the owners or managers at the action's position. 2 is a manager + // added by 1, so it is a root there: it may manage, and its grant is valid. let g = id("g"); let p = project(&[ custom("g", 1, &[], Policy::default()), add("a0", 1, g, 2, Role::Manage, &["g"]), - add("a1", 2, g, 3, Role::Manage, &["a0"]), - add("a2", 2, g, 4, Role::Read, &["a1"]), + add("a1", 2, g, 4, Role::Read, &["a0"]), + delegate("d0", 2, g, 3, Role::Write, true, &["a1"]), ]); - assert_eq!( - outcome(&p, "a0"), - Outcome::Applied, - "the owner adds directly" - ); - assert_eq!(outcome(&p, "a1"), Outcome::Refused(Refusal::NoChain)); - assert_eq!(outcome(&p, "a2"), Outcome::Refused(Refusal::NoChain)); + assert_eq!(outcome(&p, "a1"), Outcome::Applied); + assert_eq!(outcome(&p, "d0"), Outcome::Applied); + assert!(p.grant_in_force(&id("d0"))); } #[test] @@ -925,60 +924,55 @@ fn test_a_manager_may_veto_a_grant_and_the_grants_below_it_fall() { let g = id("g"); let mut events = chain_base(None); events.push(add("a2", 1, g, 4, Role::Manage, &["a1"])); - events.push(delegate("d2", 1, g, 4, Role::Manage, true, &["a2"])); - events.push(veto("v0", 4, g, "d0", &["d2", "d0"])); - events.push(add("a3", 3, g, 5, Role::Read, &["v0"])); - events.push(add("a4", 3, g, 6, Role::Read, &["d1"])); + events.push(veto("v0", 4, g, "d0", &["d1", "a2"])); + events.push(delegate("d2", 3, g, 5, Role::Read, false, &["v0"])); + events.push(delegate("d3", 3, g, 6, Role::Read, false, &["d1"])); + events.push(delegate("d4", 4, g, 7, Role::Read, false, &["v0"])); let p = project(&events); assert_eq!(outcome(&p, "v0"), Outcome::Applied); assert_eq!( - outcome(&p, "a3"), + outcome(&p, "d2"), Outcome::Refused(Refusal::NoChain), "3 reaches the owner only through d0" ); assert_eq!( - outcome(&p, "a4"), + outcome(&p, "d3"), Outcome::Applied, "before the veto, d0 stood" ); + assert_eq!( + outcome(&p, "d4"), + Outcome::Applied, + "4 is a manager, a root at its position" + ); assert!(!p.grant_in_force(&id("d0"))); - assert!(p.grant_in_force(&id("d2"))); } #[test] -fn test_a_veto_needs_manage_access_a_chain_and_a_grant_it_has_seen() { +fn test_a_veto_needs_manage_a_grant_it_has_seen() { let g = id("g"); let p = project(&[ custom("g", 1, &[], Policy::default()), - add("a0", 1, g, 2, Role::Manage, &["g"]), - add("a1", 1, g, 3, Role::Read, &["a0"]), - add("a2", 1, g, 4, Role::Manage, &["a1"]), - delegate("d0", 1, g, 2, Role::Manage, true, &["a2"]), - veto("v0", 3, g, "d0", &["d0"]), - veto("v1", 4, g, "d0", &["d0"]), - veto("v2", 2, g, "d0", &["d0"]), + add("a0", 1, g, 2, Role::Write, &["g"]), + add("a1", 1, g, 3, Role::Manage, &["a0"]), + delegate("d0", 1, g, 2, Role::Write, true, &["a1"]), + delegate("d5", 3, g, 4, Role::Read, false, &["a1"]), + veto("v0", 2, g, "d0", &["d0"]), + veto("v1", 3, g, "d0", &["d0"]), + veto("v2", 3, g, "d5", &["d0"]), + veto("v3", 3, g, "d9", &["d0"]), ]); assert_eq!(outcome(&p, "v0"), Outcome::Refused(Refusal::NotManager)); - assert_eq!( - outcome(&p, "v1"), - Outcome::Refused(Refusal::NoChain), - "4 manages without a chain" - ); + assert_eq!(outcome(&p, "v1"), Outcome::Applied); assert_eq!( outcome(&p, "v2"), - Outcome::Applied, - "2 manages through the owner's grant" + Outcome::Refused(Refusal::UnknownGrant), + "d5 is concurrent with d0, so the veto has not seen it" ); - let unseen = project(&[ - custom("g", 1, &[], Policy::default()), - add("a0", 1, g, 2, Role::Manage, &["g"]), - delegate("d0", 1, g, 2, Role::Manage, true, &["a0"]), - veto("v0", 2, g, "d1", &["d0"]), - ]); assert_eq!( - outcome(&unseen, "v0"), + outcome(&p, "v3"), Outcome::Refused(Refusal::UnknownGrant), - "d1 does not exist" + "d9 does not exist" ); } @@ -1015,29 +1009,27 @@ fn s2_events(alt: bool, mode: Option, successor: Option) -> Vec< #[test] fn test_s2_delegation_scenarios_keep_their_results() { + // (alt chain, mode, successor, Joe to Jim stands at the head). Jim (4) and Quinn (7) are + // managers, so they are roots at their positions (design §7.2). Their later actions apply in + // every mode. S2 had them vetoed, because it made only the owner a root. The mode still + // decides the grant from Joe, which is the table's last column. let g = id("s0"); - // (alt chain, mode, successor, Jim's later action applies, the grant Joe to Jim stands). let runs = [ - (false, None, None, false, false), - (true, None, None, true, false), - (false, Some(Delegation::KeepPrior), None, true, true), - (false, Some(Delegation::Transfer), Some(3), true, false), + (false, None, None, false), + (true, None, None, false), + (false, Some(Delegation::KeepPrior), None, true), + (false, Some(Delegation::Transfer), Some(3), false), ]; - for (alt, mode, successor, jim_later, joe_to_jim_stands) in runs { + for (alt, mode, successor, joe_to_jim_stands) in runs { let name = format!("alt {alt}, mode {mode:?}, successor {successor:?}"); let p = project(&s2_events(alt, mode, successor)); - let expected = if jim_later { - Outcome::Applied - } else { - Outcome::Refused(Refusal::NoChain) - }; - assert_eq!(outcome(&p, "s10"), expected, "{name}: Jim's later add"); - assert_eq!(outcome(&p, "s11"), Outcome::Applied, "{name}: concurrent"); assert_eq!( - outcome(&p, "s12"), - Outcome::Refused(Refusal::NoChain), - "{name}: Quinn's only chain is void" + outcome(&p, "s10"), + Outcome::Applied, + "{name}: Jim's later add" ); + assert_eq!(outcome(&p, "s11"), Outcome::Applied, "{name}: concurrent"); + assert_eq!(outcome(&p, "s12"), Outcome::Applied, "{name}: Quinn's add"); assert!(!p.grant_in_force(&id("s8")), "{name}: void"); assert_eq!( p.grant_in_force(&id("s6")), @@ -1046,7 +1038,7 @@ fn test_s2_delegation_scenarios_keep_their_results() { ); let members = &p.group(&g).unwrap().members; assert!(!members.contains_key(&key(2)), "{name}: Joe is removed"); - assert_eq!(members.contains_key(&key(5)), jim_later, "{name}: Zed"); + assert!(members.contains_key(&key(5)), "{name}: Zed"); } let p = project(&s2_events(false, None, None)); assert_eq!(outcome(&p, "s14"), Outcome::Refused(Refusal::Attenuated)); diff --git a/pkgs/id/src/membership/layer.rs b/pkgs/id/src/membership/layer.rs index 03454f54a1..4e46a113be 100644 --- a/pkgs/id/src/membership/layer.rs +++ b/pkgs/id/src/membership/layer.rs @@ -354,6 +354,30 @@ impl Membership { Ok(self.access_at(&deps, AuthId::Group(group), AuthId::Key(member))) } + /// The accounts that hold manage access in `group` at the causal position that `after` names. + /// Empty when the group does not exist there. Delegation takes these as its roots (design + /// §7.2). + /// + /// # Errors + /// + /// Returns [`MembershipError`] when an `after` hash is not indexed. + pub fn managers_at_position( + &mut self, + after: &[Hash], + group: Hash, + ) -> Result, MembershipError> { + let heads: HashSet = self.index.frontier(after, group)?.into_iter().collect(); + let managers = Graph::members_at(&self.state, heads, AuthId::Group(group)) + .unwrap_or_default() + .into_iter() + .filter_map(|(id, access)| match id { + AuthId::Key(key) if access.is_manage() => Some(key), + _ => None, + }) + .collect(); + Ok(managers) + } + /// Whether a create has been decided for `group`. pub fn has_group(&self, group: Hash) -> bool { self.state.has_group(AuthId::Group(group)) From 10385cc4a6bc2aa84b79aefb63b16d27d06089cb Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 12 Oct 2026 03:31:46 -0500 Subject: [PATCH 30/40] fix(rust): provision builds MemberOp::Remove with the successor field [P2.9] --- pkgs/id/src/server_config/provision.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/pkgs/id/src/server_config/provision.rs b/pkgs/id/src/server_config/provision.rs index a08f897414..8bc40150c8 100644 --- a/pkgs/id/src/server_config/provision.rs +++ b/pkgs/id/src/server_config/provision.rs @@ -362,7 +362,10 @@ mod tests { author: key(1), after: vec![last], group: Some(team), - body: Body::Member(MemberOp::Remove { member: key(2) }), + body: Body::Member(MemberOp::Remove { + member: key(2), + successor: None, + }), }; let projection = state.record(remove_bo).unwrap(); assert_eq!(projection.outcome(&remove_id), Some(&Outcome::Applied)); From 23445bffaa52a107cd984a722da019007b45028f Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 12 Oct 2026 03:36:43 -0500 Subject: [PATCH 31/40] fix(rust): the provision test names the removal's successor [P2.9] --- pkgs/id/src/server_config/provision.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/pkgs/id/src/server_config/provision.rs b/pkgs/id/src/server_config/provision.rs index a08f897414..8bc40150c8 100644 --- a/pkgs/id/src/server_config/provision.rs +++ b/pkgs/id/src/server_config/provision.rs @@ -362,7 +362,10 @@ mod tests { author: key(1), after: vec![last], group: Some(team), - body: Body::Member(MemberOp::Remove { member: key(2) }), + body: Body::Member(MemberOp::Remove { + member: key(2), + successor: None, + }), }; let projection = state.record(remove_bo).unwrap(); assert_eq!(projection.outcome(&remove_id), Some(&Outcome::Applied)); From 24984c96d36f80698e43bf7b6457a2ba39ed9bab Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 12 Oct 2026 03:36:43 -0500 Subject: [PATCH 32/40] feat(rust): cross-world authority is judged per world [P2.7] Each world is folded on its own. An action in world B is judged by B's membership and B's grants, or by a crossing grant that names B and is in force in its home world. A crossing is a Body::Cross grant that carries at most Write, is never a link in its home chains, and ends with its grantor's or grantee's standing at home. Isolation markers decide only their own world's grants out and accepts in. --- pkgs/id/src/groups/delegation.rs | 45 ++- pkgs/id/src/groups/fold.rs | 31 +- pkgs/id/src/groups/mod.rs | 10 + pkgs/id/src/groups/worlds.rs | 537 +++++++++++++++++++++++++++++++ 4 files changed, 607 insertions(+), 16 deletions(-) create mode 100644 pkgs/id/src/groups/worlds.rs diff --git a/pkgs/id/src/groups/delegation.rs b/pkgs/id/src/groups/delegation.rs index deb9de3ee5..36c54a3790 100644 --- a/pkgs/id/src/groups/delegation.rs +++ b/pkgs/id/src/groups/delegation.rs @@ -24,14 +24,25 @@ use super::policy::Delegation; use super::{Body, Delegate, Event, Key, MemberOp, Role}; /// A grant that took effect: `from` gave `to` the scope `scope` in `group`, as event `id`. +/// +/// A grant with a `target` is a crossing (P2.7, see [`super::worlds`]). It is judged and kept in +/// force like any other grant, but it is never a link in its home world's chains. #[derive(Clone, Debug, PartialEq, Eq)] -pub(super) struct Grant { - pub(super) id: Hash, - pub(super) group: Hash, - pub(super) from: Key, - pub(super) to: Key, - pub(super) scope: Role, - pub(super) redelegate: bool, +pub struct Grant { + /// The granting event's ID. + pub id: Hash, + /// The group the grant is made in. + pub group: Hash, + /// The grantor. + pub from: Key, + /// The grantee. + pub to: Key, + /// The scope granted. + pub scope: Role, + /// Whether the grantee may grant the scope on. + pub redelegate: bool, + /// The world the grant names, if it is a crossing. + pub target: Option, } /// A removal that took effect. Its successor takes over the removed member's grants under @@ -65,16 +76,19 @@ struct Link { scope: Role, redelegate: bool, reissued: bool, + crossing: bool, } impl Engine { /// Judges a grant. The author must be an active member who holds the scope at the event's - /// position, and must reach it through a chain that can be passed on. + /// position, and must reach it through a chain that can be passed on. A crossing (`target` + /// set) may carry Write at most and must name a world. pub(super) fn delegate( &mut self, by_id: &BTreeMap, event: &Event, delegate: Delegate, + target: Option<&str>, ) -> Result { let group = match self.acting_in(event) { Ok(group) => group, @@ -83,6 +97,9 @@ impl Engine { if delegate.scope == Role::Admin { return Ok(Err(Refusal::BadScope)); } + if target.is_some_and(|world| world.is_empty() || delegate.scope > Role::Write) { + return Ok(Err(Refusal::NotCrossable)); + } if delegate.grantee == event.author { return Ok(Err(Refusal::BadGrantee)); } @@ -102,7 +119,10 @@ impl Engine { Ok(Ok(Decision { group, action: None, - effect: Effect::Delegation(delegate), + effect: Effect::Delegation { + delegate, + target: target.map(str::to_owned), + }, })) } @@ -200,7 +220,8 @@ impl Engine { /// so it holds every scope. An actor that is a root is authorized. Otherwise a chain of links /// leads from a root to the actor, every link attenuating. With `need_redelegate`, the last /// link into the actor must allow the actor to grant on. The actor's own membership is not - /// checked here: a grant may reach an account that is not a member. + /// checked here: a grant may reach an account that is not a member. Crossings (grants that + /// name another world) are not links here, so they never extend a chain in this group. pub(super) fn authorized( &mut self, by_id: &BTreeMap, @@ -223,7 +244,7 @@ impl Engine { while let Some(holder) = stack.pop() { for link in links .iter() - .filter(|link| link.from == holder && link.scope >= scope) + .filter(|link| !link.crossing && link.from == holder && link.scope >= scope) { if link.to == actor && (!need_redelegate || link.redelegate) { return Ok(true); @@ -318,6 +339,7 @@ impl Engine { scope: grant.scope, redelegate: grant.redelegate, reissued: true, + crossing: grant.target.is_some(), }); } } @@ -333,6 +355,7 @@ impl Engine { scope: grant.scope, redelegate: grant.redelegate, reissued: false, + crossing: grant.target.is_some(), }); } Ok(links) diff --git a/pkgs/id/src/groups/fold.rs b/pkgs/id/src/groups/fold.rs index 756599efcd..3e72009f5f 100644 --- a/pkgs/id/src/groups/fold.rs +++ b/pkgs/id/src/groups/fold.rs @@ -94,6 +94,8 @@ pub enum Refusal { BadGrantee, /// A veto names no grant of this group that the veto has seen. UnknownGrant, + /// A grant that names another world may carry Write at most, and must name a world. + NotCrossable, } /// What became of one event. @@ -167,6 +169,7 @@ pub struct Projection { outcomes: BTreeMap, effective: BTreeSet, in_force: BTreeSet, + grants: Vec, } impl Projection { @@ -208,6 +211,12 @@ impl Projection { pub fn grant_in_force(&self, id: &Hash) -> bool { self.in_force.contains(id) } + + /// Every grant in force at the head of the events, with its grantor, grantee, scope and + /// target world. See [`Grant`]. + pub fn grants_in_force(&self) -> impl Iterator { + self.grants.iter() + } } /// Computes the state of every group from the whole set of events. The order the events are given @@ -256,7 +265,7 @@ fn run( const fn is_candidate(event: &Event) -> bool { matches!( event.body, - Body::Delegate(_) | Body::Veto { .. } | Body::Member(_) + Body::Delegate(_) | Body::Cross { .. } | Body::Veto { .. } | Body::Member(_) ) } @@ -360,7 +369,10 @@ pub(super) enum Effect { successor: Option, by: Hash, }, - Delegation(Delegate), + Delegation { + delegate: Delegate, + target: Option, + }, Veto(Hash), } @@ -459,7 +471,8 @@ impl Engine { Ok(decision) => self.manage_chain(by_id, event, *op, decision), Err(refusal) => Ok(Err(refusal)), }, - Body::Delegate(delegate) => self.delegate(by_id, event, *delegate), + Body::Delegate(delegate) => self.delegate(by_id, event, *delegate, None), + Body::Cross { delegate, world } => self.delegate(by_id, event, *delegate, Some(world)), Body::Veto { grant } => self.veto(by_id, event, *grant), } } @@ -489,7 +502,7 @@ impl Engine { Effect::Create(record) => { self.groups.insert(group, record); } - Effect::Delegation(delegate) => { + Effect::Delegation { delegate, target } => { let grant = Grant { id: event.id, group, @@ -497,6 +510,7 @@ impl Engine { to: delegate.grantee, scope: delegate.scope, redelegate: delegate.can_redelegate, + target, }; self.grants.insert(event.id, grant); } @@ -836,6 +850,12 @@ impl Engine { in_force: BTreeSet, ) -> Projection { let membership = &self.membership; + let grants: Vec = self + .grants + .values() + .filter(|grant| in_force.contains(&grant.id)) + .cloned() + .collect(); let groups = self .groups .into_iter() @@ -866,6 +886,7 @@ impl Engine { outcomes, effective, in_force, + grants, } } } @@ -873,7 +894,7 @@ impl Engine { /// Applies a state change to a group that exists. fn apply_to(record: &mut Record, effect: Effect) { match effect { - Effect::Create(_) | Effect::Delegation(_) | Effect::Veto(_) => {} + Effect::Create(_) | Effect::Delegation { .. } | Effect::Veto(_) => {} Effect::Present(member) => { record.present.insert(member); } diff --git a/pkgs/id/src/groups/mod.rs b/pkgs/id/src/groups/mod.rs index 145fdb27a9..e7e44533fb 100644 --- a/pkgs/id/src/groups/mod.rs +++ b/pkgs/id/src/groups/mod.rs @@ -16,6 +16,7 @@ pub mod fold; pub mod friendship; pub mod policy; +pub mod worlds; mod delegation; @@ -24,6 +25,7 @@ mod tests; use p2panda_core::Hash; +pub use delegation::Grant; pub use fold::{FoldError, GroupView, Outcome, Projection, Refusal, fold}; pub use friendship::{Pair, friendship_id}; pub use policy::{ @@ -90,6 +92,14 @@ pub enum Body { /// Grants a scope to an account. The author must hold the scope, and must reach it through a /// chain of grants that can be passed on (design §7.2). Delegate(Delegate), + /// Grants a scope that the grantee may use in another world (P2.7, see [`worlds`]). It is judged + /// in this event's world the way [`Body::Delegate`] is, but it gives its grantee nothing here. + Cross { + /// The grant. Its scope may be at most Write. + delegate: Delegate, + /// The world the grant names. It is not the event's own world. + world: String, + }, /// Vetoes a grant the event has seen. The author must hold Manage and a chain (design §7). /// From this event's causal position on, the grant and what depends on it fail. Veto { diff --git a/pkgs/id/src/groups/worlds.rs b/pkgs/id/src/groups/worlds.rs new file mode 100644 index 0000000000..c9b17fcfa5 --- /dev/null +++ b/pkgs/id/src/groups/worlds.rs @@ -0,0 +1,537 @@ +//! Cross-world authority (P2.7, task 03 item 7): each world judges its own actions by its own +//! membership and delegations, and a grant that names another world is the only way one world's +//! authority reaches into another. +//! +//! The design (§7.5 and the two cross-world docs) says the rules "overlap with delegation" and must +//! be reconciled, but it does not say how a grant names a world. These are the choices, taken as +//! the more restrictive reading: +//! +//! - **Per-world judgement.** Each world's events are folded on their own ([`Worlds::fold`]). A +//! removal or a grant in one world cannot change another world's fold, so a removal in A changes +//! B only through a grant that names B. +//! - **Local authority.** An action in world B at scope S is allowed by B's own membership, or by a +//! grant in B's own chains. Grants that name another world do not count here. +//! - **Crossings.** A [`Body::Cross`] grant is made in its home world, where it is judged like any +//! grant. It names a target world and carries at most Write. It is never a link in its home +//! world's chains, so it gives nothing there and cannot be passed on. It stands while its grantor +//! holds the scope at home (cascade), and while its grantee still holds at least that scope there +//! at the head: removing the grantee ends its reach into the target. +//! - **Markers are local.** A world's [`Markers`] decide two things, and only for that world. The +//! home world's isolation decides whether its members may make crossings at all. The target's +//! isolation and cross-world write setting decide whether it accepts a crossing: a read needs +//! both unisolated, and a write also needs the target's setting, as `world_hub::cross_world_allowed` +//! says. No world reads another world's marker to judge its own members. +//! - **Scope.** A crossing reaches the target only at the scope it grants or below. + +use std::collections::BTreeMap; + +use super::fold::{FoldError, Projection, fold}; +use super::{Event, Grant, Key, Role}; +use crate::world::Isolation; + +/// A world's name, as `WorldCore::world_id` names it. +pub type World = String; + +/// A world's isolation markers. The defaults are the defaults of a world with no record: isolated, +/// and no cross-world write. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Markers { + /// Whether the world takes part in cross-world access. + pub isolation: Isolation, + /// Whether the world accepts cross-world writes. + pub cross_write: bool, +} + +/// Every world's events, folded world by world, with each world's markers. +#[derive(Debug)] +pub struct Worlds { + folds: BTreeMap, + markers: BTreeMap, +} + +impl Worlds { + /// Folds each world's events on their own. + /// + /// # Errors + /// + /// Any error [`fold`] gives for one world. + pub fn fold( + events: &BTreeMap>, + markers: BTreeMap, + ) -> Result { + let folds = events + .iter() + .map(|(world, events)| Ok((world.clone(), fold(events)?))) + .collect::>()?; + Ok(Self { folds, markers }) + } + + /// The folded state of one world. + pub fn projection(&self, world: &str) -> Option<&Projection> { + self.folds.get(world) + } + + /// Whether `actor` may act in `world` at `scope`: by the world's own authority, or through a + /// crossing that names the world and is accepted there. + pub fn may_act(&self, world: &str, actor: Key, scope: Role) -> bool { + self.holds_here(world, actor, scope) + || (self.accepts(world, scope) + && self + .crossings_into(world) + .into_iter() + .any(|grant| grant.to == actor && grant.scope >= scope)) + } + + /// Whether the world's own membership, or a grant in its own chains, gives `actor` the scope. + pub fn holds_here(&self, world: &str, actor: Key, scope: Role) -> bool { + self.projection(world).is_some_and(|projection| { + projection.groups().any(|(_, group)| { + group.is_active() && group.members.get(&actor).is_some_and(|role| *role >= scope) + }) || projection + .grants_in_force() + .any(|grant| grant.target.is_none() && grant.to == actor && grant.scope >= scope) + }) + } + + /// Whether `world` accepts a crossing at `scope`: unisolated, and for a write also the write + /// setting. This is the target's half of `world_hub::cross_world_allowed`. + fn accepts(&self, world: &str, scope: Role) -> bool { + let markers = self.markers(world); + markers.isolation == Isolation::Unisolated && (scope < Role::Write || markers.cross_write) + } + + /// The crossings that name `world`, in force in their home worlds. A home world that is + /// isolated makes none. The grantee must hold the crossing's scope at home now. + fn crossings_into(&self, world: &str) -> Vec<&Grant> { + self.folds + .iter() + .filter(|(home, _)| home.as_str() != world) + .filter(|(home, _)| self.markers(home).isolation == Isolation::Unisolated) + .flat_map(|(_, projection)| { + projection.grants_in_force().filter(|grant| { + grant.target.as_deref() == Some(world) + && projection.groups().any(|(_, group)| { + group.is_active() + && group + .members + .get(&grant.to) + .is_some_and(|role| *role >= grant.scope) + }) + }) + }) + .collect() + } + + /// The highest scope each of `keys` may use in `world`. Equal maps mean equal authority. + pub fn authority(&self, world: &str, keys: &[Key]) -> BTreeMap { + const SCOPES: [Role; 5] = [ + Role::Pull, + Role::Read, + Role::Write, + Role::Manage, + Role::Admin, + ]; + keys.iter() + .filter_map(|&key| { + SCOPES + .iter() + .rev() + .find(|&&scope| self.may_act(world, key, scope)) + .map(|&scope| (key, scope)) + }) + .collect() + } + + /// The markers of one world. A world with no record has the defaults. + pub fn markers(&self, world: &str) -> Markers { + self.markers.get(world).copied().unwrap_or_default() + } +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used)] +mod tests { + use std::collections::BTreeMap; + + use p2panda_core::Hash; + use proptest::prelude::*; + + use super::{Markers, Worlds}; + use crate::groups::policy::Policy; + use crate::groups::{ + Body, Create, Delegate, Event, Key, MemberOp, Outcome, Refusal, Role, Template, + }; + use crate::world::Isolation; + use crate::world::Isolation::{Isolated, Unisolated}; + + /// The accounts the tests use. Account 1 founds each world and is its Admin. + const KEYS: [Key; 5] = [[1; 32], [2; 32], [3; 32], [4; 32], [5; 32]]; + + fn key(n: u8) -> Key { + [n; 32] + } + + fn hid(name: &str) -> Hash { + Hash::digest(name.as_bytes()) + } + + /// Builds events world by world. Each event names the one before it in its world, so a + /// world is a chain and the only thing a test varies is the order the events arrive in. + #[derive(Clone, Default)] + struct Ledger { + events: BTreeMap>, + last: BTreeMap, + groups: BTreeMap, + count: usize, + } + + impl Ledger { + fn push(&mut self, world: &str, author: u8, group: Option<&str>, body: Body) -> String { + self.count += 1; + let name = format!("{world}{}", self.count); + let event = Event { + id: hid(&name), + author: key(author), + after: self.last.get(world).copied().into_iter().collect(), + group: group.map(hid), + body, + }; + self.last.insert(world.to_owned(), event.id); + self.events.entry(world.to_owned()).or_default().push(event); + name + } + + /// Founds the world's group. Its creator is Admin. + fn create(&mut self, world: &str, founder: u8) { + let body = Body::Create(Create { + template: Template::Custom, + policy: Policy::default(), + members: Vec::new(), + admins_on_create: false, + }); + let name = self.push(world, founder, None, body); + self.groups.insert(world.to_owned(), name); + } + + fn group(&self, world: &str) -> String { + self.groups[world].clone() + } + + fn add(&mut self, world: &str, by: u8, who: u8, role: Role) -> String { + let group = self.group(world); + let body = Body::Member(MemberOp::Add { + member: key(who), + role, + }); + self.push(world, by, Some(&group), body) + } + + fn remove(&mut self, world: &str, by: u8, who: u8) -> String { + let group = self.group(world); + let body = Body::Member(MemberOp::Remove { + member: key(who), + successor: None, + }); + self.push(world, by, Some(&group), body) + } + + fn delegate( + &mut self, + world: &str, + by: u8, + to: u8, + scope: Role, + redelegate: bool, + ) -> String { + let group = self.group(world); + let body = Body::Delegate(Delegate { + grantee: key(to), + scope, + can_redelegate: redelegate, + }); + self.push(world, by, Some(&group), body) + } + + /// A grant from `by` in `world` that names `names` as the world it is used in. + fn cross( + &mut self, + world: &str, + by: u8, + to: u8, + scope: Role, + redelegate: bool, + names: &str, + ) -> String { + let group = self.group(world); + let body = Body::Cross { + delegate: Delegate { + grantee: key(to), + scope, + can_redelegate: redelegate, + }, + world: names.to_owned(), + }; + self.push(world, by, Some(&group), body) + } + + fn worlds(&self, markers: &BTreeMap) -> Worlds { + Worlds::fold(&self.events, markers.clone()).unwrap() + } + } + + /// Both worlds unisolated, each accepting cross-world writes. + fn open() -> BTreeMap { + markers(&[("a", Unisolated, true), ("b", Unisolated, true)]) + } + + fn markers(entries: &[(&str, Isolation, bool)]) -> BTreeMap { + entries + .iter() + .map(|&(world, isolation, cross_write)| { + ( + world.to_owned(), + Markers { + isolation, + cross_write, + }, + ) + }) + .collect() + } + + /// World `a`: founder 1 (Admin), manager 2, writer 3, reader 4. World `b`: founder 1 and writer + /// 5. Account 3 has authority in `a` only. + fn two_worlds() -> Ledger { + let mut ledger = Ledger::default(); + ledger.create("a", 1); + ledger.add("a", 1, 2, Role::Manage); + ledger.add("a", 1, 3, Role::Write); + ledger.add("a", 1, 4, Role::Read); + ledger.create("b", 1); + ledger.add("b", 1, 5, Role::Write); + ledger + } + + // ----- Cross-world rules (P2.7) ----- + + #[test] + fn test_a_member_whose_authority_is_only_in_another_world_is_refused_here() { + let worlds = two_worlds().worlds(&open()); + assert!(worlds.may_act("a", key(3), Role::Write)); + assert!(!worlds.may_act("b", key(3), Role::Read)); + assert!(!worlds.may_act("b", key(4), Role::Pull)); + } + + #[test] + fn test_a_grant_that_names_the_world_lets_the_grantee_act_there_within_its_scope() { + let mut ledger = two_worlds(); + ledger.cross("a", 2, 3, Role::Write, false, "b"); + let worlds = ledger.worlds(&open()); + assert!(worlds.may_act("b", key(3), Role::Read)); + assert!(worlds.may_act("b", key(3), Role::Write)); + assert!(!worlds.may_act("b", key(3), Role::Manage)); + assert!(!worlds.may_act("b", key(4), Role::Read)); + } + + #[test] + fn test_a_crossing_needs_both_worlds_unisolated_and_the_target_setting_for_writes() { + for a in [Isolated, Unisolated] { + for b in [Isolated, Unisolated] { + for cross_write in [false, true] { + let mut ledger = two_worlds(); + ledger.cross("a", 2, 3, Role::Write, false, "b"); + let worlds = ledger.worlds(&markers(&[("a", a, true), ("b", b, cross_write)])); + let both = a == Unisolated && b == Unisolated; + assert_eq!( + worlds.may_act("b", key(3), Role::Read), + both, + "read with a {a:?}, b {b:?}" + ); + assert_eq!( + worlds.may_act("b", key(3), Role::Write), + both && cross_write, + "write with a {a:?}, b {b:?}, cross_write {cross_write}" + ); + } + } + } + } + + #[test] + fn test_a_removal_in_the_home_world_changes_the_other_world_only_through_the_grant() { + let mut base = two_worlds(); + base.cross("a", 2, 3, Role::Write, false, "b"); + let keys = KEYS; + + let mut unrelated = base.clone(); + unrelated.remove("a", 1, 4); + assert_eq!( + base.worlds(&open()).authority("b", &keys), + unrelated.worlds(&open()).authority("b", &keys), + "removing an account with no grant into b must not change b" + ); + + assert!( + base.worlds(&open()).may_act("b", key(3), Role::Read), + "the grant names b and is in force before the removal" + ); + let mut grantor = base.clone(); + grantor.remove("a", 1, 2); + let after = grantor.worlds(&open()); + assert!( + !after.may_act("b", key(3), Role::Read), + "removing the grantor ends the grant that names b" + ); + assert!( + after.may_act("b", key(5), Role::Write), + "b's own members are not touched by a removal in a" + ); + } + + #[test] + fn test_removing_the_grantee_at_home_ends_its_crossing() { + let mut ledger = two_worlds(); + ledger.cross("a", 2, 3, Role::Write, false, "b"); + assert!(ledger.worlds(&open()).may_act("b", key(3), Role::Read)); + ledger.remove("a", 1, 3); + let worlds = ledger.worlds(&open()); + assert!(!worlds.may_act("b", key(3), Role::Read)); + } + + #[test] + fn test_isolation_markers_are_local_to_their_own_world() { + let mut ledger = two_worlds(); + ledger.cross("a", 2, 3, Role::Write, false, "b"); + + // Isolating a stops a's grants out. b's own members are unaffected. + let a_isolated = ledger.worlds(&markers(&[("a", Isolated, true), ("b", Unisolated, true)])); + assert!(a_isolated.may_act("b", key(5), Role::Write)); + assert!(!a_isolated.may_act("b", key(3), Role::Write)); + + // Isolating b stops b from taking grants in. b's own members keep working. + let b_isolated = ledger.worlds(&markers(&[("a", Unisolated, true), ("b", Isolated, true)])); + assert!(b_isolated.may_act("b", key(5), Role::Write)); + assert!(!b_isolated.may_act("b", key(3), Role::Read)); + + // A marker never changes b's own membership: b's founder and writer keep their scopes. + let own = BTreeMap::from([(key(1), Role::Admin), (key(5), Role::Write)]); + let plain = ledger.worlds(&markers(&[("a", Isolated, true), ("b", Isolated, true)])); + assert_eq!(plain.authority("b", &KEYS), own); + assert_eq!(a_isolated.authority("b", &KEYS), own); + assert_eq!(b_isolated.authority("b", &KEYS), own); + } + + #[test] + fn test_a_crossing_gives_nothing_in_its_home_world_and_cannot_be_passed_on() { + let mut ledger = two_worlds(); + ledger.cross("a", 2, 3, Role::Write, true, "b"); + let pass_home = ledger.delegate("a", 3, 4, Role::Read, false); + let pass_on = ledger.cross("a", 3, 4, Role::Read, false, "b"); + let worlds = ledger.worlds(&open()); + let home = worlds.projection("a").unwrap(); + assert_eq!( + home.outcome(&hid(&pass_home)), + Some(&Outcome::Refused(Refusal::NoChain)), + "a crossing is not a link in the home world's chains" + ); + assert_eq!( + home.outcome(&hid(&pass_on)), + Some(&Outcome::Refused(Refusal::NoChain)), + "a crossing cannot be passed on into another world" + ); + assert!(!worlds.may_act("b", key(4), Role::Read)); + assert!(!worlds.may_act("a", key(3), Role::Manage)); + } + + #[test] + fn test_a_crossing_above_write_is_refused() { + let mut ledger = two_worlds(); + let name = ledger.cross("a", 2, 3, Role::Manage, false, "b"); + let worlds = ledger.worlds(&open()); + assert_eq!( + worlds.projection("a").unwrap().outcome(&hid(&name)), + Some(&Outcome::Refused(Refusal::NotCrossable)) + ); + assert!(!worlds.may_act("b", key(3), Role::Manage)); + } + + // ----- Order independence (P2.7) ----- + + /// A deterministic shuffle, so a failing case can be replayed from its seed. + fn shuffled(items: &[T], mut seed: u64) -> Vec { + let mut out = items.to_vec(); + for i in (1..out.len()).rev() { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + let j = usize::try_from(seed % (i as u64 + 1)).unwrap(); + out.swap(i, j); + } + out + } + + /// Each step is (world, kind, who, scope, to, redelegate). Kinds: add or remove by the founder, + /// a cross-world grant, or a grant inside the world. + fn script() -> impl Strategy> { + prop::collection::vec((0u8..2, 0u8..4, 2u8..=5, 0u8..4, 2u8..=5, 0u8..2), 1..30) + } + + fn build(script: &[(u8, u8, u8, u8, u8, u8)]) -> Ledger { + const ROLES: [Role; 4] = [Role::Pull, Role::Read, Role::Write, Role::Manage]; + let mut ledger = Ledger::default(); + ledger.create("a", 1); + ledger.create("b", 1); + for &(world, kind, who, scope, to, redelegate) in script { + let (world, other) = if world == 0 { ("a", "b") } else { ("b", "a") }; + let role = ROLES[usize::from(scope)]; + let redelegate = redelegate == 1; + match kind { + 0 => { + ledger.add(world, 1, who, role); + } + 1 => { + ledger.remove(world, 1, who); + } + 2 => { + ledger.cross(world, who, to, role, redelegate, other); + } + _ => { + ledger.delegate(world, who, to, role, redelegate); + } + } + } + ledger + } + + fn arrive(events: &BTreeMap>, seed: u64) -> BTreeMap> { + events + .iter() + .map(|(world, events)| (world.clone(), shuffled(events, seed.max(1)))) + .collect() + } + + proptest! { + #![proptest_config(ProptestConfig::with_cases(256))] + + #[test] + fn prop_the_authority_of_each_world_is_the_same_in_every_order( + script in script(), + seed in any::(), + ) { + let ledger = build(&script); + let expected = ledger.worlds(&open()); + let in_order = arrive(&ledger.events, seed); + let shuffled_worlds = Worlds::fold(&in_order, open()).unwrap(); + let mut reversed = ledger.events.clone(); + for events in reversed.values_mut() { + events.reverse(); + } + let reversed_worlds = Worlds::fold(&reversed, open()).unwrap(); + for world in ["a", "b"] { + let want = expected.authority(world, &KEYS); + prop_assert_eq!(&shuffled_worlds.authority(world, &KEYS), &want); + prop_assert_eq!(&reversed_worlds.authority(world, &KEYS), &want); + } + } + } +} From c5f197d19e3f3aff7e899bed1fced2ef72c509e7 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 12 Oct 2026 03:54:17 -0500 Subject: [PATCH 33/40] test(rust): red tests for review findings [P2-review] --- pkgs/id/src/groups/tests.rs | 66 ++++++++++++++++++++++++++ pkgs/id/src/server_config/provision.rs | 43 +++++++++++++++++ pkgs/id/tests/production_ingest.rs | 50 +++++++++++++++++++ 3 files changed, 159 insertions(+) diff --git a/pkgs/id/src/groups/tests.rs b/pkgs/id/src/groups/tests.rs index 49b0111231..7cbb85bfed 100644 --- a/pkgs/id/src/groups/tests.rs +++ b/pkgs/id/src/groups/tests.rs @@ -1408,3 +1408,69 @@ proptest! { } } } + +// ----- Review of Phase 2 [P2-review] ----- + +#[test] +fn test_a_manager_who_is_not_an_admin_may_not_remove_an_admin() { + // Design §5.2: Manage adds and removes members at or below its own level. Admin is above it. + // An Admin may remove anyone, and any member may leave. + for remover in [3, 4] { + let events = vec![ + custom( + "g", + 1, + &[(2, Role::Admin), (3, Role::Manage), (4, Role::Manage)], + Policy::default(), + ), + remove("r", remover, id("g"), 2, &["g"]), + ]; + let p = project(&events); + assert_eq!( + outcome(&p, "r"), + Outcome::Refused(Refusal::NotAdmin), + "manager {remover} removing an Admin" + ); + assert_eq!(role_of(&p, id("g"), 2), Some(Role::Admin)); + } + let events = vec![ + custom( + "g", + 1, + &[(2, Role::Admin), (3, Role::Manage)], + Policy::default(), + ), + remove("r", 2, id("g"), 3, &["g"]), + ]; + let p = project(&events); + assert_eq!(outcome(&p, "r"), Outcome::Applied); + assert_eq!(role_of(&p, id("g"), 3), None); +} + +#[test] +fn test_a_grant_by_a_member_who_was_re_added_stands_in_every_mode() { + // 2 is removed and re-added. Its later grant is made by a member who is valid at that + // position, so it stands. Under transfer it must not be treated as the removed grantor's. + for mode in [ + Delegation::KeepPrior, + Delegation::Cascade, + Delegation::Transfer, + ] { + let policy = Policy { + delegation: Some(mode), + ..Policy::default() + }; + let events = vec![ + custom("g", 1, &[(2, Role::Manage), (3, Role::Manage)], policy), + remove("r", 1, id("g"), 2, &["g"]), + add("a", 1, id("g"), 2, Role::Manage, &["r"]), + delegate("d", 2, id("g"), 4, Role::Read, false, &["a"]), + ]; + let p = project(&events); + assert_eq!(outcome(&p, "d"), Outcome::Applied, "{mode:?}"); + assert!( + p.grant_in_force(&id("d")), + "{mode:?}: a grant made after the re-add stands" + ); + } +} diff --git a/pkgs/id/src/server_config/provision.rs b/pkgs/id/src/server_config/provision.rs index 8bc40150c8..d53b5cb2e6 100644 --- a/pkgs/id/src/server_config/provision.rs +++ b/pkgs/id/src/server_config/provision.rs @@ -536,4 +536,47 @@ mod tests { } } } + + /// A create by `who`, named `name`, as a user action sends it. + fn create_by(who: Key, name: &str) -> crate::groups::Event { + crate::groups::Event { + id: Hash::digest(name.as_bytes()), + author: who, + after: Vec::new(), + group: None, + body: Body::Create(crate::groups::Create { + template: crate::groups::Template::Custom, + policy: crate::groups::Policy::default(), + members: Vec::new(), + admins_on_create: false, + }), + } + } + + #[test] + fn test_a_create_recorded_after_the_start_meets_the_create_rule() { + // Only ann may create. A create by anyone else that arrives after the start is refused, as + // the rule refuses it at startup, and it leaves no group behind. + let config = ServerConfig::parse(&config("\n[create]\nusers = [\"ann\"]\n")).unwrap(); + let mut state = Provisioned::new(); + state.apply(&config).unwrap(); + assert!(state.record(create_by(key(1), "by-ann")).is_ok()); + for who in [2, 3, 4] { + assert!( + state + .record(create_by(key(who), &format!("by-{who}"))) + .is_err(), + "user {who} is not listed and may not create" + ); + let id = Hash::digest(format!("by-{who}").as_bytes()); + assert!(state.projection().unwrap().group(&id).is_none()); + } + assert!( + state + .projection() + .unwrap() + .group(&Hash::digest(b"by-ann")) + .is_some() + ); + } } diff --git a/pkgs/id/tests/production_ingest.rs b/pkgs/id/tests/production_ingest.rs index 05545d9971..138332cbc0 100644 --- a/pkgs/id/tests/production_ingest.rs +++ b/pkgs/id/tests/production_ingest.rs @@ -324,3 +324,53 @@ fn test_a_group_operation_that_arrives_without_its_body_is_content() { ); assert_eq!(roster_of(&shared, &create), members(&['A', 'B', 'C'])); } + +// ----- Review of Phase 2 [P2-review] ----- + +#[test] +fn test_a_member_of_any_access_can_leave_through_the_production_path() { + // Leaving is a removal by the member itself. p2panda-auth allows it for any active member, and + // the fold does too, so the production path must not void it by the member's access. + for access in [Access::pull(), Access::read(), Access::write()] { + let (_dir, shared) = open(); + let mut chains = Chains::default(); + let create = chains.create(); + create.ingest(&shared); + let group = create.event.id; + let grant = chains.op('A', group, &[group], &add('D', access.clone())); + assert!(matches!(grant.ingest(&shared), Ingest::Accepted { .. })); + let leave = chains.op('D', group, &[grant.event.id], &remove('D')); + assert_eq!( + leave.ingest(&shared), + Ingest::Accepted { + id: leave.event.id, + released: Vec::new(), + }, + "a member with {access:?} leaves" + ); + assert_eq!(roster_of(&shared, &create), members(&['A', 'B', 'C'])); + } +} + +#[test] +fn test_a_removal_whose_body_arrived_late_still_takes_effect() { + // The header commits to the body, so a later delivery with the body is the same event. A relay + // that strips the body on the first delivery must not make the removal content for good. + let (_dir, shared) = open(); + let mut chains = Chains::default(); + let create = chains.create(); + create.ingest(&shared); + let group = create.event.id; + let removal = chains.op('A', group, &[group], &remove('B')); + assert!(matches!( + shared.ingest(&removal.event.bytes, None, 0).unwrap(), + Ingest::Accepted { .. } + )); + assert_eq!( + removal.ingest(&shared), + Ingest::Duplicate { + id: removal.event.id, + } + ); + assert_eq!(roster_of(&shared, &create), members(&['A', 'C'])); +} From 3e036fa287db593f5bdf1d71fb7a7a18939b8847 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 12 Oct 2026 04:01:50 -0500 Subject: [PATCH 34/40] fix(rust): a manager may not remove an Admin [P2-review] --- pkgs/id/src/groups/fold.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/pkgs/id/src/groups/fold.rs b/pkgs/id/src/groups/fold.rs index 3e72009f5f..bc1f6566c8 100644 --- a/pkgs/id/src/groups/fold.rs +++ b/pkgs/id/src/groups/fold.rs @@ -744,6 +744,10 @@ impl Engine { if member != author && !is_manager { return Err(Refusal::NotManager); } + // Manage removes members at or below its own level. Admin is above it (design §5.2). + if member != author && record.admins.contains(&member) && !is_admin { + return Err(Refusal::NotAdmin); + } Ok(Decision { group, action: Some(GroupAction::Remove { From df29ede4b2452106f76c691e589a72fb28c478ee Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 12 Oct 2026 04:01:50 -0500 Subject: [PATCH 35/40] fix(rust): a grant made after a re-add stands under transfer [P2-review] --- pkgs/id/src/groups/delegation.rs | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/pkgs/id/src/groups/delegation.rs b/pkgs/id/src/groups/delegation.rs index 36c54a3790..75a614b9db 100644 --- a/pkgs/id/src/groups/delegation.rs +++ b/pkgs/id/src/groups/delegation.rs @@ -307,20 +307,22 @@ impl Engine { if self.void(by_id, &grant) || self.vetoed(grant.id, &past) { continue; } - let removed: Vec<&Removal> = removals + // The removals of the grantor that come after the grant. A grant made after a re-add is + // not one of them: its grantor was valid where it was made. + let superseding: Vec<&Removal> = removals .iter() - .filter(|removal| removal.member == grant.from) + .filter(|removal| { + removal.member == grant.from + && causal_past(by_id, &[removal.id]).contains(&grant.id) + }) .collect(); - if mode == Delegation::Transfer && !removed.is_empty() { + if mode == Delegation::Transfer && !superseding.is_empty() { // The removed grantor's own link is superseded. Each successor the removals name // reissues it from the removal on, if it held the scope then and holds it here. - for removal in removed { + for removal in superseding { let Some(successor) = removal.successor else { continue; }; - if !causal_past(by_id, &[removal.id]).contains(&grant.id) { - continue; - } let holds_now = self.holds(group, successor, grant.scope, after)?; if holds_now && self.authorized( From b5c1178cd6ee05052bfcc8627a4fc6208ef779c1 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 12 Oct 2026 04:01:50 -0500 Subject: [PATCH 36/40] fix(rust): any member may leave whatever its access [P2-review] --- pkgs/id/src/membership/layer.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/pkgs/id/src/membership/layer.rs b/pkgs/id/src/membership/layer.rs index 4e46a113be..93413372ec 100644 --- a/pkgs/id/src/membership/layer.rs +++ b/pkgs/id/src/membership/layer.rs @@ -316,6 +316,15 @@ impl Membership { return true; } let deps: HashSet = op.dependencies.iter().copied().collect(); + // Leaving is a removal by the member itself. Any member may leave, so it needs no manage + // access, only to be a member at its position (the crate checks that, and so does the fold). + let leaves = matches!( + &op.action, + GroupAction::Remove { member: GroupMember::Individual(who) } if *who == op.author + ); + if leaves { + return self.access_at(&deps, op.group_id, op.author).is_some(); + } self.access_at(&deps, op.group_id, op.author) .is_some_and(|access| access.is_manage()) } From 863a5077ab68c9c452bd09949cc4cf1ac83087ca Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 12 Oct 2026 04:01:50 -0500 Subject: [PATCH 37/40] fix(rust): a late body attaches its action to the stored event [P2-review] --- pkgs/id/src/event_store/ingest.rs | 44 +++++++++++++++++++++++++------ 1 file changed, 36 insertions(+), 8 deletions(-) diff --git a/pkgs/id/src/event_store/ingest.rs b/pkgs/id/src/event_store/ingest.rs index 2efd0b18de..64229442a5 100644 --- a/pkgs/id/src/event_store/ingest.rs +++ b/pkgs/id/src/event_store/ingest.rs @@ -23,7 +23,8 @@ //! //! Each call runs in one redb write transaction. It holds every decision the call causes: the //! event, each event it releases, the expiry of due events, and the waiting rows. The call -//! commits all of them or none. A refused event and a duplicate write nothing. +//! commits all of them or none. A refused event writes nothing. A duplicate writes nothing, except +//! that a stored event first received without its body takes the action of the body that arrives. //! //! # Applied state and forks //! @@ -299,7 +300,9 @@ fn ingest_in( let id = event.id; let author = author_of(&event); let rivals = held_rivals(m.pool, &event); - let outcome = match settle(m, event, action, &rivals, now, false)? { + let settled = settle(m, event, action, &rivals, now, false)?; + let attached = matches!(settled, Settled::Duplicate { attached: true }); + let outcome = match settled { Settled::Stored { applied, released } => { let released = drain(m, released.into(), now)?; if applied { @@ -308,7 +311,7 @@ fn ingest_in( Ingest::Voided { id, released } } } - Settled::Duplicate => Ingest::Duplicate { id }, + Settled::Duplicate { .. } => Ingest::Duplicate { id }, Settled::Fork { seq, released } => { drain(m, released.into(), now)?; Ingest::Fork { author, seq } @@ -319,7 +322,9 @@ fn ingest_in( } Settled::Refused(refusal) => Ingest::Refused(refusal), }; - let changed = expired > 0 || !matches!(outcome, Ingest::Duplicate { .. } | Ingest::Refused(_)); + let changed = expired > 0 + || attached + || !matches!(outcome, Ingest::Duplicate { .. } | Ingest::Refused(_)); Ok((outcome, changed)) } @@ -328,8 +333,9 @@ enum Settled { /// Stored, and applied or voided as the resolution says. `released` are the events that /// waited only for it, and each is due a decision. Stored { applied: bool, released: Vec }, - /// Already stored, or a fork proof header. Nothing changed. - Duplicate, + /// Already stored, or a fork proof header. Nothing changed, unless `attached`: a stored event + /// that was first stored without its body takes the action of the body that arrived now. + Duplicate { attached: bool }, /// A conflict at `seq`. The proof headers are present now, and `released` are the events /// that waited only for them, each due a decision. Fork { seq: SeqNum, released: Vec }, @@ -367,7 +373,9 @@ fn settle( } Decision::Duplicate => { drop_released(m, &event, from_pool)?; - Settled::Duplicate + Settled::Duplicate { + attached: attach_action(m.txn, &id, action)?, + } } Decision::Fork { seq, proof } => { drop_released(m, &event, from_pool)?; @@ -454,7 +462,7 @@ fn drain( queue.extend(released); } Settled::Fork { released, .. } => queue.extend(released), - Settled::Duplicate | Settled::Held | Settled::Skipped | Settled::Refused(_) => {} + Settled::Duplicate { .. } | Settled::Held | Settled::Skipped | Settled::Refused(_) => {} } queue.extend(m.pool.take_ready()); } @@ -562,6 +570,26 @@ fn store_action( Ok(()) } +/// Attaches the action of a group operation to a stored event that has none. Such an event was +/// first stored without its body, so it applied as content. The header commits to the body by hash +/// and size, so the body that arrives later is the one the author signed. A stored event that has +/// an action keeps it. Returns whether an action was attached, and then the resolution is run again. +fn attach_action( + txn: &WriteTransaction, + id: &Hash, + action: Option<&GroupAction>, +) -> Result { + let Some(action) = action else { + return Ok(false); + }; + if !is_stored(txn, id)? || stored_action(txn, id)?.is_some() { + return Ok(false); + } + store_action(txn, id, action)?; + refresh(txn)?; + Ok(true) +} + /// Recomputes which stored events apply, and writes the result: the applied table, and each /// chain row as the leading run of applied events from sequence zero. The result is a function of /// the stored events and the fork proofs, so every arrival order writes the same rows. From 19323cf693d30c51fd8dd30f46bb884f36aa6430 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 12 Oct 2026 04:01:50 -0500 Subject: [PATCH 38/40] fix(rust): creates recorded after the start meet the create rule [P2-review] --- pkgs/id/src/server_config/provision.rs | 27 ++++++++++++++++++++------ 1 file changed, 21 insertions(+), 6 deletions(-) diff --git a/pkgs/id/src/server_config/provision.rs b/pkgs/id/src/server_config/provision.rs index d53b5cb2e6..6baf9aac20 100644 --- a/pkgs/id/src/server_config/provision.rs +++ b/pkgs/id/src/server_config/provision.rs @@ -13,7 +13,7 @@ use p2panda_core::Hash; use thiserror::Error; -use super::{GroupSpec, ServerConfig}; +use super::{CreateRule, GroupSpec, ServerConfig}; use crate::directory::Directory; use crate::groups::{ Body, Create, Event, FoldError, Key, MemberOp, Outcome, Policy, Projection, Refusal, Template, @@ -26,6 +26,8 @@ use crate::world::hex_encode; pub struct Provisioned { directory: Directory, events: Vec, + /// The create rule of the config that was applied. Creates recorded later are checked by it. + create: CreateRule, } /// What one [`Provisioned::apply`] created. All zero means the config was already in effect. @@ -84,6 +86,7 @@ impl Provisioned { Self { directory: Directory::new(), events: Vec::new(), + create: CreateRule::Anyone, } } @@ -108,15 +111,26 @@ impl Provisioned { fold(&self.events) } - /// Records one event, as a user action does. A refused event is kept in the log with no effect, - /// as the fold decides. Read its outcome from the returned groups. + /// Records one event, as a user action does. A create must pass the config's create rule, and a + /// create that fails it is not recorded. Any other refused event is kept in the log with no + /// effect, as the fold decides. Read its outcome from the returned groups. /// /// # Errors /// - /// Fails if the events cannot be folded. - pub fn record(&mut self, event: Event) -> Result { + /// Fails with [`ProvisionError::NotAllowed`] for a create the rule refuses, and with + /// [`ProvisionError::Fold`] if the events cannot be folded. + pub fn record(&mut self, event: Event) -> Result { + if matches!(event.body, Body::Create(_)) { + let projection = self.projection()?; + if !self.create.allows(&event.author, &projection) { + return Err(ProvisionError::NotAllowed { + group: hex_encode(event.id.as_bytes()), + creator: hex_encode(&event.author), + }); + } + } self.events.push(event); - self.projection() + Ok(self.projection()?) } /// Creates the accounts and groups the config names, and adds their members. What already @@ -129,6 +143,7 @@ impl Provisioned { /// events. Users created before the failure stay, but the config is refused at startup, so no /// server runs on that partial state. pub fn apply(&mut self, config: &ServerConfig) -> Result { + self.create = config.create_rule().clone(); let mut report = Report::default(); for user in config.users() { let id = hex_encode(&user.id); From 5d6b578a212f026941b097ed784339afccfe78df Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 12 Oct 2026 04:52:28 -0500 Subject: [PATCH 39/40] test(rust): drop a redundant path in the create test [P2-review] --- pkgs/id/src/server_config/provision.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pkgs/id/src/server_config/provision.rs b/pkgs/id/src/server_config/provision.rs index 6baf9aac20..0f1f08da85 100644 --- a/pkgs/id/src/server_config/provision.rs +++ b/pkgs/id/src/server_config/provision.rs @@ -553,8 +553,8 @@ mod tests { } /// A create by `who`, named `name`, as a user action sends it. - fn create_by(who: Key, name: &str) -> crate::groups::Event { - crate::groups::Event { + fn create_by(who: Key, name: &str) -> Event { + Event { id: Hash::digest(name.as_bytes()), author: who, after: Vec::new(), From b3d22ab4a82ae4c4b603eb735a8f6d448d55af1c Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 12 Oct 2026 05:08:07 -0500 Subject: [PATCH 40/40] docs(id): phase 2 record: steps, commits, review, open items --- ...2026-10-12T04-03-47Z_phase_2_membership.md | 28 +++++++++++-------- 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/doc/2026-10-12T04-03-47Z_phase_2_membership/2026-10-12T04-03-47Z_phase_2_membership.md b/doc/2026-10-12T04-03-47Z_phase_2_membership/2026-10-12T04-03-47Z_phase_2_membership.md index a68faef71f..9ca3709e9b 100644 --- a/doc/2026-10-12T04-03-47Z_phase_2_membership/2026-10-12T04-03-47Z_phase_2_membership.md +++ b/doc/2026-10-12T04-03-47Z_phase_2_membership/2026-10-12T04-03-47Z_phase_2_membership.md @@ -7,16 +7,17 @@ ## Steps -| Step | Track | Status | Commits | Tests added | Notes | -| --------------------------------- | ---------- | ------ | -------- | -------------------------------- | ---------------------------------------------------------------------- | -| P2.1 Auth-frontier mapping | auth | done | 862401c9 | 13 unit, 2 property, 16 scenario | `membership::frontier`; S2 cases and failure modes as regressions | -| P2.2 Admission gate | auth | done | 236dcbc7 | 14 unit, 1 property | `membership::{gate, layer}`; placeholders; regression for group absent | -| P2.3 Authority-based voiding | voiding | todo | | | replaces the Phase 1 rule | -| P2.4 Friendship cap and dissolve | friend | todo | | | | -| P2.5 Delegation modes | delegation | todo | | | | -| P2.6 World capabilities | caps | todo | | | use-count bounds dropped (decision 3) | -| P2.7 Cross-world reconciliation | later | todo | | | | -| P2.8 Property and mutation checks | later | todo | | | | +| Step | Status | Commits | Tests added | Notes | +| ---------------------------------- | ------ | ---------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------- | +| P2.1 Auth-frontier mapping | done | 862401c9 | 25 unit, 16 scenario (S2 in every order), 3 property | p2panda-auth 0.7.1 at rev 3e84cac, no test_utils | +| P2.2 Admission gate | done | 236dcbc7 | gate outcomes, group-absent regression | | +| P2.3 Authority-based voiding | done | 88574505, 21d00659, 16cddd77, 24038780, 4e308e8a, d5ec3828, e1b9571b, df4e8413, 4da53d46 | 12 scenarios, property over arrival orders, production-path tests, codec tests | group actions reach production ingest; create takeover refused; late body attaches | +| P2.4 Groups, templates, friendship | done | 7d5b84bd, 3e0d4bb3, b3315bfa (superseded pair model), 6503f94b (config) | groups 34 to 50 tests, friendship template, property at 256 cases | pair module replaced by the group template (owner decision) | +| P2.5 Delegation modes | done | 0970ee94, 6ed7ddb3 | 17 mode tests, attenuation, chain search, veto, S2 table | managers are roots at their position (design 7.2) | +| P2.6 World capabilities | done | 965b749b, 4b5787a0, 3974cb29, 6cd014e5 | no-count delegation, host limits, partition counts, content kept | uses refused explicitly; wire target (chain checks) is Phase 3 in the design | +| P2.7 Cross-world reconciliation | done | 24984c96, 23445bff | 9 tests, 256-case property | crossings carry Write at most; isolation markers apply to crossings out | +| P2.8 Property and mutation checks | done | c5f197d1 to 5d6b578a (review) | five planted bugs, all caught | | +| P2.9 Server config | done | 6503f94b, 10385cc4 | 34 config tests | creation limits, provisioning by key, config keys, primary alias stored | ## Decisions @@ -35,7 +36,9 @@ ## Changes to the plan -- None yet. +- P2.4 re-scoped to the group model (owner, 2026-10-12): the friendship pair module is superseded. +- P2.9 added (server config and aliases as tags). +- P2.5 and P2.6 run in parallel with P2.3 where they did not share files; P2.6 wire target is Phase 3 in the design. ## Review notes and regression tests @@ -45,4 +48,5 @@ ## End -- End commit and full test result: pending. +- Full test result on the head: `cargo test --all-features --no-fail-fast` exit 0 (lib 1257, cli, production and voiding suites). +- Not verified: the Nix build (vendored p2panda-sync, p2panda git dependency) is not run.