diff --git a/pkgs/id/src/event_store/resolve.rs b/pkgs/id/src/event_store/resolve.rs index 5fedfa8042..323ac8cd38 100644 --- a/pkgs/id/src/event_store/resolve.rs +++ b/pkgs/id/src/event_store/resolve.rs @@ -126,6 +126,7 @@ pub(super) fn resolve( author: node.author, group: node.group, action: action.clone(), + originator: None, }, _ => Role::Other, }; diff --git a/pkgs/id/src/groups/delegation.rs b/pkgs/id/src/groups/delegation.rs index 2773b7007d..bc17fbd33f 100644 --- a/pkgs/id/src/groups/delegation.rs +++ b/pkgs/id/src/groups/delegation.rs @@ -117,6 +117,8 @@ impl Engine { return Ok(Err(Refusal::NoChain)); } Ok(Ok(Decision { + auth_author: None, + auth_originator: None, group, action: None, effect: Effect::Delegation { @@ -161,6 +163,8 @@ impl Engine { return Ok(Err(Refusal::NoChain)); } Ok(Ok(Decision { + auth_author: None, + auth_originator: None, group, action: None, effect: Effect::Veto(grant), @@ -185,19 +189,92 @@ impl Engine { { return Ok(Ok(decision)); } + // Authorize the signer, not the resolved account: for a device signer this is + // what enforces the device's scope cap (a Read-scoped device of a manager + // account holds no Manage here, however its account stands). let manages = self.authorized( by_id, decision.group, - author, + event.author, Role::Manage, &event.after, false, )?; - if manages { - Ok(Ok(decision)) - } else { - Ok(Err(Refusal::NoChain)) + if !manages { + // A Manage grant reaches the author but its chain does not stand at this + // position (cut, vetoed, or its grantor lost the scope): that is a chain + // failure, not a missing manager role. + let reached_by_grant = self.grants.values().any(|grant| { + grant.group == decision.group + && (grant.to == author || grant.to == event.author) + && grant.scope >= Role::Manage + }); + return Ok(Err(if reached_by_grant { + Refusal::NoChain + } else { + Refusal::NotManager + })); + } + // The membership layer validates the operation against its author's own + // access, so a delegated operation is placed under the chain root whose + // authority it exercises (a device is likewise placed under its account). + let mut decision = decision; + if let Some(root) = self.chain_root(by_id, decision.group, event.author, &event.after)? { + decision.auth_author = Some(root); + if root != author { + decision.auth_originator = Some(author); + } + } + Ok(Ok(decision)) + } + + /// The root whose Manage authority `actor` exercises at `after`: the actor itself + /// when it is a manager there (a device resolves to its account first, under the + /// same scope cap as [`Engine::authorized`]), otherwise the root at the head of + /// the chain of Manage links that reaches it. Deterministic in the event set: + /// roots and links are traversed in their stored (sorted) order. + fn chain_root( + &mut self, + by_id: &BTreeMap, + group: Hash, + actor: Key, + after: &[Hash], + ) -> Result, FoldError> { + if !self.groups.contains_key(&group) { + return Ok(None); + } + let actor = match self.authorized_device_account(by_id, group, actor, after) { + Some((account, device_scope)) => { + if device_scope < Role::Manage { + return Ok(None); + } + account + } + None => actor, + }; + let roots = self.membership.managers_at_position(after, group)?; + if roots.contains(&actor) { + return Ok(Some(actor)); + } + let links = self.links(by_id, group, after)?; + let mut origin: BTreeMap = roots.iter().map(|root| (*root, *root)).collect(); + let mut stack: Vec = roots.iter().copied().collect(); + while let Some(holder) = stack.pop() { + let root = origin[&holder]; + for link in links + .iter() + .filter(|link| !link.crossing && link.from == holder && link.scope >= Role::Manage) + { + if link.to == actor { + return Ok(Some(root)); + } + if link.redelegate && !origin.contains_key(&link.to) { + origin.insert(link.to, root); + stack.push(link.to); + } + } } + Ok(None) } /// The grants in force at the head of the events: every grant that its own link carries when diff --git a/pkgs/id/src/groups/fold.rs b/pkgs/id/src/groups/fold.rs index 1212abbdfe..6c24d3d660 100644 --- a/pkgs/id/src/groups/fold.rs +++ b/pkgs/id/src/groups/fold.rs @@ -522,6 +522,16 @@ pub(super) struct Decision { pub(super) group: Hash, pub(super) action: Option>, pub(super) effect: Effect, + /// The identity the membership layer should see as the operation's author, when the + /// signer acted on borrowed authority: a delegated Manage chain is exercised under + /// its root, whose own access carries the operation in the auth graph (the same + /// pattern as a device, which the layer sees as its account). `None` means the + /// effective author itself. + pub(super) auth_author: Option, + /// The account that actually acted, when `auth_author` names a different identity + /// whose authority the act exercises. The membership layer keys strong-removal + /// filtering on this account. + pub(super) auth_originator: Option, } /// A rule's verdict: a decision, or the reason it has no effect. @@ -580,9 +590,10 @@ impl Engine { }; let role = match &decision.action { Some(action) => Placed::Auth { - author: effective_author, + author: decision.auth_author.unwrap_or(effective_author), group: Some(decision.group), action: action.clone(), + originator: decision.auth_originator, }, None => Placed::Other, }; @@ -802,6 +813,8 @@ impl Engine { ), ]; Ok(Decision { + auth_author: None, + auth_originator: None, group, action: Some(GroupAction::Create { initial_members: initial, @@ -826,6 +839,8 @@ impl Engine { return Err(Refusal::AlreadyPresent); } Ok(Decision { + auth_author: None, + auth_originator: None, group, action: None, effect: Effect::Present(author), @@ -864,6 +879,8 @@ impl Engine { return Err(Refusal::OverCap { cap }); } Ok(Decision { + auth_author: None, + auth_originator: None, group, action: None, effect: Effect::Policy(policy.clone()), @@ -885,12 +902,12 @@ impl Engine { return Err(Refusal::NotActive); }; let is_admin = author_role == Role::Admin; - let is_manager = author_role >= Role::Manage; match op { MemberOp::Add { member, role } => { - if !is_manager { - return Err(Refusal::NotManager); - } + // No membership-role gate here: a delegated Manage chain authorizes the add + // just as a manager's role does, and only `manage_chain` (which runs on an Ok + // decision, design §7.2) can see the chain. It refuses there — NotManager for + // an author no Manage grant reaches, NoChain for a chain that does not stand. if role == Role::Admin && !is_admin { return Err(Refusal::NotAdmin); } @@ -903,6 +920,8 @@ impl Engine { return Err(Refusal::OverCap { cap }); } Ok(Decision { + auth_author: None, + auth_originator: None, group, action: Some(GroupAction::Add { member: GroupMember::Individual(AuthId::Key(member)), @@ -918,14 +937,13 @@ impl Engine { if !self.listed(&group, &member) { return Err(Refusal::NotAMember(member)); } - 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 { + auth_author: None, + auth_originator: None, group, action: Some(GroupAction::Remove { member: GroupMember::Individual(AuthId::Key(member)), @@ -958,6 +976,8 @@ impl Engine { Ordering::Equal => None, }; Ok(Decision { + auth_author: None, + auth_originator: None, group, action, effect: Effect::Grant { @@ -1268,6 +1288,8 @@ impl Engine { return Ok(Err(Refusal::Attenuated)); } Ok(Ok(Decision { + auth_author: None, + auth_originator: None, group, action: None, effect: Effect::DeviceAdd { @@ -1278,6 +1300,8 @@ impl Engine { })) } DeviceOp::Revoke { device } => Ok(Ok(Decision { + auth_author: None, + auth_originator: None, group, action: None, effect: Effect::DeviceRevoke { @@ -1477,6 +1501,8 @@ fn new_group(event: &Event, create: &Create) -> Result { dissolved_by: None, }; Ok(Decision { + auth_author: None, + auth_originator: None, group: event.id, action: Some(GroupAction::Create { initial_members: initial, diff --git a/pkgs/id/src/groups/tests.rs b/pkgs/id/src/groups/tests.rs index 3fdd604e86..7dbaeb7988 100644 --- a/pkgs/id/src/groups/tests.rs +++ b/pkgs/id/src/groups/tests.rs @@ -529,6 +529,147 @@ fn test_a_non_manager_may_not_add_or_remove_a_member() { assert_eq!(outcome(&p, "x0"), Outcome::Refused(Refusal::NotManager)); } +#[test] +fn test_a_delegated_manage_may_add_and_remove_a_member() { + let g = id("g"); + let p = project(&[ + custom( + "g", + 1, + &[(2, Role::Write), (3, Role::Read)], + Policy::default(), + ), + delegate("d0", 1, g, 2, Role::Manage, false, &["g"]), + add("a0", 2, g, 4, Role::Read, &["d0"]), + remove("x0", 2, g, 3, &["a0"]), + ]); + assert_eq!(outcome(&p, "d0"), Outcome::Applied); + assert_eq!( + outcome(&p, "a0"), + Outcome::Applied, + "a Write member holding a delegated Manage chain may add" + ); + assert_eq!( + outcome(&p, "x0"), + Outcome::Applied, + "and may remove another non-Admin member" + ); + assert_eq!(role_of(&p, g, 4), Some(Role::Read)); + assert_eq!(role_of(&p, g, 3), None); +} + +#[test] +fn test_a_delegated_manage_may_not_add_or_remove_an_admin() { + let g = id("g"); + let p = project(&[ + custom( + "g", + 1, + &[(2, Role::Write), (3, Role::Admin)], + Policy::default(), + ), + delegate("d0", 1, g, 2, Role::Manage, false, &["g"]), + add("a0", 2, g, 4, Role::Admin, &["d0"]), + remove("x0", 2, g, 3, &["d0"]), + ]); + assert_eq!(outcome(&p, "a0"), Outcome::Refused(Refusal::NotAdmin)); + assert_eq!(outcome(&p, "x0"), Outcome::Refused(Refusal::NotAdmin)); +} + +#[test] +fn test_a_cut_manage_chain_refuses_the_add_as_no_chain() { + let g = id("g"); + let p = project(&[ + custom( + "g", + 1, + &[(2, Role::Write), (3, Role::Read)], + Policy::default(), + ), + delegate("d0", 1, g, 2, Role::Manage, false, &["g"]), + veto("v0", 1, g, "d0", &["d0"]), + add("a0", 2, g, 4, Role::Read, &["v0"]), + remove("x0", 2, g, 3, &["v0"]), + ]); + assert_eq!(outcome(&p, "v0"), Outcome::Applied); + assert_eq!(outcome(&p, "a0"), Outcome::Refused(Refusal::NoChain)); + assert_eq!(outcome(&p, "x0"), Outcome::Refused(Refusal::NoChain)); +} + +#[test] +fn test_a_delegated_add_concurrent_with_a_strong_removal_of_the_delegatee_is_void() { + let g = id("g"); + let p = project(&[ + custom( + "g", + 1, + &[(2, Role::Write)], + with_removal(Removal::Strong, None), + ), + delegate("d0", 1, g, 2, Role::Manage, false, &["g"]), + add("a0", 2, g, 4, Role::Read, &["d0"]), + remove("r0", 1, g, 2, &["d0"]), + ]); + assert_eq!(outcome(&p, "r0"), Outcome::Applied); + assert_eq!( + role_of(&p, g, 4), + None, + "strong remove voids the removed member's concurrent operations, delegated or not" + ); +} + +#[test] +fn test_a_descendant_of_a_voided_delegated_add_takes_no_effect() { + // Member 2's delegated add makes member 4 a manager; member 4 adds member 5. + // A concurrent strong removal of member 2 voids the first add, and the + // descendant add must fall with it — the fold must still project. + let g = id("g"); + let p = project(&[ + custom( + "g", + 1, + &[(2, Role::Write)], + with_removal(Removal::Strong, None), + ), + delegate("d0", 1, g, 2, Role::Manage, false, &["g"]), + add("a0", 2, g, 4, Role::Manage, &["d0"]), + add("a1", 4, g, 5, Role::Read, &["a0"]), + remove("r0", 1, g, 2, &["d0"]), + ]); + assert_eq!(outcome(&p, "r0"), Outcome::Applied); + assert_eq!(role_of(&p, g, 4), None); + assert_eq!(role_of(&p, g, 5), None); +} + +#[test] +fn test_a_read_scoped_device_of_a_manager_may_not_add_a_member() { + let g = id("g"); + let p = project(&[ + custom("g", 1, &[(2, Role::Manage)], Policy::default()), + device_add("dv0", 2, g, 50, Role::Read, &["g"]), + add("a0", 50, g, 3, Role::Read, &["dv0"]), + ]); + assert_eq!(outcome(&p, "dv0"), Outcome::Applied); + assert_eq!( + outcome(&p, "a0"), + Outcome::Refused(Refusal::NotManager), + "the device's Read scope caps it, however its account stands" + ); + assert_eq!(role_of(&p, g, 3), None); +} + +#[test] +fn test_a_manage_scoped_device_of_a_manager_may_add_a_member() { + let g = id("g"); + let p = project(&[ + custom("g", 1, &[(2, Role::Manage)], Policy::default()), + device_add("dv0", 2, g, 50, Role::Manage, &["g"]), + add("a0", 50, g, 3, Role::Read, &["dv0"]), + ]); + assert_eq!(outcome(&p, "a0"), Outcome::Applied); + assert_eq!(role_of(&p, g, 3), Some(Role::Read)); +} + #[test] fn test_only_an_invitee_may_accept_a_friendship_request() { let g = pair_group(1, 2, 0); @@ -1792,7 +1933,12 @@ fn test_an_admin_scoped_device_grant_is_applied_under_weak_remove_without_a_read fn test_a_device_authored_grant_stands_under_weak_remove_with_a_wide_removal_past() { let g = id("g"); let events = vec![ - custom("g", 1, &[], with_removal(Removal::Weak, Some(Delegation::KeepPrior))), + custom( + "g", + 1, + &[], + with_removal(Removal::Weak, Some(Delegation::KeepPrior)), + ), 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"]), diff --git a/pkgs/id/src/membership/layer.rs b/pkgs/id/src/membership/layer.rs index e681303930..dd4b365966 100644 --- a/pkgs/id/src/membership/layer.rs +++ b/pkgs/id/src/membership/layer.rs @@ -46,6 +46,13 @@ pub enum Role { Auth { /// The key that signed the event. author: [u8; 32], + /// The account that actually acted, when `author` is a different identity whose + /// authority the act exercises (a delegated Manage chain is placed under its root). + /// `None` means the author acted on its own authority. The layer keys strong-removal + /// filtering on this account, mirroring how p2panda-auth keys it on the author: a + /// concurrent removal of the originator voids the operation, whoever it was placed + /// under. + originator: Option<[u8; 32]>, /// The group the event names, if any. group: Option, /// The membership change. @@ -113,6 +120,23 @@ pub struct Membership { accepted: Vec, /// Membership operations the layer refused. A refused operation takes no effect. refused: HashSet, + /// The acting account of each operation placed under a different authority identity, + /// by operation ID. + originators: HashMap, + /// Delegated operations voided by a concurrent strong removal of their originator. + /// A voided operation stands in the graph as its placeholder, so its descendants do + /// not stall, but it takes no effect. + voided: HashSet, + /// The no-op placeholder standing in the graph for each voided operation, by ID. + placeholders: HashMap, + /// The removal that voided each voided operation, by operation ID. When that + /// removal is itself voided, the operation it voided is re-evaluated. + voided_by: HashMap, + /// The original operation of each operation that stands in the graph as a + /// placeholder, by ID, so a revived operation can be replayed as itself. + originals: HashMap, + /// The `after` hashes of every decided event, for concurrency checks. + afters: HashMap>, } impl Membership { @@ -168,10 +192,12 @@ impl Membership { /// Decides one event whose `after` hashes are all indexed. fn decide(&mut self, event: CausalEvent) -> Result { let CausalEvent { id, after, role } = event; + self.afters.insert(id, after.clone()); let Role::Auth { author, group, action, + originator, } = role else { self.index.insert(id, after, None)?; @@ -200,6 +226,35 @@ impl Membership { group_id: AuthId::Group(group), action, }; + if let Some(originator) = originator + && AuthId::Key(originator) != op.author + { + self.originators.insert(id, AuthId::Key(originator)); + // The originator was already removed by an operation concurrent with this + // one: strong remove voids it, exactly as if it had been placed under the + // originator itself. It stands in the graph as a placeholder instead. + if let Some(cause) = self.voiding_removal(&op) { + match self.placeholder_for(&op) { + Some(noop) => { + self.placeholders.insert(id, noop.clone()); + self.voided.insert(id); + self.voided_by.insert(id, cause); + self.originals.insert(id, op.clone()); + return match self.process(&noop)? { + Ok(()) => { + self.index.insert(id, after, Some(group))?; + Ok(Outcome::Applied) + } + Err(_) => { + self.index.insert(id, after, None)?; + Ok(Outcome::Applied) + } + }; + } + None => {} + } + } + } match gate::admit(&self.state, &op) { Admission::Admit => {} Admission::Wait(missing) => { @@ -214,6 +269,7 @@ impl Membership { match self.process(&op)? { Ok(()) => { self.index.insert(id, after, Some(group))?; + self.void_concurrent_delegated(&op)?; Ok(Outcome::Applied) } Err(message) => self.refuse(op, group, after, Refusal::Invalid(message)), @@ -277,7 +333,7 @@ impl Membership { Ok(Ok(())) } Err(error) => { - self.state = rebuild(&self.accepted)?; + self.state = self.rebuild_state()?; Ok(Err(error.to_string())) } } @@ -299,7 +355,7 @@ impl Membership { /// 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) { + if self.refused.contains(id) || self.voided.contains(id) { return false; } // The resolver filters the concurrent operations of a removed member, which includes the @@ -427,6 +483,237 @@ impl Membership { .find_map(|(who, access)| (who == GroupMember::Individual(member)).then_some(access)) } + /// The member an operation removes, or demotes out of manage access, if any: + /// the removals p2panda-auth's strong-remove resolver keys its filter on. + fn removed_member(op: &AuthOperation) -> Option { + match &op.action { + GroupAction::Remove { member } => Some(member.id()), + GroupAction::Demote { member, access } if !access.is_manage() => Some(member.id()), + _ => None, + } + } + + /// Whether `ancestor` is in the causal past of `event`, the event itself included, + /// walking the recorded `after` hashes through every decided event. + fn in_past(&self, event: &Hash, ancestor: &Hash) -> bool { + let mut stack = vec![*event]; + let mut seen = HashSet::new(); + while let Some(next) = stack.pop() { + if next == *ancestor { + return true; + } + if seen.insert(next) + && let Some(after) = self.afters.get(&next) + { + stack.extend(after.iter().copied()); + } + } + false + } + + /// Whether two decided operations are concurrent: neither is in the other's past. + fn concurrent(&self, a: &Hash, b: &Hash) -> bool { + !self.in_past(a, b) && !self.in_past(b, a) + } + + /// The account that acted in `op`: its originator when it was placed under a + /// delegated authority, otherwise its author. + fn actor_of(&self, op: &AuthOperation) -> AuthId { + self.originators.get(&op.id).copied().unwrap_or(op.author) + } + + /// The accepted removal of `op`'s originator that is concurrent with `op` and + /// still in effect, if any. A voided removal does not count: it took no effect, + /// so it voids nothing. + fn voiding_removal(&self, op: &AuthOperation) -> Option { + let originator = self.originators.get(&op.id)?; + self.accepted + .iter() + .find(|other| { + other.group_id == op.group_id + && !self.voided.contains(&other.id) + && Self::removed_member(other) == Some(*originator) + && self.concurrent(&other.id, &op.id) + // A delegated operation that removes the remover in turn is a + // mutual removal and stands, as in `void_concurrent_delegated`. + // The remover is matched by the account that acted, not by the + // authority identity the operation was placed under. + && !matches!( + &op.action, + GroupAction::Remove { member } if member.id() == self.actor_of(other) + ) + }) + .map(|other| other.id) + } + + /// Whether a removal of `op`'s originator already stands accepted, concurrent + /// with `op`. + fn concurrently_removed(&self, op: &AuthOperation) -> bool { + self.voiding_removal(op).is_some() + } + + /// The no-op placeholder for a voided operation, in the shape `refuse` uses: a + /// promotion of the least manager at the operation's dependencies, which changes + /// nothing. `None` when no manager stands there. + fn placeholder_for(&self, op: &AuthOperation) -> Option { + Self::placeholder_in(&self.state, op) + } + + /// After a removal is applied, void every accepted delegated operation whose + /// originator it removes and which is concurrent with it, rebuilding the state + /// with those operations standing as placeholders. A delegated operation that + /// removes the remover in turn is a mutual removal and stands, as it would if + /// it had been placed under its originator. + fn void_concurrent_delegated( + &mut self, + removal: &AuthOperation, + ) -> Result<(), MembershipError> { + let Some(removed) = Self::removed_member(removal) else { + return Ok(()); + }; + let mut changed = false; + let remover = self.actor_of(removal); + let candidates: Vec = self + .accepted + .iter() + .filter(|other| { + other.id != removal.id + && other.group_id == removal.group_id + && self.originators.get(&other.id) == Some(&removed) + && !self.voided.contains(&other.id) + && self.concurrent(&other.id, &removal.id) + && !matches!( + &other.action, + GroupAction::Remove { member } if member.id() == remover + ) + }) + .cloned() + .collect(); + let mut newly_voided_removals: Vec = Vec::new(); + for candidate in candidates { + if let Some(noop) = self.placeholder_for(&candidate) { + self.placeholders.insert(candidate.id, noop); + self.voided.insert(candidate.id); + self.voided_by.insert(candidate.id, removal.id); + if Self::removed_member(&candidate).is_some() { + newly_voided_removals.push(candidate.id); + } + changed = true; + } + } + // A removal voided in this pass took no effect, so the operations it had + // voided are re-evaluated: one with no remaining voiding removal in + // effect revives and is replayed as itself. + for voided_removal in newly_voided_removals { + let revivable: Vec = self + .voided_by + .iter() + .filter(|(_, cause)| **cause == voided_removal) + .map(|(id, _)| *id) + .collect(); + for id in revivable { + let Some(original) = self + .originals + .get(&id) + .cloned() + .or_else(|| self.accepted.iter().find(|op| op.id == id).cloned()) + else { + continue; + }; + if self.voiding_removal(&original).is_none() { + self.voided.remove(&id); + self.voided_by.remove(&id); + self.placeholders.remove(&id); + changed = true; + } + } + } + if changed { + self.state = self.rebuild_state()?; + } + Ok(()) + } + + /// Rebuilds the graph state from the accepted operations, with each voided + /// operation standing as its placeholder. + fn rebuild_state(&self) -> Result { + let ops: Vec = self + .accepted + .iter() + .map(|op| { + if self.voided.contains(&op.id) { + self.placeholders + .get(&op.id) + .cloned() + .unwrap_or_else(|| op.clone()) + } else { + // An operation that arrived voided stands in `accepted` as its + // placeholder; replay it as itself once it has revived. + self.originals + .get(&op.id) + .cloned() + .unwrap_or_else(|| op.clone()) + } + }) + .collect(); + if self.voided.is_empty() { + return rebuild(&ops); + } + // Voiding an operation can strip a later operation of the authority it was + // accepted with (a member added by a voided add goes on to act). Replaying + // such a descendant unchanged fails, and treating that as an invariant + // failure would make the whole event set unprojectable. Instead the + // descendant stands as a placeholder too, mirroring the resolver's rule + // that operations depending on filtered state are not applied. + // `Graph::process` consumes the state and an error loses it, so each + // operation is tried as a prefix replay from the last good state. + let mut state = Graph::init(); + let mut replayed: Vec = Vec::new(); + for op in &ops { + let mut trial = replayed.clone(); + trial.push(op.clone()); + match rebuild(&trial) { + Ok(next) => { + state = next; + replayed = trial; + } + Err(_) => { + if let Some(noop) = Self::placeholder_in(&state, op) { + let mut trial = replayed.clone(); + trial.push(noop); + if let Ok(next) = rebuild(&trial) { + state = next; + replayed = trial; + } + } + } + } + } + Ok(state) + } + + /// The no-op placeholder for `op` against an explicit graph state: a promotion + /// of the least manager at the operation's dependencies, which changes nothing. + fn placeholder_in(state: &GroupState, op: &AuthOperation) -> Option { + let AuthId::Group(group) = op.group_id else { + return None; + }; + let heads: HashSet = op.dependencies.iter().copied().collect(); + let target = Graph::members_at(state, heads, AuthId::Group(group)) + .ok()? + .into_iter() + .filter(|(id, access)| matches!(id, AuthId::Key(_)) && access.is_manage()) + .map(|(id, _)| id) + .min()?; + Some(AuthOperation { + action: GroupAction::Promote { + member: GroupMember::Individual(target), + access: Access::read(), + }, + ..op.clone() + }) + } + /// Whether the event is held, waiting for an `after` hash. pub fn is_held(&self, id: &Hash) -> bool { self.held.contains_key(id) @@ -483,6 +770,7 @@ mod tests { author: key(author), group: group.map(id), action, + originator: None, }, } } @@ -549,6 +837,159 @@ mod tests { assert_eq!(layer.dependencies(&id(10)), Some(&[][..])); } + /// An operation placed under a delegated authority identity, with its originator. + fn auth_as( + n: u8, + author: u8, + originator: 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, + originator: Some(key(originator)), + }, + } + } + + #[test] + fn test_a_delegated_operation_is_void_when_its_originator_is_removed_concurrently() { + // Add first, removal second: the removal voids the delegated add on arrival. + let mut layer = Membership::new(); + layer.receive(create(10, 1, &[1])).unwrap(); + layer + .receive(auth(11, 1, Some(10), &[10], add(2, Access::write()))) + .unwrap(); + layer + .receive(auth_as(12, 1, 2, Some(10), &[11], add(4, Access::read()))) + .unwrap(); + assert!(member_keys(&layer, 10).contains(&AuthId::Key(key(4)))); + layer + .receive(auth(13, 1, Some(10), &[11], remove(2))) + .unwrap(); + assert!( + !member_keys(&layer, 10).contains(&AuthId::Key(key(4))), + "strong remove voids the removed member's concurrent delegated operations" + ); + assert!(!layer.is_effective(&id(12))); + } + + #[test] + fn test_a_delegated_operation_after_its_originators_removal_takes_no_effect() { + // Removal first, delegated add second: the add stands as a placeholder only. + let mut layer = Membership::new(); + layer.receive(create(10, 1, &[1])).unwrap(); + layer + .receive(auth(11, 1, Some(10), &[10], add(2, Access::write()))) + .unwrap(); + layer + .receive(auth(13, 1, Some(10), &[11], remove(2))) + .unwrap(); + let outcomes = layer + .receive(auth_as(12, 1, 2, Some(10), &[11], add(4, Access::read()))) + .unwrap(); + assert_eq!(outcome_of(&outcomes, 12), Outcome::Applied); + assert!(!member_keys(&layer, 10).contains(&AuthId::Key(key(4)))); + assert!(!layer.is_effective(&id(12))); + } + + #[test] + fn test_a_delegated_mutual_removal_stands_in_either_order() { + // Member 2, acting on member 1's delegated Manage, removes member 3; + // member 3 concurrently removes member 2. A mutual removal stands in + // both arrival orders. + for remove_first in [true, false] { + let mut layer = Membership::new(); + layer.receive(create(10, 1, &[1, 3])).unwrap(); + layer + .receive(auth(11, 1, Some(10), &[10], add(2, Access::write()))) + .unwrap(); + let delegated = auth_as(12, 1, 2, Some(10), &[11], remove(3)); + let removal = auth(13, 3, Some(10), &[11], remove(2)); + if remove_first { + layer.receive(removal).unwrap(); + layer.receive(delegated).unwrap(); + } else { + layer.receive(delegated).unwrap(); + layer.receive(removal).unwrap(); + } + assert!( + layer.is_effective(&id(12)), + "mutual removal stands (remove_first={remove_first})" + ); + assert!(!member_keys(&layer, 10).contains(&AuthId::Key(key(3)))); + } + } + + #[test] + fn test_delegated_mutual_removals_by_two_delegatees_stand_in_either_order() { + // Members 2 and 3 both act on member 1's delegated Manage and remove + // each other concurrently. The mutual-removal exemption matches the + // account that acted, not the authority identity, so both stand. + for second_first in [true, false] { + let mut layer = Membership::new(); + layer.receive(create(10, 1, &[1])).unwrap(); + layer + .receive(auth(11, 1, Some(10), &[10], add(2, Access::write()))) + .unwrap(); + layer + .receive(auth(15, 1, Some(10), &[11], add(3, Access::write()))) + .unwrap(); + let by2 = auth_as(12, 1, 2, Some(10), &[15], remove(3)); + let by3 = auth_as(13, 1, 3, Some(10), &[15], remove(2)); + if second_first { + layer.receive(by3).unwrap(); + layer.receive(by2).unwrap(); + } else { + layer.receive(by2).unwrap(); + layer.receive(by3).unwrap(); + } + assert!(layer.is_effective(&id(12)), "second_first={second_first}"); + assert!(layer.is_effective(&id(13)), "second_first={second_first}"); + assert!(!member_keys(&layer, 10).contains(&AuthId::Key(key(2)))); + assert!(!member_keys(&layer, 10).contains(&AuthId::Key(key(3)))); + } + } + + #[test] + fn test_an_add_by_a_member_whose_delegated_removal_was_voided_survives() { + // Member 2's delegated removal of member 3 is itself voided by member + // 1's concurrent removal of member 2, so member 3's delegated add + // stands — whether the add arrives after the voiding or before it + // (in which case it revives when its voiding removal is voided). + for add_last in [true, false] { + let mut layer = Membership::new(); + layer.receive(create(10, 1, &[1])).unwrap(); + layer + .receive(auth(11, 1, Some(10), &[10], add(2, Access::write()))) + .unwrap(); + layer + .receive(auth(15, 1, Some(10), &[11], add(3, Access::write()))) + .unwrap(); + let delegated_removal = auth_as(12, 1, 2, Some(10), &[15], remove(3)); + let removal = auth(13, 1, Some(10), &[15], remove(2)); + let add = auth_as(14, 1, 3, Some(10), &[15], add(4, Access::read())); + layer.receive(delegated_removal).unwrap(); + if add_last { + layer.receive(removal).unwrap(); + layer.receive(add).unwrap(); + } else { + layer.receive(add).unwrap(); + layer.receive(removal).unwrap(); + } + assert!(!layer.is_effective(&id(12)), "add_last={add_last}"); + assert!(layer.is_effective(&id(14)), "add_last={add_last}"); + assert!(member_keys(&layer, 10).contains(&AuthId::Key(key(3)))); + assert!(member_keys(&layer, 10).contains(&AuthId::Key(key(4)))); + } + } + #[test] fn test_a_duplicate_changes_nothing() { let mut layer = Membership::new(); @@ -728,6 +1169,7 @@ mod tests { author: key(1), group: Some(friendship), action: GroupAction::Create { initial_members }, + originator: None, }, }; let outcomes = layer.receive(create).unwrap(); @@ -790,6 +1232,7 @@ mod tests { author: key(1), group: None, action: remove(2), + originator: None, }, }) .unwrap();