From 567e993f7ec4bf70d3165deb1ba1b9014657f478 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 1 Nov 2026 07:10:35 -0600 Subject: [PATCH 1/7] fix(id): let a delegated Manage chain authorize member add/remove (#171) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit member() refused NotManager on membership role before manage_chain() could validate a delegation, so a member below Manage holding a valid delegated Manage chain could neither add nor remove members. member() no longer gates on the role for Add/Remove-other; manage_chain() is the single authorization gate and now splits its refusal: NoChain when a Manage grant reaches the author but its chain does not stand, NotManager when no Manage grant reaches the author at all. Admin-only behavior is unchanged (adding an Admin and removing an Admin still refuse NotAdmin in member()). Tests: three new groups regression tests (delegated add/remove applied, delegated Admin add/remove refused NotAdmin, veto-cut chain refused NoChain); cargo test (pkgs/id) groups::tests:: — 133 passed, 0 failed, including the existing non-manager guard test. --- pkgs/id/src/groups/delegation.rs | 9 ++++- pkgs/id/src/groups/fold.rs | 11 ++---- pkgs/id/src/groups/tests.rs | 67 ++++++++++++++++++++++++++++++++ 3 files changed, 79 insertions(+), 8 deletions(-) diff --git a/pkgs/id/src/groups/delegation.rs b/pkgs/id/src/groups/delegation.rs index 2773b7007d..910b906521 100644 --- a/pkgs/id/src/groups/delegation.rs +++ b/pkgs/id/src/groups/delegation.rs @@ -195,8 +195,15 @@ impl Engine { )?; if manages { Ok(Ok(decision)) - } else { + } else if self.grants.values().any(|grant| { + grant.group == decision.group && grant.to == author && grant.scope >= Role::Manage + }) { + // 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. Ok(Err(Refusal::NoChain)) + } else { + Ok(Err(Refusal::NotManager)) } } diff --git a/pkgs/id/src/groups/fold.rs b/pkgs/id/src/groups/fold.rs index 1212abbdfe..af07a99487 100644 --- a/pkgs/id/src/groups/fold.rs +++ b/pkgs/id/src/groups/fold.rs @@ -885,12 +885,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); } @@ -918,9 +918,6 @@ 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); diff --git a/pkgs/id/src/groups/tests.rs b/pkgs/id/src/groups/tests.rs index 3fdd604e86..326b653587 100644 --- a/pkgs/id/src/groups/tests.rs +++ b/pkgs/id/src/groups/tests.rs @@ -529,6 +529,73 @@ 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_only_an_invitee_may_accept_a_friendship_request() { let g = pair_group(1, 2, 0); From 6f4befb8c8bb793d6aea92f29ac65e48a61b94c8 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 1 Nov 2026 07:47:51 -0600 Subject: [PATCH 2/7] fix(id): carry delegated Manage authority through the membership layer (#171) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Codex review round 1 on PR 3694 found two real defects in the first cut; both fixed here. P2 (membership layer): removing the fold gate was not enough — Engine::apply placed the operation under the signer, whose own access is below Manage, so p2panda-auth refused it. Decision now carries auth_author: manage_chain resolves the chain root whose authority the operation exercises (deterministic traversal mirroring authorized()), and apply() places the operation under that root — the same pattern as a device, which the layer already sees as its account. P1 (device scope): manage_chain previously authorized the device-resolved account, so a Read-scoped device of a manager account would have passed as a root once the member() gate was gone. It now authorizes the signer (event.author), so authorized() enforces the device scope cap; chain_root applies the same cap. Regression tests: a Read-scoped device of a manager may not add (NotManager); a Manage-scoped device may add. Tests (pkgs/id, laptop, results read back from the on-disk log): the 6 key tests pass individually; full lib suite 1659 passed / 0 failed. A later all-targets run flaked once on log_sync::tests::test_a_bulk_session_moves_every_event_across_pages (60s sync budget under load ~57; unrelated subsystem) — it passes solo in 44.8s. --- pkgs/id/src/groups/delegation.rs | 84 ++++++++++++++++++++++++++++---- pkgs/id/src/groups/fold.rs | 17 ++++++- pkgs/id/src/groups/tests.rs | 29 +++++++++++ 3 files changed, 120 insertions(+), 10 deletions(-) diff --git a/pkgs/id/src/groups/delegation.rs b/pkgs/id/src/groups/delegation.rs index 910b906521..5713cb3e41 100644 --- a/pkgs/id/src/groups/delegation.rs +++ b/pkgs/id/src/groups/delegation.rs @@ -117,6 +117,7 @@ impl Engine { return Ok(Err(Refusal::NoChain)); } Ok(Ok(Decision { + auth_author: None, group, action: None, effect: Effect::Delegation { @@ -161,6 +162,7 @@ impl Engine { return Ok(Err(Refusal::NoChain)); } Ok(Ok(Decision { + auth_author: None, group, action: None, effect: Effect::Veto(grant), @@ -185,26 +187,90 @@ 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 if self.grants.values().any(|grant| { - grant.group == decision.group && grant.to == author && grant.scope >= Role::Manage - }) { + 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. - Ok(Err(Refusal::NoChain)) - } else { - Ok(Err(Refusal::NotManager)) + 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); + } + 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 af07a99487..e719408452 100644 --- a/pkgs/id/src/groups/fold.rs +++ b/pkgs/id/src/groups/fold.rs @@ -522,6 +522,12 @@ 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, } /// A rule's verdict: a decision, or the reason it has no effect. @@ -580,7 +586,7 @@ 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(), }, @@ -802,6 +808,7 @@ impl Engine { ), ]; Ok(Decision { + auth_author: None, group, action: Some(GroupAction::Create { initial_members: initial, @@ -826,6 +833,7 @@ impl Engine { return Err(Refusal::AlreadyPresent); } Ok(Decision { + auth_author: None, group, action: None, effect: Effect::Present(author), @@ -864,6 +872,7 @@ impl Engine { return Err(Refusal::OverCap { cap }); } Ok(Decision { + auth_author: None, group, action: None, effect: Effect::Policy(policy.clone()), @@ -903,6 +912,7 @@ impl Engine { return Err(Refusal::OverCap { cap }); } Ok(Decision { + auth_author: None, group, action: Some(GroupAction::Add { member: GroupMember::Individual(AuthId::Key(member)), @@ -923,6 +933,7 @@ impl Engine { return Err(Refusal::NotAdmin); } Ok(Decision { + auth_author: None, group, action: Some(GroupAction::Remove { member: GroupMember::Individual(AuthId::Key(member)), @@ -955,6 +966,7 @@ impl Engine { Ordering::Equal => None, }; Ok(Decision { + auth_author: None, group, action, effect: Effect::Grant { @@ -1265,6 +1277,7 @@ impl Engine { return Ok(Err(Refusal::Attenuated)); } Ok(Ok(Decision { + auth_author: None, group, action: None, effect: Effect::DeviceAdd { @@ -1275,6 +1288,7 @@ impl Engine { })) } DeviceOp::Revoke { device } => Ok(Ok(Decision { + auth_author: None, group, action: None, effect: Effect::DeviceRevoke { @@ -1474,6 +1488,7 @@ fn new_group(event: &Event, create: &Create) -> Result { dissolved_by: None, }; Ok(Decision { + auth_author: 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 326b653587..d258294fa5 100644 --- a/pkgs/id/src/groups/tests.rs +++ b/pkgs/id/src/groups/tests.rs @@ -596,6 +596,35 @@ fn test_a_cut_manage_chain_refuses_the_add_as_no_chain() { assert_eq!(outcome(&p, "x0"), Outcome::Refused(Refusal::NoChain)); } +#[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); From 50cc9393d6ca1789d42a3f6c9703eb4a5c56ecb4 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 1 Nov 2026 07:48:03 -0600 Subject: [PATCH 3/7] style(id): rustfmt the chain_root hunk (#171) --- pkgs/id/src/groups/delegation.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/pkgs/id/src/groups/delegation.rs b/pkgs/id/src/groups/delegation.rs index 5713cb3e41..70d5dde0c4 100644 --- a/pkgs/id/src/groups/delegation.rs +++ b/pkgs/id/src/groups/delegation.rs @@ -252,8 +252,7 @@ impl Engine { 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 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]; From a031c2cc059dfbf1c13fbc01b4334ca920fc5ab1 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 1 Nov 2026 08:03:48 -0600 Subject: [PATCH 4/7] =?UTF-8?q?test(id):=20regression=20=E2=80=94=20delega?= =?UTF-8?q?ted=20add=20vs=20strong=20removal=20of=20the=20delegatee=20(#17?= =?UTF-8?q?1)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Codex round 2 (PR 3694): placing a delegated operation under its chain root also removes it from the membership resolver's concurrent-removal filtering, which keys on the recorded author. Baseline parity check: a direct manager's add concurrent with their own removal does not persist (either removal mode; the layer always uses the StrongRemove resolver). This test encodes the same expectation for a delegated add and currently FAILS (member 4 persists) — it is the resume anchor for the remaining work: originator-aware filtering in the membership layer (Placement/AuthOperation carry the signer separately from the authority identity, and the layer filters by the signer). Pushed deliberately as a failing test so the remaining defect is executable, not prose. --- pkgs/id/src/groups/tests.rs | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/pkgs/id/src/groups/tests.rs b/pkgs/id/src/groups/tests.rs index d258294fa5..a1d9a2ef39 100644 --- a/pkgs/id/src/groups/tests.rs +++ b/pkgs/id/src/groups/tests.rs @@ -596,6 +596,28 @@ fn test_a_cut_manage_chain_refuses_the_add_as_no_chain() { 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_read_scoped_device_of_a_manager_may_not_add_a_member() { let g = id("g"); From a74a650c10d91c24ce96819483406e87b4133b2e Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 1 Nov 2026 13:32:59 -0600 Subject: [PATCH 5/7] fix(id): key strong-removal filtering on the delegated originator (#171) Codex round 2 P1 on PR #3694: a delegated add placed under its chain root survived a concurrent strong removal of the delegatee, because p2panda-auth keys its strong-remove filter on the operation author (the root). The placement now carries the originator separately: Decision.auth_originator -> Role::Auth.originator. The membership layer records it and voids a delegated operation when a removal (or demote out of Manage) of its originator is concurrent with it, in either arrival order: an already-accepted delegated operation is replaced by a no-op placeholder on rebuild when the removal lands, and a delegated operation arriving after its originators removal stands as a placeholder only. Mutual removals are exempt, mirroring the resolver. is_effective reports voided operations as not taking effect. Tests: the regression test added in a031c2cc0 now passes; two new membership-layer tests cover both arrival orders. Laptop (pkgs/id): full lib suite 1660 passed / 0 failed; groups::tests 67 passed; membership 42 passed. --- pkgs/id/src/event_store/resolve.rs | 1 + pkgs/id/src/groups/delegation.rs | 5 + pkgs/id/src/groups/fold.rs | 14 ++ pkgs/id/src/membership/layer.rs | 239 ++++++++++++++++++++++++++++- 4 files changed, 257 insertions(+), 2 deletions(-) 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 70d5dde0c4..bc17fbd33f 100644 --- a/pkgs/id/src/groups/delegation.rs +++ b/pkgs/id/src/groups/delegation.rs @@ -118,6 +118,7 @@ impl Engine { } Ok(Ok(Decision { auth_author: None, + auth_originator: None, group, action: None, effect: Effect::Delegation { @@ -163,6 +164,7 @@ impl Engine { } Ok(Ok(Decision { auth_author: None, + auth_originator: None, group, action: None, effect: Effect::Veto(grant), @@ -219,6 +221,9 @@ impl Engine { 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)) } diff --git a/pkgs/id/src/groups/fold.rs b/pkgs/id/src/groups/fold.rs index e719408452..6c24d3d660 100644 --- a/pkgs/id/src/groups/fold.rs +++ b/pkgs/id/src/groups/fold.rs @@ -528,6 +528,10 @@ pub(super) struct Decision { /// 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. @@ -589,6 +593,7 @@ impl Engine { author: decision.auth_author.unwrap_or(effective_author), group: Some(decision.group), action: action.clone(), + originator: decision.auth_originator, }, None => Placed::Other, }; @@ -809,6 +814,7 @@ impl Engine { ]; Ok(Decision { auth_author: None, + auth_originator: None, group, action: Some(GroupAction::Create { initial_members: initial, @@ -834,6 +840,7 @@ impl Engine { } Ok(Decision { auth_author: None, + auth_originator: None, group, action: None, effect: Effect::Present(author), @@ -873,6 +880,7 @@ impl Engine { } Ok(Decision { auth_author: None, + auth_originator: None, group, action: None, effect: Effect::Policy(policy.clone()), @@ -913,6 +921,7 @@ impl Engine { } Ok(Decision { auth_author: None, + auth_originator: None, group, action: Some(GroupAction::Add { member: GroupMember::Individual(AuthId::Key(member)), @@ -934,6 +943,7 @@ impl Engine { } Ok(Decision { auth_author: None, + auth_originator: None, group, action: Some(GroupAction::Remove { member: GroupMember::Individual(AuthId::Key(member)), @@ -967,6 +977,7 @@ impl Engine { }; Ok(Decision { auth_author: None, + auth_originator: None, group, action, effect: Effect::Grant { @@ -1278,6 +1289,7 @@ impl Engine { } Ok(Ok(Decision { auth_author: None, + auth_originator: None, group, action: None, effect: Effect::DeviceAdd { @@ -1289,6 +1301,7 @@ impl Engine { } DeviceOp::Revoke { device } => Ok(Ok(Decision { auth_author: None, + auth_originator: None, group, action: None, effect: Effect::DeviceRevoke { @@ -1489,6 +1502,7 @@ fn new_group(event: &Event, create: &Create) -> Result { }; Ok(Decision { auth_author: None, + auth_originator: None, group: event.id, action: Some(GroupAction::Create { initial_members: initial, diff --git a/pkgs/id/src/membership/layer.rs b/pkgs/id/src/membership/layer.rs index e681303930..eca2f52476 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,17 @@ 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 `after` hashes of every decided event, for concurrency checks. + afters: HashMap>, } impl Membership { @@ -168,10 +186,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 +220,33 @@ 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 self.concurrently_removed(&op) { + match self.placeholder_for(&op) { + Some(noop) => { + self.placeholders.insert(id, noop.clone()); + self.voided.insert(id); + 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 +261,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 +325,7 @@ impl Membership { Ok(Ok(())) } Err(error) => { - self.state = rebuild(&self.accepted)?; + self.state = self.rebuild_state()?; Ok(Err(error.to_string())) } } @@ -299,7 +347,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 +475,128 @@ 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) + } + + /// Whether a removal of `op`'s originator already stands accepted, concurrent + /// with `op`. + fn concurrently_removed(&self, op: &AuthOperation) -> bool { + let Some(originator) = self.originators.get(&op.id) else { + return false; + }; + self.accepted.iter().any(|other| { + other.group_id == op.group_id + && Self::removed_member(other) == Some(*originator) + && self.concurrent(&other.id, &op.id) + }) + } + + /// 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 { + let group = match op.group_id { + AuthId::Group(group) => group, + AuthId::Key(_) => return None, + }; + let target = self.manager_at(group, &op.dependencies)?; + Some(AuthOperation { + action: GroupAction::Promote { + member: GroupMember::Individual(target), + access: Access::read(), + }, + ..op.clone() + }) + } + + /// 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 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() == removal.author + ) + }) + .cloned() + .collect(); + for candidate in candidates { + if let Some(noop) = self.placeholder_for(&candidate) { + self.placeholders.insert(candidate.id, noop); + self.voided.insert(candidate.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| { + self.placeholders + .get(&op.id) + .cloned() + .unwrap_or_else(|| op.clone()) + }) + .collect(); + rebuild(&ops) + } + /// 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 +653,7 @@ mod tests { author: key(author), group: group.map(id), action, + originator: None, }, } } @@ -549,6 +720,68 @@ 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_duplicate_changes_nothing() { let mut layer = Membership::new(); @@ -728,6 +961,7 @@ mod tests { author: key(1), group: Some(friendship), action: GroupAction::Create { initial_members }, + originator: None, }, }; let outcomes = layer.receive(create).unwrap(); @@ -790,6 +1024,7 @@ mod tests { author: key(1), group: None, action: remove(2), + originator: None, }, }) .unwrap(); From 1bd5964c26a1ca165a72b0a051abc361ba5d4a7c Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 1 Nov 2026 13:58:50 -0600 Subject: [PATCH 6/7] fix(id): voiding a delegated operation must not break its descendants (#171) Codex round 2 on PR #3694, both findings fixed: P1: voiding a delegated add stripped authority from its descendants, and the strict rebuild treated their replay failure as an internal invariant failure, making the whole event set unprojectable. When voided operations exist, rebuild_state now replays tolerantly: an operation that no longer stands replay is replaced by its placeholder (or dropped), mirroring the resolver rule that operations depending on filtered state are not applied. P2: the mutual-removal exemption existed only in the post-arrival path. concurrently_removed now exempts a delegated operation that removes the remover in turn, so both arrival orders agree. Tests: groups descendant regression (delegated add of a manager, manager adds a member, concurrent strong removal of the delegatee: neither member stands, fold projects); membership mutual-removal test in both arrival orders. Laptop: groups:: 102 passed, membership:: 43 passed. --- pkgs/id/src/groups/tests.rs | 30 ++++++++- pkgs/id/src/membership/layer.rs | 104 ++++++++++++++++++++++++++++---- 2 files changed, 120 insertions(+), 14 deletions(-) diff --git a/pkgs/id/src/groups/tests.rs b/pkgs/id/src/groups/tests.rs index a1d9a2ef39..7dbaeb7988 100644 --- a/pkgs/id/src/groups/tests.rs +++ b/pkgs/id/src/groups/tests.rs @@ -618,6 +618,29 @@ fn test_a_delegated_add_concurrent_with_a_strong_removal_of_the_delegatee_is_voi ); } +#[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"); @@ -1910,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 eca2f52476..0be7cca874 100644 --- a/pkgs/id/src/membership/layer.rs +++ b/pkgs/id/src/membership/layer.rs @@ -518,6 +518,12 @@ impl Membership { other.group_id == op.group_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`. + && !matches!( + &op.action, + GroupAction::Remove { member } if member.id() == other.author + ) }) } @@ -525,18 +531,7 @@ impl Membership { /// 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 { - let group = match op.group_id { - AuthId::Group(group) => group, - AuthId::Key(_) => return None, - }; - let target = self.manager_at(group, &op.dependencies)?; - Some(AuthOperation { - action: GroupAction::Promote { - member: GroupMember::Individual(target), - access: Access::read(), - }, - ..op.clone() - }) + Self::placeholder_in(&self.state, op) } /// After a removal is applied, void every accepted delegated operation whose @@ -594,7 +589,62 @@ impl Membership { .unwrap_or_else(|| op.clone()) }) .collect(); - rebuild(&ops) + 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. @@ -782,6 +832,34 @@ mod tests { 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_a_duplicate_changes_nothing() { let mut layer = Membership::new(); From eba455e7afe9d9e8aa8871bfdb7baf13fba55f8a Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 1 Nov 2026 14:13:47 -0600 Subject: [PATCH 7/7] fix(id): voided removals void nothing; mutual exemption matches the actor (#171) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Codex round 3 on PR #3694, both P2 findings fixed: - Exclude voided removals from originator filtering: voiding_removal() now skips removals that are themselves voided, and when a removal is voided its own victims are re-evaluated — an operation whose voiding removal no longer stands revives and is replayed as itself (voided_by/originals bookkeeping). - Match mutual removals against the actual originator: both mutual-removal predicates now resolve the other operation's actor (originator, falling back to author) instead of comparing against the borrowed authority identity, so two delegatees of the same manager removing each other are mutual in either arrival order. Tests: two new membership-layer tests, each in both arrival orders (delegated mutual removals by two delegatees; an add by a member whose delegated removal was voided, including the revive-on-void case). Laptop: membership:: 45 passed, groups:: 102 passed. --- pkgs/id/src/membership/layer.rs | 170 ++++++++++++++++++++++++++++---- 1 file changed, 150 insertions(+), 20 deletions(-) diff --git a/pkgs/id/src/membership/layer.rs b/pkgs/id/src/membership/layer.rs index 0be7cca874..dd4b365966 100644 --- a/pkgs/id/src/membership/layer.rs +++ b/pkgs/id/src/membership/layer.rs @@ -129,6 +129,12 @@ pub struct Membership { 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>, } @@ -227,11 +233,13 @@ impl Membership { // 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 self.concurrently_removed(&op) { + 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))?; @@ -508,23 +516,40 @@ impl Membership { !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 { - let Some(originator) = self.originators.get(&op.id) else { - return false; - }; - self.accepted.iter().any(|other| { - other.group_id == op.group_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`. - && !matches!( - &op.action, - GroupAction::Remove { member } if member.id() == other.author - ) - }) + self.voiding_removal(op).is_some() } /// The no-op placeholder for a voided operation, in the shape `refuse` uses: a @@ -547,6 +572,7 @@ impl Membership { return Ok(()); }; let mut changed = false; + let remover = self.actor_of(removal); let candidates: Vec = self .accepted .iter() @@ -558,18 +584,50 @@ impl Membership { && self.concurrent(&other.id, &removal.id) && !matches!( &other.action, - GroupAction::Remove { member } if member.id() == removal.author + 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()?; } @@ -583,10 +641,19 @@ impl Membership { .accepted .iter() .map(|op| { - self.placeholders - .get(&op.id) - .cloned() - .unwrap_or_else(|| op.clone()) + 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() { @@ -860,6 +927,69 @@ mod tests { } } + #[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();