From fcd740acd51b0dd1e40535b1968c8fc06f27e1eb Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 1 Nov 2026 14:43:23 -0600 Subject: [PATCH 1/2] =?UTF-8?q?feat(id):=20chat=20v1=20core=20remainder=20?= =?UTF-8?q?=E2=80=94=20store=20wiring,=20membership/history=20enforcement,?= =?UTF-8?q?=20rate=20admission=20(#3950)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ChainExt gains a chat field (mirrors document): a chat.message.v1 event carries its ChatMessage in the signed header, validated by ChainExt::validate (chat body required for the chat kind, refused for every other kind, message checked). Events without a chat body keep their exact wire encoding. EventStore (new event_store/chat.rs): - chat_records(group): the record conversion — applied chat events of the group become ChatRecords with after from the extension and the backlink from the header, the shape the causal projection consumes. - group_policy(group): the group's policy record from the resolved fold. - chat_timeline(group, reader): the policy-enforcing read — a non-member is refused (StoreError::NotMember); a member gets the projected timeline cut by the policy history rule via chat::visible_history. FromJoin shows only records causally following the reader's join event; Recent/Causal are narrowed conservatively to that set (their message-level meaning is deferred in the design, as in the encryption history layer). LocalEvents::send_chat: write admission — the message is checked, the node's key must be on the group roster, and a sliding-window SendRate (world-chat starting configuration, 50 per 10 seconds, with a ChatRateConfig seam) must admit the send before anything is signed. Tests: two independent members exchange signed chat events through two stores with duplicate and out-of-order delivery and project identical timelines; non-member writes refused at admission and non-member reads refused; rate burst/refusal at both the limiter and the send path; conversion binds records to their group. Full lib suite on the laptop: 1491 passed, 1 pre-existing failure (store_traits sqlite lock test — sqlx/sqlx-macros-core gained sqlx-sqlite edges in the lock with the sqlx 0.9.0 update, PR #632; this diff touches no manifest or lock). Queue task 5893. --- pkgs/id/src/attestation.rs | 2 + pkgs/id/src/chain.rs | 32 ++ pkgs/id/src/chat.rs | 182 ++++++++++- pkgs/id/src/event_store/chat.rs | 389 ++++++++++++++++++++++++ pkgs/id/src/event_store/ingest.rs | 3 + pkgs/id/src/event_store/mod.rs | 5 + pkgs/id/src/event_store/sync.rs | 4 + pkgs/id/src/idset.rs | 1 + pkgs/id/src/local_events.rs | 210 ++++++++++++- pkgs/id/src/log_sync.rs | 2 + pkgs/id/src/store_traits.rs | 1 + pkgs/id/tests/aliases.rs | 1 + pkgs/id/tests/bridge_poc.rs | 2 + pkgs/id/tests/chain_properties.rs | 3 + pkgs/id/tests/cli_documents.rs | 1 + pkgs/id/tests/content_removal.rs | 3 + pkgs/id/tests/crash/store.rs | 1 + pkgs/id/tests/documents.rs | 3 + pkgs/id/tests/event_store_properties.rs | 4 + pkgs/id/tests/production_ingest.rs | 2 + pkgs/id/tests/retention_pruning.rs | 1 + pkgs/id/tests/search.rs | 2 + pkgs/id/tests/tag_claims.rs | 3 + pkgs/id/tests/voiding_properties.rs | 1 + pkgs/id/tests/voiding_scenarios.rs | 1 + 25 files changed, 851 insertions(+), 8 deletions(-) create mode 100644 pkgs/id/src/event_store/chat.rs diff --git a/pkgs/id/src/attestation.rs b/pkgs/id/src/attestation.rs index 6bc92196c3..98006bb9d3 100644 --- a/pkgs/id/src/attestation.rs +++ b/pkgs/id/src/attestation.rs @@ -199,6 +199,7 @@ pub fn sign_genesis( link: None, checkpoint: None, rotation: None, + chat: None, }, )?) } @@ -248,6 +249,7 @@ pub fn sign_claim( link: None, checkpoint: None, rotation: None, + chat: None, }, )?) } diff --git a/pkgs/id/src/chain.rs b/pkgs/id/src/chain.rs index 429e8b536c..791f6271f7 100644 --- a/pkgs/id/src/chain.rs +++ b/pkgs/id/src/chain.rs @@ -22,6 +22,7 @@ use p2panda_core::{AnyHeader, Hash, Header, HeaderError, SeqNum, SigningKey}; use serde::{Deserialize, Serialize}; use unicode_normalization::is_nfc; +use crate::chat::{ChatMessage, is_chat_message_kind}; use crate::documents::{DocumentRef, is_document_kind, is_removal_kind}; use crate::issuer_rotation::{IssuerRotation, check_rotation, is_rotation_kind}; use crate::note_links::{NoteLinkOp, check_note_link_op, is_note_link_kind}; @@ -137,6 +138,10 @@ pub struct ChainExt { /// with the header and persisted with it, because the event store keeps the /// header but not an event body, so an event carries its whole rotation. pub rotation: Option, + /// The chat message of a `chat.message.v1`, and `None` for every other kind. It is the + /// message's body (#3799): it is signed with the header, so an event carries its + /// message, and sync needs no separate body. + pub chat: Option, } /// The wire form of [`ChainExt`]: the same fields, plus the domain tag. Keys @@ -163,6 +168,8 @@ struct Wire { checkpoint: Option, #[serde(default, skip_serializing_if = "Option::is_none")] rotation: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + chat: Option, } impl From for Wire { @@ -179,6 +186,7 @@ impl From for Wire { link: ext.link, checkpoint: ext.checkpoint, rotation: ext.rotation, + chat: ext.chat, } } } @@ -201,6 +209,7 @@ impl TryFrom for ChainExt { link: wire.link, checkpoint: wire.checkpoint, rotation: wire.rotation, + chat: wire.chat, }; ext.validate()?; Ok(ext) @@ -370,6 +379,26 @@ impl ChainExt { .map_err(|err| ChainError::Extension(err.to_string()))?; } } + match (is_chat_message_kind(&self.kind), &self.chat) { + (false, None) => {} + (false, Some(_)) => { + return Err(ChainError::Extension(format!( + "kind {:?} carries a chat message", + self.kind + ))); + } + (true, None) => { + return Err(ChainError::Extension(format!( + "kind {:?} needs its chat message", + self.kind + ))); + } + (true, Some(message)) => { + message + .check() + .map_err(|err| ChainError::Extension(err.to_string()))?; + } + } Ok(()) } } @@ -528,6 +557,7 @@ mod tests { link: None, checkpoint: None, rotation: None, + chat: None, } } @@ -1237,6 +1267,7 @@ mod golden { link: None, checkpoint: None, rotation: None, + chat: None, }, ) .unwrap(); @@ -1257,6 +1288,7 @@ mod golden { link: None, checkpoint: None, rotation: None, + chat: None, }, ) .unwrap(); diff --git a/pkgs/id/src/chat.rs b/pkgs/id/src/chat.rs index 43865bddb8..9b8d6d8a73 100644 --- a/pkgs/id/src/chat.rs +++ b/pkgs/id/src/chat.rs @@ -21,7 +21,7 @@ //! Text is sanitized and bounded with the world-chat rules (see [`crate::world`]): control //! characters are stripped and the text is at most [`MAX_TEXT_BYTES`] bytes. The send-rate //! limit (50 per 10 seconds) is an admission rule of the sending path, not a property of a -//! stored message, so it is enforced where events are admitted, not here. +//! stored message, so it is enforced where events are admitted ([`SendRate`]), not on a stored message. //! //! A message may carry object references as links. Only `blob` and `event` are v1 link //! kinds. A link names content by hash and names its author; it never embeds a capability. @@ -34,12 +34,13 @@ //! events are admitted. This module defines the message shape and the projection those //! checks operate on. World chat behavior is untouched. -use std::collections::{BTreeMap, HashMap, HashSet}; +use std::collections::{BTreeMap, HashMap, HashSet, VecDeque}; use p2panda_core::Hash; use serde::{Deserialize, Serialize}; use crate::text::sanitize_chat; +use crate::groups::policy::History; use crate::waiting::AuthorKey; /// The kind of a `chat.message.v1` event, as the header's `kind` names it. @@ -317,6 +318,137 @@ pub fn project(records: impl IntoIterator) -> Vec timeline } +/// The most messages one author may send in one send-rate window: the world-chat +/// starting configuration (world chat's burst of 50). +pub const SEND_RATE_MAX: usize = 50; + +/// The send-rate window, in milliseconds: 10 seconds, the world-chat window. +pub const SEND_RATE_WINDOW_MS: u64 = 10_000; + +/// The send-rate admission configuration for one author. The defaults are the world-chat +/// limits; a different configuration is a seam a caller may choose when a channel's needs +/// or a test motivate one (#3950). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ChatRateConfig { + /// The most sends admitted in one window. + pub max: usize, + /// The window's length, in milliseconds. + pub window_ms: u64, +} + +impl Default for ChatRateConfig { + fn default() -> Self { + Self { + max: SEND_RATE_MAX, + window_ms: SEND_RATE_WINDOW_MS, + } + } +} + +/// Sliding-window send-rate admission for one author (#3950): at most +/// [`ChatRateConfig::max`] sends in any trailing window of [`ChatRateConfig::window_ms`] +/// milliseconds, the world-chat rule. Admission is a property of the sending path, so the +/// limiter lives with the sender, never with a stored message. +#[derive(Clone, Debug)] +pub struct SendRate { + config: ChatRateConfig, + sent: VecDeque, +} + +impl SendRate { + /// A limiter under `config`, with nothing sent yet. + #[must_use] + pub fn new(config: ChatRateConfig) -> Self { + Self { + config, + sent: VecDeque::new(), + } + } + + /// Whether a send at `now_ms` is admitted. An admitted send is recorded; a refused + /// one is not. A send stops counting once it is a full window old. + pub fn admit(&mut self, now_ms: u64) -> bool { + while let Some(front) = self.sent.front() { + if now_ms.saturating_sub(*front) >= self.config.window_ms { + self.sent.pop_front(); + } else { + break; + } + } + if self.sent.len() >= self.config.max { + return false; + } + self.sent.push_back(now_ms); + true + } +} + +impl Default for SendRate { + fn default() -> Self { + Self::new(ChatRateConfig::default()) + } +} + +/// Whether `record` causally follows `ancestor`: `ancestor` is among the record's causal +/// parents, transitively, over `parents`, which maps every event's ID to the IDs of its +/// `after` and backlink parents. A record does not follow itself. +#[must_use] +pub fn causally_follows( + record: &ChatRecord, + ancestor: &Hash, + parents: &HashMap>, +) -> bool { + let mut stack: Vec = record.after.clone(); + if let Some(backlink) = record.backlink { + stack.push(backlink); + } + let mut seen: HashSet = HashSet::new(); + while let Some(id) = stack.pop() { + if id == *ancestor { + return true; + } + if seen.insert(id) { + if let Some(grandparents) = parents.get(&id) { + stack.extend(grandparents.iter().copied()); + } + } + } + false +} + +/// The part of a projected `timeline` a reader may see under a channel group's history +/// policy (#3950), given the event that made the reader a member (`join`) and the causal +/// `parents` of every event. +/// +/// - [`History::Full`]: the whole timeline. +/// - [`History::FromJoin`]: the records that causally follow the join event — the reader +/// sees what was written with their membership in its causal past, and nothing from +/// before it. +/// - [`History::Recent`] and [`History::Causal`]: narrowed conservatively to the +/// from-join set for now. A recent window counts key epochs (P4.5), not messages, and +/// causal history is deferred in the design; until a message-level meaning exists, a +/// reader under either rule sees a subset of what the policy allows, never more. +#[must_use] +pub fn visible_history( + timeline: Vec, + policy: &History, + join: Option<&Hash>, + parents: &HashMap>, +) -> Vec { + match policy { + History::Full => timeline, + History::FromJoin | History::Recent(_) | History::Causal => { + let Some(join) = join else { + return Vec::new(); + }; + timeline + .into_iter() + .filter(|record| causally_follows(record, join, parents)) + .collect() + } + } +} + #[cfg(test)] #[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] mod tests { @@ -339,6 +471,52 @@ mod tests { } } + #[test] + fn test_send_rate_admits_the_burst_and_refuses_past_it() { + // The default configuration is the world-chat starting configuration. + let config = ChatRateConfig::default(); + assert_eq!(config.max, 50); + assert_eq!(config.window_ms, 10_000); + + let mut rate = SendRate::new(ChatRateConfig { + max: 3, + window_ms: 1_000, + }); + assert!(rate.admit(0)); + assert!(rate.admit(100)); + assert!(rate.admit(200)); + // The window is full: a fourth send inside it is refused, and the refusal is + // not recorded. + assert!(!rate.admit(300)); + // Once the oldest send is a full window old, a send is admitted again. + assert!(rate.admit(1_000)); + } + + #[test] + fn test_visible_history_from_join_shows_only_what_follows_the_join() { + let join = Hash::digest(b"join"); + let before = record(11, Vec::new(), "before the join"); + let mut after = record(12, Vec::new(), "after the join"); + after.after = vec![join]; + // A third message follows `after` through its backlink alone. + let mut chained = record(13, Vec::new(), "chained"); + chained.backlink = Some(after.id); + let mut parents: HashMap> = HashMap::new(); + parents.insert(after.id, vec![join]); + parents.insert(chained.id, vec![after.id]); + let timeline = vec![before.clone(), after.clone(), chained.clone()]; + + let full = visible_history(timeline.clone(), &History::Full, Some(&join), &parents); + assert_eq!(full.len(), 3); + + let from_join = visible_history(timeline.clone(), &History::FromJoin, Some(&join), &parents); + let texts: Vec<&str> = from_join.iter().map(|r| r.message.text.as_str()).collect(); + assert_eq!(texts, vec!["after the join", "chained"]); + + // With no join event known, a from-join reader sees nothing. + assert!(visible_history(timeline, &History::FromJoin, None, &parents).is_empty()); + } + #[test] fn test_message_sanitizes_and_bounds_text() { let message = ChatMessage::new(" hello\u{7} world ", Vec::new()).unwrap(); diff --git a/pkgs/id/src/event_store/chat.rs b/pkgs/id/src/event_store/chat.rs new file mode 100644 index 0000000000..71ccd55e18 --- /dev/null +++ b/pkgs/id/src/event_store/chat.rs @@ -0,0 +1,389 @@ +//! Chat over the event store (#3799 remainder, #3950). +//! +//! A chat message is its `chat.message.v1` event in the channel group. The event applies +//! like any content event, and the store keeps it either way. [`EventStore::chat_records`] +//! is the record conversion the causal projection in [`crate::chat`] consumes: a stored +//! event becomes a [`ChatRecord`] with its `after` taken from the header extension and its +//! author's previous event taken from the header backlink (the store keeps the author's +//! own head out of `after`; see `local_events`). +//! +//! [`EventStore::chat_timeline`] is the policy-enforcing read: a reader who is not on the +//! group's roster reads nothing ([`StoreError::NotMember`]), and a member reads the +//! projected timeline cut by the group policy's history rule (see +//! [`crate::chat::visible_history`] for the exact semantics of each rule). + +use std::collections::HashMap; + +use p2panda_auth::group::{GroupAction, GroupMember}; +use p2panda_core::Hash; +use redb::{ReadableDatabase, ReadableTable}; + +use super::resolve::{self, author_of}; +use super::{ACTIONS, APPLIED, 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}; +use crate::membership::AuthId; +use crate::waiting::AuthorKey; + +impl EventStore { + /// The chat records of `group`: each applied `chat.message.v1` event that names the + /// group, converted to a [`ChatRecord`], sorted by event ID. Events of any other kind, + /// and chat events of other groups, are not records of this group. + /// + /// # Errors + /// + /// Returns a redb error if the read fails, or [`StoreError::Corrupt`] for a stored chat + /// event that carries no message. + pub fn chat_records(&self, group: &Hash) -> Result, StoreError> { + let txn = self.db.begin_read()?; + let events = txn.open_table(EVENTS)?; + let applied_table = txn.open_table(APPLIED)?; + + let mut records = Vec::new(); + for row in events.iter()? { + let (_position, bytes) = row?; + let event = decode_stored(bytes.value())?; + if applied_table.get(event.id.as_bytes().as_slice())?.is_none() { + continue; + } + let ext = &event.header.extensions; + if ext.kind != CHAT_MESSAGE_KIND || ext.group != Some(*group) { + continue; + } + let Some(message) = ext.chat.clone() else { + return Err(corrupt("a stored chat event carries no message".to_owned())); + }; + records.push(ChatRecord { + id: event.id, + author: author_of(&event), + after: ext.after.clone(), + backlink: event.header.backlink, + message, + }); + } + records.sort_by_key(|record| *record.id.as_bytes()); + Ok(records) + } + + /// The policy record of `group` in the resolved state, as last set by an Admin, or + /// `None` when the store holds no group with that ID. + /// + /// # Errors + /// + /// Returns a redb error if the read fails, or [`StoreError::Corrupt`]. + pub fn group_policy(&self, group: &Hash) -> Result, StoreError> { + let txn = self.db.begin_read()?; + let (stored, forks, headers) = { + let events = txn.open_table(EVENTS)?; + let actions = txn.open_table(ACTIONS)?; + let forks = txn.open_table(FORKS)?; + let proof_headers = txn.open_table(PROOF_HEADERS)?; + resolve::load(&events, &actions, &forks, &proof_headers)? + }; + let resolved = resolve::resolve(&stored, &forks, &headers)?; + Ok(resolved + .projection + .as_ref() + .and_then(|projection| projection.group(group)) + .map(|view| view.policy.clone())) + } + + /// The chat timeline of `group` as `reader` may see it: the projected records, gated + /// on membership and cut by the group's history policy. + /// + /// A reader who is not a member of the group in the resolved state is refused with + /// [`StoreError::NotMember`]. Under a full-history policy a member sees the whole + /// projected timeline. Under any other history rule the reader sees the part of the + /// timeline that causally follows the event that made them a member (the create that + /// listed them, or the add that named them), as [`visible_history`] defines. + /// + /// # Errors + /// + /// Returns [`StoreError::NotMember`] for a reader off the roster, a redb error if the + /// read fails, or [`StoreError::Corrupt`]. + pub fn chat_timeline( + &self, + group: &Hash, + reader: &AuthorKey, + ) -> Result, StoreError> { + let txn = self.db.begin_read()?; + let (stored, forks, headers) = { + let events = txn.open_table(EVENTS)?; + let actions = txn.open_table(ACTIONS)?; + let forks = txn.open_table(FORKS)?; + let proof_headers = txn.open_table(PROOF_HEADERS)?; + resolve::load(&events, &actions, &forks, &proof_headers)? + }; + let resolved = resolve::resolve(&stored, &forks, &headers)?; + if !resolve::roster_of(&resolved, group).contains(reader) { + return Err(StoreError::NotMember); + } + let policy = resolved + .projection + .as_ref() + .and_then(|projection| projection.group(group)) + .map(|view| view.policy.clone()) + .unwrap_or_default(); + let timeline = project(self.chat_records(group)?); + if policy.history == History::Full { + return Ok(timeline); + } + // The causal parents of every applied event: its `after` and its backlink. + let mut parents: HashMap> = HashMap::new(); + for item in &stored { + if !resolved.applied.contains(&item.event.id) { + continue; + } + let mut event_parents = item.event.header.extensions.after.clone(); + if let Some(backlink) = item.event.header.backlink { + event_parents.push(backlink); + } + parents.insert(item.event.id, event_parents); + } + let join = join_event(&stored, &resolved.applied, reader, &parents); + Ok(visible_history(timeline, &policy.history, join.as_ref(), &parents)) + } +} + +/// The event that made `reader` a member: a create listing them, or an add naming them. +/// When several qualify, the one with the smallest causal past is the join; ties break by +/// event ID, so the choice depends only on the stored events. +fn join_event( + stored: &[resolve::Stored], + applied: &std::collections::HashSet, + reader: &AuthorKey, + parents: &HashMap>, +) -> Option { + let names_reader = |member: &GroupMember| { + matches!(member, GroupMember::Individual(AuthId::Key(key)) if key == reader) + }; + let mut candidates: Vec = Vec::new(); + for item in stored { + if !applied.contains(&item.event.id) { + continue; + } + let joined = match &item.action { + Some(GroupAction::Create { initial_members }) => { + initial_members.iter().any(|(member, _)| names_reader(member)) + } + Some(GroupAction::Add { member, .. }) => names_reader(member), + _ => false, + }; + if joined { + candidates.push(item.event.id); + } + } + candidates.sort_by_key(|id| (past_size(*id, parents), *id.as_bytes())); + candidates.into_iter().next() +} + +/// How many events sit in the causal past of `id`, itself included, over `parents`. +fn past_size(id: Hash, parents: &HashMap>) -> usize { + let mut seen = std::collections::HashSet::new(); + let mut stack = vec![id]; + while let Some(current) = stack.pop() { + if seen.insert(current) { + if let Some(event_parents) = parents.get(¤t) { + stack.extend(event_parents.iter().copied()); + } + } + } + seen.len() +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod tests { + use super::*; + use crate::chain::{ChainExt, sign}; + use crate::chat::ChatMessage; + use crate::membership::body::encode_body; + use crate::waiting::WaitingLimits; + use p2panda_core::{SeqNum, SigningKey}; + + fn key(n: u8) -> SigningKey { + SigningKey::from_bytes(&[n; 32]) + } + + fn author(key: &SigningKey) -> AuthorKey { + *key.verifying_key().as_bytes() + } + + fn individual(key: &SigningKey) -> GroupMember { + GroupMember::Individual(AuthId::Key(author(key))) + } + + fn open() -> (tempfile::TempDir, EventStore) { + let dir = tempfile::tempdir().unwrap(); + let store = EventStore::open(dir.path(), WaitingLimits::default(), 0).unwrap(); + (dir, store) + } + + /// A signed group operation and its encoded body, as the production path carries them. + fn group_op( + key: &SigningKey, + seq: SeqNum, + backlink: Option, + after: Vec, + group: Option, + action: &GroupAction, + ) -> (crate::chain::Event, Vec) { + let body = encode_body(action).unwrap(); + let ext = ChainExt { + kind: "group.op".to_owned(), + group, + after, + tag: None, + document: None, + removes: None, + chat: None, + }; + let event = sign(key, seq, backlink, Some(&body), ext).unwrap(); + (event, body) + } + + /// A signed chat event in `group`. + fn chat_event( + key: &SigningKey, + seq: SeqNum, + backlink: Option, + after: Vec, + group: Hash, + text: &str, + ) -> crate::chain::Event { + let ext = ChainExt { + kind: CHAT_MESSAGE_KIND.to_owned(), + group: Some(group), + after, + tag: None, + document: None, + removes: None, + chat: Some(ChatMessage::new(text, Vec::new()).unwrap()), + }; + sign(key, seq, backlink, None, ext).unwrap() + } + + /// A store holding a channel created by Alice with Bob as a member. + fn channel() -> (tempfile::TempDir, EventStore, SigningKey, SigningKey, Hash, Hash) { + let (dir, mut store) = open(); + let (alice, bob) = (key(41), key(42)); + let create = GroupAction::Create { + initial_members: vec![ + (individual(&alice), p2panda_auth::Access::manage()), + (individual(&bob), p2panda_auth::Access::write()), + ], + }; + let (create_event, create_body) = group_op(&alice, 0, None, vec![], None, &create); + let group = create_event.id; + store + .ingest_with_body(&create_event.bytes, Some(&create_body), 0) + .unwrap(); + assert!(store.event_applied(&group).unwrap()); + (dir, store, alice, bob, group, create_event.id) + } + + #[test] + fn test_chat_records_convert_stored_events_and_bind_to_the_group() { + let (_dir, mut store, alice, bob, group, create_id) = channel(); + + let first = chat_event(&alice, 1, Some(create_id), vec![], group, "hello from alice"); + store.ingest(&first.bytes, 0).unwrap(); + let second = chat_event(&bob, 0, None, vec![create_id], group, "hello from bob"); + store.ingest(&second.bytes, 0).unwrap(); + + // A chat event in another group is not a record of this one. + let other_group = Hash::digest(b"another channel"); + let stray = chat_event(&alice, 2, Some(first.id), vec![], other_group, "elsewhere"); + store.ingest(&stray.bytes, 0).unwrap(); + + let records = store.chat_records(&group).unwrap(); + assert_eq!(records.len(), 2); + let by_id: HashMap = + records.iter().map(|record| (record.id, record)).collect(); + let first_record = by_id[&first.id]; + assert_eq!(first_record.author, author(&alice)); + assert_eq!(first_record.backlink, Some(create_id)); + assert_eq!(first_record.message.text, "hello from alice"); + let second_record = by_id[&second.id]; + assert_eq!(second_record.author, author(&bob)); + assert_eq!(second_record.after, vec![create_id]); + assert_eq!(second_record.backlink, None); + } + + #[test] + fn test_two_members_exchange_through_two_stores_with_replay_and_reorder() { + // Two independent members, each with their own store, exchange signed chat events: + // the create reaches both, then each side's messages cross over. Delivery to Bob's + // store is out of order (Alice's second message first) and duplicated; both stores + // still project the same timeline. + let (alice, bob) = (key(43), key(44)); + let (_dir_a, mut store_a) = open(); + let (_dir_b, mut store_b) = open(); + let create = GroupAction::Create { + initial_members: vec![ + (individual(&alice), p2panda_auth::Access::manage()), + (individual(&bob), p2panda_auth::Access::write()), + ], + }; + let (create_event, create_body) = group_op(&alice, 0, None, vec![], None, &create); + let group = create_event.id; + for store in [&mut store_a, &mut store_b] { + store + .ingest_with_body(&create_event.bytes, Some(&create_body), 0) + .unwrap(); + } + + let alice_first = chat_event(&alice, 1, Some(group), vec![], group, "first from alice"); + store_a.ingest(&alice_first.bytes, 0).unwrap(); + let bob_first = chat_event(&bob, 0, None, vec![group], group, "first from bob"); + store_b.ingest(&bob_first.bytes, 0).unwrap(); + // Alice replies to Bob: her event names Bob's as its `after`. + let alice_second = chat_event( + &alice, + 2, + Some(alice_first.id), + vec![bob_first.id], + group, + "second from alice", + ); + + // Bob's store gets Alice's second message before her first, and her first twice. + store_b.ingest(&alice_second.bytes, 0).unwrap(); + store_b.ingest(&alice_first.bytes, 0).unwrap(); + store_b.ingest(&alice_first.bytes, 0).unwrap(); + store_b.ingest(&alice_second.bytes, 0).unwrap(); + // Alice's store gets Bob's message, twice. + store_a.ingest(&bob_first.bytes, 0).unwrap(); + store_a.ingest(&bob_first.bytes, 0).unwrap(); + store_a.ingest(&alice_second.bytes, 0).unwrap(); + + let timeline_a = store_a.chat_timeline(&group, &author(&alice)).unwrap(); + let timeline_b = store_b.chat_timeline(&group, &author(&bob)).unwrap(); + let texts_a: Vec<&str> = timeline_a.iter().map(|r| r.message.text.as_str()).collect(); + let texts_b: Vec<&str> = timeline_b.iter().map(|r| r.message.text.as_str()).collect(); + assert_eq!(texts_a, texts_b); + assert_eq!(texts_a.len(), 3); + let position = |text: &str| texts_a.iter().position(|t| *t == text).unwrap(); + assert!(position("first from alice") < position("second from alice")); + assert!(position("first from bob") < position("second from alice")); + + // A third key is not a member: it reads nothing, and the refusal is explicit. + let carol = key(45); + assert!(matches!( + store_a.chat_timeline(&group, &author(&carol)), + Err(StoreError::NotMember) + )); + } + + #[test] + fn test_group_policy_comes_from_the_create() { + let (_dir, store, _alice, _bob, group, _create) = channel(); + // The membership create bridges to a group create under the custom template with + // the default policy record (see `resolve`), so the policy is the default: full + // history for a member. + assert_eq!(store.group_policy(&group).unwrap(), Some(Policy::default())); + // A group the store never saw has no policy. + let unseen = Hash::digest(b"no such group"); + assert_eq!(store.group_policy(&unseen).unwrap(), None); + } +} diff --git a/pkgs/id/src/event_store/ingest.rs b/pkgs/id/src/event_store/ingest.rs index e22a101e84..12e0786eb5 100644 --- a/pkgs/id/src/event_store/ingest.rs +++ b/pkgs/id/src/event_store/ingest.rs @@ -1159,6 +1159,7 @@ mod tests { link: None, checkpoint: None, rotation: None, + chat: None, }; sign(key, seq, backlink, None, ext).unwrap() } @@ -1882,6 +1883,7 @@ mod tests { link: None, checkpoint: None, rotation: None, + chat: None, }; sign(&signer, seq, backlink, None, ext).unwrap() }; @@ -1918,6 +1920,7 @@ mod tests { link: None, checkpoint: None, rotation: None, + chat: None, }; let event = sign(key, seq, backlink, Some(&body), ext).unwrap(); (event, body) diff --git a/pkgs/id/src/event_store/mod.rs b/pkgs/id/src/event_store/mod.rs index a8b1dcba56..9d250cce13 100644 --- a/pkgs/id/src/event_store/mod.rs +++ b/pkgs/id/src/event_store/mod.rs @@ -62,6 +62,7 @@ use redb::{ use crate::chain::{self, Event}; +mod chat; mod claims; mod documents; mod ingest; @@ -163,6 +164,9 @@ pub enum StoreError { /// refuses further calls. Reopening it rebuilds them. #[error("event store is unusable after a failed write: reopen it")] Unusable, + /// The reader is not a member of the group whose chat they asked to read (#3950). + #[error("the reader is not a member of this group")] + NotMember, } fn corrupt(message: impl Into) -> StoreError { @@ -1699,6 +1703,7 @@ mod tests { link: None, checkpoint: None, rotation: None, + chat: None, } } diff --git a/pkgs/id/src/event_store/sync.rs b/pkgs/id/src/event_store/sync.rs index cd6355a183..1774fd6942 100644 --- a/pkgs/id/src/event_store/sync.rs +++ b/pkgs/id/src/event_store/sync.rs @@ -857,6 +857,7 @@ mod tests { link: None, checkpoint: None, rotation: None, + chat: None, }; events.push(chain::sign(&key, seq, backlink, Some(body), ext).unwrap()); } @@ -1113,6 +1114,7 @@ mod tests { link: None, checkpoint: None, rotation: None, + chat: None, }, ) .unwrap(); @@ -1159,6 +1161,7 @@ mod tests { link: None, checkpoint: None, rotation: None, + chat: None, }, ) .unwrap(); @@ -1209,6 +1212,7 @@ mod tests { link: None, checkpoint: None, rotation: None, + chat: None, }, ) .unwrap(); diff --git a/pkgs/id/src/idset.rs b/pkgs/id/src/idset.rs index eb1f123a3c..7ddeac2830 100644 --- a/pkgs/id/src/idset.rs +++ b/pkgs/id/src/idset.rs @@ -909,6 +909,7 @@ mod tests { link: None, checkpoint: None, rotation: None, + chat: None, }, ) .unwrap(); diff --git a/pkgs/id/src/local_events.rs b/pkgs/id/src/local_events.rs index cfa5728b40..2094c3f476 100644 --- a/pkgs/id/src/local_events.rs +++ b/pkgs/id/src/local_events.rs @@ -22,6 +22,7 @@ use anyhow::{Context, Result, bail}; use p2panda_core::{Hash, SigningKey}; use crate::chain::{ChainExt, Event, MAX_AFTER, sign}; +use crate::chat::{CHAT_MESSAGE_KIND, ChatMessage, ChatRecord, SendRate}; use crate::documents::{DOCUMENT_KIND, DocumentRef, REMOVAL_KIND}; use crate::event_store::{EventStore, Ingest}; use crate::notes::{ @@ -219,6 +220,8 @@ pub struct LocalEvents { /// The node's own local-only claims (#1793): never signed, never synced. local: LocalClaims, key: SigningKey, + /// Send-rate admission for this node's own chat sends (#3950). + chat_rate: SendRate, } impl LocalEvents { @@ -231,7 +234,12 @@ impl LocalEvents { std::fs::create_dir_all(dir).with_context(|| format!("create {}", dir.display()))?; let store = EventStore::open(dir, WaitingLimits::default(), now_ms())?; let local = LocalClaims::open(dir).context("open the local claim store")?; - Ok(Self { store, local, key }) + Ok(Self { + store, + local, + key, + chat_rate: SendRate::default(), + }) } /// Runs one range-sync session over `conn` against this node's store: the session @@ -289,7 +297,7 @@ impl LocalEvents { bail!("a publish names the same tag twice"); } } - let id = self.record(DOCUMENT_KIND, None, Some(document.clone()), None, None, &[])?; + let id = self.record(DOCUMENT_KIND, None, None, Some(document.clone()), None, None, None, &[])?; let mut claims = Vec::with_capacity(tags.len()); for (name, value) in tags { claims.push(self.set_tag(id, name, value.as_deref())?); @@ -301,6 +309,56 @@ impl LocalEvents { }) } + /// Sends `message` as a `chat.message.v1` event in the channel `group`, and returns + /// the event's ID. + /// + /// Admission is refused before anything is signed when the node's key is not a member + /// of the group under its policy ([`EventStore::roster`]), and when the node's sends + /// inside the trailing rate window already number the configured maximum + /// ([`SendRate`], the world-chat starting configuration of 50 per 10 seconds, #3950). + /// + /// # Errors + /// + /// Fails if the message is refused by [`ChatMessage::check`], the node is not a + /// member, the send rate is exhausted, or the store cannot record the event. + pub fn send_chat(&mut self, group: Hash, message: ChatMessage) -> Result { + message.check()?; + let author = self.author(); + if !self.store.roster(&group)?.contains(&author) { + bail!( + "the node's key is not a member of the channel group, so its chat write is refused at admission" + ); + } + if !self.chat_rate.admit(now_ms()) { + bail!( + "the chat send rate is exhausted: at most {} messages in {} ms", + crate::chat::SEND_RATE_MAX, + crate::chat::SEND_RATE_WINDOW_MS + ); + } + self.record( + CHAT_MESSAGE_KIND, + Some(group), + None, + None, + None, + None, + Some(message), + &[], + ) + } + + /// The chat timeline of `group` as this node may see it: the store's read, gated on + /// this node's membership and cut by the group's history policy (see + /// [`EventStore::chat_timeline`]). + /// + /// # Errors + /// + /// Fails if the node is not a member of the group, or the store cannot be read. + pub fn chat_timeline(&self, group: Hash) -> Result> { + Ok(self.store.chat_timeline(&group, &self.author())?) + } + /// Sets the tag `name` on `subject`, with `value` if given. The new claim's ID is the event's. /// /// The claim is shared: it is signed into the event store and published to peers, exactly as @@ -341,7 +399,7 @@ impl LocalEvents { name: name.to_owned(), value: value.map(str::to_owned), }; - self.record(SET_KIND, Some(op), None, None, None, &[]) + self.record(SET_KIND, None, Some(op), None, None, None, None, &[]) } } } @@ -417,12 +475,14 @@ impl LocalEvents { for group in claims.chunks(MAX_CLEAR_CLAIMS) { self.record( CLEAR_KIND, + None, Some(TagOp::Clear { claims: group.to_vec(), }), None, None, None, + None, &required, )?; } @@ -530,10 +590,12 @@ impl LocalEvents { let ids: Vec = group.iter().map(|claim| claim.id).collect(); last = Some(self.record( CLEAR_KIND, + None, Some(TagOp::Clear { claims: ids }), None, None, None, + None, &required, )?); } @@ -605,7 +667,7 @@ impl LocalEvents { let content = DocumentRef::for_bytes(media_type, content)?; let op = NoteOp::Create { content }; check_note_op(NOTE_CREATE_KIND, &op)?; - self.record(NOTE_CREATE_KIND, None, None, None, Some(op), &[]) + self.record(NOTE_CREATE_KIND, None, None, None, None, Some(op), None, &[]) } /// Adds one revision with `content` to the note `note`, building on `parents`. The @@ -658,7 +720,7 @@ impl LocalEvents { parents: parents.to_vec(), }; check_note_op(NOTE_REVISE_KIND, &op)?; - self.record(NOTE_REVISE_KIND, None, None, None, Some(op), &required) + self.record(NOTE_REVISE_KIND, None, None, None, None, Some(op), None, &required) } /// Every note in the store, in note ID order, each with its revisions and heads. @@ -875,10 +937,12 @@ impl LocalEvents { fn record( &mut self, kind: &str, + group: Option, tag: Option, document: Option, removes: Option, note: Option, + chat: Option, required: &[Hash], ) -> Result { let author = self.author(); @@ -886,7 +950,7 @@ impl LocalEvents { let chain = self.store.chain(&author)?.unwrap_or_default(); let ext = ChainExt { kind: kind.to_owned(), - group: None, + group, after, tag, document, @@ -895,6 +959,7 @@ impl LocalEvents { link: None, checkpoint: None, rotation: None, + chat, }; let event = sign(&self.key, chain.next_seq, chain.head, None, ext)?; match self.store.ingest(&event.bytes, now_ms())? { @@ -1566,3 +1631,136 @@ mod tests { assert!(events.clear_tag(subject, "topic").is_err()); } } + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod chat_tests { + use super::*; + use crate::membership::AuthId; + use crate::membership::body::encode_body; + use p2panda_auth::group::{GroupAction, GroupMember}; + + fn key(n: u8) -> SigningKey { + SigningKey::from_bytes(&[n; 32]) + } + + fn individual(key: &SigningKey) -> GroupMember { + GroupMember::Individual(AuthId::Key(*key.verifying_key().as_bytes())) + } + + /// The channel create event (Alice creates, Bob is a member) and its encoded body. + fn create_event(alice: &SigningKey, bob: &SigningKey) -> (Event, Vec) { + let action = GroupAction::Create { + initial_members: vec![ + (individual(alice), p2panda_auth::Access::manage()), + (individual(bob), p2panda_auth::Access::write()), + ], + }; + let body = encode_body(&action).unwrap(); + let ext = ChainExt { + kind: "group.op".to_owned(), + group: None, + after: Vec::new(), + tag: None, + document: None, + removes: None, + chat: None, + }; + let event = sign(alice, 0, None, Some(&body), ext).unwrap(); + (event, body) + } + + /// A node whose store already holds the channel create, as sync would have brought it. + fn node(dir: &Path, key: SigningKey, create: &Event, body: &[u8]) -> LocalEvents { + let mut node = LocalEvents::open(dir, key).unwrap(); + node.store + .ingest_with_body(&create.bytes, Some(body), 0) + .unwrap(); + node + } + + /// Moves `from`'s applied chat events into `to`'s store, as a sync session would. + fn exchange(from: &LocalEvents, to: &mut LocalEvents) { + let events = from + .store + .applied_events(&from.author(), None, None, usize::MAX) + .unwrap(); + for event in &events { + if event.header.extensions.kind == CHAT_MESSAGE_KIND { + to.store.ingest(&event.bytes, now_ms()).unwrap(); + } + } + } + + #[test] + fn test_two_members_exchange_chat_and_a_non_member_is_refused() { + let (alice, bob, carol) = (key(51), key(52), key(53)); + let (create, body) = create_event(&alice, &bob); + let group = create.id; + let dir_a = tempfile::tempdir().unwrap(); + let dir_b = tempfile::tempdir().unwrap(); + let dir_c = tempfile::tempdir().unwrap(); + let mut node_a = node(dir_a.path(), alice, &create, &body); + let mut node_b = node(dir_b.path(), bob, &create, &body); + let mut node_c = node(dir_c.path(), carol, &create, &body); + + // A non-member's write is refused at admission: nothing is signed or recorded. + let refused = node_c.send_chat(group, ChatMessage::new("carol here", Vec::new()).unwrap()); + assert!(refused.is_err()); + assert!(node_c.store.chat_records(&group).unwrap().is_empty()); + + let first = node_a + .send_chat(group, ChatMessage::new("hello from alice", Vec::new()).unwrap()) + .unwrap(); + let second = node_b + .send_chat(group, ChatMessage::new("hello from bob", Vec::new()).unwrap()) + .unwrap(); + + exchange(&node_a, &mut node_b); + exchange(&node_b, &mut node_a); + + let timeline_a = node_a.chat_timeline(group).unwrap(); + let timeline_b = node_b.chat_timeline(group).unwrap(); + let texts_a: Vec<&str> = timeline_a + .iter() + .map(|record| record.message.text.as_str()) + .collect(); + let texts_b: Vec<&str> = timeline_b + .iter() + .map(|record| record.message.text.as_str()) + .collect(); + assert_eq!(texts_a, texts_b); + assert_eq!(texts_a.len(), 2); + let ids: Vec = timeline_a.iter().map(|record| record.id).collect(); + assert!(ids.contains(&first)); + assert!(ids.contains(&second)); + } + + #[test] + fn test_send_rate_admits_the_configured_burst_and_refuses_past_it() { + let (alice, bob) = (key(54), key(55)); + let (create, body) = create_event(&alice, &bob); + let group = create.id; + let dir = tempfile::tempdir().unwrap(); + let mut node = node(dir.path(), alice, &create, &body); + // The configuration seam (#3950): a small burst in a wide window, so the test + // does not depend on how fast the sends happen. The default configuration is + // the world-chat 50 per 10 seconds, unit-tested in the chat module. + node.chat_rate = SendRate::new(crate::chat::ChatRateConfig { + max: 3, + window_ms: 60_000, + }); + for index in 0..3 { + node.send_chat( + group, + ChatMessage::new(&format!("message {index}"), Vec::new()).unwrap(), + ) + .unwrap(); + } + let refused = node.send_chat( + group, + ChatMessage::new("one too many", Vec::new()).unwrap(), + ); + assert!(refused.is_err()); + } +} diff --git a/pkgs/id/src/log_sync.rs b/pkgs/id/src/log_sync.rs index c40bdd96f4..e9dee6f162 100644 --- a/pkgs/id/src/log_sync.rs +++ b/pkgs/id/src/log_sync.rs @@ -717,6 +717,7 @@ mod tests { link: None, checkpoint: None, rotation: None, + chat: None, }; events.push(sign(signer, seq, backlink, None, ext).unwrap()); } @@ -1311,6 +1312,7 @@ mod tests { link: None, checkpoint: None, rotation: None, + chat: None, }; let rival = sign(alice, 1, Some(honest[0].id), None, rival_ext).unwrap(); assert!(matches!( diff --git a/pkgs/id/src/store_traits.rs b/pkgs/id/src/store_traits.rs index 46da8921e5..3d5aeb07f1 100644 --- a/pkgs/id/src/store_traits.rs +++ b/pkgs/id/src/store_traits.rs @@ -806,6 +806,7 @@ mod tests { link: None, checkpoint: None, rotation: None, + chat: None, }; sign(signer, seq, backlink, body, ext).unwrap() } diff --git a/pkgs/id/tests/aliases.rs b/pkgs/id/tests/aliases.rs index ff2f54fde6..700f8635b6 100644 --- a/pkgs/id/tests/aliases.rs +++ b/pkgs/id/tests/aliases.rs @@ -63,6 +63,7 @@ impl Writer { link: None, checkpoint: None, rotation: None, + chat: None, }; let event = sign(&self.key, self.seq, self.last, None, ext).unwrap(); self.seq += 1; diff --git a/pkgs/id/tests/bridge_poc.rs b/pkgs/id/tests/bridge_poc.rs index 567992e55c..ce6d0692a8 100644 --- a/pkgs/id/tests/bridge_poc.rs +++ b/pkgs/id/tests/bridge_poc.rs @@ -170,6 +170,7 @@ impl Author { link: None, checkpoint: None, rotation: None, + chat: None, }; let event = sign(&self.key, self.seq, self.last, None, ext).unwrap(); self.seq += 1; @@ -204,6 +205,7 @@ impl Author { link: None, checkpoint: None, rotation: None, + chat: None, }; sign(&self.key, seq, backlink, Some(b"rival"), ext).unwrap() } diff --git a/pkgs/id/tests/chain_properties.rs b/pkgs/id/tests/chain_properties.rs index c1814419f1..f2f8ad8407 100644 --- a/pkgs/id/tests/chain_properties.rs +++ b/pkgs/id/tests/chain_properties.rs @@ -65,6 +65,7 @@ fn chain_ext() -> impl Strategy { link: None, checkpoint: None, rotation: None, + chat: None, } }) } @@ -128,6 +129,7 @@ proptest! { link: None, checkpoint: None, rotation: None, + after: after.clone(), tag: None, document: None, removes: None, chat: None, }; prop_assert!(sign(&key(), 0, None, None, ext.clone()).is_err()); prop_assert!(ext.validate().is_err()); @@ -198,6 +200,7 @@ proptest! { link: None, checkpoint: None, rotation: None, + after: Vec::new(), tag: None, document: None, removes: None, chat: None, }, ) .encode(); diff --git a/pkgs/id/tests/cli_documents.rs b/pkgs/id/tests/cli_documents.rs index a3987c34b3..064e1f1921 100644 --- a/pkgs/id/tests/cli_documents.rs +++ b/pkgs/id/tests/cli_documents.rs @@ -199,6 +199,7 @@ fn test_events_lists_the_tags_and_a_removal_on_a_document() { link: None, checkpoint: None, rotation: None, + chat: None, }, ); diff --git a/pkgs/id/tests/content_removal.rs b/pkgs/id/tests/content_removal.rs index 041ed9f161..a8da96065f 100644 --- a/pkgs/id/tests/content_removal.rs +++ b/pkgs/id/tests/content_removal.rs @@ -101,6 +101,7 @@ fn document_ext(doc: &DocumentRef, after: Vec) -> ChainExt { link: None, checkpoint: None, rotation: None, + chat: None, } } @@ -120,6 +121,7 @@ fn tag_ext(subject: Hash, name: &str, value: &str, after: Vec) -> ChainExt link: None, checkpoint: None, rotation: None, + chat: None, } } @@ -135,6 +137,7 @@ fn removal_ext(target: Hash, after: Vec) -> ChainExt { link: None, checkpoint: None, rotation: None, + chat: None, } } diff --git a/pkgs/id/tests/crash/store.rs b/pkgs/id/tests/crash/store.rs index 7159449c5e..5927af2768 100644 --- a/pkgs/id/tests/crash/store.rs +++ b/pkgs/id/tests/crash/store.rs @@ -438,6 +438,7 @@ fn workload() -> Vec> { link: None, checkpoint: None, rotation: None, + chat: None, }; let a0 = sign(&author, 0, None, None, ext("message", Vec::new())).unwrap(); let a1 = sign(&author, 1, Some(a0.id), None, ext("message", Vec::new())).unwrap(); diff --git a/pkgs/id/tests/documents.rs b/pkgs/id/tests/documents.rs index 896935862e..6a6188a09a 100644 --- a/pkgs/id/tests/documents.rs +++ b/pkgs/id/tests/documents.rs @@ -110,6 +110,7 @@ fn document_ext(doc: &DocumentRef, after: Vec) -> ChainExt { link: None, checkpoint: None, rotation: None, + chat: None, } } @@ -129,6 +130,7 @@ fn tag_ext(op: TagOp, after: Vec) -> ChainExt { link: None, checkpoint: None, rotation: None, + chat: None, } } @@ -383,6 +385,7 @@ fn test_a_document_event_that_does_not_fit_its_kind_is_not_signed() { link: None, checkpoint: None, rotation: None, + chat: None, }; assert!(sign(&key, 0, None, None, missing).is_err()); let with_tag = ChainExt { diff --git a/pkgs/id/tests/event_store_properties.rs b/pkgs/id/tests/event_store_properties.rs index 974c4318c6..02587619b1 100644 --- a/pkgs/id/tests/event_store_properties.rs +++ b/pkgs/id/tests/event_store_properties.rs @@ -152,6 +152,7 @@ fn signed( link: None, checkpoint: None, rotation: None, + chat: None, }; sign(key, seq, backlink, None, ext).unwrap() } @@ -343,6 +344,7 @@ fn present_event( link: None, checkpoint: None, rotation: None, + chat: None, }; sign(key, seq, backlink, None, ext).unwrap() } @@ -767,6 +769,7 @@ proptest! { link: None, checkpoint: None, rotation: None, + after: Vec::new(), tag: None, document: None, removes: None, chat: None, }, ) .encode(); @@ -814,6 +817,7 @@ fn print_ingest_seeds() { link: None, checkpoint: None, rotation: None, + chat: None, }; sign(key, seq, backlink, None, ext).unwrap() }; diff --git a/pkgs/id/tests/production_ingest.rs b/pkgs/id/tests/production_ingest.rs index 7bcc78577d..96a7c1b257 100644 --- a/pkgs/id/tests/production_ingest.rs +++ b/pkgs/id/tests/production_ingest.rs @@ -82,6 +82,7 @@ impl Chains { link: None, checkpoint: None, rotation: None, + chat: None, }; let event = sign(&key(who), seq, backlink, body.as_deref(), ext).unwrap(); self.last.insert(who, (seq, event.id)); @@ -300,6 +301,7 @@ fn test_a_body_that_does_not_match_its_payload_hash_is_refused() { link: None, checkpoint: None, rotation: None, + chat: None, }, ) .unwrap(); diff --git a/pkgs/id/tests/retention_pruning.rs b/pkgs/id/tests/retention_pruning.rs index f419b773ca..e722c90599 100644 --- a/pkgs/id/tests/retention_pruning.rs +++ b/pkgs/id/tests/retention_pruning.rs @@ -74,6 +74,7 @@ impl Chains { link: None, checkpoint: None, rotation: None, + chat: None, }; let event = sign(&key(who), seq, backlink, body.as_deref(), ext).unwrap(); self.last.insert(who, (seq, event.id)); diff --git a/pkgs/id/tests/search.rs b/pkgs/id/tests/search.rs index 33a8ddb51e..a8195e1f50 100644 --- a/pkgs/id/tests/search.rs +++ b/pkgs/id/tests/search.rs @@ -92,6 +92,7 @@ impl Writer { link: None, checkpoint: None, rotation: None, + chat: None, }) } } @@ -108,6 +109,7 @@ fn tag_ext(kind: &str, op: TagOp, after: Vec) -> ChainExt { link: None, checkpoint: None, rotation: None, + chat: None, } } diff --git a/pkgs/id/tests/tag_claims.rs b/pkgs/id/tests/tag_claims.rs index 22f2d64bea..d2c8c30565 100644 --- a/pkgs/id/tests/tag_claims.rs +++ b/pkgs/id/tests/tag_claims.rs @@ -79,6 +79,7 @@ impl Writer { link: None, checkpoint: None, rotation: None, + chat: None, }; let event = sign(&self.key, self.seq, self.last, None, ext).unwrap(); self.seq += 1; @@ -266,6 +267,7 @@ fn test_a_tag_event_whose_operation_does_not_fit_its_kind_is_not_signed() { link: None, checkpoint: None, rotation: None, + chat: None, }; assert!(sign(&a.key, 0, None, None, mismatch).is_err()); let missing = ChainExt { @@ -279,6 +281,7 @@ fn test_a_tag_event_whose_operation_does_not_fit_its_kind_is_not_signed() { link: None, checkpoint: None, rotation: None, + chat: None, }; assert!(sign(&a.key, 0, None, None, missing).is_err()); } diff --git a/pkgs/id/tests/voiding_properties.rs b/pkgs/id/tests/voiding_properties.rs index d561ae78ca..c8f19341dc 100644 --- a/pkgs/id/tests/voiding_properties.rs +++ b/pkgs/id/tests/voiding_properties.rs @@ -150,6 +150,7 @@ fn scenario(seed: u64) -> Vec { link: None, checkpoint: None, rotation: None, + chat: None, }; let body = action.as_ref().map(|action| encode_body(action).unwrap()); let event = sign(&key(who), seq, backlink, body.as_deref(), ext).unwrap(); diff --git a/pkgs/id/tests/voiding_scenarios.rs b/pkgs/id/tests/voiding_scenarios.rs index 17aafdcc34..ced1d42fac 100644 --- a/pkgs/id/tests/voiding_scenarios.rs +++ b/pkgs/id/tests/voiding_scenarios.rs @@ -100,6 +100,7 @@ impl Builder { link: None, checkpoint: None, rotation: None, + chat: None, }; let body = action.as_ref().map(|action| encode_body(action).unwrap()); let event = sign(&key(who), seq, backlink, body.as_deref(), ext).unwrap(); From e6ac5525dbb05c833c21fe5301aa48d19e11c12c Mon Sep 17 00:00:00 2001 From: repo-worker-code-k Date: Sun, 8 Nov 2026 11:26:43 -0600 Subject: [PATCH 2/2] =?UTF-8?q?fix(id):=20complete=20chat=20v1=20port=20?= =?UTF-8?q?=E2=80=94=20Codex=20fixes=20chunking/NFC/causal=20ancestors=20+?= =?UTF-8?q?=20P1=20membership=20gate?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - chain.rs: header text chunking for chat text over the 512-byte CBOR string limit (P2 4437276309, carried from PR branch merge bd403f5631) - chat.rs: NFC-normalize message text and link hints at construction, refuse non-NFC at validation (P2 4437276319) - event_store/chat.rs: preserve causal chat ancestors across non-chat events in chat_records (P2 4437276331) - event_store/resolve.rs: membership-gate chat.message.v1 at its causal position on the receiving path (P1 4471198623); membership layer now fed full causal graph (after + backlink) - ChainExt chat field added to remaining initializers across src/tests --- pkgs/id/src/chain.rs | 100 +++++++++++++++- pkgs/id/src/chat.rs | 108 ++++++++++++++++- pkgs/id/src/currency.rs | 4 + pkgs/id/src/currency/graph.rs | 2 + pkgs/id/src/event_store/chat.rs | 166 ++++++++++++++++++++++++--- pkgs/id/src/event_store/ingest.rs | 4 + pkgs/id/src/event_store/resolve.rs | 52 ++++++++- pkgs/id/src/event_store/sync.rs | 1 + pkgs/id/src/issuer_rotation.rs | 2 + pkgs/id/src/local_events.rs | 94 +++++++++++---- pkgs/id/src/log_sync.rs | 34 +++++- pkgs/id/src/world/signed.rs | 2 + pkgs/id/tests/retention_pruning.rs | 6 + pkgs/id/tests/tag_clear_authority.rs | 2 + 14 files changed, 525 insertions(+), 52 deletions(-) diff --git a/pkgs/id/src/chain.rs b/pkgs/id/src/chain.rs index 791f6271f7..8d0149e3e1 100644 --- a/pkgs/id/src/chain.rs +++ b/pkgs/id/src/chain.rs @@ -22,7 +22,7 @@ use p2panda_core::{AnyHeader, Hash, Header, HeaderError, SeqNum, SigningKey}; use serde::{Deserialize, Serialize}; use unicode_normalization::is_nfc; -use crate::chat::{ChatMessage, is_chat_message_kind}; +use crate::chat::{ChatLink, ChatMessage, is_chat_message_kind}; use crate::documents::{DocumentRef, is_document_kind, is_removal_kind}; use crate::issuer_rotation::{IssuerRotation, check_rotation, is_rotation_kind}; use crate::note_links::{NoteLinkOp, check_note_link_op, is_note_link_kind}; @@ -49,6 +49,10 @@ const LENGTH_LIMIT: u64 = 512; /// Byte budget for speculative pre-allocation. Matches p2panda's decoder. const OOM_MITIGATION: usize = 64; +/// p2panda's header decoder caps each CBOR text string at 512 bytes. Longer chat +/// text is represented as chunks so the message shape's 2,048-byte limit remains usable. +const CHAT_TEXT_CHUNK_BYTES: usize = 512; + /// Why an event header, or the extension it carries, was refused. #[derive(Debug, thiserror::Error)] pub enum ChainError { @@ -144,6 +148,92 @@ pub struct ChainExt { pub chat: Option, } +#[derive(Serialize)] +#[serde(untagged)] +enum ChatTextWireRef<'a> { + Plain(&'a str), + Chunks(Vec<&'a str>), +} + +#[derive(Deserialize)] +#[serde(untagged)] +enum ChatTextWire { + Plain(String), + Chunks(Vec), +} + +#[derive(Serialize)] +struct ChatMessageWireRef<'a> { + text: ChatTextWireRef<'a>, + links: &'a [ChatLink], +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct ChatMessageWire { + text: ChatTextWire, + #[serde(default)] + links: Vec, +} + +/// A chat message's header-only wire representation. Keeping chunking here +/// leaves the general `ChatMessage` serde shape unchanged. +#[derive(Clone, Debug, PartialEq, Eq)] +struct HeaderChatMessage(ChatMessage); + +impl Serialize for HeaderChatMessage { + fn serialize(&self, serializer: S) -> Result + where + S: serde::Serializer, + { + let message = &self.0; + let text = if message.text.len() <= CHAT_TEXT_CHUNK_BYTES { + ChatTextWireRef::Plain(&message.text) + } else { + ChatTextWireRef::Chunks(chat_text_chunks(&message.text)) + }; + ChatMessageWireRef { + text, + links: &message.links, + } + .serialize(serializer) + } +} + +impl<'de> Deserialize<'de> for HeaderChatMessage { + fn deserialize(deserializer: D) -> Result + where + D: serde::Deserializer<'de>, + { + let wire = ChatMessageWire::deserialize(deserializer)?; + let text = match wire.text { + ChatTextWire::Plain(text) => text, + ChatTextWire::Chunks(chunks) => chunks.concat(), + }; + Ok(Self(ChatMessage { + text, + links: wire.links, + })) + } +} + +/// Splits only at UTF-8 character boundaries, keeping each CBOR text string +/// inside the header decoder's declared length limit. +fn chat_text_chunks(text: &str) -> Vec<&str> { + let mut chunks = Vec::new(); + let mut start = 0; + for (index, character) in text.char_indices() { + if index > start && index + character.len_utf8() - start > CHAT_TEXT_CHUNK_BYTES { + chunks.push(&text[start..index]); + start = index; + } + } + if start < text.len() { + chunks.push(&text[start..]); + } + chunks +} + /// The wire form of [`ChainExt`]: the same fields, plus the domain tag. Keys /// this form does not name are refused. `tag`, `document` and `removes` are left /// out when they are `None`, so events of other kinds keep their encoding. @@ -169,7 +259,7 @@ struct Wire { #[serde(default, skip_serializing_if = "Option::is_none")] rotation: Option, #[serde(default, skip_serializing_if = "Option::is_none")] - chat: Option, + chat: Option, } impl From for Wire { @@ -186,7 +276,7 @@ impl From for Wire { link: ext.link, checkpoint: ext.checkpoint, rotation: ext.rotation, - chat: ext.chat, + chat: ext.chat.map(HeaderChatMessage), } } } @@ -209,7 +299,7 @@ impl TryFrom for ChainExt { link: wire.link, checkpoint: wire.checkpoint, rotation: wire.rotation, - chat: wire.chat, + chat: wire.chat.map(|message| message.0), }; ext.validate()?; Ok(ext) @@ -1038,6 +1128,8 @@ mod tests { }, }), rotation: None, + + chat: None, }, ) .unwrap() diff --git a/pkgs/id/src/chat.rs b/pkgs/id/src/chat.rs index 9b8d6d8a73..587cb527a4 100644 --- a/pkgs/id/src/chat.rs +++ b/pkgs/id/src/chat.rs @@ -38,9 +38,10 @@ use std::collections::{BTreeMap, HashMap, HashSet, VecDeque}; use p2panda_core::Hash; use serde::{Deserialize, Serialize}; +use unicode_normalization::{UnicodeNormalization, is_nfc}; -use crate::text::sanitize_chat; use crate::groups::policy::History; +use crate::text::sanitize_chat; use crate::waiting::AuthorKey; /// The kind of a `chat.message.v1` event, as the header's `kind` names it. @@ -111,6 +112,9 @@ impl ChatLink { hint.len() ))); } + if self.hint.as_deref().is_some_and(|hint| !is_nfc(hint)) { + return Err(ChatError::Hint("the hint is not NFC".to_owned())); + } Ok(()) } @@ -152,10 +156,17 @@ impl ChatMessage { /// Returns [`ChatError::Text`] when the sanitized text is empty or too long, and the /// failing link's error when a link is refused. pub fn new(text: &str, links: Vec) -> Result { - let message = Self { - text: sanitize_chat(text), - links, - }; + let text = sanitize_chat(text).nfc().collect(); + let links = links + .into_iter() + .map(|mut link| { + if let Some(hint) = &mut link.hint { + *hint = hint.nfc().collect(); + } + link + }) + .collect(); + let message = Self { text, links }; message.check()?; Ok(message) } @@ -175,6 +186,9 @@ impl ChatMessage { if self.text.is_empty() { return Err(ChatError::Text("the text is empty".to_owned())); } + if !is_nfc(&self.text) { + return Err(ChatError::Text("the text is not NFC".to_owned())); + } if self.text.len() > MAX_TEXT_BYTES { return Err(ChatError::Text(format!( "the text is {} bytes, it must be at most {MAX_TEXT_BYTES}", @@ -452,7 +466,10 @@ pub fn visible_history( #[cfg(test)] #[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] mod tests { + use p2panda_core::SigningKey; + use super::*; + use crate::chain::{ChainExt, decode, sign}; fn author(seed: u8) -> AuthorKey { [seed; 32] @@ -509,7 +526,8 @@ mod tests { let full = visible_history(timeline.clone(), &History::Full, Some(&join), &parents); assert_eq!(full.len(), 3); - let from_join = visible_history(timeline.clone(), &History::FromJoin, Some(&join), &parents); + let from_join = + visible_history(timeline.clone(), &History::FromJoin, Some(&join), &parents); let texts: Vec<&str> = from_join.iter().map(|r| r.message.text.as_str()).collect(); assert_eq!(texts, vec!["after the join", "chained"]); @@ -643,4 +661,82 @@ mod tests { let texts: Vec<&str> = timeline.iter().map(|r| r.message.text.as_str()).collect(); assert_eq!(texts, vec!["first from seven", "second from seven"]); } + + fn chat_ext(message: ChatMessage) -> ChainExt { + ChainExt { + kind: CHAT_MESSAGE_KIND.to_owned(), + group: None, + after: Vec::new(), + tag: None, + document: None, + removes: None, + note: None, + link: None, + checkpoint: None, + rotation: None, + chat: Some(message), + } + } + + fn decode_round_trip(message: ChatMessage) -> ChatMessage { + let event = sign( + &SigningKey::from_bytes(&[7; 32]), + 0, + None, + None, + chat_ext(message), + ) + .unwrap(); + let decoded = decode(&event.bytes).unwrap(); + decoded.header.extensions.chat.unwrap() + } + + fn blob_link(hint: Option<&str>) -> ChatLink { + ChatLink { + kind: ChatLinkKind::Blob, + hash: Hash::digest(b"attachment"), + author: author(1), + hint: hint.map(str::to_owned), + } + } + + #[test] + fn test_text_within_the_message_cap_crosses_the_header_decoder() { + // A full 2,048-byte message of multibyte text is split into header-sized + // chunks and decodes to the same text; the message limit is still enforced. + let text = "\u{e9}".repeat(MAX_TEXT_BYTES / 2); + assert_eq!(text.len(), MAX_TEXT_BYTES); + let message = ChatMessage::new(&text, Vec::new()).unwrap(); + assert_eq!(decode_round_trip(message.clone()), message); + assert!(matches!( + ChatMessage::new(&"a".repeat(MAX_TEXT_BYTES + 1), Vec::new()), + Err(ChatError::Text(_)) + )); + } + + #[test] + fn test_messages_and_hint_strings_normalize_to_nfc_before_signing() { + // The header decoder requires NFC text. A built message normalizes instead of + // failing later on its own ingestion. + let message = ChatMessage::new("e\u{301}", Vec::new()).unwrap(); + assert_eq!(message.text, "\u{e9}"); + assert_eq!(decode_round_trip(message.clone()), message); + + let hinted = ChatMessage::new("see this", vec![blob_link(Some("re\u{301}lay"))]).unwrap(); + assert_eq!(hinted.links[0].hint.as_deref(), Some("r\u{e9}lay")); + assert_eq!(decode_round_trip(hinted.clone()), hinted); + + // A manually built value that skipped normalization is refused rather than + // producing an event the decoder cannot read back. + let raw = ChatMessage { + text: "e\u{301}".to_owned(), + links: Vec::new(), + }; + assert!(matches!(raw.check(), Err(ChatError::Text(_)))); + let raw_hint = ChatMessage { + text: "hello".to_owned(), + links: vec![blob_link(Some("re\u{301}lay"))], + }; + assert!(matches!(raw_hint.check(), Err(ChatError::Hint(_)))); + } } diff --git a/pkgs/id/src/currency.rs b/pkgs/id/src/currency.rs index 0ffb6807f3..8b783cef3e 100644 --- a/pkgs/id/src/currency.rs +++ b/pkgs/id/src/currency.rs @@ -352,6 +352,8 @@ pub fn sign_authorisation( link: None, checkpoint: None, rotation: None, + + chat: None, }, )?) } @@ -385,6 +387,8 @@ pub fn sign_revoke( link: None, checkpoint: None, rotation: None, + + chat: None, }, )?) } diff --git a/pkgs/id/src/currency/graph.rs b/pkgs/id/src/currency/graph.rs index 3dec5bfc34..c50fc4c5d2 100644 --- a/pkgs/id/src/currency/graph.rs +++ b/pkgs/id/src/currency/graph.rs @@ -467,6 +467,8 @@ fn sign_body( link: None, checkpoint: None, rotation: None, + + chat: None, }, )?) } diff --git a/pkgs/id/src/event_store/chat.rs b/pkgs/id/src/event_store/chat.rs index 71ccd55e18..78ce1ba45b 100644 --- a/pkgs/id/src/event_store/chat.rs +++ b/pkgs/id/src/event_store/chat.rs @@ -12,14 +12,16 @@ //! projected timeline cut by the group policy's history rule (see //! [`crate::chat::visible_history`] for the exact semantics of each rule). -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use p2panda_auth::group::{GroupAction, GroupMember}; use p2panda_core::Hash; use redb::{ReadableDatabase, ReadableTable}; use super::resolve::{self, author_of}; -use super::{ACTIONS, APPLIED, EVENTS, EventStore, FORKS, PROOF_HEADERS, StoreError, corrupt, decode_stored}; +use super::{ + ACTIONS, APPLIED, 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}; use crate::membership::AuthId; @@ -39,13 +41,39 @@ impl EventStore { let events = txn.open_table(EVENTS)?; let applied_table = txn.open_table(APPLIED)?; - let mut records = Vec::new(); + let mut applied_events = Vec::new(); for row in events.iter()? { let (_position, bytes) = row?; let event = decode_stored(bytes.value())?; if applied_table.get(event.id.as_bytes().as_slice())?.is_none() { continue; } + applied_events.push(event); + } + + // Chat projection only receives chat records. Preserve causal paths that + // pass through other event kinds by adding reachable chat ancestors to + // each record's projection frontier. + let chat_ids: HashSet = applied_events + .iter() + .filter_map(|event| { + let ext = &event.header.extensions; + (ext.kind == CHAT_MESSAGE_KIND && ext.group == Some(*group)).then_some(event.id) + }) + .collect(); + let causal_parents: HashMap> = applied_events + .iter() + .map(|event| { + let mut parents = event.header.extensions.after.clone(); + if let Some(backlink) = event.header.backlink { + parents.push(backlink); + } + (event.id, parents) + }) + .collect(); + + let mut records = Vec::new(); + for event in applied_events { let ext = &event.header.extensions; if ext.kind != CHAT_MESSAGE_KIND || ext.group != Some(*group) { continue; @@ -53,10 +81,34 @@ impl EventStore { let Some(message) = ext.chat.clone() else { return Err(corrupt("a stored chat event carries no message".to_owned())); }; + let mut ancestors = HashSet::new(); + let mut stack = causal_parents.get(&event.id).cloned().unwrap_or_default(); + let mut chat_ancestors = Vec::new(); + while let Some(parent) = stack.pop() { + if !ancestors.insert(parent) { + continue; + } + if chat_ids.contains(&parent) { + // The projection follows chat-to-chat links transitively, so + // retain only the nearest chat ancestor on each causal path. + chat_ancestors.push(parent); + continue; + } + if let Some(parents) = causal_parents.get(&parent) { + stack.extend(parents.iter().copied()); + } + } + chat_ancestors.sort_by_key(|ancestor| *ancestor.as_bytes()); + let mut after = ext.after.clone(); + for ancestor in chat_ancestors { + if Some(ancestor) != event.header.backlink && !after.contains(&ancestor) { + after.push(ancestor); + } + } records.push(ChatRecord { id: event.id, author: author_of(&event), - after: ext.after.clone(), + after, backlink: event.header.backlink, message, }); @@ -141,7 +193,12 @@ impl EventStore { parents.insert(item.event.id, event_parents); } let join = join_event(&stored, &resolved.applied, reader, &parents); - Ok(visible_history(timeline, &policy.history, join.as_ref(), &parents)) + Ok(visible_history( + timeline, + &policy.history, + join.as_ref(), + &parents, + )) } } @@ -154,18 +211,16 @@ fn join_event( reader: &AuthorKey, parents: &HashMap>, ) -> Option { - let names_reader = |member: &GroupMember| { - matches!(member, GroupMember::Individual(AuthId::Key(key)) if key == reader) - }; + let names_reader = |member: &GroupMember| matches!(member, GroupMember::Individual(AuthId::Key(key)) if key == reader); let mut candidates: Vec = Vec::new(); for item in stored { if !applied.contains(&item.event.id) { continue; } let joined = match &item.action { - Some(GroupAction::Create { initial_members }) => { - initial_members.iter().any(|(member, _)| names_reader(member)) - } + Some(GroupAction::Create { initial_members }) => initial_members + .iter() + .any(|(member, _)| names_reader(member)), Some(GroupAction::Add { member, .. }) => names_reader(member), _ => false, }; @@ -237,6 +292,10 @@ mod tests { document: None, removes: None, chat: None, + note: None, + link: None, + checkpoint: None, + rotation: None, }; let event = sign(key, seq, backlink, Some(&body), ext).unwrap(); (event, body) @@ -259,12 +318,23 @@ mod tests { document: None, removes: None, chat: Some(ChatMessage::new(text, Vec::new()).unwrap()), + note: None, + link: None, + checkpoint: None, + rotation: None, }; sign(key, seq, backlink, None, ext).unwrap() } /// A store holding a channel created by Alice with Bob as a member. - fn channel() -> (tempfile::TempDir, EventStore, SigningKey, SigningKey, Hash, Hash) { + fn channel() -> ( + tempfile::TempDir, + EventStore, + SigningKey, + SigningKey, + Hash, + Hash, + ) { let (dir, mut store) = open(); let (alice, bob) = (key(41), key(42)); let create = GroupAction::Create { @@ -286,7 +356,14 @@ mod tests { fn test_chat_records_convert_stored_events_and_bind_to_the_group() { let (_dir, mut store, alice, bob, group, create_id) = channel(); - let first = chat_event(&alice, 1, Some(create_id), vec![], group, "hello from alice"); + let first = chat_event( + &alice, + 1, + Some(create_id), + vec![], + group, + "hello from alice", + ); store.ingest(&first.bytes, 0).unwrap(); let second = chat_event(&bob, 0, None, vec![create_id], group, "hello from bob"); store.ingest(&second.bytes, 0).unwrap(); @@ -375,6 +452,69 @@ mod tests { )); } + #[test] + fn test_chat_records_keep_causal_order_across_a_non_chat_event() { + // Alice writes, records a non-chat event, then writes again. Her second chat + // event names the non-chat event as its backlink, so the two messages are only + // causally ordered through it. + let (_dir, mut store, alice, _bob, group, create_id) = channel(); + let first = chat_event(&alice, 1, Some(create_id), vec![], group, "first"); + store.ingest(&first.bytes, 0).unwrap(); + + let intervening = sign( + &alice, + 2, + Some(first.id), + None, + ChainExt { + kind: "message".to_owned(), + group: None, + after: Vec::new(), + tag: None, + document: None, + removes: None, + chat: None, + note: None, + link: None, + checkpoint: None, + rotation: None, + }, + ) + .unwrap(); + store.ingest(&intervening.bytes, 0).unwrap(); + assert!(store.event_applied(&intervening.id).unwrap()); + + let second = chat_event(&alice, 3, Some(intervening.id), vec![], group, "second"); + store.ingest(&second.bytes, 0).unwrap(); + + let timeline = store.chat_timeline(&group, &author(&alice)).unwrap(); + let texts: Vec<&str> = timeline.iter().map(|r| r.message.text.as_str()).collect(); + assert_eq!(texts, vec!["first", "second"]); + } + + #[test] + fn test_chat_from_a_non_member_does_not_apply() { + // An outsider signs a chat event naming the channel group, with the group's + // create in its causal past, and delivers it directly to the store. The local + // send path's membership check cannot stop a received event, so resolution + // must: the event does not apply and never reaches a member's timeline + // (Codex P1 on PR #3965). + let (_dir, mut store, alice, _bob, group, create_id) = channel(); + let carol = key(43); + let forged = chat_event( + &carol, + 0, + None, + vec![create_id], + group, + "forged from outside", + ); + store.ingest(&forged.bytes, 0).unwrap(); + assert!(!store.event_applied(&forged.id).unwrap()); + let timeline = store.chat_timeline(&group, &author(&alice)).unwrap(); + assert!(timeline.is_empty()); + } + #[test] fn test_group_policy_comes_from_the_create() { let (_dir, store, _alice, _bob, group, _create) = channel(); diff --git a/pkgs/id/src/event_store/ingest.rs b/pkgs/id/src/event_store/ingest.rs index 12e0786eb5..7c2801b0c1 100644 --- a/pkgs/id/src/event_store/ingest.rs +++ b/pkgs/id/src/event_store/ingest.rs @@ -1574,6 +1574,8 @@ mod tests { }, }), rotation: None, + + chat: None, }; let y0 = sign(&y, 0, None, None, ext).unwrap(); assert_eq!(ingest(&mut store, &y0), Ingest::Waiting { id: y0.id }); @@ -1632,6 +1634,8 @@ mod tests { }, }), rotation: None, + + chat: None, }; sign(key, seq, backlink, None, ext).unwrap() } diff --git a/pkgs/id/src/event_store/resolve.rs b/pkgs/id/src/event_store/resolve.rs index 28820cec50..0a179b973d 100644 --- a/pkgs/id/src/event_store/resolve.rs +++ b/pkgs/id/src/event_store/resolve.rs @@ -44,6 +44,7 @@ use redb::ReadableTable; 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, @@ -79,6 +80,12 @@ struct Node { /// 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, + /// True for a `chat.message.v1` event: chat content is membership-gated at its causal + /// position (see [`content_applies`]). + chat: bool, + /// The author's own previous event, from the header backlink. A chat event's + /// membership position includes it: a first message may name its group only here. + backlink: Option, } /// The author of an event. @@ -113,6 +120,8 @@ pub(super) fn resolve( after: event.header.extensions.after.clone(), action: item.action.clone(), excluded, + chat: event.header.extensions.kind == CHAT_MESSAGE_KIND, + backlink: event.header.backlink, }); } for header in proof_headers { @@ -127,6 +136,8 @@ pub(super) fn resolve( after: header.header.extensions.after.clone(), action: None, excluded: true, + chat: header.header.extensions.kind == CHAT_MESSAGE_KIND, + backlink: header.header.backlink, }); } @@ -162,11 +173,20 @@ pub(super) fn resolve( if let Some(layer) = membership.as_mut() { for &index in &order { let node = &nodes[index]; + // The layer's causal graph is the full one: an event also follows its + // author's previous event (the header backlink), not only the frontier + // its `after` names. Without the backlink edges, a position reached + // only through an author's own chain — a chat message whose past runs + // through the author's non-chat events, say — cannot be judged, and + // membership at that position reads as absent (Codex P1 on PR #3965). let after: Vec = node .after .iter() + .chain(node.backlink.iter()) .filter(|dep| position.contains_key(dep)) .copied() + .collect::>() + .into_iter() .collect(); let role = match (&node.action, node.excluded) { (Some(action), false) if !voided.contains(&node.id) => Role::Auth { @@ -417,19 +437,37 @@ fn role_of(access: &p2panda_auth::Access<()>) -> GroupRole { } /// Whether content applies. It applies unless it names a voided event and its author is not a -/// member of its group at its position. +/// member of its group at its position. A chat message is judged by the same membership rule +/// whether or not it names a voided event (Codex P1 on PR #3965): the local `send_chat` check +/// only governs cooperative senders, so a `chat.message.v1` event an outsider signed and +/// delivered through ingest or sync must not apply — and so never reach a member's timeline — +/// unless its author was a member of the group at the event's causal position. That position +/// includes the author's backlink, because a member's first message in a group may name the +/// group only through it. fn content_applies( node: &Node, applied: &HashSet, membership: Option<&mut Membership>, ) -> Result { let names_voided = node.after.iter().any(|dep| !applied.contains(dep)); - let (Some(group), Some(layer), true) = (node.group, membership, names_voided) else { + let gated = names_voided || node.chat; + let (Some(group), Some(layer), true) = (node.group, membership, gated) else { return Ok(true); }; if !layer.has_group(group) { return Ok(true); } + if node.chat { + let mut position = node.after.clone(); + if let Some(backlink) = node.backlink + && !position.contains(&backlink) + { + position.push(backlink); + } + return layer + .is_member_at(node.author, group, &position) + .map_err(|err| corrupt(format!("the membership layer: {err}"))); + } layer .is_member_at(node.author, group, &node.after) .map_err(|err| corrupt(format!("the membership layer: {err}"))) @@ -590,6 +628,8 @@ mod tests { after: after.iter().map(|a| Hash::digest([*a])).collect(), action: None, excluded: false, + chat: false, + backlink: None, } } @@ -610,6 +650,8 @@ mod tests { after: base[i].after.clone(), action: None, excluded: false, + chat: false, + backlink: None, }) .collect(); let position: HashMap = nodes @@ -676,6 +718,8 @@ mod tests { )], }), excluded: false, + chat: false, + backlink: None, }; let pass_through = Node { id: Hash::digest([42]), @@ -684,6 +728,8 @@ mod tests { after: vec![Hash::digest([41])], action: None, excluded: true, + chat: false, + backlink: None, }; vec![create, pass_through] } @@ -711,6 +757,8 @@ mod tests { )], }), excluded: false, + chat: false, + backlink: None, }; assert!(matches!(fold_projection_checked(&[create]), Ok(Some(_)))); diff --git a/pkgs/id/src/event_store/sync.rs b/pkgs/id/src/event_store/sync.rs index 1774fd6942..a5c9d2d212 100644 --- a/pkgs/id/src/event_store/sync.rs +++ b/pkgs/id/src/event_store/sync.rs @@ -1277,6 +1277,7 @@ mod tests { link: None, checkpoint: None, rotation: None, + chat: None, } } // The group create, by A, listing A, B and C as managers. The group is diff --git a/pkgs/id/src/issuer_rotation.rs b/pkgs/id/src/issuer_rotation.rs index eabfb2c570..f03bafdcb3 100644 --- a/pkgs/id/src/issuer_rotation.rs +++ b/pkgs/id/src/issuer_rotation.rs @@ -753,6 +753,8 @@ pub fn sign_rotation( link: None, checkpoint: None, rotation: Some(rotation.clone()), + + chat: None, }, )?) } diff --git a/pkgs/id/src/local_events.rs b/pkgs/id/src/local_events.rs index 2094c3f476..ab4778cca8 100644 --- a/pkgs/id/src/local_events.rs +++ b/pkgs/id/src/local_events.rs @@ -25,12 +25,12 @@ use crate::chain::{ChainExt, Event, MAX_AFTER, sign}; use crate::chat::{CHAT_MESSAGE_KIND, ChatMessage, ChatRecord, SendRate}; use crate::documents::{DOCUMENT_KIND, DocumentRef, REMOVAL_KIND}; use crate::event_store::{EventStore, Ingest}; +use crate::local_claims::LocalClaims; use crate::notes::{ AppliedNote, CREATE_KIND as NOTE_CREATE_KIND, NoteFoldError, NoteOp, NoteRecord, REVISE_KIND as NOTE_REVISE_KIND, check_note_op, fold_notes, }; use crate::search::{Hit, ValueMatch, search_store}; -use crate::local_claims::LocalClaims; use crate::tag_claims::{ CLEAR_KIND, Claim, LocalClaim, MAX_CLEAR_CLAIMS, SET_KIND, TagOp, TagScope, check_op, }; @@ -297,7 +297,16 @@ impl LocalEvents { bail!("a publish names the same tag twice"); } } - let id = self.record(DOCUMENT_KIND, None, None, Some(document.clone()), None, None, None, &[])?; + let id = self.record( + DOCUMENT_KIND, + None, + None, + Some(document.clone()), + None, + None, + None, + &[], + )?; let mut claims = Vec::with_capacity(tags.len()); for (name, value) in tags { claims.push(self.set_tag(id, name, value.as_deref())?); @@ -417,21 +426,14 @@ impl LocalEvents { /// # Errors /// /// Fails if the store cannot be read or written, or the local claim file cannot be written. - pub fn set_tag_scope( - &mut self, - subject: Hash, - name: &str, - scope: TagScope, - ) -> Result { + pub fn set_tag_scope(&mut self, subject: Hash, name: &str, scope: TagScope) -> Result { let me = self.author(); let mut moved = 0; let shared: Vec = self .store .tag_claims()? .into_iter() - .filter(|claim| { - claim.subject == subject && claim.name == name && claim.author == me - }) + .filter(|claim| claim.subject == subject && claim.name == name && claim.author == me) .collect(); match scope { TagScope::Local => { @@ -615,7 +617,12 @@ impl LocalEvents { .into_iter() .filter(|claim| claim.subject == subject) .collect(); - claims.extend(self.local.on_subject(&subject).iter().map(LocalClaim::as_claim)); + claims.extend( + self.local + .on_subject(&subject) + .iter() + .map(LocalClaim::as_claim), + ); claims.sort_by_key(|claim| *claim.id.as_bytes()); Ok(claims) } @@ -667,7 +674,16 @@ impl LocalEvents { let content = DocumentRef::for_bytes(media_type, content)?; let op = NoteOp::Create { content }; check_note_op(NOTE_CREATE_KIND, &op)?; - self.record(NOTE_CREATE_KIND, None, None, None, None, Some(op), None, &[]) + self.record( + NOTE_CREATE_KIND, + None, + None, + None, + None, + Some(op), + None, + &[], + ) } /// Adds one revision with `content` to the note `note`, building on `parents`. The @@ -720,7 +736,16 @@ impl LocalEvents { parents: parents.to_vec(), }; check_note_op(NOTE_REVISE_KIND, &op)?; - self.record(NOTE_REVISE_KIND, None, None, None, None, Some(op), None, &required) + self.record( + NOTE_REVISE_KIND, + None, + None, + None, + None, + Some(op), + None, + &required, + ) } /// Every note in the store, in note ID order, each with its revisions and heads. @@ -1281,6 +1306,8 @@ mod tests { link: None, checkpoint: None, rotation: None, + + chat: None, }, ) .unwrap(); @@ -1458,7 +1485,10 @@ mod tests { assert!(events.store.tag_claims().unwrap().is_empty()); assert_eq!(events.store.sync_entries().unwrap(), before); assert_eq!(events.review_tags().unwrap(), visible); - assert_eq!(events.search("city", Some("Oslo")).unwrap()[0].claims, visible); + assert_eq!( + events.search("city", Some("Oslo")).unwrap()[0].claims, + visible + ); } #[test] @@ -1469,7 +1499,12 @@ mod tests { .set_tag_scoped(subject, "city", Some("Oslo"), TagScope::Local) .unwrap(); - assert_eq!(events.set_tag_scope(subject, "city", TagScope::Shared).unwrap(), 1); + assert_eq!( + events + .set_tag_scope(subject, "city", TagScope::Shared) + .unwrap(), + 1 + ); let shared = events.tags_on(subject).unwrap(); assert_eq!(shared.len(), 1); assert_eq!(shared[0].scope, TagScope::Shared); @@ -1477,7 +1512,12 @@ mod tests { assert!(events.local.claims().is_empty()); assert_eq!(events.store.tag_claims().unwrap(), shared); - assert_eq!(events.set_tag_scope(subject, "city", TagScope::Local).unwrap(), 1); + assert_eq!( + events + .set_tag_scope(subject, "city", TagScope::Local) + .unwrap(), + 1 + ); let local = events.tags_on(subject).unwrap(); assert_eq!(local.len(), 1); assert_eq!(local[0].scope, TagScope::Local); @@ -1665,6 +1705,11 @@ mod chat_tests { document: None, removes: None, chat: None, + + note: None, + link: None, + checkpoint: None, + rotation: None, }; let event = sign(alice, 0, None, Some(&body), ext).unwrap(); (event, body) @@ -1710,10 +1755,16 @@ mod chat_tests { assert!(node_c.store.chat_records(&group).unwrap().is_empty()); let first = node_a - .send_chat(group, ChatMessage::new("hello from alice", Vec::new()).unwrap()) + .send_chat( + group, + ChatMessage::new("hello from alice", Vec::new()).unwrap(), + ) .unwrap(); let second = node_b - .send_chat(group, ChatMessage::new("hello from bob", Vec::new()).unwrap()) + .send_chat( + group, + ChatMessage::new("hello from bob", Vec::new()).unwrap(), + ) .unwrap(); exchange(&node_a, &mut node_b); @@ -1757,10 +1808,7 @@ mod chat_tests { ) .unwrap(); } - let refused = node.send_chat( - group, - ChatMessage::new("one too many", Vec::new()).unwrap(), - ); + let refused = node.send_chat(group, ChatMessage::new("one too many", Vec::new()).unwrap()); assert!(refused.is_err()); } } diff --git a/pkgs/id/src/log_sync.rs b/pkgs/id/src/log_sync.rs index e9dee6f162..4aeb1f1c73 100644 --- a/pkgs/id/src/log_sync.rs +++ b/pkgs/id/src/log_sync.rs @@ -977,6 +977,7 @@ mod tests { link: None, checkpoint: None, rotation: None, + chat: None, } } let create_body = encode_body(&GroupAction::Create { @@ -986,15 +987,36 @@ mod tests { .collect(), }) .unwrap(); - let create = sign(&key(b'A'), 0, None, Some(&create_body), ext(None, Vec::new(), "group.op")).unwrap(); + let create = sign( + &key(b'A'), + 0, + None, + Some(&create_body), + ext(None, Vec::new(), "group.op"), + ) + .unwrap(); let grp = create.id; let op_body = encode_body(&GroupAction::Add { member: GroupMember::Individual(gauth(b'E')), access: Access::manage(), }) .unwrap(); - let op = sign(&key(b'D'), 0, None, Some(&op_body), ext(Some(grp), vec![grp], "group.op")).unwrap(); - let target = sign(&key(b'D'), 1, Some(op.id), None, ext(Some(grp), vec![op.id], "message")).unwrap(); + let op = sign( + &key(b'D'), + 0, + None, + Some(&op_body), + ext(Some(grp), vec![grp], "group.op"), + ) + .unwrap(); + let target = sign( + &key(b'D'), + 1, + Some(op.id), + None, + ext(Some(grp), vec![op.id], "message"), + ) + .unwrap(); let (_da, store_a) = open(); let (_db, store_b) = open(); @@ -1031,7 +1053,11 @@ mod tests { assert_eq!(outcome.method, SyncMethod::Range); assert_eq!(answered.method, SyncMethod::Range); - assert_eq!(outcome.received.voided, 1, "B stores the target without applying it: {:?}", outcome.received); + assert_eq!( + outcome.received.voided, 1, + "B stores the target without applying it: {:?}", + outcome.received + ); assert_eq!(outcome.received.accepted, 0, "{:?}", outcome.received); assert_eq!(outcome.received.refused, 0, "{:?}", outcome.received); assert_eq!(answered.received.voided, 0, "{:?}", answered.received); diff --git a/pkgs/id/src/world/signed.rs b/pkgs/id/src/world/signed.rs index e390ac97bf..afdb5be355 100644 --- a/pkgs/id/src/world/signed.rs +++ b/pkgs/id/src/world/signed.rs @@ -87,6 +87,8 @@ pub fn sign_move( link: None, checkpoint: None, rotation: None, + + chat: None, }, ) } diff --git a/pkgs/id/tests/retention_pruning.rs b/pkgs/id/tests/retention_pruning.rs index e722c90599..0f10ff4ed8 100644 --- a/pkgs/id/tests/retention_pruning.rs +++ b/pkgs/id/tests/retention_pruning.rs @@ -136,6 +136,8 @@ impl Chains { link: None, checkpoint: None, rotation: None, + + chat: None, }; let event = sign(&key(who), seq, backlink, None, ext).unwrap(); self.last.insert(who, (seq, event.id)); @@ -174,6 +176,8 @@ impl Chains { link: None, checkpoint: None, rotation: None, + + chat: None, }; let event = sign(&key(who), seq, backlink, None, ext).unwrap(); self.last.insert(who, (seq, event.id)); @@ -210,6 +214,8 @@ impl Chains { }), checkpoint: None, rotation: None, + + chat: None, }; let event = sign(&key(who), seq, backlink, None, ext).unwrap(); self.last.insert(who, (seq, event.id)); diff --git a/pkgs/id/tests/tag_clear_authority.rs b/pkgs/id/tests/tag_clear_authority.rs index 3ce9995ed6..7f4a89b1f1 100644 --- a/pkgs/id/tests/tag_clear_authority.rs +++ b/pkgs/id/tests/tag_clear_authority.rs @@ -54,6 +54,8 @@ impl Chains { link: None, checkpoint: None, rotation: None, + + chat: None, }; let event = sign(&key(who), seq, backlink, body.as_deref(), ext).unwrap(); self.last.insert(who, (seq, event.id));