diff --git a/pkgs/id/src/event_store/chat.rs b/pkgs/id/src/event_store/chat.rs index 78ce1ba45b..70c56c8d09 100644 --- a/pkgs/id/src/event_store/chat.rs +++ b/pkgs/id/src/event_store/chat.rs @@ -20,7 +20,8 @@ use redb::{ReadableDatabase, ReadableTable}; use super::resolve::{self, author_of}; use super::{ - ACTIONS, APPLIED, EVENTS, EventStore, FORKS, PROOF_HEADERS, StoreError, corrupt, decode_stored, + ACTIONS, APPLIED, DEVICE_OPS, EVENTS, EventStore, FORKS, PROOF_HEADERS, StoreError, corrupt, + decode_stored, }; use crate::chat::{CHAT_MESSAGE_KIND, ChatRecord, project, visible_history}; use crate::groups::policy::{History, Policy}; @@ -128,9 +129,10 @@ impl EventStore { let (stored, forks, headers) = { let events = txn.open_table(EVENTS)?; let actions = txn.open_table(ACTIONS)?; + let device_ops = txn.open_table(DEVICE_OPS)?; let forks = txn.open_table(FORKS)?; let proof_headers = txn.open_table(PROOF_HEADERS)?; - resolve::load(&events, &actions, &forks, &proof_headers)? + resolve::load(&events, &actions, &device_ops, &forks, &proof_headers)? }; let resolved = resolve::resolve(&stored, &forks, &headers)?; Ok(resolved @@ -162,9 +164,10 @@ impl EventStore { let (stored, forks, headers) = { let events = txn.open_table(EVENTS)?; let actions = txn.open_table(ACTIONS)?; + let device_ops = txn.open_table(DEVICE_OPS)?; let forks = txn.open_table(FORKS)?; let proof_headers = txn.open_table(PROOF_HEADERS)?; - resolve::load(&events, &actions, &forks, &proof_headers)? + resolve::load(&events, &actions, &device_ops, &forks, &proof_headers)? }; let resolved = resolve::resolve(&stored, &forks, &headers)?; if !resolve::roster_of(&resolved, group).contains(reader) { diff --git a/pkgs/id/src/event_store/claims.rs b/pkgs/id/src/event_store/claims.rs index 86385855e3..2f827d2421 100644 --- a/pkgs/id/src/event_store/claims.rs +++ b/pkgs/id/src/event_store/claims.rs @@ -12,7 +12,7 @@ use p2panda_core::Hash; use redb::ReadableDatabase; use super::resolve::{self, author_of}; -use super::{ACTIONS, EVENTS, EventStore, FORKS, PROOF_HEADERS, StoreError, corrupt}; +use super::{ACTIONS, DEVICE_OPS, EVENTS, EventStore, FORKS, PROOF_HEADERS, StoreError, corrupt}; use crate::chain::Event; use crate::groups::{Projection, Role as GroupRole}; use crate::tag_claims::{Applied, Claim, TagOp, compacted_claims, is_tag_kind}; @@ -32,7 +32,8 @@ fn parents_of(event: &Event) -> Vec { impl EventStore { /// The default-view claims in the store. An applied `tag.clear` hides a claim only when the - /// marker's author is that claim's author, or is an Admin of the group owning the subject. + /// marker's author is that claim's author, is an Admin of the group owning the subject, or + /// signs as a device an Admin of that group authorized at Admin scope (issue #5656). /// Unauthorized markers remain stored and accessible through the raw/applied event APIs. /// /// # Errors @@ -44,9 +45,10 @@ impl EventStore { let (stored, forks, headers) = { let events = txn.open_table(EVENTS)?; let actions = txn.open_table(ACTIONS)?; + let device_ops = txn.open_table(DEVICE_OPS)?; let forks = txn.open_table(FORKS)?; let proof_headers = txn.open_table(PROOF_HEADERS)?; - resolve::load(&events, &actions, &forks, &proof_headers)? + resolve::load(&events, &actions, &device_ops, &forks, &proof_headers)? }; let resolved = resolve::resolve(&stored, &forks, &headers)?; @@ -101,7 +103,10 @@ impl EventStore { /// settled projection is intentional: role is resolved from the store's current group state, not /// replayed at the marker's causal position. A subject without a stored, applied event with a /// group extension has no group-admin authority; there is no inferred owner for missing or -/// ungrouped subjects. +/// ungrouped subjects. A marker signed by a device key acts with the effective role the +/// settled projection gives that device in the subject's group (the authorizing account's +/// role capped by the grant's scope), so an Admin-scoped device of an Admin account hides a +/// claim exactly as the account itself would (issue #5656). fn default_view_events( applied: &[Applied], subject_groups: &HashMap, @@ -131,10 +136,14 @@ fn default_view_events( let Some(group) = subject_groups.get(subject) else { return false; }; + let Some(projection) = projection else { + return false; + }; projection - .and_then(|projection| projection.group(group)) + .group(group) .and_then(|view| view.members.get(&clear_author)) == Some(&GroupRole::Admin) + || projection.device_role(group, &clear_author) == Some(GroupRole::Admin) }); } event diff --git a/pkgs/id/src/event_store/ingest.rs b/pkgs/id/src/event_store/ingest.rs index 62bbb92e7c..6af6deda2b 100644 --- a/pkgs/id/src/event_store/ingest.rs +++ b/pkgs/id/src/event_store/ingest.rs @@ -95,12 +95,12 @@ use p2panda_auth::group::GroupAction; use p2panda_core::{Hash, SeqNum}; use redb::{ReadableTable, ReadableTableMetadata, WriteTransaction}; -use super::resolve::{self, decode_action, encode_action}; +use super::resolve::{self, decode_action, encode_action, encode_device_op}; use super::waiting_rows::{Hold, Mirror}; use super::{ - ACTIONS, APPLIED, CHAINS, Chain, EVENTS, EventStore, FORKS, ForkProof, HASHES, PROOF_HEADERS, - PROOF_IDS, StoreError, corrupt, decode_stored, lowest_proof, position_key, store_chain, - store_event, store_fork, + ACTIONS, APPLIED, CHAINS, Chain, DEVICE_OPS, EVENTS, EventStore, FORKS, ForkProof, HASHES, + PROOF_HEADERS, PROOF_IDS, StoreError, corrupt, decode_stored, lowest_proof, position_key, + store_chain, store_event, store_fork, }; use crate::chain::{self, Event}; use crate::documents::{is_document_kind, is_removal_kind}; @@ -239,6 +239,12 @@ impl EventStore { /// - A writer-set or rescind event's verified body is retained with the store /// (`writer_set_bodies`), so the stored object can be read back and projected /// (issue #6690; see the `writer_set` submodule). + /// - A device operation carried by a `group.event` body is recorded with the store + /// (`device_ops`), so the resolution can fold it as a group device event (issue + /// #5656). The membership body codec does not carry device operations, so without + /// this channel a device grant could never reach the event-store fold. A body that + /// claims to be a `group.event` device operation but does not decode, or names an + /// author other than the event's signer, is refused. /// - A tag event (kind `tag.set` or `tag.clear`) takes no body. Its operation is in its /// header (#182), so a payload on a tag event is refused. Its tag takes no membership /// action, and the fold reads it from the stored header (see `claims`). @@ -282,15 +288,55 @@ impl EventStore { Err(refusal) => return Ok(Ingest::Refused(refusal)), } }; + let device = if is_tag_kind(kind) || is_document_kind(kind) || is_removal_kind(kind) { + None + } else { + match body_device_op(&event, body) { + Ok(device) => device, + Err(refusal) => return Ok(Ingest::Refused(refusal)), + } + }; let result = self.ingest_event(event, action.as_ref(), now_ms)?; if let Some(body) = retain_body && !matches!(result, Ingest::Refused(_)) { self.record_writer_body(&event_id, body)?; } + if let Some((op, group)) = &device + && !matches!(result, Ingest::Refused(_)) + { + self.record_device_op(&event_id, op, group.as_ref())?; + } Ok(result) } + /// Records the device operation a verified `group.event` body carries, by event ID + /// (issue #5656). Written after the ingest decision, in its own transaction, like + /// [`EventStore::record_writer_body`]: the row is keyed by the event's ID and read + /// back only for events the store holds, so recording one for an event that is held + /// or later released is inert until the event is stored, and a duplicate delivery + /// simply rewrites the same row. + /// + /// # Errors + /// + /// Returns a redb error if the write fails, or [`StoreError::Corrupt`] if the op + /// does not encode. + fn record_device_op( + &self, + id: &Hash, + op: &crate::groups::DeviceOp, + group: Option<&Hash>, + ) -> Result<(), StoreError> { + let encoded = encode_device_op(op, group)?; + let txn = self.db.begin_write()?; + { + let mut device_ops = txn.open_table(DEVICE_OPS)?; + device_ops.insert(id.as_bytes().as_slice(), encoded.as_slice())?; + } + txn.commit()?; + Ok(()) + } + /// Verifies one received event, which may be a group operation, and applies what it allows. /// `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 @@ -438,6 +484,42 @@ impl EventStore { } } +/// The first bytes of every `group.event` body: a CBOR array of seven items, then the +/// family's tag as a text string. A body that starts with these bytes claims to be a +/// group-layer event in the wire family of [`crate::groups::event`]. +const GROUP_EVENT_CLAIM: &[u8] = b"\x87\x6bgroup.event"; + +/// The device operation an event's body carries, with the group the body names (issue +/// #5656). `Ok(None)` when the body is absent, is not a `group.event` body, or is a +/// `group.event` body of any other kind: those stay content, exactly as before. The +/// caller has already verified the body is the one the header commits to (see +/// [`body_action`]). A body that claims to be a `group.event` device operation and +/// does not decode is refused, as is one whose named author is not the event's +/// signer: the grant a device operation records is the signer's, so a body naming +/// another author is not the operation it claims to be. +fn body_device_op( + event: &Event, + body: Option<&[u8]>, +) -> Result)>, Refusal> { + let Some(body) = body else { + return Ok(None); + }; + if !body.starts_with(GROUP_EVENT_CLAIM) { + return Ok(None); + } + let wire = + crate::groups::event::decode(body).map_err(|err| Refusal::Malformed(err.to_string()))?; + let crate::groups::event::EventBody::Group(crate::groups::Body::Device(op)) = wire.body else { + return Ok(None); + }; + if wire.author != author_of(event) { + return Err(Refusal::Malformed( + "a device operation body names an author other than the event's signer".to_owned(), + )); + } + Ok(Some((op, wire.group))) +} + /// 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. @@ -954,9 +1036,10 @@ 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 device_ops = txn.open_table(DEVICE_OPS)?; let forks = txn.open_table(FORKS)?; let proof_headers = txn.open_table(PROOF_HEADERS)?; - resolve::load(&events, &actions, &forks, &proof_headers)? + resolve::load(&events, &actions, &device_ops, &forks, &proof_headers)? }; let resolved = resolve::resolve(&stored, &forks, &headers)?; diff --git a/pkgs/id/src/event_store/mod.rs b/pkgs/id/src/event_store/mod.rs index 5aede500d1..ea4622cc00 100644 --- a/pkgs/id/src/event_store/mod.rs +++ b/pkgs/id/src/event_store/mod.rs @@ -123,6 +123,14 @@ const WRITER_SET_BODIES: TableDefinition<'static, &'static [u8], &'static [u8]> /// 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"); +/// Each device operation's encoded op and the group its body names, by event ID (P8.3, +/// issue #5656). A device operation travels as a `group.event` body, which the membership +/// body codec does not carry, so it has no [`ACTIONS`] row; this table is its storage +/// channel to the resolution, whose bridge folds it as a group device event. Written only +/// from the ingest path, after the body has been verified against the header's payload +/// commitment and the body's author checked against the event's signer. +const DEVICE_OPS: TableDefinition<'static, &'static [u8], &'static [u8]> = + TableDefinition::new("device_ops"); /// 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"); @@ -657,13 +665,14 @@ impl EventStore { create_fresh(storage)? }; verify_schema(&db)?; - // The blocks and writer-set-bodies tables are additive: stores created - // before them gain them here, on the write every open already - // performs, instead of a format change that would refuse them. + // The blocks, writer-set-bodies and device-ops tables are additive: + // stores created before them gain them here, on the write every open + // already performs, instead of a format change that would refuse them. { let txn = db.begin_write()?; txn.open_table(BLOCKS)?; txn.open_table(WRITER_SET_BODIES)?; + txn.open_table(DEVICE_OPS)?; txn.commit()?; } let mut store = Self { @@ -750,9 +759,10 @@ impl EventStore { let (stored, forks, headers) = { let events = txn.open_table(EVENTS)?; let actions = txn.open_table(ACTIONS)?; + let device_ops = txn.open_table(DEVICE_OPS)?; let forks = txn.open_table(FORKS)?; let proof_headers = txn.open_table(PROOF_HEADERS)?; - resolve::load(&events, &actions, &forks, &proof_headers)? + resolve::load(&events, &actions, &device_ops, &forks, &proof_headers)? }; let resolved = resolve::resolve(&stored, &forks, &headers)?; Ok(resolve::roster_of(&resolved, group)) @@ -977,6 +987,7 @@ impl EventStore { let mut hashes_table = txn.open_table(HASHES)?; let mut groups_table = txn.open_multimap_table(GROUPS)?; let mut actions_table = txn.open_table(ACTIONS)?; + let mut device_ops_table = txn.open_table(DEVICE_OPS)?; let mut applied_table = txn.open_table(APPLIED)?; for id in &to_prune { @@ -991,6 +1002,7 @@ impl EventStore { if meta.has_action { actions_table.remove(id.as_bytes().as_slice())?; } + device_ops_table.remove(id.as_bytes().as_slice())?; applied_table.remove(id.as_bytes().as_slice())?; } } diff --git a/pkgs/id/src/event_store/resolve.rs b/pkgs/id/src/event_store/resolve.rs index 0a179b973d..52f282584d 100644 --- a/pkgs/id/src/event_store/resolve.rs +++ b/pkgs/id/src/event_store/resolve.rs @@ -46,8 +46,8 @@ use super::{StoreError, corrupt, decode_proof, decode_stored, split_position}; use crate::chain::Event; use crate::chat::CHAT_MESSAGE_KIND; use crate::groups::{ - Body as GroupBody, Create as GroupCreate, Event as GroupEvent, MemberOp, Policy, Projection, - Role as GroupRole, Template, + Body as GroupBody, Create as GroupCreate, DeviceOp, Event as GroupEvent, MemberOp, Policy, + Projection, Role as GroupRole, Template, }; use crate::membership::{AuthId, CausalEvent, Membership, Role}; use crate::rejection::Reason; @@ -58,6 +58,11 @@ use crate::waiting::AuthorKey; pub(super) struct Stored { pub event: Event, pub action: Option>, + /// The device operation the event's `group.event` body carries, with the group the body + /// names, when one was recorded at ingest (issue #5656). A device operation has no + /// membership action: the body codec does not carry it, so it reaches the fold only + /// through this channel. + pub device: Option<(DeviceOp, Option)>, } /// The applied state of a set of events. @@ -77,6 +82,8 @@ struct Node { group: Option, after: Vec, action: Option>, + /// The device operation the event's body carries, with the group the body names. + device: Option<(DeviceOp, 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, @@ -119,6 +126,7 @@ pub(super) fn resolve( group: event.header.extensions.group, after: event.header.extensions.after.clone(), action: item.action.clone(), + device: item.device.clone(), excluded, chat: event.header.extensions.kind == CHAT_MESSAGE_KIND, backlink: event.header.backlink, @@ -135,6 +143,7 @@ pub(super) fn resolve( group: header.header.extensions.group, after: header.header.extensions.after.clone(), action: None, + device: None, excluded: true, chat: header.header.extensions.kind == CHAT_MESSAGE_KIND, backlink: header.header.backlink, @@ -347,6 +356,19 @@ fn bridged_after( /// One stored group operation as a group event, or `None` when it has no group-event form. fn bridge(node: &Node) -> Option { + // A device operation bridges from its recorded body, not from a membership action: the + // group the body names is the group the operation was made in, and the header's group + // stands when the body names none (issue #5656). + if let Some((op, body_group)) = &node.device { + let group = body_group.or(node.group)?; + return Some(GroupEvent { + id: node.id, + author: node.author, + after: Vec::new(), + group: Some(group), + body: GroupBody::Device(*op), + }); + } let action = node.action.as_ref()?; let body = match action { GroupAction::Create { initial_members } => { @@ -538,6 +560,7 @@ pub(super) type Loaded = (Vec, HashMap, Vec); pub(super) fn load( events: &T, actions: &T, + device_ops: &T, forks: &T, proof_headers: &T, ) -> Result @@ -552,7 +575,15 @@ where Some(row) => Some(decode_action(row.value())?), None => None, }; - stored.push(Stored { event, action }); + let device = match device_ops.get(event.id.as_bytes().as_slice())? { + Some(row) => Some(decode_device_op(row.value())?), + None => None, + }; + stored.push(Stored { + event, + action, + device, + }); } // An author has a row at each point it has forked at. Its fork point is the lowest of them. let mut fork_points: HashMap = HashMap::new(); @@ -578,6 +609,50 @@ pub(super) fn encode_action(action: &GroupAction) -> Result, Ok(value.encode()) } +/// Encodes a device operation and the group its body names for its table, as the CBOR +/// array `[op, group]`, where `group` is the group's bytes or null. Mirrors +/// [`encode_action`]; the group travels with the op because the bridged fold event names +/// the group the operation was made in, which the event header alone may not carry. +pub(super) fn encode_device_op(op: &DeviceOp, group: Option<&Hash>) -> Result, StoreError> { + let op_value = cbor_core::Value::serialized(op) + .map_err(|err| corrupt(format!("a device operation does not encode: {err}")))?; + let group_value = match group { + Some(group) => cbor_core::Value::ByteString(group.as_bytes().to_vec().into()), + None => cbor_core::Value::null(), + }; + Ok(cbor_core::Value::Array(vec![op_value, group_value]).encode()) +} + +/// Decodes a device operation and the group its body names from its table. +pub(super) fn decode_device_op(bytes: &[u8]) -> Result<(DeviceOp, Option), StoreError> { + let value = cbor_core::Value::decode(bytes) + .map_err(|err| corrupt(format!("a device operation row is not CBOR: {err}")))?; + let cbor_core::Value::Array(items) = value else { + return Err(corrupt("a device operation row is not an array".to_owned())); + }; + let [op_value, group_value] = items.try_into().map_err(|_| { + corrupt("a device operation row does not hold an op and a group".to_owned()) + })?; + let op: DeviceOp = op_value + .deserialized() + .map_err(|err| corrupt(format!("a device operation row does not decode: {err}")))?; + let group = match group_value { + value if value.encode() == cbor_core::Value::null().encode() => None, + cbor_core::Value::ByteString(bytes) => { + let bytes: [u8; 32] = bytes.as_ref().try_into().map_err(|_| { + corrupt("a device operation row's group is not 32 bytes".to_owned()) + })?; + Some(Hash::from_bytes(bytes)) + } + _ => { + return Err(corrupt( + "a device operation row's group is neither bytes nor null".to_owned(), + )); + } + }; + Ok((op, group)) +} + /// Decodes a group action from its table. pub(super) fn decode_action(bytes: &[u8]) -> Result, StoreError> { let value = cbor_core::Value::decode(bytes) @@ -627,6 +702,7 @@ mod tests { group: None, after: after.iter().map(|a| Hash::digest([*a])).collect(), action: None, + device: None, excluded: false, chat: false, backlink: None, @@ -649,6 +725,7 @@ mod tests { group: None, after: base[i].after.clone(), action: None, + device: None, excluded: false, chat: false, backlink: None, @@ -717,6 +794,7 @@ mod tests { p2panda_auth::Access::manage(), )], }), + device: None, excluded: false, chat: false, backlink: None, @@ -727,6 +805,7 @@ mod tests { group: None, after: vec![Hash::digest([41])], action: None, + device: None, excluded: true, chat: false, backlink: None, @@ -756,6 +835,7 @@ mod tests { p2panda_auth::Access::manage(), )], }), + device: None, excluded: false, chat: false, backlink: None, diff --git a/pkgs/id/src/event_store/writer_set.rs b/pkgs/id/src/event_store/writer_set.rs index cbd9dc2a9f..f5cc72d555 100644 --- a/pkgs/id/src/event_store/writer_set.rs +++ b/pkgs/id/src/event_store/writer_set.rs @@ -199,9 +199,10 @@ impl EventStore { let (stored, forks, headers) = { let events = txn.open_table(super::EVENTS)?; let actions = txn.open_table(super::ACTIONS)?; + let device_ops = txn.open_table(super::DEVICE_OPS)?; let forks = txn.open_table(super::FORKS)?; let proof_headers = txn.open_table(super::PROOF_HEADERS)?; - resolve::load(&events, &actions, &forks, &proof_headers)? + resolve::load(&events, &actions, &device_ops, &forks, &proof_headers)? }; let resolved = resolve::resolve(&stored, &forks, &headers)?; let members: BTreeMap = resolved diff --git a/pkgs/id/src/groups/fold.rs b/pkgs/id/src/groups/fold.rs index 40089755b5..e87b75e277 100644 --- a/pkgs/id/src/groups/fold.rs +++ b/pkgs/id/src/groups/fold.rs @@ -326,6 +326,25 @@ impl Projection { self.active_devices(group, account).len() } + /// The effective role of `device` in `group` at the head of the events (P8.3): the + /// role of the account that authorized the device, capped by the grant's scope. A + /// device authorized by several accounts takes the greatest of their capped roles. + /// `None` when the device holds no active grant in the group: never granted, revoked, + /// voided, or its account no longer a member. The settled `devices` list is already + /// filtered to active grants, so only the account's current role remains to check. + pub fn device_role(&self, group: &Hash, device: &Key) -> Option { + let view = self.groups.get(group)?; + self.devices + .iter() + .filter(|grant| grant.group == *group && grant.device == *device) + .filter_map(|grant| { + view.members + .get(&grant.account) + .map(|role| (*role).min(grant.scope)) + }) + .max() + } + /// All active authorized devices across all members in `group` at the head of the events (P8.3). pub fn group_active_devices(&self, group: &Hash) -> BTreeSet { let Some(view) = self.groups.get(group) else { diff --git a/pkgs/id/tests/tag_clear_authority.rs b/pkgs/id/tests/tag_clear_authority.rs index 7f4a89b1f1..b5ab5cecb3 100644 --- a/pkgs/id/tests/tag_clear_authority.rs +++ b/pkgs/id/tests/tag_clear_authority.rs @@ -6,6 +6,8 @@ use std::collections::BTreeMap; use id::chain::{ChainExt, Event, sign}; use id::event_store::{EventStore, Ingest}; +use id::groups::event::encode as encode_group_event; +use id::groups::{Body as GroupBody, DeviceOp, Event as GroupEvent, Role as GroupRole}; use id::membership::AuthId; use id::membership::body::encode_body; use id::tag_claims::{CLEAR_KIND, SET_KIND, TagOp}; @@ -101,6 +103,20 @@ impl Chains { ) } + /// A device operation by `who` in `group`, carried as a `group.event` body — the + /// channel a device grant or revocation travels to the store by (issue #5656). + fn device_op(&mut self, who: char, group: Hash, after: &[Hash], op: DeviceOp) -> EventWithBody { + let wire = GroupEvent { + id: Hash::digest(format!("device op by {who}: {op:?}").as_bytes()), + author: author(who), + after: after.to_vec(), + group: Some(group), + body: GroupBody::Device(op), + }; + let body = encode_group_event(&wire).unwrap(); + self.sign(who, Some(group), after, "group.event", None, Some(body)) + } + fn clear(&mut self, who: char, claims: &[Hash], after: &[Hash]) -> EventWithBody { self.sign( who, @@ -151,6 +167,71 @@ fn grouped_subject_scenario(clearer: char) -> (tempfile::TempDir, EventStore, Ha (dir, store, claim.event.id, clear.event.id) } +/// B's claim on a grouped subject, then a clear signed by the device key `D`, which A — +/// the group's Admin creator — authorized at `scope`. When `revoke` is set, A revokes the +/// device again before the clear. +fn device_clear_scenario(scope: GroupRole, revoke: bool) -> (tempfile::TempDir, EventStore) { + let (dir, mut store) = open(); + let mut chains = Chains::default(); + let group_create = chains.create_group(); + let group = group_create.event.id; + let subject = chains.sign('B', Some(group), &[group], "test.subject", None, None); + let claim = chains.set_tag('B', subject.event.id, &[subject.event.id]); + let grant = chains.device_op( + 'A', + group, + &[group], + DeviceOp::Add { + device: author('D'), + scope, + }, + ); + deliver(&mut store, &group_create); + deliver(&mut store, &subject); + deliver(&mut store, &claim); + deliver(&mut store, &grant); + if revoke { + let revoke = chains.device_op( + 'A', + group, + &[grant.event.id], + DeviceOp::Revoke { + device: author('D'), + }, + ); + deliver(&mut store, &revoke); + } + let clear = chains.clear('D', &[claim.event.id], &[claim.event.id]); + deliver(&mut store, &clear); + (dir, store) +} + +#[test] +fn test_an_admin_scoped_device_of_an_admin_may_clear_another_authors_tag() { + // The device's effective role is the authorizing account's Admin role capped by the + // grant's Admin scope: Admin, so its clear hides B's claim (issue #5656). + let (_dir, store) = device_clear_scenario(GroupRole::Admin, false); + assert!(store.tag_claims().unwrap().is_empty()); +} + +#[test] +fn test_a_lower_scoped_device_may_not_clear_another_authors_tag() { + // A Write-scoped device of an Admin account has effective role Write: not Admin, so + // its clear is retained but does not hide the claim. + let (_dir, store) = device_clear_scenario(GroupRole::Write, false); + let claims = store.tag_claims().unwrap(); + assert_eq!(claims.len(), 1); +} + +#[test] +fn test_a_revoked_device_may_not_clear_another_authors_tag() { + // The grant was revoked before the clear: the device holds no active grant, so its + // clear does not hide the claim. + let (_dir, store) = device_clear_scenario(GroupRole::Admin, true); + let claims = store.tag_claims().unwrap(); + assert_eq!(claims.len(), 1); +} + #[test] fn test_a_claim_author_may_clear_its_tag_in_the_default_view() { let (_dir, store, _claim, _clear) = grouped_subject_scenario('B');