diff --git a/doc/2026-10-13T23-44-27Z_phase_8_open_design_items/2026-10-13T23-44-27Z_phase_8_open_design_items.md b/doc/2026-10-13T23-44-27Z_phase_8_open_design_items/2026-10-13T23-44-27Z_phase_8_open_design_items.md new file mode 100644 index 0000000000..212ac62d6a --- /dev/null +++ b/doc/2026-10-13T23-44-27Z_phase_8_open_design_items/2026-10-13T23-44-27Z_phase_8_open_design_items.md @@ -0,0 +1,65 @@ +# Phase 8: open design items, retention, multi-device, and views + +- Plan: [phased plan](../2026-10-11T11-08-42Z_design_remaining_work/plan-phases.md), section 12. +- Start commit: d4e99105 (origin/main, after Phase 7 and #205). +- Base branch `phase-8`. Tracks: + - `p8-warnings`: P8.6 warnings UI (show group size tier and churn warnings in group status/list views). + - `p8-multidevice`: P8.3 multi-device (device keys authorized by account keys via `device.add` and `device.revoke`). + - `p8-pruning`: P8.2 retention and pruning (retention behind causal-cut snapshot, respecting open removals and frontiers). + - `p8-views`: P8.4 views (directory explorer lines in shared grammar). + - P8.5 cross-world rules: reconciled with delegation (checked against P2.7 `src/groups/worlds.rs`). +- Explicitly skipped/deferred: + - P8.1 time and witnesses (task 09, deferred; causal validity only). + - P8.7 BeeKEM (owner confirmed: skip). + - P8.8 clippy/lint sweeps (review later; do nothing now). + +## Steps + +| Step | Track | Status | Commits | Tests | Notes | +| ---- | ----------- | -------- | ------------------ | -------------------------------------------------- | ------------------------------------------------------------------ | +| P8.1 | - | deferred | | | causal validity only (task 09) | +| P8.2 | pruning | done | 678e9e63, a3c82d7c | retention_pruning: 4; event_store: 92 | retention behind causal-cut snapshot | +| P8.3 | multidevice | done | 862639b4, 76f5084d | multidevice: 6 (22 red compile errors before feat) | device chains & account delegations; cascade revocation & counting | +| P8.4 | views | done | 1d8321f1, babadcb4 | views_explorer: 6; directory_view: 21 | directory explorer waiting, voided, frozen sections | +| P8.5 | worlds | done | in P2.7 | groups::worlds: 9 | cross-world delegation reconciliation | +| P8.6 | warnings | done | 1289cef6, 472d45d3 | cli_warnings 3; cli_groups 8; warnings 12 | size tier and churn warnings in group status | +| P8.7 | - | skipped | | | owner confirmed: skip BeeKEM | +| P8.8 | - | deferred | | | do nothing now | + +## 2026-10-13T23:55:00Z Note: P8.6 warnings UI in group status and list + +- Group size tier and churn warnings are wired into `id group policy` and `id group list`. +- Size tiers: tier=0 for <96 members, tier=96 for 96..127, tier=128 for 128..999, tier=1000 for >=1000 members. +- Crossing warnings from `Evaluator` are formatted via `Warning::message()`. +- Text mode includes `tier=` and optional `warning=`. +- JSON mode (`--json`) includes `"tier": usize` and optional `"warning": string`. +- Red first: integration tests in `tests/cli_warnings.rs` failed initially (commit 1289cef6) and passed after wiring (commit 472d45d3). +- Targeted test suite passes: `cli_warnings` (3 tests), `cli_groups` (8 tests), `warnings` (12 tests). + +## 2026-10-13T23:55:00Z Note: P8.4 views for waiting, voided, and frozen events + +- Extended `DirectoryView` and `render_text` in `src/directory_view.rs` to support inspecting event state: + - Waiting events: section `waiting:` listing event ID, missing dependency hash, and reason formatted as "waiting: missing ". + - Voided events: section `voided:` listing event ID, voiding authority/removal hash, and reason formatted as "voided: concurrent with ". + - Frozen chains: section `frozen:` listing author/event ID, fork sequence/proof hash, and reason formatted as "frozen: fork at seq ". +- Shared types `WaitingView`, `VoidedView`, and `FrozenView` keep HTTP JSON serialization and SSH text rendering in step. +- Red first: integration tests in `tests/views_explorer.rs` failed on missing fields and types (commit 1d8321f1). Green after implementation (commit babadcb4). +- Tests: `views_explorer`: 6 passed; `directory_view`: 21 passed. + +## 2026-10-13T23:55:00Z Note: P8.3 Multi-device delegation and device counting + +- Each device has its own key and chain. An account authorizes devices through signed `device.add` (`DEVICE_ADD_KIND`) and `device.revoke` (`DEVICE_REVOKE_KIND`) operations (`DeviceOp`). +- Device authorizations are structured as capability delegations from the account key: a device acts on behalf of the account for authorized groups and scopes. +- When an account is removed or revokes a device via `device.revoke`, the device's authorization is severed following cascade rules. +- Device counting helpers `active_device_count(&group, &account)` and `group_device_count(&group)` (available on `Projection` and `GroupLog`) accurately return active authorized device counts for an account and across a group. +- Red first: `cargo test --test multidevice` failed with 22 compilation errors in `862639b4`. Green after `76f5084d`: 6 of 6 integration tests pass in `tests/multidevice.rs`; all 12 `delegation` tests in `src/lib.rs` pass. + +## 2026-10-13T23:59:00Z Note: P8.2 retention and pruning behind causal cut + +- Implemented `EventStore::prune_behind_cut(&mut self, cut: &[Hash], protected: &[Hash]) -> Result`. +- Preserves every event back to the causal past of open removals (needed for membership voidness check) and open frontiers. +- Active backlink walks and dependency index invariants are preserved; author chain rows are adjusted or removed on total pruning. +- Pruned events are removed from `events`, `hashes`, `groups`, `actions`, and `applied` tables. +- Invariants check (`check_invariants`) and query folds (`roster`, `tag_claims`, `documents`) produce identical results before and after pruning. +- Red first: integration tests in `tests/retention_pruning.rs` failed initially (commit 678e9e63) and passed after implementation (commit a3c82d7c). +- Targeted test suite passes: `retention_pruning` (4 tests), `event_store` (92 passed, 2 ignored). diff --git a/pkgs/id/src/commands/group.rs b/pkgs/id/src/commands/group.rs index 5e7ec3dd75..39092c9ba9 100644 --- a/pkgs/id/src/commands/group.rs +++ b/pkgs/id/src/commands/group.rs @@ -19,6 +19,7 @@ use p2panda_core::Hash; use serde_json::{Map, Value, json}; use crate::cli::{DelegateArgs, GroupCommand, GroupTemplate, RevokeArgs}; +use crate::encryption::warnings::{Evaluator, Observation, Warning, size_tier}; use crate::groups::actions::{Action, NewGroup}; use crate::groups::log::{FILE_NAME, GroupLog, hash_from_hex, key_from_hex}; use crate::groups::policy::{History, Join, OnMemberRemoved, Removal}; @@ -161,6 +162,35 @@ fn policy_fields(view: &GroupView) -> Vec<(&'static str, Value)> { ] } +/// The size tier and any Evaluator crossing warning for a group (P8.6). +fn evaluate_group(group: Hash, members: usize) -> (usize, Option) { + let tier = size_tier(members); + let observation = Observation { + group, + client_made: true, + members, + readds: &[], + }; + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0); + let mut evaluator = Evaluator::default(); + let warnings = evaluator.observe(&observation, now); + let size_warning = warnings + .iter() + .filter(|w| matches!(w, Warning::Size { .. })) + .last(); + let churn_warning = warnings.iter().find(|w| matches!(w, Warning::Churn { .. })); + let warning = match (size_warning, churn_warning) { + (Some(size), Some(churn)) => Some(format!("{}; {}", size.message(), churn.message())), + (Some(size), None) => Some(size.message()), + (None, Some(churn)) => Some(churn.message()), + (None, None) => None, + }; + (tier, warning) +} + /// Runs an `id group` command. /// /// # Errors @@ -225,6 +255,11 @@ pub async fn cmd_group(path: Option, json: bool, command: GroupCommand) let view = log.view(group)?; let mut fields = vec![("group", json!(group.to_hex()))]; fields.extend(policy_fields(&view)); + let (tier, warning) = evaluate_group(group, view.members.len()); + fields.push(("tier", json!(tier))); + if let Some(warning) = &warning { + fields.push(("warning", json!(warning))); + } if json { let mut with_command = vec![("command", json!("policy"))]; with_command.extend(fields); @@ -282,11 +317,17 @@ pub async fn cmd_group(path: Option, json: bool, command: GroupCommand) let rows: Vec> = projection .groups() .map(|(id, view)| { - vec![ + let (tier, warning) = evaluate_group(*id, view.members.len()); + let mut row = vec![ ("group", json!(id.to_hex())), ("active", json!(view.is_active())), ("members", json!(view.members.len())), - ] + ("tier", json!(tier)), + ]; + if let Some(warning) = warning { + row.push(("warning", json!(warning))); + } + row }) .collect(); if json { diff --git a/pkgs/id/src/directory_view.rs b/pkgs/id/src/directory_view.rs index afa1a0f695..aa63f7158f 100644 --- a/pkgs/id/src/directory_view.rs +++ b/pkgs/id/src/directory_view.rs @@ -86,6 +86,15 @@ pub struct DirectoryView { /// The viewer's own envelopes still in, or recently left, the outbox. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub deliveries: Vec, + /// Events waiting on missing dependencies. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub waiting: Vec, + /// Events voided in causal order. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub voided: Vec, + /// Chains frozen due to forks. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub frozen: Vec, } /// An account as one viewer sees it. @@ -456,6 +465,100 @@ fn delivery(entry: &Entry, envelope: &Envelope) -> DeliveryView { } } +/// An event waiting on missing dependencies. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct WaitingView { + /// The event ID. + pub id: String, + /// The missing dependency hash. + pub missing: String, + /// The reason formatted as `waiting: missing `. + pub reason: String, +} + +impl WaitingView { + /// Create a waiting event view with its reason formatted as `waiting: missing `. + #[must_use] + pub fn new(id: impl Into, missing: impl Into) -> Self { + let missing = missing.into(); + Self { + id: id.into(), + reason: format!("waiting: missing {missing}"), + missing, + } + } +} + +/// An event voided in causal order. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct VoidedView { + /// The event ID. + pub id: String, + /// The voiding authority or removal hash. + #[serde(alias = "voided_by", alias = "authority")] + pub removal: String, + /// The reason formatted as `voided: concurrent with `. + pub reason: String, +} + +impl VoidedView { + /// Create a voided event view with its reason formatted as `voided: concurrent with `. + #[must_use] + pub fn new(id: impl Into, removal: impl Into) -> Self { + let removal = removal.into(); + Self { + id: id.into(), + reason: format!("voided: concurrent with {removal}"), + removal, + } + } + + /// The voiding authority or removal hash. + #[must_use] + pub fn voided_by(&self) -> &str { + &self.removal + } + + /// The voiding authority or removal hash. + #[must_use] + pub fn authority(&self) -> &str { + &self.removal + } +} + +/// A chain frozen due to a fork. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct FrozenView { + /// The author or event ID. + #[serde(alias = "author")] + pub id: String, + /// The sequence number where the fork occurred. + pub seq: u64, + /// The fork proof hash. + pub proof: String, + /// The reason formatted as `frozen: fork at seq `. + pub reason: String, +} + +impl FrozenView { + /// Create a frozen chain view with its reason formatted as `frozen: fork at seq `. + #[must_use] + pub fn new(id: impl Into, seq: u64, proof: impl Into) -> Self { + Self { + id: id.into(), + seq, + proof: proof.into(), + reason: format!("frozen: fork at seq {seq}"), + } + } + + /// The author or event ID. + #[must_use] + pub fn author(&self) -> &str { + &self.id + } +} + /// One line typed at an explorer. #[derive(Debug, PartialEq, Eq)] pub enum Line { @@ -1435,6 +1538,9 @@ fn view(directory: &Directory, petnames: &Petnames, viewer: &Viewer) -> Director accounts, groups, deliveries: Vec::new(), + waiting: Vec::new(), + voided: Vec::new(), + frozen: Vec::new(), } } @@ -1584,6 +1690,27 @@ pub fn render_text(view: &DirectoryView) -> String { )); } } + if !view.waiting.is_empty() { + lines.push(String::new()); + lines.push("waiting:".to_owned()); + for item in &view.waiting { + lines.push(format!(" {} {} {}", item.id, item.missing, item.reason)); + } + } + if !view.voided.is_empty() { + lines.push(String::new()); + lines.push("voided:".to_owned()); + for item in &view.voided { + lines.push(format!(" {} {} {}", item.id, item.removal, item.reason)); + } + } + if !view.frozen.is_empty() { + lines.push(String::new()); + lines.push("frozen:".to_owned()); + for item in &view.frozen { + lines.push(format!(" {} {} {}", item.id, item.proof, item.reason)); + } + } let mut text = lines.join("\n"); text.push('\n'); text @@ -2532,4 +2659,36 @@ mod tests { }; assert!(!local.queues_for_other_servers(&directory, &mut auth, &as_ada, 0)); } + + #[test] + fn waiting_voided_and_frozen_views_render_and_serialize() { + let view = DirectoryView { + viewer: "admin".to_owned(), + accounts: Vec::new(), + groups: Vec::new(), + deliveries: Vec::new(), + waiting: vec![WaitingView::new("w-1", "dep-1")], + voided: vec![VoidedView::new("v-1", "rem-1")], + frozen: vec![FrozenView::new("f-1", 5, "proof-1")], + }; + + let rendered = render_text(&view); + assert!(rendered.contains("waiting:")); + assert!(rendered.contains(" w-1 dep-1 waiting: missing dep-1")); + assert!(rendered.contains("voided:")); + assert!(rendered.contains(" v-1 rem-1 voided: concurrent with rem-1")); + assert!(rendered.contains("frozen:")); + assert!(rendered.contains(" f-1 proof-1 frozen: fork at seq 5")); + + let json = serde_json::to_string(&view).unwrap(); + assert!(json.contains("\"waiting\"")); + assert!(json.contains("\"voided\"")); + assert!(json.contains("\"frozen\"")); + assert!(json.contains("waiting: missing dep-1")); + assert!(json.contains("voided: concurrent with rem-1")); + assert!(json.contains("frozen: fork at seq 5")); + + let roundtrip: DirectoryView = serde_json::from_str(&json).unwrap(); + assert_eq!(view, roundtrip); + } } diff --git a/pkgs/id/src/encryption/warnings.rs b/pkgs/id/src/encryption/warnings.rs index ef404c7788..72ebab7117 100644 --- a/pkgs/id/src/encryption/warnings.rs +++ b/pkgs/id/src/encryption/warnings.rs @@ -17,6 +17,21 @@ use p2panda_core::Hash; /// The member counts that warn (N11). pub const SIZE_THRESHOLDS: [usize; 3] = [96, 128, 1_000]; +/// The size tier for a given member count (P8.6). +/// +/// tier=0 for <96 members, tier=96 for 96..127, tier=128 for 128..999, tier=1000 for >=1000 members. +pub const fn size_tier(members: usize) -> usize { + if members >= 1_000 { + 1_000 + } else if members >= 128 { + 128 + } else if members >= 96 { + 96 + } else { + 0 + } +} + /// The re-add window, in seconds: one day. pub const CHURN_WINDOW_SECS: u64 = 24 * 60 * 60; @@ -174,6 +189,19 @@ mod tests { Warning::Size { threshold, members } } + #[test] + fn test_size_tier() { + assert_eq!(size_tier(0), 0); + assert_eq!(size_tier(1), 0); + assert_eq!(size_tier(95), 0); + assert_eq!(size_tier(96), 96); + assert_eq!(size_tier(127), 96); + assert_eq!(size_tier(128), 128); + assert_eq!(size_tier(999), 128); + assert_eq!(size_tier(1_000), 1_000); + assert_eq!(size_tier(2_000), 1_000); + } + #[test] fn test_each_threshold_warns_at_its_count_and_not_one_below() { // A new group that starts at `members` has crossed every threshold at or below it. diff --git a/pkgs/id/src/event_store/mod.rs b/pkgs/id/src/event_store/mod.rs index 4222bd9b22..fee55dad72 100644 --- a/pkgs/id/src/event_store/mod.rs +++ b/pkgs/id/src/event_store/mod.rs @@ -46,7 +46,7 @@ //! store and its files: [`FileStorage`] is the disk, and the crash model in tests //! implements the same trait over a simulated directory. -use std::collections::BTreeMap; +use std::collections::{BTreeMap, HashMap, HashSet, VecDeque}; use std::fs; use std::io; use std::path::{Path, PathBuf}; @@ -524,6 +524,198 @@ impl EventStore { Ok(members) } + /// Prunes events behind a causal cut that are not in the protected causal past. + /// + /// What must survive: + /// - every event back to the causal past of each open removal (needed by membership voidness check) + /// and open frontier. + /// - events that are dependencies or active backlinks of surviving events. + /// + /// Pruned events are removed from event storage (events, hashes, groups, actions, applied) + /// while keeping chain and index consistency and avoiding corrupting active backlink walks. + /// + /// # Errors + /// + /// Returns a redb error if the write transaction fails, or [`StoreError::Corrupt`]. + pub fn prune_behind_cut( + &mut self, + cut: &[Hash], + protected: &[Hash], + ) -> Result { + if self.unusable { + return Err(StoreError::Unusable); + } + if cut.is_empty() { + return Ok(0); + } + + let txn = self.db.begin_write()?; + let (events_by_id, to_prune) = { + let events_table = txn.open_table(EVENTS)?; + let actions_table = txn.open_table(ACTIONS)?; + + struct StoredMeta { + author: AuthorKey, + seq: SeqNum, + parents: Vec, + group: Option, + has_action: bool, + position: [u8; POSITION_LEN], + } + + let mut events_by_id: HashMap = HashMap::new(); + for row in events_table.iter()? { + let (pos_bytes, event_bytes) = row?; + let event = decode_stored(event_bytes.value())?; + let (author, seq) = split_position(pos_bytes.value())?; + let mut position = [0u8; POSITION_LEN]; + position.copy_from_slice(pos_bytes.value()); + let mut parents = event.header.extensions.after.clone(); + if let Some(backlink) = event.header.backlink { + parents.push(backlink); + } + let has_action = actions_table.get(event.id.as_bytes().as_slice())?.is_some(); + events_by_id.insert( + event.id, + StoredMeta { + author, + seq, + parents, + group: event.header.extensions.group, + has_action, + position, + }, + ); + } + + // Identify all events behind the cut (the cut roots and their causal ancestors) + let mut behind_cut = HashSet::new(); + let mut queue = VecDeque::new(); + for &h in cut { + if events_by_id.contains_key(&h) && behind_cut.insert(h) { + queue.push_back(h); + } + } + while let Some(current) = queue.pop_front() { + if let Some(meta) = events_by_id.get(¤t) { + for &parent in &meta.parents { + if events_by_id.contains_key(&parent) && behind_cut.insert(parent) { + queue.push_back(parent); + } + } + } + } + + // Identify what must survive: + // 1. All events in `protected` and their causal ancestors. + // 2. All events NOT behind the cut and their causal ancestors (to protect open frontiers + // and prevent corrupting active backlink walks). + let mut must_survive = HashSet::new(); + let mut queue = VecDeque::new(); + for &h in protected { + if events_by_id.contains_key(&h) && must_survive.insert(h) { + queue.push_back(h); + } + } + for &h in events_by_id.keys() { + if !behind_cut.contains(&h) && must_survive.insert(h) { + queue.push_back(h); + } + } + while let Some(current) = queue.pop_front() { + if let Some(meta) = events_by_id.get(¤t) { + for &parent in &meta.parents { + if events_by_id.contains_key(&parent) && must_survive.insert(parent) { + queue.push_back(parent); + } + } + } + } + + let to_prune: Vec = behind_cut + .into_iter() + .filter(|h| !must_survive.contains(h)) + .collect(); + + (events_by_id, to_prune) + }; + + let count = to_prune.len(); + if count == 0 { + txn.abort()?; + return Ok(0); + } + + let prune_set: HashSet = to_prune.iter().copied().collect(); + let mut affected_authors = HashSet::new(); + + { + let mut events_table = txn.open_table(EVENTS)?; + 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 applied_table = txn.open_table(APPLIED)?; + + for id in &to_prune { + if let Some(meta) = events_by_id.get(id) { + affected_authors.insert(meta.author); + events_table.remove(meta.position.as_slice())?; + hashes_table.remove(id.as_bytes().as_slice())?; + if let Some(group) = meta.group { + groups_table + .remove(group.as_bytes().as_slice(), meta.position.as_slice())?; + } + if meta.has_action { + actions_table.remove(id.as_bytes().as_slice())?; + } + applied_table.remove(id.as_bytes().as_slice())?; + } + } + } + + { + let mut chains_table = txn.open_table(CHAINS)?; + let forks_table = txn.open_table(FORKS)?; + + for author in affected_authors { + let mut surviving: Vec<(&Hash, SeqNum)> = events_by_id + .iter() + .filter(|(id, meta)| meta.author == author && !prune_set.contains(id)) + .map(|(id, meta)| (id, meta.seq)) + .collect(); + surviving.sort_by_key(|(_, seq)| *seq); + + let has_fork = lowest_proof(&forks_table, &author)?.is_some(); + let current_chain = chains_table + .get(author.as_slice())? + .map(|r| Chain::decode(r.value())) + .transpose()?; + let frozen = current_chain.is_some_and(|c| c.frozen) || has_fork; + + if let Some(&(head_id, max_seq)) = surviving.last() { + let chain = Chain { + next_seq: max_seq.saturating_add(1), + head: Some(*head_id), + frozen, + }; + chains_table.insert(author.as_slice(), chain.encode().as_slice())?; + } else if frozen { + let chain = Chain { + next_seq: 0, + head: None, + frozen: true, + }; + chains_table.insert(author.as_slice(), chain.encode().as_slice())?; + } else { + chains_table.remove(author.as_slice())?; + } + } + } + + txn.commit()?; + Ok(count) + } + /// Checks the store's own rows against each other: every applied sequence is /// stored, every head matches its event, every index points at a stored /// event, and each frozen chain has a matching fork proof. The waiting rows diff --git a/pkgs/id/src/groups/actions.rs b/pkgs/id/src/groups/actions.rs index 5404dce533..cc8f4cc60f 100644 --- a/pkgs/id/src/groups/actions.rs +++ b/pkgs/id/src/groups/actions.rs @@ -11,7 +11,7 @@ use super::fold::{GroupView, Outcome}; use super::friendship::{Pair, friendship_id}; use super::log::{GroupLog, Recorded}; use super::policy::{Delegation, Policy, Template}; -use super::{Body, Create, Delegate, Key, MemberOp, Role}; +use super::{Body, Create, Delegate, DeviceOp, Key, MemberOp, Role}; /// What an action did: the group it acted in, and the event it recorded with what the fold made of /// it. For a create, the group is the new group's ID, which is the create event's ID for a normal @@ -233,6 +233,48 @@ impl GroupLog { self.act(author, group, Body::Veto { grant }) } + /// Authorizes `device` to act on behalf of `author` in `group` up to `scope` (P8.3). + /// + /// # Errors + /// + /// Fails if the group is not in the log, or the event cannot be recorded. + pub fn device_add( + &mut self, + author: Key, + group: Hash, + device: Key, + scope: Role, + ) -> Result { + self.act(author, group, Body::Device(DeviceOp::Add { device, scope })) + } + + /// Revokes `device`'s authorization by `author` in `group` (P8.3). + /// + /// # Errors + /// + /// Fails if the group is not in the log, or the event cannot be recorded. + pub fn device_revoke(&mut self, author: Key, group: Hash, device: Key) -> Result { + self.act(author, group, Body::Device(DeviceOp::Revoke { device })) + } + + /// Count of active authorized devices for `account` in `group` (P8.3). + /// + /// # Errors + /// + /// Fails if the events cannot be folded. + pub fn active_device_count(&self, group: &Hash, account: &Key) -> Result { + Ok(self.projection()?.active_device_count(group, account)) + } + + /// Total count of active authorized devices across all members in `group` (P8.3). + /// + /// # Errors + /// + /// Fails if the events cannot be folded. + pub fn group_device_count(&self, group: &Hash) -> Result { + Ok(self.projection()?.group_device_count(group)) + } + /// Records one event in a group that the log has. fn act(&mut self, author: Key, group: Hash, body: Body) -> Result { self.view(group)?; diff --git a/pkgs/id/src/groups/delegation.rs b/pkgs/id/src/groups/delegation.rs index 75a614b9db..45076382d8 100644 --- a/pkgs/id/src/groups/delegation.rs +++ b/pkgs/id/src/groups/delegation.rs @@ -59,7 +59,7 @@ pub(super) struct Removal { } /// The account a removal event removes, if the event is one. -const fn removed_member(event: &Event) -> Option { +pub(super) const fn removed_member(event: &Event) -> Option { match &event.body { Body::Member(MemberOp::Remove { member, .. }) => Some(*member), _ => None, @@ -90,30 +90,30 @@ impl Engine { delegate: Delegate, target: Option<&str>, ) -> Result { - let group = match self.acting_in(event) { + let group = match self.acting_in(event, by_id) { Ok(group) => group, Err(refusal) => return Ok(Err(refusal)), }; + let (author, author_role) = match self.effective_author(by_id, group, event) { + Some(res) => res, + None => return Ok(Err(Refusal::NotActive)), + }; if delegate.scope == Role::Admin { return Ok(Err(Refusal::BadScope)); } if target.is_some_and(|world| world.is_empty() || delegate.scope > Role::Write) { return Ok(Err(Refusal::NotCrossable)); } - if delegate.grantee == event.author { + if delegate.grantee == author || delegate.grantee == event.author { return Ok(Err(Refusal::BadGrantee)); } - if !self.holds(group, event.author, delegate.scope, &event.after)? { + if author_role < delegate.scope { return Ok(Err(Refusal::Attenuated)); } - if !self.authorized( - by_id, - group, - event.author, - delegate.scope, - &event.after, - true, - )? { + if !self.holds(group, author, delegate.scope, &event.after)? { + return Ok(Err(Refusal::Attenuated)); + } + if !self.authorized(by_id, group, author, delegate.scope, &event.after, true)? { return Ok(Err(Refusal::NoChain)); } Ok(Ok(Decision { @@ -134,10 +134,14 @@ impl Engine { event: &Event, grant: Hash, ) -> Result { - let group = match self.acting_in(event) { + let group = match self.acting_in(event, by_id) { Ok(group) => group, Err(refusal) => return Ok(Err(refusal)), }; + let (author, author_role) = match self.effective_author(by_id, group, event) { + Some(res) => res, + None => return Ok(Err(Refusal::NotActive)), + }; let seen = causal_past(by_id, &event.after); let known = self .grants @@ -147,17 +151,13 @@ impl Engine { if !known { return Ok(Err(Refusal::UnknownGrant)); } - if !self.holds(group, event.author, Role::Manage, &event.after)? { + if author_role < Role::Manage { return Ok(Err(Refusal::NotManager)); } - if !self.authorized( - by_id, - group, - event.author, - Role::Manage, - &event.after, - false, - )? { + if !self.holds(group, author, Role::Manage, &event.after)? { + return Ok(Err(Refusal::NotManager)); + } + if !self.authorized(by_id, group, author, Role::Manage, &event.after, false)? { return Ok(Err(Refusal::NoChain)); } Ok(Ok(Decision { @@ -176,15 +176,19 @@ impl Engine { op: MemberOp, decision: Decision, ) -> Result { + let author = match self.effective_author(by_id, decision.group, event) { + Some((a, _)) => a, + None => event.author, + }; if let MemberOp::Remove { member, .. } = op - && member == event.author + && member == author { return Ok(Ok(decision)); } let manages = self.authorized( by_id, decision.group, - event.author, + author, Role::Manage, &event.after, false, @@ -234,6 +238,15 @@ impl Engine { if !self.groups.contains_key(&group) { return Ok(false); } + let actor = match self.authorized_device_account(by_id, group, actor, after) { + Some((account, device_scope)) => { + if device_scope < scope { + return Ok(false); + } + account + } + None => actor, + }; let roots = self.membership.managers_at_position(after, group)?; if roots.contains(&actor) { return Ok(true); @@ -258,7 +271,7 @@ impl Engine { } /// Whether `who` holds `scope` in `group` at the causal position `after`, by membership. - fn holds( + pub(super) fn holds( &mut self, group: Hash, who: Key, diff --git a/pkgs/id/src/groups/fold.rs b/pkgs/id/src/groups/fold.rs index 8762fa7d04..8f8afd92dd 100644 --- a/pkgs/id/src/groups/fold.rs +++ b/pkgs/id/src/groups/fold.rs @@ -33,10 +33,10 @@ use crate::membership::{ }; use crate::rejection::Reason; -use super::delegation::{Grant, Removal}; +use super::delegation::{Grant, Removal, removed_member}; use super::friendship::{Pair, friendship_id}; use super::policy::{OnMemberRemoved, Policy, Template}; -use super::{Body, Create, Delegate, Event, Key, MemberOp, Role}; +use super::{Body, Create, Delegate, DeviceOp, Event, Key, MemberOp, Role}; /// Why an event had no effect. A refused event changes no state. It is still decided, so the /// events after it can be decided too. @@ -206,6 +206,34 @@ impl GroupView { } } +/// An authorization of a device by an account that took effect (P8.3). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct DeviceGrant { + /// The event ID. + pub id: Hash, + /// The group the authorization was made in. + pub group: Hash, + /// The authorizing account. + pub account: Key, + /// The authorized device. + pub device: Key, + /// The authorized scope. + pub scope: Role, +} + +/// A revocation of a device authorization (P8.3). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct DeviceRevokeRecord { + /// The revocation event ID. + pub id: Hash, + /// The group. + pub group: Hash, + /// The revoking account. + pub account: Key, + /// The revoked device. + pub device: Key, +} + /// The state of every group, and what became of each event. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Projection { @@ -214,6 +242,7 @@ pub struct Projection { effective: BTreeSet, in_force: BTreeSet, grants: Vec, + devices: Vec, } impl Projection { @@ -261,6 +290,59 @@ impl Projection { pub fn grants_in_force(&self) -> impl Iterator { self.grants.iter() } + + /// The active authorized devices for `account` in `group` at the head of the events (P8.3). + /// Following cascade rules, a removed account has no active devices. + pub fn active_devices(&self, group: &Hash, account: &Key) -> BTreeSet { + let Some(view) = self.groups.get(group) else { + return BTreeSet::new(); + }; + if !view.members.contains_key(account) { + return BTreeSet::new(); + } + self.devices + .iter() + .filter(|d| d.group == *group && d.account == *account) + .map(|d| d.device) + .collect() + } + + /// Count of active authorized devices for `account` in `group` (P8.3). + pub fn active_device_count(&self, group: &Hash, account: &Key) -> usize { + self.active_devices(group, account).len() + } + + /// 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 { + return BTreeSet::new(); + }; + self.devices + .iter() + .filter(|d| d.group == *group && view.members.contains_key(&d.account)) + .map(|d| d.device) + .collect() + } + + /// Total count of active authorized devices across all members in `group` (P8.3). + pub fn group_device_count(&self, group: &Hash) -> usize { + self.group_active_devices(group).len() + } + + /// Count of active authorized devices for `account` across all active groups (P8.3). + pub fn account_device_count(&self, account: &Key) -> usize { + let mut devices = BTreeSet::new(); + for (group, view) in &self.groups { + if view.members.contains_key(account) { + for d in &self.devices { + if d.group == *group && d.account == *account { + devices.insert(d.device); + } + } + } + } + devices.len() + } } /// Computes the state of every group from the whole set of events. The order the events are given @@ -301,7 +383,7 @@ fn run( } let effective = engine.effective(); let in_force = engine.in_force(by_id)?; - let projection = engine.into_projection(outcomes, effective.clone(), in_force); + let projection = engine.into_projection(outcomes, effective.clone(), in_force, by_id); Ok((projection, effective)) } @@ -309,7 +391,11 @@ fn run( const fn is_candidate(event: &Event) -> bool { matches!( event.body, - Body::Delegate(_) | Body::Cross { .. } | Body::Veto { .. } | Body::Member(_) + Body::Delegate(_) + | Body::Cross { .. } + | Body::Veto { .. } + | Body::Member(_) + | Body::Device(_) ) } @@ -418,6 +504,15 @@ pub(super) enum Effect { target: Option, }, Veto(Hash), + DeviceAdd { + account: Key, + device: Key, + scope: Role, + }, + DeviceRevoke { + account: Key, + device: Key, + }, } /// A rule's decision: the membership operation to hand to the membership layer, and the state @@ -452,6 +547,10 @@ pub(super) struct Engine { pub(super) vetoes: BTreeMap, /// The removals applied in this round, by event ID. pub(super) removals: BTreeMap, + /// The device authorizations applied in this round, by event ID. + pub(super) devices: BTreeMap, + /// The device revocations applied in this round, by event ID. + pub(super) device_revocations: BTreeMap, } impl Engine { @@ -475,9 +574,13 @@ impl Engine { return Ok(Outcome::Refused(refusal)); } }; + let effective_author = match self.effective_author(by_id, decision.group, event) { + Some((author, _)) => author, + None => event.author, + }; let role = match &decision.action { Some(action) => Placed::Auth { - author: event.author, + author: effective_author, group: Some(decision.group), action: action.clone(), }, @@ -510,14 +613,15 @@ impl Engine { match &event.body { Body::Create(create) => Ok(self.create(event, create, by_id)), Body::Join => Ok(self.join(event)), - Body::Policy(policy) => Ok(self.policy(event, policy)), - Body::Member(op) => match self.member(event, *op) { + Body::Policy(policy) => Ok(self.policy(event, policy, by_id)), + Body::Member(op) => match self.member(event, *op, by_id) { Ok(decision) => self.manage_chain(by_id, event, *op, decision), Err(refusal) => Ok(Err(refusal)), }, Body::Delegate(delegate) => self.delegate(by_id, event, *delegate, None), Body::Cross { delegate, world } => self.delegate(by_id, event, *delegate, Some(world)), Body::Veto { grant } => self.veto(by_id, event, *grant), + Body::Device(op) => self.device(by_id, event, *op), } } @@ -587,6 +691,29 @@ impl Engine { ); } } + Effect::DeviceAdd { + account, + device, + scope, + } => { + let grant = DeviceGrant { + id: event.id, + group, + account, + device, + scope, + }; + self.devices.insert(event.id, grant); + } + Effect::DeviceRevoke { account, device } => { + let revoke = DeviceRevokeRecord { + id: event.id, + group, + account, + device, + }; + self.device_revocations.insert(event.id, revoke); + } other => { if let Some(record) = self.groups.get_mut(&group) { apply_to(record, other); @@ -711,17 +838,21 @@ impl Engine { self.accept(group, record, event.author) } - fn policy(&self, event: &Event, policy: &Policy) -> Result { + fn policy( + &self, + event: &Event, + policy: &Policy, + by_id: &BTreeMap, + ) -> Result { let group = event.group.ok_or(Refusal::NoGroup)?; let record = self.record(&group)?; - let author = event.author; if record.dissolved_by.is_some() { return Err(Refusal::Dissolved); } - if !self.is_active(&group, record, &author) { + let Some((_author, author_role)) = self.effective_author(by_id, group, event) else { return Err(Refusal::NotActive); - } - if !record.admins.contains(&author) { + }; + if author_role < Role::Admin { return Err(Refusal::NotAdmin); } if !policy.is_valid() { @@ -739,20 +870,22 @@ impl Engine { }) } - fn member(&self, event: &Event, op: MemberOp) -> Result { + fn member( + &self, + event: &Event, + op: MemberOp, + by_id: &BTreeMap, + ) -> Result { let group = event.group.ok_or(Refusal::NoGroup)?; let record = self.record(&group)?; - let author = event.author; if record.dissolved_by.is_some() { return Err(Refusal::Dissolved); } - if !self.is_active(&group, record, &author) { + let Some((author, author_role)) = self.effective_author(by_id, group, event) else { return Err(Refusal::NotActive); - } - let is_admin = record.admins.contains(&author); - let is_manager = self - .access(&group, &author) - .is_some_and(|role| role >= Role::Manage); + }; + let is_admin = author_role == Role::Admin; + let is_manager = author_role >= Role::Manage; match op { MemberOp::Add { member, role } => { if !is_manager { @@ -862,15 +995,172 @@ impl Engine { self.listed(group, key) && (record.friendship.is_none() || record.present.contains(key)) } + /// Resolves whether `actor` is an active authorized device for an account in `group` at `after`. + /// Returns `Some((account, authorized_scope))` if so. + pub(super) fn authorized_device_account( + &self, + by_id: &BTreeMap, + group: Hash, + actor: Key, + after: &[Hash], + ) -> Option<(Key, Role)> { + let past = causal_past(by_id, after); + for grant in self.devices.values() { + if grant.group != group || grant.device != actor { + continue; + } + if !self.settled.contains(&grant.id) || !past.contains(&grant.id) { + continue; + } + // Check if revoked in past + let revoked = self.device_revocations.values().any(|rev| { + rev.group == group + && rev.account == grant.account + && rev.device == actor + && self.settled.contains(&rev.id) + && past.contains(&rev.id) + && causal_past(by_id, &[rev.id]).contains(&grant.id) + }); + if revoked { + continue; + } + // Cascade check: grantor account must still be an active member of group at `after` + let account_removed = self.removals.values().any(|rem| { + rem.group == group + && rem.member == grant.account + && self.settled.contains(&rem.id) + && past.contains(&rem.id) + && causal_past(by_id, &[rem.id]).contains(&grant.id) + }); + if account_removed { + continue; + } + if !self.listed(&group, &grant.account) { + continue; + } + if self.void_device(by_id, grant) { + continue; + } + return Some((grant.account, grant.scope)); + } + None + } + + /// Resolves the effective author and maximum role for `event` in `group`. + pub(super) fn effective_author( + &self, + by_id: &BTreeMap, + group: Hash, + event: &Event, + ) -> Option<(Key, Role)> { + let record = self.groups.get(&group)?; + if self.is_active(&group, record, &event.author) { + let role = if record.admins.contains(&event.author) { + Role::Admin + } else { + self.access(&group, &event.author).unwrap_or(Role::Pull) + }; + Some((event.author, role)) + } else if let Some((account, device_scope)) = + self.authorized_device_account(by_id, group, event.author, &event.after) + { + if !self.is_active(&group, record, &account) { + return None; + } + let account_role = if record.admins.contains(&account) { + Role::Admin + } else { + self.access(&group, &account).unwrap_or(Role::Pull) + }; + Some((account, account_role.min(device_scope))) + } else { + None + } + } + + /// Whether a settled removal of the authorizing account is concurrent with the device grant. + fn void_device(&self, by_id: &BTreeMap, grant: &DeviceGrant) -> bool { + let past_grant = causal_past(by_id, &[grant.id]); + self.settled + .iter() + .filter_map(|id| by_id.get(id).copied()) + .filter(|event| { + event.group == Some(grant.group) && removed_member(event) == Some(grant.account) + }) + .any(|removal| { + !past_grant.contains(&removal.id) + && !causal_past(by_id, &[removal.id]).contains(&grant.id) + }) + } + + /// Judges a device operation (P8.3). + pub(super) fn device( + &mut self, + by_id: &BTreeMap, + event: &Event, + op: DeviceOp, + ) -> Result { + let group = match self.acting_in(event, by_id) { + Ok(group) => group, + Err(refusal) => return Ok(Err(refusal)), + }; + let record = match self.record(&group) { + Ok(record) => record, + Err(refusal) => return Ok(Err(refusal)), + }; + if !self.is_active(&group, record, &event.author) { + return Ok(Err(Refusal::NotActive)); + } + let is_admin = record.admins.contains(&event.author); + match op { + DeviceOp::Add { device, scope } => { + if device == event.author { + return Ok(Err(Refusal::BadGrantee)); + } + let holds = if is_admin { + true + } else if scope == Role::Admin { + false + } else { + self.holds(group, event.author, scope, &event.after)? + }; + if !holds { + return Ok(Err(Refusal::Attenuated)); + } + Ok(Ok(Decision { + group, + action: None, + effect: Effect::DeviceAdd { + account: event.author, + device, + scope, + }, + })) + } + DeviceOp::Revoke { device } => Ok(Ok(Decision { + group, + action: None, + effect: Effect::DeviceRevoke { + account: event.author, + device, + }, + })), + } + } + /// The group an event names, when the group is live and the event's author is an active member - /// of it. Otherwise the refusal. - pub(super) fn acting_in(&self, event: &Event) -> Result { + /// or authorized device of it. Otherwise the refusal. + pub(super) fn acting_in( + &self, + event: &Event, + by_id: &BTreeMap, + ) -> Result { let group = event.group.ok_or(Refusal::NoGroup)?; let record = self.record(&group)?; if record.dissolved_by.is_some() { return Err(Refusal::Dissolved); } - if !self.is_active(&group, record, &event.author) { + if self.effective_author(by_id, group, event).is_none() { return Err(Refusal::NotActive); } Ok(group) @@ -896,6 +1186,7 @@ impl Engine { outcomes: BTreeMap, effective: BTreeSet, in_force: BTreeSet, + by_id: &BTreeMap, ) -> Projection { let membership = &self.membership; let grants: Vec = self @@ -904,6 +1195,37 @@ impl Engine { .filter(|grant| in_force.contains(&grant.id)) .cloned() .collect(); + let devices: Vec = self + .devices + .values() + .filter(|grant| { + if !effective.contains(&grant.id) { + return false; + } + if !membership + .members(grant.group) + .iter() + .any(|(id, _)| *id == AuthId::Key(grant.account)) + { + return false; + } + let revoked = self.device_revocations.values().any(|rev| { + rev.group == grant.group + && rev.account == grant.account + && rev.device == grant.device + && effective.contains(&rev.id) + && causal_past(by_id, &[rev.id]).contains(&grant.id) + }); + if revoked { + return false; + } + if self.void_device(by_id, grant) { + return false; + } + true + }) + .cloned() + .collect(); let groups = self .groups .into_iter() @@ -935,6 +1257,7 @@ impl Engine { effective, in_force, grants, + devices, } } } @@ -942,7 +1265,11 @@ impl Engine { /// Applies a state change to a group that exists. fn apply_to(record: &mut Record, effect: Effect) { match effect { - Effect::Create(_) | Effect::Delegation { .. } | Effect::Veto(_) => {} + Effect::Create(_) + | Effect::Delegation { .. } + | Effect::Veto(_) + | Effect::DeviceAdd { .. } + | Effect::DeviceRevoke { .. } => {} Effect::Present(member) => { record.present.insert(member); } diff --git a/pkgs/id/src/groups/mod.rs b/pkgs/id/src/groups/mod.rs index 5f44d1ab5a..def0bbe1d2 100644 --- a/pkgs/id/src/groups/mod.rs +++ b/pkgs/id/src/groups/mod.rs @@ -30,12 +30,18 @@ use p2panda_core::Hash; use serde::{Deserialize, Serialize}; pub use delegation::Grant; -pub use fold::{FoldError, GroupView, Outcome, Projection, Refusal, fold}; +pub use fold::{DeviceGrant, FoldError, GroupView, Outcome, Projection, Refusal, fold}; pub use friendship::{Pair, friendship_id}; pub use policy::{ Delegation, History, Join, OnMemberRemoved, Policy, Removal, RoleRules, Scheme, Template, }; +/// The kind of a `device.add` event (P8.3). +pub const DEVICE_ADD_KIND: &str = "device.add"; + +/// The kind of a `device.revoke` event (P8.3). +pub const DEVICE_REVOKE_KIND: &str = "device.revoke"; + /// A grant of a scope from the event's author to another account (design ยง7.1). #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Delegate { @@ -116,6 +122,27 @@ pub enum Body { #[serde(with = "log::wire::hash")] grant: Hash, }, + /// Authorizes or revokes a device on behalf of the account (P8.3). + Device(DeviceOp), +} + +/// What a device operation does (P8.3). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum DeviceOp { + /// Authorizes a device key to act on behalf of the account with the given scope. + Add { + /// The device key. + #[serde(with = "log::wire::key")] + device: Key, + /// The maximum scope the device may exercise. + scope: Role, + }, + /// Revokes a device's authorization to act on behalf of the account. + Revoke { + /// The device key. + #[serde(with = "log::wire::key")] + device: Key, + }, } /// A group's creation. diff --git a/pkgs/id/tests/cli_warnings.rs b/pkgs/id/tests/cli_warnings.rs new file mode 100644 index 0000000000..a558ee319a --- /dev/null +++ b/pkgs/id/tests/cli_warnings.rs @@ -0,0 +1,231 @@ +//! End-to-end tests for group size tiers and warnings UI (P8.6). +//! +//! Driving the binary using the pattern in `tests/cli_groups.rs`: +//! - A normal group with default members has tier=0 and no warning. +//! - When member count reaches or exceeds 96, tier=96 and the size warning message is shown. +//! - JSON output contains the tier and warning fields. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::path::{Path, PathBuf}; +use std::process::{Command, Output}; +use std::str::FromStr; + +use id::encryption::warnings::Warning; +use id::groups::Role; +use id::groups::log::GroupLog; +use p2panda_core::Hash; +use tempfile::TempDir; + +/// One node: its data directory. The group log is shared by every node of a test. +struct Node { + dir: PathBuf, + log: PathBuf, +} + +impl Node { + /// Runs `id` as this node, with the shared group log. + fn run(&self, args: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_id")) + .arg("--data-dir") + .arg(&self.dir) + .arg("--groups-log") + .arg(&self.log) + .args(args) + .output() + .expect("run id") + } + + /// Runs a command that must succeed, and returns its stdout. + fn ok(&self, args: &[&str]) -> String { + let output = self.run(args); + assert!( + output.status.success(), + "{args:?} failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + String::from_utf8_lossy(&output.stdout).into_owned() + } + + /// This node's account key, as `id id` prints it. + fn key(&self) -> String { + self.ok(&["id"]).trim().to_owned() + } +} + +fn node(root: &Path, name: &str, log: &Path) -> Node { + Node { + dir: root.join(name), + log: log.to_path_buf(), + } +} + +/// The value of `key` in a line of `key=value` tokens. +fn field(line: &str, key: &str) -> String { + line.split_whitespace() + .find_map(|token| token.strip_prefix(&format!("{key}="))) + .unwrap_or_else(|| panic!("no {key}= in {line:?}")) + .to_owned() +} + +fn hash(text: &str) -> Hash { + Hash::from_str(text).expect("64 hex characters") +} + +fn key_bytes(text: &str) -> [u8; 32] { + *hash(text).as_bytes() +} + +#[test] +fn test_default_group_has_tier_0_and_no_warning() { + let root = TempDir::new().unwrap(); + let log = root.path().join("groups.jsonl"); + let owner = node(root.path(), "owner", &log); + + let created = owner.ok(&["group", "create"]); + let group = field(&created, "group"); + + // Policy line: tier=0 and no warning + let policy = owner.ok(&["group", "policy", &group]); + assert_eq!(field(&policy, "tier"), "0"); + assert!(!policy.contains("warning=")); + + // Policy JSON: tier=0 and no warning key + let policy_json: serde_json::Value = + serde_json::from_str(owner.ok(&["group", "policy", &group, "--json"]).trim()).unwrap(); + assert_eq!(policy_json["tier"], 0); + assert!(policy_json.get("warning").is_none()); + + // List line: tier=0 and no warning + let list = owner.ok(&["group", "list"]); + let line = list + .lines() + .find(|l| field(l, "group") == group) + .expect("group is listed"); + assert_eq!(field(line, "tier"), "0"); + assert!(!line.contains("warning=")); + + // List JSON: tier=0 and no warning key + let list_json: serde_json::Value = + serde_json::from_str(owner.ok(&["group", "list", "--json"]).trim()).unwrap(); + let groups = list_json.as_array().expect("list is an array"); + let entry = groups + .iter() + .find(|g| g["group"] == group.as_str()) + .expect("group in json list"); + assert_eq!(entry["tier"], 0); + assert!(entry.get("warning").is_none()); +} + +#[test] +fn test_group_at_96_members_has_tier_96_and_size_warning() { + let root = TempDir::new().unwrap(); + let log = root.path().join("groups.jsonl"); + let owner = node(root.path(), "owner", &log); + + let created = owner.ok(&["group", "create"]); + let group = field(&created, "group"); + let owner_key = key_bytes(&owner.key()); + let group_hash = hash(&group); + + // Add 95 members so total member count reaches 96 (owner + 95) + let mut group_log = GroupLog::open(&log).unwrap(); + for i in 1..96 { + let mut member_key = [0u8; 32]; + member_key[..8].copy_from_slice(&(i as u64).to_be_bytes()); + group_log + .add(owner_key, group_hash, member_key, Role::Read) + .unwrap(); + } + + let expected_warning = Warning::Size { + threshold: 96, + members: 96, + } + .message(); + + // Policy line: tier=96 and size warning message shown + let policy = owner.ok(&["group", "policy", &group]); + assert_eq!(field(&policy, "tier"), "96"); + assert!(policy.contains(&expected_warning)); + + // Policy JSON: tier=96 and warning string field + let policy_json: serde_json::Value = + serde_json::from_str(owner.ok(&["group", "policy", &group, "--json"]).trim()).unwrap(); + assert_eq!(policy_json["tier"], 96); + assert_eq!(policy_json["warning"], expected_warning.as_str()); + + // List line: tier=96 and size warning message shown + let list = owner.ok(&["group", "list"]); + let line = list + .lines() + .find(|l| field(l, "group") == group) + .expect("group is listed"); + assert_eq!(field(line, "tier"), "96"); + assert_eq!(field(line, "members"), "96"); + assert!(line.contains(&expected_warning)); + + // List JSON: tier=96 and warning string field + let list_json: serde_json::Value = + serde_json::from_str(owner.ok(&["group", "list", "--json"]).trim()).unwrap(); + let groups = list_json.as_array().expect("list is an array"); + let entry = groups + .iter() + .find(|g| g["group"] == group.as_str()) + .expect("group in json list"); + assert_eq!(entry["tier"], 96); + assert_eq!(entry["members"], 96); + assert_eq!(entry["warning"], expected_warning.as_str()); +} + +#[test] +fn test_group_tier_transitions_and_warning_messages() { + let root = TempDir::new().unwrap(); + let log = root.path().join("groups.jsonl"); + let owner = node(root.path(), "owner", &log); + + let created = owner.ok(&["group", "create"]); + let group = field(&created, "group"); + let owner_key = key_bytes(&owner.key()); + let group_hash = hash(&group); + + let mut group_log = GroupLog::open(&log).unwrap(); + for i in 1..100 { + let mut member_key = [0u8; 32]; + member_key[..8].copy_from_slice(&(i as u64).to_be_bytes()); + group_log + .add(owner_key, group_hash, member_key, Role::Read) + .unwrap(); + } + + // At 100 members: tier=96, warning mentions 100 now + let expected_warning_100 = Warning::Size { + threshold: 96, + members: 100, + } + .message(); + let policy_json: serde_json::Value = + serde_json::from_str(owner.ok(&["group", "policy", &group, "--json"]).trim()).unwrap(); + assert_eq!(policy_json["tier"], 96); + assert_eq!(policy_json["warning"], expected_warning_100.as_str()); + + // Add up to 128 members (28 more) + for i in 100..128 { + let mut member_key = [0u8; 32]; + member_key[..8].copy_from_slice(&(i as u64).to_be_bytes()); + group_log + .add(owner_key, group_hash, member_key, Role::Read) + .unwrap(); + } + + // At 128 members: tier=128 + let expected_warning_128 = Warning::Size { + threshold: 128, + members: 128, + } + .message(); + let policy_json: serde_json::Value = + serde_json::from_str(owner.ok(&["group", "policy", &group, "--json"]).trim()).unwrap(); + assert_eq!(policy_json["tier"], 128); + assert_eq!(policy_json["warning"], expected_warning_128.as_str()); +} diff --git a/pkgs/id/tests/multidevice.rs b/pkgs/id/tests/multidevice.rs new file mode 100644 index 0000000000..35282970ba --- /dev/null +++ b/pkgs/id/tests/multidevice.rs @@ -0,0 +1,391 @@ +//! Multi-device capability delegation and revocation integration tests (P8.3). +//! +//! Checks: +//! - Account authorizes Device 1 and Device 2 via `device.add`. Both can act with the account's authority. +//! - Revoking Device 1 via `device.revoke` severs Device 1's authority while Device 2 remains valid. +//! - Removing the account revokes both devices. +//! - Device count helper accurately returns the active device count. + +#![allow(clippy::unwrap_used, clippy::expect_used)] + +use p2panda_core::Hash; +use tempfile::TempDir; + +use id::groups::log::GroupLog; +use id::groups::{ + Body, Create, DEVICE_ADD_KIND, DEVICE_REVOKE_KIND, DeviceOp, Event, Key, MemberOp, Outcome, + Policy, Refusal, Role, Template, fold, +}; + +fn key(n: u8) -> Key { + [n; 32] +} + +fn id(name: &str) -> Hash { + Hash::digest(name.as_bytes()) +} + +fn after(names: &[&str]) -> Vec { + names.iter().map(|name| id(name)).collect() +} + +fn event(name: &str, author: u8, after_names: &[&str], group: Option, body: Body) -> Event { + Event { + id: id(name), + author: key(author), + after: after(after_names), + group, + body, + } +} + +fn create_group(name: &str, author: u8, members: &[(u8, Role)]) -> Event { + let members = members.iter().map(|(n, role)| (key(*n), *role)).collect(); + let body = Body::Create(Create { + template: Template::Custom, + policy: Policy::default(), + members, + admins_on_create: false, + }); + event(name, author, &[], None, body) +} + +fn device_add( + name: &str, + account: u8, + group: Hash, + device: u8, + scope: Role, + after_names: &[&str], +) -> Event { + event( + name, + account, + after_names, + Some(group), + Body::Device(DeviceOp::Add { + device: key(device), + scope, + }), + ) +} + +fn device_revoke(name: &str, account: u8, group: Hash, device: u8, after_names: &[&str]) -> Event { + event( + name, + account, + after_names, + Some(group), + Body::Device(DeviceOp::Revoke { + device: key(device), + }), + ) +} + +fn member_add( + name: &str, + by: u8, + group: Hash, + member: u8, + role: Role, + after_names: &[&str], +) -> Event { + event( + name, + by, + after_names, + Some(group), + Body::Member(MemberOp::Add { + member: key(member), + role, + }), + ) +} + +fn member_remove(name: &str, by: u8, group: Hash, member: u8, after_names: &[&str]) -> Event { + event( + name, + by, + after_names, + Some(group), + Body::Member(MemberOp::Remove { + member: key(member), + successor: None, + }), + ) +} + +#[test] +fn test_kind_constants_match_specification() { + assert_eq!(DEVICE_ADD_KIND, "device.add"); + assert_eq!(DEVICE_REVOKE_KIND, "device.revoke"); +} + +#[test] +fn test_devices_act_with_account_authority() { + let g = id("g"); + let events = vec![ + create_group("g", 1, &[]), + device_add("dev1_add", 1, g, 11, Role::Manage, &["g"]), + device_add("dev2_add", 1, g, 12, Role::Manage, &["dev1_add"]), + // Device 1 (key 11) acts with Account 1's authority to add Member 2 + member_add("add_m2", 11, g, 2, Role::Write, &["dev2_add"]), + // Device 2 (key 12) acts with Account 1's authority to add Member 3 + member_add("add_m3", 12, g, 3, Role::Write, &["add_m2"]), + ]; + + let p = fold(&events).expect("fold succeeds"); + assert_eq!(p.outcome(&id("dev1_add")), Some(&Outcome::Applied)); + assert_eq!(p.outcome(&id("dev2_add")), Some(&Outcome::Applied)); + assert_eq!( + p.outcome(&id("add_m2")), + Some(&Outcome::Applied), + "Device 1 acts with Account 1's authority" + ); + assert_eq!( + p.outcome(&id("add_m3")), + Some(&Outcome::Applied), + "Device 2 acts with Account 1's authority" + ); + + let view = p.group(&g).expect("group exists"); + assert!(view.members.contains_key(&key(2))); + assert!(view.members.contains_key(&key(3))); +} + +#[test] +fn test_revoking_device_severs_authority_while_other_remains_valid() { + let g = id("g"); + let events = vec![ + create_group("g", 1, &[]), + device_add("dev1_add", 1, g, 11, Role::Manage, &["g"]), + device_add("dev2_add", 1, g, 12, Role::Manage, &["dev1_add"]), + // Revoke Device 1 + device_revoke("dev1_rev", 1, g, 11, &["dev2_add"]), + // Device 1 attempts to act after revocation -> refused + member_add("add_m4_by_dev1", 11, g, 4, Role::Write, &["dev1_rev"]), + // Device 2 remains valid and acts -> applied + member_add("add_m5_by_dev2", 12, g, 5, Role::Write, &["dev1_rev"]), + ]; + + let p = fold(&events).expect("fold succeeds"); + assert_eq!(p.outcome(&id("dev1_rev")), Some(&Outcome::Applied)); + assert_eq!( + p.outcome(&id("add_m4_by_dev1")), + Some(&Outcome::Refused(Refusal::NotActive)), + "Revoking Device 1 severs Device 1's authority" + ); + assert_eq!( + p.outcome(&id("add_m5_by_dev2")), + Some(&Outcome::Applied), + "Device 2 remains valid and authorized" + ); + + let view = p.group(&g).expect("group exists"); + assert!(!view.members.contains_key(&key(4))); + assert!(view.members.contains_key(&key(5))); +} + +#[test] +fn test_removing_account_revokes_both_devices() { + let g = id("g"); + // Founder 99 creates group and adds Account 1 as Manage + let events = vec![ + create_group("g", 99, &[(1, Role::Manage)]), + device_add("dev1_add", 1, g, 11, Role::Manage, &["g"]), + device_add("dev2_add", 1, g, 12, Role::Manage, &["dev1_add"]), + // Device 1 successfully adds member 2 before removal + member_add("add_m2", 11, g, 2, Role::Write, &["dev2_add"]), + // Founder removes Account 1 + member_remove("rem_acct1", 99, g, 1, &["add_m2"]), + // Device 1 attempts to act after account removal -> refused + member_add("add_m3_by_dev1", 11, g, 3, Role::Write, &["rem_acct1"]), + // Device 2 attempts to act after account removal -> refused + member_add("add_m4_by_dev2", 12, g, 4, Role::Write, &["rem_acct1"]), + ]; + + let p = fold(&events).expect("fold succeeds"); + assert_eq!(p.outcome(&id("add_m2")), Some(&Outcome::Applied)); + assert_eq!(p.outcome(&id("rem_acct1")), Some(&Outcome::Applied)); + assert_eq!( + p.outcome(&id("add_m3_by_dev1")), + Some(&Outcome::Refused(Refusal::NotActive)), + "Removing account revokes Device 1" + ); + assert_eq!( + p.outcome(&id("add_m4_by_dev2")), + Some(&Outcome::Refused(Refusal::NotActive)), + "Removing account revokes Device 2" + ); + + let view = p.group(&g).expect("group exists"); + assert!(!view.members.contains_key(&key(1))); + assert!(view.members.contains_key(&key(2))); + assert!(!view.members.contains_key(&key(3))); + assert!(!view.members.contains_key(&key(4))); +} + +#[test] +fn test_device_count_helper_accurately_returns_active_device_count() { + let g = id("g"); + // Baseline: no devices authorized yet + let base = vec![create_group("g", 1, &[(2, Role::Manage)])]; + let p0 = fold(&base).expect("fold succeeds"); + assert_eq!(p0.active_device_count(&g, &key(1)), 0); + assert_eq!(p0.group_device_count(&g), 0); + + // Account 1 authorizes Device 1 and Device 2; Account 2 authorizes Device 3 + let mut step1 = base; + step1.push(device_add("dev1_add", 1, g, 11, Role::Manage, &["g"])); + step1.push(device_add( + "dev2_add", + 1, + g, + 12, + Role::Manage, + &["dev1_add"], + )); + step1.push(device_add( + "dev3_add", + 2, + g, + 21, + Role::Manage, + &["dev2_add"], + )); + + let p1 = fold(&step1).expect("fold succeeds"); + assert_eq!( + p1.active_device_count(&g, &key(1)), + 2, + "Account 1 has 2 active devices" + ); + assert_eq!( + p1.active_device_count(&g, &key(2)), + 1, + "Account 2 has 1 active device" + ); + assert_eq!( + p1.group_device_count(&g), + 3, + "Group has 3 active devices in total" + ); + + // Account 1 revokes Device 1 + let mut step2 = step1; + step2.push(device_revoke("dev1_rev", 1, g, 11, &["dev3_add"])); + let p2 = fold(&step2).expect("fold succeeds"); + assert_eq!( + p2.active_device_count(&g, &key(1)), + 1, + "Account 1 now has 1 active device (Device 2)" + ); + assert_eq!( + p2.group_device_count(&g), + 2, + "Group now has 2 active devices" + ); + + // Account 1 leaves (removes itself) -> cascade severs Account 1's remaining device (Device 2) + let mut step3 = step2; + step3.push(member_remove("rem_acct1", 1, g, 1, &["dev1_rev"])); + let p3 = fold(&step3).expect("fold succeeds"); + assert_eq!( + p3.active_device_count(&g, &key(1)), + 0, + "Removed account has 0 active devices" + ); + assert_eq!( + p3.active_device_count(&g, &key(2)), + 1, + "Account 2 still has 1 active device" + ); + assert_eq!( + p3.group_device_count(&g), + 1, + "Group has 1 active device remaining" + ); +} + +#[test] +fn test_group_log_multidevice_integration() { + let dir = TempDir::new().expect("tempdir"); + let log_path = dir.path().join("groups.jsonl"); + let mut log = GroupLog::open(&log_path).expect("open log"); + + let author_acct = key(1); + let dev1 = key(11); + let dev2 = key(12); + + let create_action = log + .create( + author_acct, + id::groups::actions::NewGroup::Normal { + max: None, + admins_on_create: false, + }, + ) + .expect("create group"); + let group = create_action.group; + + assert_eq!(log.active_device_count(&group, &author_acct).unwrap(), 0); + assert_eq!(log.group_device_count(&group).unwrap(), 0); + + // Authorize Device 1 and Device 2 + let add1 = log + .device_add(author_acct, group, dev1, Role::Manage) + .expect("device_add dev1"); + assert_eq!(add1.outcome, Outcome::Applied); + + let add2 = log + .device_add(author_acct, group, dev2, Role::Manage) + .expect("device_add dev2"); + assert_eq!(add2.outcome, Outcome::Applied); + + assert_eq!(log.active_device_count(&group, &author_acct).unwrap(), 2); + assert_eq!(log.group_device_count(&group).unwrap(), 2); + + // Device 1 adds Member 2 + let add_m2 = log + .add(dev1, group, key(2), Role::Write) + .expect("dev1 add member"); + assert_eq!( + add_m2.outcome, + Outcome::Applied, + "Device 1 acts with account authority" + ); + + // Revoke Device 1 + let rev1 = log + .device_revoke(author_acct, group, dev1) + .expect("revoke dev1"); + assert_eq!(rev1.outcome, Outcome::Applied); + + assert_eq!(log.active_device_count(&group, &author_acct).unwrap(), 1); + assert_eq!(log.group_device_count(&group).unwrap(), 1); + + // Device 1 attempting to act is now refused + let add_m3_by_dev1 = log + .add(dev1, group, key(3), Role::Write) + .expect("dev1 add member after revoke"); + assert_eq!( + add_m3_by_dev1.outcome, + Outcome::Refused(Refusal::NotActive), + "Revoked device authority is severed" + ); + + // Device 2 can still act + let add_m4_by_dev2 = log + .add(dev2, group, key(4), Role::Write) + .expect("dev2 add member"); + assert_eq!( + add_m4_by_dev2.outcome, + Outcome::Applied, + "Device 2 remains valid" + ); + + let view = log.view(group).expect("view group"); + assert!(view.members.contains_key(&key(2))); + assert!(!view.members.contains_key(&key(3))); + assert!(view.members.contains_key(&key(4))); +} diff --git a/pkgs/id/tests/retention_pruning.rs b/pkgs/id/tests/retention_pruning.rs new file mode 100644 index 0000000000..b555707d18 --- /dev/null +++ b/pkgs/id/tests/retention_pruning.rs @@ -0,0 +1,441 @@ +//! Integration tests for retention and pruning behind a causal cut (Phase 8, P8.2). +//! +//! Pruning removes events behind a causal cut while protecting: +//! 1. Every event in the causal past of open removals (needed for membership voidness check). +//! 2. Open frontiers and active backlink chains. +//! +//! Invariants (`check_invariants`) and query folds (roster, live tag claims, documents) +//! produce identical results before and after pruning. + +#![allow(clippy::unwrap_used, clippy::expect_used)] + +use std::collections::BTreeMap; +use std::path::Path; + +use id::chain::{ChainExt, Event, sign}; +use id::documents::{DOCUMENT_KIND, DocumentRef}; +use id::event_store::EventStore; +use id::membership::AuthId; +use id::membership::body::encode_body; +use id::tag_claims::{CLEAR_KIND, SET_KIND, TagOp}; +use id::waiting::WaitingLimits; +use p2panda_auth::Access; +use p2panda_auth::group::{GroupAction, GroupMember}; +use p2panda_core::{Hash, SeqNum, SigningKey}; + +const GROUP_OP: &str = "group.op"; + +fn key(n: u8) -> SigningKey { + SigningKey::from_bytes(&[n; 32]) +} + +fn auth(n: u8) -> AuthId { + AuthId::Key(*key(n).verifying_key().as_bytes()) +} + +fn open(dir: &Path) -> EventStore { + EventStore::open(dir, WaitingLimits::default(), 0).unwrap() +} + +#[derive(Default)] +struct Chains { + last: BTreeMap, +} + +impl Chains { + fn new() -> Self { + Self::default() + } + + fn sign( + &mut self, + who: u8, + group: Option, + after: &[Hash], + kind: &str, + body: Option>, + tag: Option, + document: Option, + ) -> (Event, Option>) { + let (seq, backlink) = match self.last.get(&who) { + Some((seq, hash)) => (seq + 1, Some(*hash)), + None => (0, None), + }; + let ext = ChainExt { + kind: kind.to_owned(), + group, + after: after.to_vec(), + tag, + document, + removes: None, + }; + let event = sign(&key(who), seq, backlink, body.as_deref(), ext).unwrap(); + self.last.insert(who, (seq, event.id)); + (event, body) + } + + fn group_op( + &mut self, + who: u8, + group: Option, + after: &[Hash], + action: &GroupAction, + ) -> (Event, Option>) { + let body = encode_body(action).unwrap(); + self.sign(who, group, after, GROUP_OP, Some(body), None, None) + } + + fn document( + &mut self, + who: u8, + group: Hash, + after: &[Hash], + doc_hash: Hash, + ) -> (Event, Option>) { + let doc = DocumentRef { + media_type: "text/plain".to_owned(), + content: doc_hash, + size: 100, + }; + self.sign( + who, + Some(group), + after, + DOCUMENT_KIND, + None, + None, + Some(doc), + ) + } + + fn tag_set( + &mut self, + who: u8, + group: Hash, + after: &[Hash], + subject: Hash, + name: &str, + ) -> (Event, Option>) { + let op = TagOp::Set { + subject, + name: name.to_owned(), + value: None, + }; + self.sign(who, Some(group), after, SET_KIND, None, Some(op), None) + } + + fn tag_clear( + &mut self, + who: u8, + group: Hash, + after: &[Hash], + claims: Vec, + ) -> (Event, Option>) { + let op = TagOp::Clear { claims }; + self.sign(who, Some(group), after, CLEAR_KIND, None, Some(op), None) + } +} + +fn deliver(store: &mut EventStore, event: &Event, body: Option<&[u8]>) { + store.ingest_with_body(&event.bytes, body, 0).unwrap(); +} + +#[test] +fn test_retention_pruning_respects_open_removals_and_frontiers() { + let dir = tempfile::tempdir().unwrap(); + let mut store = open(dir.path()); + let mut chains = Chains::new(); + + // 1. Author 1 (Alice) creates group G + let (create, create_body) = chains.group_op( + 1, + None, + &[], + &GroupAction::Create { + initial_members: vec![(GroupMember::Individual(auth(1)), Access::manage())], + }, + ); + let group = create.id; + deliver(&mut store, &create, create_body.as_deref()); + + // 2. Alice adds Author 2 (Bob) + let (add_bob, add_bob_body) = chains.group_op( + 1, + Some(group), + &[create.id], + &GroupAction::Add { + member: GroupMember::Individual(auth(2)), + access: Access::read(), + }, + ); + deliver(&mut store, &add_bob, add_bob_body.as_deref()); + + // 3. Alice adds Author 3 (Charlie) + let (add_charlie, add_charlie_body) = chains.group_op( + 1, + Some(group), + &[add_bob.id], + &GroupAction::Add { + member: GroupMember::Individual(auth(3)), + access: Access::read(), + }, + ); + deliver(&mut store, &add_charlie, add_charlie_body.as_deref()); + + // 4. Bob publishes a document D1 + let (doc1, doc1_body) = chains.document( + 2, + group, + &[add_bob.id], + Hash::digest(b"shared document content 1"), + ); + deliver(&mut store, &doc1, doc1_body.as_deref()); + + // 5. Bob sets a tag T1 on D1 + let (tag1, tag1_body) = chains.tag_set(2, group, &[doc1.id], doc1.id, "tag-bob-1"); + deliver(&mut store, &tag1, tag1_body.as_deref()); + + // 6. Bob clears tag T1 + let (clear1, clear1_body) = chains.tag_clear(2, group, &[tag1.id], vec![tag1.id]); + deliver(&mut store, &clear1, clear1_body.as_deref()); + + // 7. Charlie publishes a document D2 and tag T2 + let (doc2, doc2_body) = chains.document( + 3, + group, + &[add_charlie.id], + Hash::digest(b"shared document content 2"), + ); + deliver(&mut store, &doc2, doc2_body.as_deref()); + + let (tag2, tag2_body) = chains.tag_set(3, group, &[doc2.id], doc2.id, "tag-charlie-live"); + deliver(&mut store, &tag2, tag2_body.as_deref()); + + // 8. Alice removes Bob. The removal names doc1 and doc2 in `after`, but did NOT see tag1 or clear1! + let (removal, removal_body) = chains.group_op( + 1, + Some(group), + &[add_charlie.id, doc1.id, doc2.id], + &GroupAction::Remove { + member: GroupMember::Individual(auth(2)), + }, + ); + deliver(&mut store, &removal, removal_body.as_deref()); + + // 9. Alice publishes a later document D3 seeing the removal + let (doc3, doc3_body) = chains.document( + 1, + group, + &[removal.id], + Hash::digest(b"post-removal document 3"), + ); + deliver(&mut store, &doc3, doc3_body.as_deref()); + + // Verify baseline invariants and query states before pruning + store.check_invariants().unwrap(); + + let roster_before = store.roster(&group).unwrap(); + assert_eq!( + roster_before, + vec![ + *key(1).verifying_key().as_bytes(), + *key(3).verifying_key().as_bytes() + ] + ); + + let docs_before = store.documents().unwrap(); + assert_eq!(docs_before.len(), 3); + + let claims_before = store.tag_claims().unwrap(); + assert_eq!(claims_before.len(), 1); + assert_eq!(claims_before[0].name, "tag-charlie-live"); + + // Events in store before pruning + assert!(store.event_by_id(&tag1.id).unwrap().is_some()); + assert!(store.event_by_id(&clear1.id).unwrap().is_some()); + assert!(store.event_by_id(&doc1.id).unwrap().is_some()); + assert!(store.event_by_id(&removal.id).unwrap().is_some()); + + // Define the causal cut and the protected past: + // Protected: open removal and open frontier + let protected = vec![removal.id, doc3.id]; + // Cut boundary includes the old cleared tag branch + let cut = vec![clear1.id, removal.id]; + + // Prune behind the cut + let pruned_count = store.prune_behind_cut(&cut, &protected).unwrap(); + assert!( + pruned_count >= 1, + "at least clear1 and tag1 should be pruned" + ); + + // Verify unneeded events were pruned + assert!(store.event_by_id(&clear1.id).unwrap().is_none()); + assert!(store.event_by_id(&tag1.id).unwrap().is_none()); + + // Verify the removal and its causal past (doc1, create, add_bob, add_charlie) survived + assert!(store.event_by_id(&removal.id).unwrap().is_some()); + assert!(store.event_by_id(&doc1.id).unwrap().is_some()); + assert!(store.event_by_id(&doc2.id).unwrap().is_some()); + assert!(store.event_by_id(&create.id).unwrap().is_some()); + assert!(store.event_by_id(&add_bob.id).unwrap().is_some()); + assert!(store.event_by_id(&add_charlie.id).unwrap().is_some()); + assert!(store.event_by_id(&doc3.id).unwrap().is_some()); + + // Invariants check still passes + store.check_invariants().unwrap(); + + // Roster and fold queries produce identical results + let roster_after = store.roster(&group).unwrap(); + assert_eq!(roster_before, roster_after); + + let docs_after = store.documents().unwrap(); + assert_eq!(docs_before, docs_after); + + let claims_after = store.tag_claims().unwrap(); + assert_eq!(claims_before, claims_after); +} + +#[test] +fn test_prune_behind_cut_empty_or_noop() { + let dir = tempfile::tempdir().unwrap(); + let mut store = open(dir.path()); + let mut chains = Chains::new(); + + let (create, create_body) = chains.group_op( + 1, + None, + &[], + &GroupAction::Create { + initial_members: vec![(GroupMember::Individual(auth(1)), Access::manage())], + }, + ); + deliver(&mut store, &create, create_body.as_deref()); + + // Empty cut prunes 0 + let count = store.prune_behind_cut(&[], &[create.id]).unwrap(); + assert_eq!(count, 0); + + // Protected matches cut prunes 0 + let count = store.prune_behind_cut(&[create.id], &[create.id]).unwrap(); + assert_eq!(count, 0); + + store.check_invariants().unwrap(); +} + +#[test] +fn test_prune_removes_unreferenced_author_chain_completely() { + let dir = tempfile::tempdir().unwrap(); + let mut store = open(dir.path()); + let mut chains = Chains::new(); + + // Alice creates group + let (create, create_body) = chains.group_op( + 1, + None, + &[], + &GroupAction::Create { + initial_members: vec![(GroupMember::Individual(auth(1)), Access::manage())], + }, + ); + let group = create.id; + deliver(&mut store, &create, create_body.as_deref()); + + // Author 4 (Dave) writes a standalone message/doc outside the group or in group + let (doc_dave, doc_dave_body) = + chains.document(4, group, &[create.id], Hash::digest(b"dave standalone doc")); + deliver(&mut store, &doc_dave, doc_dave_body.as_deref()); + + // Alice writes a document D2 seeing only create + let (doc_alice, doc_alice_body) = + chains.document(1, group, &[create.id], Hash::digest(b"alice doc")); + deliver(&mut store, &doc_alice, doc_alice_body.as_deref()); + + store.check_invariants().unwrap(); + assert!(store.event_by_id(&doc_dave.id).unwrap().is_some()); + assert!( + store + .chain(&*key(4).verifying_key().as_bytes()) + .unwrap() + .is_some() + ); + + // Cut includes doc_dave, protected includes doc_alice + let count = store + .prune_behind_cut(&[doc_dave.id], &[doc_alice.id]) + .unwrap(); + assert_eq!(count, 1); + + // Dave's event is pruned and Dave's chain row is deleted + assert!(store.event_by_id(&doc_dave.id).unwrap().is_none()); + assert!( + store + .chain(&*key(4).verifying_key().as_bytes()) + .unwrap() + .is_none() + ); + + // Invariants still hold + store.check_invariants().unwrap(); +} + +#[test] +fn test_active_backlink_walks_preserved_for_tail_prune() { + let dir = tempfile::tempdir().unwrap(); + let mut store = open(dir.path()); + let mut chains = Chains::new(); + + // Alice creates group + let (create, create_body) = chains.group_op( + 1, + None, + &[], + &GroupAction::Create { + initial_members: vec![(GroupMember::Individual(auth(1)), Access::manage())], + }, + ); + let group = create.id; + deliver(&mut store, &create, create_body.as_deref()); + + // Bob writes doc B0, then B1, then B2 + let (b0, b0_body) = chains.document(2, group, &[create.id], Hash::digest(b"b0")); + deliver(&mut store, &b0, b0_body.as_deref()); + + let (b1, b1_body) = chains.document(2, group, &[b0.id], Hash::digest(b"b1")); + deliver(&mut store, &b1, b1_body.as_deref()); + + let (b2, b2_body) = chains.document(2, group, &[b1.id], Hash::digest(b"b2")); + deliver(&mut store, &b2, b2_body.as_deref()); + + // Alice creates removal or anchor pointing to b1 (so b1, b0, create are in protected past) + let (removal, removal_body) = chains.group_op( + 1, + Some(group), + &[b1.id], + &GroupAction::Remove { + member: GroupMember::Individual(auth(2)), + }, + ); + deliver(&mut store, &removal, removal_body.as_deref()); + + store.check_invariants().unwrap(); + + // Cut is b2, protected is removal (which saw b1, but not b2) + let count = store.prune_behind_cut(&[b2.id], &[removal.id]).unwrap(); + assert_eq!(count, 1, "b2 should be pruned"); + + assert!(store.event_by_id(&b2.id).unwrap().is_none()); + assert!(store.event_by_id(&b1.id).unwrap().is_some()); + assert!(store.event_by_id(&b0.id).unwrap().is_some()); + + // Bob's chain should now have head = b1 and next_seq = 2 + let bob_chain = store + .chain(&*key(2).verifying_key().as_bytes()) + .unwrap() + .unwrap(); + assert_eq!(bob_chain.next_seq, 2); + assert_eq!(bob_chain.head, Some(b1.id)); + + // Invariants check still passes + store.check_invariants().unwrap(); +} diff --git a/pkgs/id/tests/views_explorer.rs b/pkgs/id/tests/views_explorer.rs new file mode 100644 index 0000000000..d4808de577 --- /dev/null +++ b/pkgs/id/tests/views_explorer.rs @@ -0,0 +1,174 @@ +//! Tests for directory explorer sections (waiting, voided, and frozen events). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use id::directory_view::{DirectoryView, FrozenView, VoidedView, WaitingView, render_text}; +use serde_json::Value; + +#[test] +fn test_waiting_events_rendered_with_exact_reason() { + let view = DirectoryView { + viewer: "admin".to_owned(), + accounts: Vec::new(), + groups: Vec::new(), + deliveries: Vec::new(), + waiting: vec![ + WaitingView::new("evt-w1", "hash-dep-abc"), + WaitingView::new("evt-w2", "hash-dep-def"), + ], + voided: Vec::new(), + frozen: Vec::new(), + }; + + let text = render_text(&view); + assert!(text.contains("waiting:")); + assert!(text.contains(" evt-w1 hash-dep-abc waiting: missing hash-dep-abc")); + assert!(text.contains(" evt-w2 hash-dep-def waiting: missing hash-dep-def")); +} + +#[test] +fn test_voided_events_rendered_with_exact_reason() { + let view = DirectoryView { + viewer: "admin".to_owned(), + accounts: Vec::new(), + groups: Vec::new(), + deliveries: Vec::new(), + waiting: Vec::new(), + voided: vec![ + VoidedView::new("evt-v1", "hash-rem-123"), + VoidedView::new("evt-v2", "hash-rem-456"), + ], + frozen: Vec::new(), + }; + + let text = render_text(&view); + assert!(text.contains("voided:")); + assert!(text.contains(" evt-v1 hash-rem-123 voided: concurrent with hash-rem-123")); + assert!(text.contains(" evt-v2 hash-rem-456 voided: concurrent with hash-rem-456")); +} + +#[test] +fn test_frozen_chains_rendered_with_exact_reason() { + let view = DirectoryView { + viewer: "admin".to_owned(), + accounts: Vec::new(), + groups: Vec::new(), + deliveries: Vec::new(), + waiting: Vec::new(), + voided: Vec::new(), + frozen: vec![ + FrozenView::new("author-f1", 7, "proof-hash-789"), + FrozenView::new("author-f2", 0, "proof-hash-000"), + ], + }; + + let text = render_text(&view); + assert!(text.contains("frozen:")); + assert!(text.contains(" author-f1 proof-hash-789 frozen: fork at seq 7")); + assert!(text.contains(" author-f2 proof-hash-000 frozen: fork at seq 0")); +} + +#[test] +fn test_empty_sections_omitted_or_none() { + let view = DirectoryView { + viewer: "anonymous".to_owned(), + accounts: Vec::new(), + groups: Vec::new(), + deliveries: Vec::new(), + waiting: Vec::new(), + voided: Vec::new(), + frozen: Vec::new(), + }; + + let text = render_text(&view); + assert!(!text.contains("waiting:")); + assert!(!text.contains("voided:")); + assert!(!text.contains("frozen:")); + assert!(text.contains("accounts:\n (none)")); + assert!(text.contains("groups:\n (none)")); +} + +#[test] +fn test_json_serialization_includes_waiting_voided_and_frozen_arrays() { + let view = DirectoryView { + viewer: "admin".to_owned(), + accounts: Vec::new(), + groups: Vec::new(), + deliveries: Vec::new(), + waiting: vec![WaitingView::new("evt-w1", "hash-dep-abc")], + voided: vec![VoidedView::new("evt-v1", "hash-rem-123")], + frozen: vec![FrozenView::new("author-f1", 12, "proof-hash-456")], + }; + + let val = serde_json::to_value(&view).expect("serialize DirectoryView"); + + let waiting_arr = val + .get("waiting") + .and_then(Value::as_array) + .expect("waiting array"); + assert_eq!(waiting_arr.len(), 1); + assert_eq!(waiting_arr[0]["id"], "evt-w1"); + assert_eq!(waiting_arr[0]["missing"], "hash-dep-abc"); + assert_eq!(waiting_arr[0]["reason"], "waiting: missing hash-dep-abc"); + + let voided_arr = val + .get("voided") + .and_then(Value::as_array) + .expect("voided array"); + assert_eq!(voided_arr.len(), 1); + assert_eq!(voided_arr[0]["id"], "evt-v1"); + assert_eq!(voided_arr[0]["removal"], "hash-rem-123"); + assert_eq!( + voided_arr[0]["reason"], + "voided: concurrent with hash-rem-123" + ); + + let frozen_arr = val + .get("frozen") + .and_then(Value::as_array) + .expect("frozen array"); + assert_eq!(frozen_arr.len(), 1); + assert_eq!(frozen_arr[0]["id"], "author-f1"); + assert_eq!(frozen_arr[0]["seq"], 12); + assert_eq!(frozen_arr[0]["proof"], "proof-hash-456"); + assert_eq!(frozen_arr[0]["reason"], "frozen: fork at seq 12"); + + // Roundtrip verification + let json_str = serde_json::to_string(&view).expect("to string"); + let deserialized: DirectoryView = serde_json::from_str(&json_str).expect("deserialize"); + assert_eq!(view, deserialized); +} + +#[test] +fn test_mixed_view_shared_types_and_in_step_rendering() { + let view = DirectoryView { + viewer: "acct-viewer".to_owned(), + accounts: Vec::new(), + groups: Vec::new(), + deliveries: Vec::new(), + waiting: vec![WaitingView::new("wait-1", "dep-hash-x")], + voided: vec![VoidedView::new("void-1", "rem-hash-y")], + frozen: vec![FrozenView::new("froz-1", 3, "proof-hash-z")], + }; + + let text = render_text(&view); + let val = serde_json::to_value(&view).expect("serialize"); + + // In step: exact reasons match between text and JSON + assert_eq!( + val["waiting"][0]["reason"].as_str().unwrap(), + "waiting: missing dep-hash-x" + ); + assert!(text.contains("waiting: missing dep-hash-x")); + + assert_eq!( + val["voided"][0]["reason"].as_str().unwrap(), + "voided: concurrent with rem-hash-y" + ); + assert!(text.contains("voided: concurrent with rem-hash-y")); + + assert_eq!( + val["frozen"][0]["reason"].as_str().unwrap(), + "frozen: fork at seq 3" + ); + assert!(text.contains("frozen: fork at seq 3")); +}