diff --git a/.github/workflows/_ci-relay.yml b/.github/workflows/_ci-relay.yml index f9eb369724..cbe5cd4882 100644 --- a/.github/workflows/_ci-relay.yml +++ b/.github/workflows/_ci-relay.yml @@ -129,6 +129,7 @@ jobs: --test e2e_event_reminder \ --test e2e_author_only_deletion \ --test e2e_existence_oracle \ + --test e2e_channel_pins \ --archive-file target/ci/backend-integration-tests.tar.zst - name: Build PostgreSQL test archive if: steps.relay-artifacts-cache.outputs.cache-hit != 'true' && matrix.artifact == 'postgres-tests' @@ -648,7 +649,7 @@ jobs: run: | cargo nextest run \ --archive-file target/ci/backend-integration-tests.tar.zst \ - -E 'binary(e2e_event_reminder) | binary(e2e_author_only_deletion) | binary(e2e_existence_oracle)' \ + -E 'binary(e2e_event_reminder) | binary(e2e_author_only_deletion) | binary(e2e_existence_oracle) | binary(e2e_channel_pins)' \ --run-ignored ignored-only env: RELAY_URL: ws://localhost:3000 diff --git a/crates/buzz-core/src/channel.rs b/crates/buzz-core/src/channel.rs index 36ee3f43c2..165d29238d 100644 --- a/crates/buzz-core/src/channel.rs +++ b/crates/buzz-core/src/channel.rs @@ -41,6 +41,9 @@ pub const MAX_CHANNEL_LABELS: usize = 8; /// Maximum length of one channel label, in bytes. pub const MAX_CHANNEL_LABEL_LEN: usize = 64; +/// Maximum number of messages one channel can pin (NIP-PM). +pub const MAX_CHANNEL_PINS: usize = 250; + /// Names a label may not take, because the channel type uses the same `t` /// tag. A label equal to one of these could make a channel look like /// another type. The list includes types that a later relay may add. diff --git a/crates/buzz-core/src/kind.rs b/crates/buzz-core/src/kind.rs index 754d0016a3..732b7a794d 100644 --- a/crates/buzz-core/src/kind.rs +++ b/crates/buzz-core/src/kind.rs @@ -511,6 +511,11 @@ pub const KIND_WORKFLOW_DEF: u32 = 30620; /// `hidden_at` per viewer; this is the only Nostr-visible projection of it. pub const KIND_DM_VISIBILITY: u32 = 30622; +/// NIP-PM: a channel's pin list (relay-signed, parameterized replaceable, +/// d=channel_id, h=channel_id). One `e` tag per pinned message, newest pin first. Members +/// change it only through [`KIND_PIN_MESSAGE`] and [`KIND_UNPIN_MESSAGE`]. +pub const KIND_CHANNEL_PINS: u32 = 30623; + /// Lower bound of the NIP-33 parameterized replaceable range (30000–39999). pub const PARAM_REPLACEABLE_KIND_MIN: u32 = 30000; /// Upper bound of the NIP-33 parameterized replaceable range (30000–39999). @@ -547,7 +552,8 @@ pub const KIND_STREAM_MESSAGE: u32 = 9; pub const KIND_STREAM_MESSAGE_V2: u32 = 40002; /// V1 used kind:10004 (replaceable range + NIP-51 collision — wrong). pub const KIND_STREAM_MESSAGE_EDIT: u32 = 40003; -/// A stream message that has been pinned in a channel. +/// A stream message that has been pinned in a channel. Not a NIP-PM pin: +/// see [`KIND_PIN_MESSAGE`]. pub const KIND_STREAM_MESSAGE_PINNED: u32 = 40004; /// A stream message that has been bookmarked by a user. pub const KIND_STREAM_MESSAGE_BOOKMARKED: u32 = 40005; @@ -557,6 +563,18 @@ pub const KIND_STREAM_MESSAGE_SCHEDULED: u32 = 40006; pub const KIND_STREAM_REMINDER: u32 = 40007; /// A diff/patch message showing file changes (unified diff format). pub const KIND_STREAM_MESSAGE_DIFF: u32 = 40008; +/// NIP-PM: member-signed command that pins one message of its `h` channel. +pub const KIND_PIN_MESSAGE: u32 = 40010; +/// NIP-PM: member-signed command that unpins one message of its `h` channel. +pub const KIND_UNPIN_MESSAGE: u32 = 40011; +/// NIP-PM: the message kinds a channel can pin. +pub const PINNABLE_KINDS: [u32; 5] = [ + KIND_STREAM_MESSAGE, + KIND_STREAM_MESSAGE_V2, + KIND_STREAM_MESSAGE_DIFF, + KIND_FORUM_POST, + KIND_FORUM_COMMENT, +]; /// Canvas (shared document) for a channel. pub const KIND_CANVAS: u32 = 40100; /// System message for channel state changes (join, leave, rename, etc.). @@ -786,11 +804,14 @@ pub const ALL_KINDS: &[u32] = &[ KIND_STREAM_MESSAGE_SCHEDULED, KIND_STREAM_REMINDER, KIND_STREAM_MESSAGE_DIFF, + KIND_PIN_MESSAGE, + KIND_UNPIN_MESSAGE, KIND_CANVAS, KIND_SYSTEM_MESSAGE, KIND_CHANNEL_SUMMARY, KIND_PRESENCE_SNAPSHOT, KIND_DM_VISIBILITY, + KIND_CHANNEL_PINS, KIND_DM_OPEN, KIND_DM_ADD_MEMBER, KIND_DM_HIDE, @@ -934,6 +955,7 @@ pub const fn is_relay_only_kind(kind: u32) -> bool { | KIND_CHANNEL_SUMMARY | KIND_PRESENCE_SNAPSHOT | KIND_DM_VISIBILITY + | KIND_CHANNEL_PINS | KIND_THREAD_SUMMARY | KIND_WINDOW_BOUNDS | KIND_THREAD_WINDOW_BOUNDS @@ -965,6 +987,7 @@ const _: () = assert!(is_parameterized_replaceable(KIND_EMOJI_ENTRY)); // 30180 const _: () = assert!(is_parameterized_replaceable(KIND_WORKFLOW_DEF)); // 30620 ∈ 30000–39999 const _: () = assert!(is_parameterized_replaceable(KIND_EVENT_REMINDER)); // 30300 ∈ 30000–39999 const _: () = assert!(is_parameterized_replaceable(KIND_DM_VISIBILITY)); // 30622 ∈ 30000–39999 +const _: () = assert!(is_parameterized_replaceable(KIND_CHANNEL_PINS)); // 30623 ∈ 30000–39999 const _: () = assert!(is_parameterized_replaceable(KIND_PROJECT)); // 30621 ∈ 30000–39999 const _: () = assert!(is_parameterized_replaceable(KIND_THREAD_SUMMARY)); // 39005 ∈ 30000–39999 const _: () = assert!(is_parameterized_replaceable(KIND_WINDOW_BOUNDS)); // 39006 ∈ 30000–39999 diff --git a/crates/buzz-db/src/lib.rs b/crates/buzz-db/src/lib.rs index 106b46eda3..07e2b8f387 100644 --- a/crates/buzz-db/src/lib.rs +++ b/crates/buzz-db/src/lib.rs @@ -97,9 +97,10 @@ pub use store::{ admin_moderation, allowlist, api_token, archived_identities, artifact, artifact_sync, channel, channel_members, community, community_auth, deletion, dm, entity_deletion, event, feed, git_repo, leader_lock, media, membership_snapshot, moderation, nip_fi_binding, - operator_listener, partition, personal_read, product_feedback, push, reaction, read_state, - relay_admin_actions, relay_invite, relay_members, relay_operators, reminder, replaceable, - storage_accounting, thread, thread_window, user, user_deletion, user_deletion_fences, workflow, + operator_listener, partition, personal_read, pins, product_feedback, push, reaction, + read_state, relay_admin_actions, relay_invite, relay_members, relay_operators, reminder, + replaceable, storage_accounting, thread, thread_window, user, user_deletion, + user_deletion_fences, workflow, }; pub use allowlist::AllowlistEntry; diff --git a/crates/buzz-db/src/store/event.rs b/crates/buzz-db/src/store/event.rs index d9a3209453..59b0222c9b 100644 --- a/crates/buzz-db/src/store/event.rs +++ b/crates/buzz-db/src/store/event.rs @@ -2989,8 +2989,13 @@ impl Db { /// resending a deletion repairs a target an earlier write left live. Ingest /// accepts the resend only within its timestamp window, so this does not /// repair older rows. - /// Returns `(StoredEvent, was_inserted, deleted)`, where `deleted[i]` - /// tells whether `targets[i]` was soft-deleted by this call. + /// + /// A target that is pinned leaves its channel's NIP-PM pin list in the + /// same transaction; the list is re-signed with `relay_signer`. + /// + /// Returns `(StoredEvent, was_inserted, deleted, pin_lists)`, where + /// `deleted[i]` tells whether `targets[i]` was soft-deleted by this call + /// and `pin_lists` holds each pin list this call rewrote. #[datastore_span(name = "insert_deletion_event", system = "postgresql")] pub async fn insert_deletion_event( &self, @@ -2999,7 +3004,8 @@ impl Db { channel_id: Option, thread_meta: Option>, targets: &[crate::event::DeletionTarget<'_>], - ) -> Result<(StoredEvent, bool, Vec)> { + relay_signer: &nostr::Keys, + ) -> Result<(StoredEvent, bool, Vec, Vec)> { let mut tx = crate::begin_community_event_write_transaction( &self.pool, community_id, @@ -3018,8 +3024,9 @@ impl Db { crate::insert_mentions_in_transaction(&mut tx, event, channel_id).await?; } let mut deleted = Vec::with_capacity(targets.len()); + let mut messages = Vec::new(); for target in targets { - deleted.push( + let (was_deleted, channel_id) = crate::event::soft_delete_event_and_update_thread_in_tx( &mut tx, target.event_id, @@ -3027,11 +3034,14 @@ impl Db { target.parent_event_id, target.root_event_id, ) - .await?, - ); + .await?; + deleted.push(was_deleted); + messages.extend(channel_id.map(|channel_id| (channel_id, target.event_id))); } + let pin_lists = + crate::pins::unpin_deleted_messages(&mut tx, &messages, relay_signer).await?; tx.commit().await?; - Ok((stored, inserted, deleted)) + Ok((stored, inserted, deleted, pin_lists)) } /// Soft-delete NIP-29 discovery events for a channel created by a specific relay pubkey. @@ -7291,7 +7301,14 @@ mod postgres_tests { .expect("install failure injection"); let error = db - .insert_deletion_event(community, &deletion, Some(channel), None, &targets) + .insert_deletion_event( + community, + &deletion, + Some(channel), + None, + &targets, + &nostr::Keys::generate(), + ) .await .expect_err("a failed target soft-delete must fail the deletion"); assert!( @@ -7314,8 +7331,15 @@ mod postgres_tests { .execute(&pool) .await .expect("remove failure injection"); - let (_, inserted, deleted) = db - .insert_deletion_event(community, &deletion, Some(channel), None, &targets) + let (_, inserted, deleted, _) = db + .insert_deletion_event( + community, + &deletion, + Some(channel), + None, + &targets, + &nostr::Keys::generate(), + ) .await .expect("resend after the failure clears"); assert!(inserted, "the resend stores the deletion"); @@ -7353,8 +7377,15 @@ mod postgres_tests { root_event_id: None, }]; - let (_, inserted, deleted) = db - .insert_deletion_event(community, &deletion, Some(channel), None, &targets) + let (_, inserted, deleted, _) = db + .insert_deletion_event( + community, + &deletion, + Some(channel), + None, + &targets, + &nostr::Keys::generate(), + ) .await .expect("resend the deletion"); assert!(!inserted, "the deletion was already stored"); @@ -7369,8 +7400,15 @@ mod postgres_tests { .is_some() ); - let (_, inserted, deleted) = db - .insert_deletion_event(community, &deletion, Some(channel), None, &targets) + let (_, inserted, deleted, _) = db + .insert_deletion_event( + community, + &deletion, + Some(channel), + None, + &targets, + &nostr::Keys::generate(), + ) .await .expect("resend again"); assert!(!inserted); diff --git a/crates/buzz-db/src/store/event_deletion.rs b/crates/buzz-db/src/store/event_deletion.rs index 135a460f5b..af6fd783c8 100644 --- a/crates/buzz-db/src/store/event_deletion.rs +++ b/crates/buzz-db/src/store/event_deletion.rs @@ -1,6 +1,9 @@ //! Atomic event deletion, retention-free purging, and thread accounting. -use buzz_core::{kind::KIND_CANVAS, CommunityId}; +use buzz_core::{ + kind::{KIND_CANVAS, KIND_CHANNEL_PINS, PINNABLE_KINDS}, + CommunityId, +}; use chrono::{DateTime, Utc}; use sqlx::PgPool; use uuid::Uuid; @@ -384,7 +387,7 @@ pub async fn soft_delete_event_and_update_thread( crate::observability::WriterOperation::EventWrite, ) .await?; - let deleted = soft_delete_event_and_update_thread_in_tx( + let (deleted, _) = soft_delete_event_and_update_thread_in_tx( &mut tx, event_id, None, @@ -401,13 +404,18 @@ pub async fn soft_delete_event_and_update_thread( /// Callers that must fence the delete with their own writes (e.g. the admin /// action lease/marker) run this inside their transaction; the caller commits. /// `None` discovers the target timestamp once; `Some` never falls back to ID-only. +/// +/// Returns whether this call deleted the event, and the channel of a target +/// that is a message. That channel's NIP-PM pin list may hold the message: the +/// caller passes it to [`crate::pins::unpin_deleted_messages`] once it has +/// deleted every target. pub(crate) async fn soft_delete_event_and_update_thread_in_tx( tx: &mut AdmittedTx, event_id: &[u8], created_at: Option>, parent_event_id: Option<&[u8]>, root_event_id: Option<&[u8]>, -) -> Result { +) -> Result<(bool, Option)> { let community_id = tx.community(); use crate::store::replaceable::event_replacement_lock_key; @@ -437,7 +445,7 @@ pub(crate) async fn soft_delete_event_and_update_thread_in_tx( } }; let Some((kind, channel_id, created_at)) = target else { - return Ok(false); + return Ok((false, None)); }; // Relay-signed move removals are the source channel's only replay record. @@ -446,6 +454,13 @@ pub(crate) async fn soft_delete_event_and_update_thread_in_tx( "artifact removal markers cannot be deleted".into(), )); } + // A deleted pin list would clear a channel's pins with no new list for + // subscribers to replace their copy with. + if kind == KIND_CHANNEL_PINS as i32 { + return Err(DbError::InvalidData( + "the pin list cannot be deleted".into(), + )); + } if let Some(channel_id) = channel_id { if kind == KIND_CANVAS as i32 { @@ -512,7 +527,9 @@ pub(crate) async fn soft_delete_event_and_update_thread_in_tx( } } - Ok(deleted) + let message_channel = + channel_id.filter(|_| PINNABLE_KINDS.map(|kind| kind as i32).contains(&kind)); + Ok((deleted, message_channel)) } #[cfg(test)] diff --git a/crates/buzz-db/src/store/event_deletion/postgres_tests.rs b/crates/buzz-db/src/store/event_deletion/postgres_tests.rs index fdae0d9041..18c02c0a80 100644 --- a/crates/buzz-db/src/store/event_deletion/postgres_tests.rs +++ b/crates/buzz-db/src/store/event_deletion/postgres_tests.rs @@ -117,13 +117,14 @@ async fn known_targets_across_months_are_exact_and_tenant_scoped() { created_at: timestamp(&may), ..target(&jan) }; - let (_, inserted, deleted) = db + let (_, inserted, deleted, _) = db .insert_deletion_event( community, &deletion, None, None, &[wrong, target(&missing), target(&jan), target(&may)], + &Keys::generate(), ) .await .expect("delete targets"); @@ -139,7 +140,8 @@ async fn known_targets_across_months_are_exact_and_tenant_scoped() { &deletion, None, None, - &[target(&jan), target(&may)] + &[target(&jan), target(&may)], + &Keys::generate() ) .await .expect("replay") @@ -198,10 +200,17 @@ async fn retention_free_contract() { ..target(&ev) }; assert_eq!( - db.insert_deletion_event(community, &deletion, None, None, &[wrong]) - .await - .expect("wrong timestamp") - .2, + db.insert_deletion_event( + community, + &deletion, + None, + None, + &[wrong], + &Keys::generate() + ) + .await + .expect("wrong timestamp") + .2, [false] ); assert_eq!(counts(&db, community, ev.id.as_bytes()).await, (1, 1, 1)); @@ -213,25 +222,40 @@ async fn retention_free_contract() { &deletion, None, None, - &[target(&ev), target(&marker)] + &[target(&ev), target(&marker)], + &Keys::generate() ) .await .is_err()); assert_eq!(counts(&db, community, ev.id.as_bytes()).await, (1, 1, 1)); assert_eq!( - db.insert_deletion_event(community, &deletion, None, None, &[target(&ev)]) - .await - .expect("hard purge") - .2, + db.insert_deletion_event( + community, + &deletion, + None, + None, + &[target(&ev)], + &Keys::generate() + ) + .await + .expect("hard purge") + .2, [true] ); assert_eq!(counts(&db, community, ev.id.as_bytes()).await, (0, 0, 0)); assert_eq!(counts(&db, other, ev.id.as_bytes()).await, (1, 1, 1)); assert_eq!( - db.insert_deletion_event(community, &deletion, None, None, &[target(&ev)]) - .await - .expect("replay purge") - .2, + db.insert_deletion_event( + community, + &deletion, + None, + None, + &[target(&ev)], + &Keys::generate() + ) + .await + .expect("replay purge") + .2, [false] ); assert!(soft_delete_event_and_update_thread( @@ -333,7 +357,8 @@ async fn known_target_batch_rollback_then_replay_repairs_and_counts_once() { &deletion, None, None, - &[reply_target, target(&marker)] + &[reply_target, target(&marker)], + &Keys::generate() ) .await .is_err()); @@ -349,20 +374,35 @@ async fn known_target_batch_rollback_then_replay_repairs_and_counts_once() { .expect("independent pool"), ); let targets = [reply_target]; + let relay = Keys::generate(); let (a, b) = tokio::join!( - db.insert_deletion_event(community, &deletion, Some(channel), None, &targets), - concurrent.insert_deletion_event(community, &deletion, Some(channel), None, &targets), + db.insert_deletion_event(community, &deletion, Some(channel), None, &targets, &relay), + concurrent.insert_deletion_event( + community, + &deletion, + Some(channel), + None, + &targets, + &relay + ), ); - let (_, inserted_a, a) = a.expect("first replay"); - let (_, inserted_b, b) = b.expect("second replay"); + let (_, inserted_a, a, _) = a.expect("first replay"); + let (_, inserted_b, b, _) = b.expect("second replay"); assert!(!inserted_a && !inserted_b); assert_ne!(a, b); assert_eq!(counter().await, (0, 0)); assert_eq!( - db.insert_deletion_event(community, &deletion, Some(channel), None, &targets) - .await - .expect("repeat replay") - .2, + db.insert_deletion_event( + community, + &deletion, + Some(channel), + None, + &targets, + &Keys::generate() + ) + .await + .expect("repeat replay") + .2, [false] ); assert_eq!(counter().await, (0, 0)); @@ -412,9 +452,16 @@ async fn production_known_target_statements_prune_to_one_month() { ); seed(&db, community, &ev, channel).await; let deletion = event(5, MAY, vec![]); - db.insert_deletion_event(community, &deletion, None, None, &[target(&ev)]) - .await - .expect("exercise production statements"); + db.insert_deletion_event( + community, + &deletion, + None, + None, + &[target(&ev)], + &Keys::generate(), + ) + .await + .expect("exercise production statements"); // Explain the exact statements production executes, with their real // bindings. Production runs them unnamed (`.persistent(false)`), so they // are planned with the bound parameters; the lock test below covers the @@ -469,20 +516,6 @@ async fn production_known_target_statements_prune_to_one_month() { } } -/// Monthly `events` partitions (not their indexes) this backend holds a -/// relation lock on right now. -async fn locked_event_partitions(tx: &mut AdmittedTx) -> Vec { - sqlx::query_scalar( - "SELECT DISTINCT c.relname::text FROM pg_locks l \ - JOIN pg_class c ON c.oid = l.relation \ - WHERE l.locktype = 'relation' AND l.pid = pg_backend_pid() \ - AND c.relkind = 'r' AND c.relname LIKE 'events\\_p%' ORDER BY 1", - ) - .fetch_all(tx.conn()) - .await - .expect("observe partition locks") -} - #[tokio::test] #[ignore = "requires Postgres"] async fn production_known_target_deletion_locks_one_partition() { @@ -520,7 +553,7 @@ async fn production_known_target_deletion_locks_one_partition() { .expect("admit deletion"); // Known-target select, purge and soft delete all run on the production // path (read-state events are retention-free). - let deleted = soft_delete_event_and_update_thread_in_tx( + let (deleted, _) = soft_delete_event_and_update_thread_in_tx( &mut tx, ev.id.as_bytes(), Some(timestamp(&ev)), @@ -530,7 +563,7 @@ async fn production_known_target_deletion_locks_one_partition() { .await .expect("production deletion"); assert!(deleted, "round {round}"); - let locked = locked_event_partitions(&mut tx).await; + let locked = crate::test_support::locked_event_partitions(&mut tx).await; // Roll back so the next round deletes the same row again. tx.rollback().await.expect("rollback"); assert_eq!( @@ -573,7 +606,14 @@ async fn known_canvas_target_uses_canonical_replacement_lock() { // No channel: a channel event this old is below the floor. let deletion = event(5, MAY, vec![]); delete_db - .insert_deletion_event(community, &deletion, None, None, &[target(&canvas)]) + .insert_deletion_event( + community, + &deletion, + None, + None, + &[target(&canvas)], + &Keys::generate(), + ) .await }); // Observe an actual advisory-lock wait, not merely a task that hasn't yet diff --git a/crates/buzz-db/src/store/mod.rs b/crates/buzz-db/src/store/mod.rs index e9c2e0d72b..f2f94dce93 100644 --- a/crates/buzz-db/src/store/mod.rs +++ b/crates/buzz-db/src/store/mod.rs @@ -62,6 +62,8 @@ pub mod operator_listener; pub mod partition; /// Private signer-owned accessory read progress. pub mod personal_read; +/// NIP-PM channel pin list persistence. +pub mod pins; /// Buzz product-feedback sidecar persistence. pub mod product_feedback; /// Community-scoped push lease and durable wake-outbox persistence. diff --git a/crates/buzz-db/src/store/pins.rs b/crates/buzz-db/src/store/pins.rs new file mode 100644 index 0000000000..6a52671a80 --- /dev/null +++ b/crates/buzz-db/src/store/pins.rs @@ -0,0 +1,402 @@ +//! NIP-PM channel pins. +//! +//! A channel's pins are one relay-signed kind:30623 event. Every writer takes +//! that event's replacement lock before it reads the list, so the pin and +//! unpin commands of a channel, and the deletes that remove a pinned message, +//! apply one at a time. + +use buzz_core::channel::MAX_CHANNEL_PINS; +use buzz_core::kind::{KIND_CHANNEL_PINS, KIND_PIN_MESSAGE, KIND_UNPIN_MESSAGE, PINNABLE_KINDS}; +use buzz_core::{CommunityId, StoredEvent}; +use buzz_datastore_tracing::datastore_span; +use chrono::{DateTime, Utc}; +use uuid::Uuid; + +use crate::error::{DbError, Result}; +use crate::{AdmittedTx, Db}; + +pub(crate) const COMMAND_KINDS: [i32; 2] = [KIND_PIN_MESSAGE as i32, KIND_UNPIN_MESSAGE as i32]; + +/// How long the ID and timestamp of a pin or unpin command outlive account +/// erasure. A resend of the command is still a duplicate for that long; the +/// relay accepts no command with an older timestamp. +const REPLAY_RECORD_SECS: i64 = 60 * 60; + +/// Whether account erasure reduces this event to its ID and timestamp rather +/// than removing it: a pin or unpin command young enough to be sent again. +pub(crate) fn keeps_replay_record( + kind: i32, + created_at: DateTime, + now: DateTime, +) -> bool { + COMMAND_KINDS.contains(&kind) + && created_at > now - chrono::Duration::seconds(REPLAY_RECORD_SECS) +} + +/// What a NIP-PM command does to its target message. +pub enum PinChange<'a> { + /// Pin the target. `notice` is the relay-signed kind:40099 system message + /// that announces it, stored only when the pin changes the list. + Pin { + /// The `message_pinned` system message for this pin. + notice: &'a nostr::Event, + }, + /// Unpin the target. + Unpin, +} + +/// What storing one NIP-PM command did. +pub struct PinCommandWrite { + /// The command. + pub stored: StoredEvent, + /// `false` when this exact command was stored before. It was not applied + /// again. + pub inserted: bool, + /// The channel's new pin list, when the command changed it. + pub list: Option, +} + +/// Take the replacement lock of `channel_id`'s pin list, then read the pinned +/// message IDs behind it, newest pin first. +async fn lock_pins( + tx: &mut AdmittedTx, + channel_id: Uuid, + relay_pubkey: &[u8], +) -> Result>> { + let kind = KIND_CHANNEL_PINS as i32; + crate::replaceable::take_replacement_lock(tx, kind, relay_pubkey, Some(channel_id)).await?; + let tags: Option>> = sqlx::query_scalar::<_, sqlx::types::Json<_>>( + "SELECT tags FROM events WHERE community_id = $1 AND kind = $2 AND pubkey = $3 \ + AND channel_id = $4 AND deleted_at IS NULL ORDER BY created_at DESC, id ASC LIMIT 1", + ) + .bind(tx.community().as_uuid()) + .bind(kind) + .bind(relay_pubkey) + .bind(channel_id) + .fetch_optional(tx.conn()) + .await? + .map(|tags| tags.0); + pinned_ids(&tags.unwrap_or_default()) +} + +/// Take the replacement lock of `channel_id`'s pin list, then read the pinned +/// message IDs behind the list head that [`replace_pins`] recorded. +/// +/// Every message delete calls this. Reading the head's +/// exact `created_at` first keeps it to the list's own `events` partition, and +/// to none when the channel has never had a list. Taking the lock before the +/// read means a pin that commits first is seen. +async fn lock_recorded_pins( + tx: &mut AdmittedTx, + channel_id: Uuid, + relay_pubkey: &[u8], +) -> Result>> { + let kind = KIND_CHANNEL_PINS as i32; + crate::replaceable::take_replacement_lock(tx, kind, relay_pubkey, Some(channel_id)).await?; + let head: Option> = sqlx::query_scalar( + "SELECT created_at FROM parameterized_event_watermarks \ + WHERE community_id = $1 AND kind = $2 AND pubkey = $3 AND d_tag = $4", + ) + .bind(tx.community().as_uuid()) + .bind(kind) + .bind(relay_pubkey) + .bind(channel_id.to_string()) + .fetch_optional(tx.conn()) + .await?; + let Some(head) = head else { + return Ok(Vec::new()); + }; + // Unnamed, so it is always planned with `head` and prunes to its month + // (see the known-target statements in `event_deletion`). + let tags: Option>> = sqlx::query_scalar::<_, sqlx::types::Json<_>>( + "SELECT tags FROM events WHERE community_id = $1 AND kind = $2 AND pubkey = $3 \ + AND channel_id = $4 AND created_at = $5 AND deleted_at IS NULL ORDER BY id ASC LIMIT 1", + ) + .persistent(false) + .bind(tx.community().as_uuid()) + .bind(kind) + .bind(relay_pubkey) + .bind(channel_id) + .bind(head) + .fetch_optional(tx.conn()) + .await? + .map(|tags| tags.0); + pinned_ids(&tags.unwrap_or_default()) +} + +/// The message IDs a pin list's tags pin, in order. +fn pinned_ids(tags: &[Vec]) -> Result>> { + tags.iter() + .filter(|tag| tag.first().is_some_and(|name| name == "e")) + .map(|tag| { + tag.get(1) + .and_then(|id| hex::decode(id).ok()) + .ok_or_else(|| DbError::InvalidData("malformed pin list entry".to_string())) + }) + .collect() +} + +/// The entries of `ids` that are live messages of `channel_id`, in order. +async fn live_messages( + tx: &mut AdmittedTx, + channel_id: Uuid, + mut ids: Vec>, +) -> Result>> { + // Unnamed, so by default it is planned with the channel and the IDs and + // probes the ID index. A cached generic plan assumes an average channel + // and reads this channel's whole index instead. + let live: std::collections::HashSet> = sqlx::query_scalar( + "SELECT id FROM events WHERE community_id = $1 AND channel_id = $2 AND id = ANY($3) \ + AND kind = ANY($4) AND deleted_at IS NULL", + ) + .persistent(false) + .bind(tx.community().as_uuid()) + .bind(channel_id) + .bind(&ids) + .bind(PINNABLE_KINDS.map(|kind| kind as i32).as_slice()) + .fetch_all(tx.conn()) + .await? + .into_iter() + .collect(); + ids.retain(|id| live.contains(id)); + Ok(ids) +} + +/// Sign and store `ids` as `channel_id`'s pin list, and record it as the +/// list head [`lock_recorded_pins`] reads. The caller holds the list's +/// replacement lock ([`lock_pins`]) and commits. +async fn replace_pins( + tx: &mut AdmittedTx, + channel_id: Uuid, + ids: &[Vec], + relay_signer: &nostr::Keys, +) -> Result { + let tag = |name: &str, value: &str| { + nostr::Tag::parse([name, value]).map_err(|error| DbError::InvalidData(error.to_string())) + }; + let channel = channel_id.to_string(); + // `d` addresses the list; `h` lets a `#h` filter, which names the channel + // (NIP-CL), match it. + let mut tags = vec![tag("d", &channel)?, tag("h", &channel)?]; + for id in ids { + tags.push(tag("e", &hex::encode(id))?); + } + let (stored, inserted) = crate::channel::replace_signed_group_state_under_lock( + tx, + channel_id, + KIND_CHANNEL_PINS as i32, + tags, + relay_signer, + ) + .await?; + if !inserted { + return Err(DbError::InvalidData( + "pin list replacement failed".to_string(), + )); + } + let created_at_secs = stored.event.created_at.as_secs() as i64; + let created_at = DateTime::from_timestamp(created_at_secs, 0) + .ok_or(DbError::InvalidTimestamp(created_at_secs))?; + sqlx::query( + "INSERT INTO parameterized_event_watermarks \ + (community_id, kind, pubkey, d_tag, created_at, event_id) \ + VALUES ($1, $2, $3, $4, $5, $6) \ + ON CONFLICT (community_id, kind, pubkey, d_tag) DO UPDATE SET \ + created_at = EXCLUDED.created_at, event_id = EXCLUDED.event_id", + ) + .bind(tx.community().as_uuid()) + .bind(KIND_CHANNEL_PINS as i32) + .bind(stored.event.pubkey.to_bytes().as_slice()) + .bind(&channel) + .bind(created_at) + .bind(stored.event.id.as_bytes().as_slice()) + .execute(tx.conn()) + .await?; + Ok(stored) +} + +/// Remove deleted messages from their channels' pin lists, on the transaction +/// that deleted them. `deleted` holds each message's channel and ID. Returns +/// each list that held one of them, rewritten once. +/// +/// The caller deletes every message first. A delete then never waits for a +/// message while it holds a list lock, and takes the list locks in one order, +/// so two deletes cannot wait on each other. +pub(crate) async fn unpin_deleted_messages( + tx: &mut AdmittedTx, + deleted: &[(Uuid, &[u8])], + relay_signer: &nostr::Keys, +) -> Result> { + let mut channels: std::collections::BTreeMap> = Default::default(); + for (channel_id, event_id) in deleted { + channels.entry(*channel_id).or_default().push(event_id); + } + let mut lists = Vec::new(); + for (channel_id, event_ids) in channels { + let pins = + lock_recorded_pins(tx, channel_id, &relay_signer.public_key().to_bytes()).await?; + if !pins.iter().any(|id| event_ids.contains(&id.as_slice())) { + continue; + } + let pins = live_messages(tx, channel_id, pins).await?; + lists.push(replace_pins(tx, channel_id, &pins, relay_signer).await?); + } + Ok(lists) +} + +/// The author column of a command record that account erasure scrubbed. +const ERASED: &[u8] = &[]; + +/// Remove the community's erased command records from `cutoff` and before. +async fn delete_erased_command_records(tx: &mut AdmittedTx, cutoff: DateTime) -> Result { + let result = sqlx::query( + "DELETE FROM events WHERE community_id = $1 AND kind = ANY($2) \ + AND pubkey = $3 AND created_at <= $4", + ) + .bind(tx.community().as_uuid()) + .bind(COMMAND_KINDS.as_slice()) + .bind(ERASED) + .bind(cutoff) + .execute(tx.conn()) + .await?; + Ok(result.rows_affected()) +} + +impl Db { + /// Store a NIP-PM pin (kind:40010) or unpin (kind:40011) command and + /// apply it to `channel_id`'s pin list, in one transaction. + /// + /// Pinning a message that is already pinned, or unpinning one that is + /// not, stores the command and leaves the list alone. A list that + /// changes also drops every entry whose message is gone. + /// + /// Account erasure keeps the ID and timestamp of a command under an hour + /// old, so a resend of it is still a duplicate here. + /// + /// Returns [`DbError::AccessDenied`], with nothing stored, when the + /// target of a pin is not a live message of the channel or the channel + /// already holds [`MAX_CHANNEL_PINS`] pins. + #[datastore_span(name = "apply_pin_command", system = "postgresql")] + pub async fn apply_pin_command( + &self, + community: CommunityId, + channel_id: Uuid, + event: &nostr::Event, + target: &[u8], + change: PinChange<'_>, + relay_signer: &nostr::Keys, + ) -> Result { + let mut tx = crate::begin_community_event_write_transaction( + &self.pool, + community, + crate::observability::WriterOperation::EventWrite, + ) + .await?; + // The lock also orders two copies of the same command: the second + // waits, then finds the first stored. + let mut pins = + lock_pins(&mut tx, channel_id, &relay_signer.public_key().to_bytes()).await?; + let (stored, inserted) = crate::event::insert_event_with_thread_metadata_tx( + &mut tx, + event, + Some(channel_id), + None, + ) + .await?; + if !inserted { + tx.rollback().await?; + return Ok(PinCommandWrite { + stored, + inserted, + list: None, + }); + } + + let pinned = pins.iter().position(|id| id == target); + let list = match (change, pinned) { + (PinChange::Pin { notice }, pinned) => { + // A listed message can be gone: bulk erasure leaves the list. + if live_messages(&mut tx, channel_id, vec![target.to_vec()]) + .await? + .is_empty() + { + return Err(DbError::AccessDenied( + "target is not a message in this channel".to_string(), + )); + } + if pinned.is_some() { + None + } else { + pins = live_messages(&mut tx, channel_id, pins).await?; + if pins.len() >= MAX_CHANNEL_PINS { + return Err(DbError::AccessDenied("pin limit reached".to_string())); + } + pins.insert(0, target.to_vec()); + let list = replace_pins(&mut tx, channel_id, &pins, relay_signer).await?; + crate::event::insert_event_in_transaction(&mut tx, notice, Some(channel_id)) + .await?; + Some(list) + } + } + (PinChange::Unpin, Some(index)) => { + pins.remove(index); + pins = live_messages(&mut tx, channel_id, pins).await?; + Some(replace_pins(&mut tx, channel_id, &pins, relay_signer).await?) + } + (PinChange::Unpin, None) => None, + }; + tx.commit().await?; + Ok(PinCommandWrite { + stored, + inserted, + list, + }) + } + + /// Remove, in every community, the records account erasure left of pin + /// and unpin commands that are now an hour old. Returns how many. + /// + /// The relay calls this from its leader-only periodic tick, so a record + /// goes whether or not its channel sees another command. + #[datastore_span(name = "reap_expired_pin_command_records", system = "postgresql")] + pub async fn reap_expired_pin_command_records(&self) -> Result { + let cutoff = Utc::now() - chrono::Duration::seconds(REPLAY_RECORD_SECS); + let mut connection = crate::observability::acquire_writer( + &self.pool, + crate::observability::WriterOperation::Maintenance, + ) + .await?; + // Every index on `events` leads with the community, so probe once for + // each community rather than scan the table for the kinds. + let communities: Vec = sqlx::query_scalar( + "SELECT community.id FROM communities community \ + WHERE community.deletion_state = 'active' AND community.deleted_at IS NULL \ + AND EXISTS (SELECT 1 FROM events record \ + WHERE record.community_id = community.id AND record.kind = ANY($1) \ + AND record.pubkey = $2 AND record.created_at <= $3)", + ) + .bind(COMMAND_KINDS.as_slice()) + .bind(ERASED) + .bind(cutoff) + .fetch_all(&mut *connection) + .await?; + drop(connection); + + let removed = crate::sweep_admitted_communities( + &self.pool, + communities, + crate::observability::WriterOperation::Maintenance, + "pin_command_record_reap", + |_, mut tx| async move { + let removed = delete_erased_command_records(&mut tx, cutoff).await?; + tx.commit().await?; + Ok(removed) + }, + ) + .await; + Ok(removed.into_iter().sum()) + } +} + +#[cfg(test)] +mod postgres_tests; diff --git a/crates/buzz-db/src/store/pins/postgres_tests.rs b/crates/buzz-db/src/store/pins/postgres_tests.rs new file mode 100644 index 0000000000..afb5361720 --- /dev/null +++ b/crates/buzz-db/src/store/pins/postgres_tests.rs @@ -0,0 +1,630 @@ +//! NIP-PM pin list writes through the production entry points. + +use super::*; +use buzz_core::kind::{KIND_PIN_MESSAGE, KIND_SYSTEM_MESSAGE, KIND_UNPIN_MESSAGE}; +use nostr::{Event, EventBuilder, Keys, Kind, Tag}; +use sqlx::PgPool; + +struct Fixture { + db: Db, + community: CommunityId, + channel: Uuid, + relay: Keys, +} + +async fn channel(pool: &PgPool, community: Uuid) -> Uuid { + let channel = Uuid::new_v4(); + sqlx::query("INSERT INTO channels (id, community_id, name, created_by) VALUES ($1,$2,$3,$4)") + .bind(channel) + .bind(community) + .bind(format!("pins-{}", channel.simple())) + .bind(vec![7_u8; 32]) + .execute(pool) + .await + .expect("channel"); + channel +} + +async fn fixture() -> Fixture { + fixture_on( + PgPool::connect(&crate::test_support::database_url()) + .await + .expect("test database"), + ) + .await +} + +async fn fixture_on(pool: PgPool) -> Fixture { + let community = Uuid::new_v4(); + sqlx::query("INSERT INTO communities (id, host) VALUES ($1, $2)") + .bind(community) + .bind(format!("pins-{}.example", community.simple())) + .execute(&pool) + .await + .expect("community"); + let channel = channel(&pool, community).await; + Fixture { + db: Db::from_pool(pool), + community: CommunityId::from_uuid(community), + channel, + relay: Keys::generate(), + } +} + +fn event(kind: u32, channel: Uuid, target: Option<&Event>) -> Event { + let mut tags = vec![Tag::parse(["h", &channel.to_string()]).expect("h")]; + tags.extend(target.map(|target| Tag::parse(["e", &target.id.to_hex()]).expect("e"))); + EventBuilder::new(Kind::Custom(kind as u16), "") + .tags(tags) + // Two commands for one target are different events. + .tag(Tag::parse(["client-id", &Uuid::new_v4().to_string()]).expect("client-id")) + .sign_with_keys(&Keys::generate()) + .expect("signed event") +} + +impl Fixture { + /// Store a live message of `kind` in `channel`. + async fn message_in(&self, channel: Uuid, kind: u32) -> Event { + let message = event(kind, channel, None); + self.db + .insert_event(self.community, &message, Some(channel)) + .await + .expect("message"); + message + } + + async fn message(&self) -> Event { + self.message_in(self.channel, 9).await + } + + async fn apply(&self, command: &Event, target: &Event) -> Result { + let notice = + EventBuilder::new(Kind::Custom(KIND_SYSTEM_MESSAGE as u16), target.id.to_hex()) + .tag(Tag::parse(["h", &self.channel.to_string()]).expect("h")) + .sign_with_keys(&self.relay) + .expect("notice"); + let change = if command.kind.as_u16() as u32 == KIND_PIN_MESSAGE { + PinChange::Pin { notice: ¬ice } + } else { + PinChange::Unpin + }; + self.db + .apply_pin_command( + self.community, + self.channel, + command, + target.id.as_bytes(), + change, + &self.relay, + ) + .await + } + + async fn pin(&self, target: &Event) -> Result { + self.apply(&event(KIND_PIN_MESSAGE, self.channel, Some(target)), target) + .await + } + + async fn unpin(&self, target: &Event) -> Result { + self.apply( + &event(KIND_UNPIN_MESSAGE, self.channel, Some(target)), + target, + ) + .await + } + + /// Every stored pin list row of the channel as `(created_at, pinned IDs)`, + /// with the notices stored in the channel. + async fn stored(&self) -> (Vec<(i64, Vec)>, i64) { + let lists: Vec<(i64, sqlx::types::Json>>)> = sqlx::query_as( + "SELECT extract(epoch FROM created_at)::bigint, tags FROM events \ + WHERE community_id = $1 AND channel_id = $2 AND kind = $3", + ) + .bind(self.community.as_uuid()) + .bind(self.channel) + .bind(KIND_CHANNEL_PINS as i32) + .fetch_all(&self.db.pool) + .await + .expect("pin lists"); + let notices = sqlx::query_scalar( + "SELECT count(*) FROM events WHERE community_id = $1 AND channel_id = $2 AND kind = $3", + ) + .bind(self.community.as_uuid()) + .bind(self.channel) + .bind(KIND_SYSTEM_MESSAGE as i32) + .fetch_one(&self.db.pool) + .await + .expect("notices"); + let lists = lists + .into_iter() + .map(|(created_at, tags)| (created_at, pinned(&tags.0))) + .collect(); + (lists, notices) + } + + /// The channel's one pin list as `(created_at, pinned IDs)`. + async fn list(&self) -> (i64, Vec) { + let (mut lists, _) = self.stored().await; + assert_eq!(lists.len(), 1, "a channel keeps one pin list row"); + lists.remove(0) + } + + async fn is_stored(&self, event: &Event) -> bool { + sqlx::query_scalar( + "SELECT EXISTS (SELECT 1 FROM events WHERE community_id = $1 AND id = $2)", + ) + .bind(self.community.as_uuid()) + .bind(event.id.as_bytes().as_slice()) + .fetch_one(&self.db.pool) + .await + .expect("event row") + } + + /// Delete `targets` the way a kind:5 or kind:9005 does. + async fn delete(&self, deletion: &Event, targets: &[&Event]) -> Vec { + let targets: Vec<_> = targets + .iter() + .map(|target| crate::event::DeletionTarget { + event_id: target.id.as_bytes(), + created_at: chrono::DateTime::from_timestamp(target.created_at.as_secs() as i64, 0) + .expect("timestamp"), + parent_event_id: None, + root_event_id: None, + }) + .collect(); + self.db + .insert_deletion_event( + self.community, + deletion, + Some(self.channel), + None, + &targets, + &self.relay, + ) + .await + .expect("deletion") + .3 + } +} + +fn pinned(tags: &[Vec]) -> Vec { + tags.iter() + .filter(|tag| tag[0] == "e") + .map(|tag| tag[1].clone()) + .collect() +} + +fn ids(events: &[&Event]) -> Vec { + events.iter().map(|event| event.id.to_hex()).collect() +} + +fn denied(result: Result) -> String { + match result { + Err(DbError::AccessDenied(reason)) => reason, + Err(error) => panic!("unexpected error: {error}"), + Ok(_) => panic!("the command was applied"), + } +} + +/// Pins go to the front, each list replaces the last with a later +/// `created_at`, and a command that has nothing to change is stored without +/// a new list or notice. +/// Mutation: apply `(Pin, Some(_))` like `(Pin, None)` → RED (a second list +/// and notice for the pin of an already pinned message). +#[tokio::test] +#[ignore = "requires Postgres"] +async fn pins_and_unpins_rewrite_one_relay_signed_list() { + let f = fixture().await; + let (a, b) = (f.message().await, f.message().await); + + let first = f.pin(&a).await.expect("pin a"); + let list = first.list.expect("the pin changes the list"); + assert!(first.inserted); + assert_eq!(list.event.pubkey, f.relay.public_key()); + assert_eq!(list.event.content, ""); + let channel = f.channel.to_string(); + assert_eq!( + list.event + .tags + .iter() + .take(2) + .map(|tag| tag.as_slice().to_vec()) + .collect::>(), + [ + vec!["d".to_owned(), channel.clone()], + vec!["h".to_owned(), channel] + ], + "the list is addressed by `d` and names its channel with `h`" + ); + assert!(list.event.verify().is_ok(), "the list is signed"); + let (first_at, first_ids) = f.list().await; + assert_eq!(first_ids, ids(&[&a])); + + assert!(f.pin(&b).await.expect("pin b").list.is_some()); + let (second_at, second_ids) = f.list().await; + assert_eq!(second_ids, ids(&[&b, &a]), "the newest pin is first"); + assert!(second_at > first_at, "a new list is newer than the last"); + assert_eq!(f.stored().await.1, 2, "one notice for each pin"); + + let again = f.pin(&a).await.expect("pin a again"); + assert!(again.inserted && again.list.is_none()); + let never = f.message().await; + let absent = f.unpin(&never).await.expect("unpin a message never pinned"); + assert!(absent.inserted && absent.list.is_none()); + assert_eq!(f.list().await, (second_at, ids(&[&b, &a]))); + assert_eq!(f.stored().await.1, 2, "no notice when nothing changes"); + + assert!(f.unpin(&a).await.expect("unpin a").list.is_some()); + assert_eq!(f.list().await.1, ids(&[&b])); + assert!(f.unpin(&b).await.expect("unpin b").list.is_some()); + assert!( + f.list().await.1.is_empty(), + "the last unpin leaves an empty list" + ); + assert_eq!(f.stored().await.1, 2, "an unpin posts no notice"); +} + +/// A command sent again is not applied again, so a repeated pin cannot undo +/// an unpin made in between. Two copies sent at once apply once. +/// Mutation: drop the `!inserted` return → RED (the resend pins again). +#[tokio::test] +#[ignore = "requires Postgres"] +async fn a_resent_command_is_not_applied_again() { + let f = fixture().await; + let a = f.message().await; + let pin = event(KIND_PIN_MESSAGE, f.channel, Some(&a)); + assert!(f.apply(&pin, &a).await.expect("pin").list.is_some()); + assert!(f.unpin(&a).await.expect("unpin").list.is_some()); + + let resent = f.apply(&pin, &a).await.expect("resend"); + assert!(!resent.inserted && resent.list.is_none()); + assert_eq!(resent.stored.event.id, pin.id); + assert!(f.list().await.1.is_empty(), "the unpin stands"); + assert_eq!(f.stored().await.1, 1, "the resend posts no notice"); + + let b = f.message().await; + let racing = event(KIND_PIN_MESSAGE, f.channel, Some(&b)); + let (one, two) = tokio::join!(f.apply(&racing, &b), f.apply(&racing, &b)); + let (one, two) = (one.expect("first copy"), two.expect("second copy")); + assert_ne!(one.inserted, two.inserted, "one copy is the duplicate"); + assert_eq!(one.list.is_some(), one.inserted); + assert_eq!(two.list.is_some(), two.inserted); + assert_eq!(f.list().await.1, ids(&[&b])); + assert_eq!(f.stored().await.1, 2); +} + +/// A pin whose target is not a live message of the channel is refused and +/// leaves nothing behind: no command, no list, no notice. +/// Mutation: drop the `kind = ANY` or `channel_id` predicate from +/// `live_messages` → RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn a_pin_needs_a_live_message_of_the_channel() { + let f = fixture().await; + let elsewhere = channel(&f.db.pool, *f.community.as_uuid()).await; + let deleted = f.message().await; + f.delete(&event(5, f.channel, Some(&deleted)), &[&deleted]) + .await; + for (case, target) in [ + ("another channel", f.message_in(elsewhere, 9).await), + ("a reaction", f.message_in(f.channel, 7).await), + ("a deleted message", deleted), + ("a message never stored", event(9, f.channel, None)), + ] { + let command = event(KIND_PIN_MESSAGE, f.channel, Some(&target)); + assert_eq!( + denied(f.apply(&command, &target).await), + "target is not a message in this channel", + "{case}" + ); + assert!(!f.is_stored(&command).await, "{case}: command stored"); + } + assert_eq!(f.stored().await, (Vec::new(), 0)); +} + +/// A channel holds at most [`MAX_CHANNEL_PINS`] pins. Entries whose message +/// was removed without the list being told do not count, and leave the list +/// the next time it changes. +/// Mutation: skip `live_messages(pins)` before the limit check → RED (the +/// pin after the erasure is refused); check the target only when it is not +/// listed → RED (the erased message is pinned again). +#[tokio::test] +#[ignore = "requires Postgres"] +async fn the_pin_limit_counts_live_messages_only() { + let f = fixture().await; + let mut messages = Vec::new(); + for _ in 0..MAX_CHANNEL_PINS { + let message = f.message().await; + assert!(f.pin(&message).await.expect("pin").list.is_some()); + messages.push(message); + } + let over = f.message().await; + let command = event(KIND_PIN_MESSAGE, f.channel, Some(&over)); + assert_eq!(denied(f.apply(&command, &over).await), "pin limit reached"); + assert!(!f.is_stored(&command).await); + assert_eq!(f.list().await.1.len(), MAX_CHANNEL_PINS); + + // An account erasure removes messages in bulk and leaves the list alone. + sqlx::query("UPDATE events SET deleted_at = NOW() WHERE community_id = $1 AND id = $2") + .bind(f.community.as_uuid()) + .bind(messages[0].id.as_bytes().as_slice()) + .execute(&f.db.pool) + .await + .expect("erase a pinned message"); + // Still listed, but no longer a message that can be pinned. + let again = event(KIND_PIN_MESSAGE, f.channel, Some(&messages[0])); + assert_eq!( + denied(f.apply(&again, &messages[0]).await), + "target is not a message in this channel" + ); + assert!(!f.is_stored(&again).await); + assert!(f + .pin(&over) + .await + .expect("pin after erasure") + .list + .is_some()); + let list = f.list().await.1; + assert_eq!(list.len(), MAX_CHANNEL_PINS); + assert_eq!(list[0], over.id.to_hex()); + assert!(!list.contains(&messages[0].id.to_hex())); +} + +/// Pins sent at the same time all land: no command overwrites another's. +/// Mutation: read the list before `take_replacement_lock` → RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn concurrent_pins_all_land() { + let f = fixture().await; + let mut messages = Vec::new(); + for _ in 0..8 { + messages.push(f.message().await); + } + let writes = futures_util::future::join_all(messages.iter().map(|message| f.pin(message))); + for write in writes.await { + assert!(write.expect("pin").list.is_some()); + } + let mut list = f.list().await.1; + list.sort(); + let mut expected = ids(&messages.iter().collect::>()); + expected.sort(); + assert_eq!(list, expected); +} + +/// One deletion of several pinned messages deletes them all, then takes the +/// list lock and rewrites the list once. A delete that waited for a message +/// while it held the list lock could deadlock with a delete of that message. +/// Mutation: update the list after each target in `insert_deletion_event` → +/// RED (the second message is not deleted when the delete waits for the lock). +#[tokio::test] +#[ignore = "requires Postgres"] +async fn a_delete_takes_the_list_lock_after_its_messages() { + let f = fixture().await; + let (a, b, kept) = (f.message().await, f.message().await, f.message().await); + for message in [&a, &b, &kept] { + f.pin(message).await.expect("pin"); + } + + let key = crate::replaceable::event_replacement_lock_key( + f.community, + KIND_CHANNEL_PINS as i32, + &f.relay.public_key().to_bytes(), + Some(f.channel.as_bytes().as_slice()), + ); + let mut holder = f.db.pool.begin().await.expect("holder"); + sqlx::query("SELECT pg_advisory_xact_lock($1)") + .bind(key) + .execute(&mut *holder) + .await + .expect("hold the list lock"); + + let deleter = Fixture { + db: Db::from_pool(f.db.pool.clone()), + community: f.community, + channel: f.channel, + relay: f.relay.clone(), + }; + let (first, second) = (a.clone(), b.clone()); + let delete = tokio::spawn(async move { + let deletion = event(5, deleter.channel, None); + deleter.delete(&deletion, &[&first, &second]).await + }); + tokio::time::timeout(std::time::Duration::from_secs(5), async { + loop { + let waiting: bool = sqlx::query_scalar( + "SELECT EXISTS (SELECT 1 FROM pg_locks WHERE locktype = 'advisory' \ + AND NOT granted AND (classid::bigint << 32) | objid::bigint = $1)", + ) + .bind(key) + .fetch_one(&mut *holder) + .await + .expect("lock wait"); + if waiting { + break; + } + assert!(!delete.is_finished(), "the delete took no list lock"); + tokio::time::sleep(std::time::Duration::from_millis(10)).await; + } + }) + .await + .expect("the delete waits for the list lock"); + let unlocked: i64 = sqlx::query_scalar( + "SELECT count(*) FROM (SELECT 1 FROM events WHERE community_id = $1 \ + AND id = ANY($2) FOR UPDATE SKIP LOCKED) message", + ) + .bind(f.community.as_uuid()) + .bind(vec![a.id.as_bytes().to_vec(), b.id.as_bytes().to_vec()]) + .fetch_one(&mut *holder) + .await + .expect("message locks"); + assert_eq!(unlocked, 0, "both messages are deleted before the lock"); + holder.rollback().await.expect("release the list lock"); + + let lists = delete.await.expect("join"); + assert_eq!(lists.len(), 1, "one new list for both messages"); + assert_eq!(f.list().await.1, ids(&[&kept])); +} + +/// Account erasure leaves the ID and timestamp of a recent command. The sweep +/// removes those an hour old in every community, and only those. Nothing has +/// to happen in the channel: it is archived and takes no further command. +/// Mutation: drop the `kind`, `pubkey` or `created_at` predicate from the +/// sweep's `DELETE` → RED (a message, a command or a young record is removed); +/// delete nothing → RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn erased_command_records_expire_after_an_hour() { + let f = fixture().await; + let neighbor = fixture().await; + let message = f.message().await; + let command = event(KIND_PIN_MESSAGE, f.channel, Some(&message)); + f.apply(&command, &message).await.expect("pin"); + sqlx::query("UPDATE channels SET archived_at = now() WHERE id = $1") + .bind(f.channel) + .execute(&f.db.pool) + .await + .expect("archive"); + + // (community, kind, age in minutes, erased, kept) + let rows = [ + (&f, KIND_PIN_MESSAGE, 61, true, false), + (&f, KIND_UNPIN_MESSAGE, 61, true, false), + (&f, KIND_PIN_MESSAGE, 59, true, true), + (&f, KIND_PIN_MESSAGE, 61, false, true), + (&f, 9, 61, true, true), + (&neighbor, KIND_PIN_MESSAGE, 61, true, false), + (&neighbor, KIND_PIN_MESSAGE, 59, true, true), + (&neighbor, KIND_UNPIN_MESSAGE, 61, false, true), + ]; + let mut ids = Vec::new(); + for (owner, kind, minutes, erased, _) in rows { + let id = Uuid::new_v4().as_bytes().repeat(2); + let author: &[u8] = if erased { &[] } else { &[7; 32] }; + sqlx::query( + "INSERT INTO events (community_id, id, pubkey, created_at, kind, tags, content, sig, \ + channel_id, deleted_at) VALUES ($1, $2, $3, $4, $5, $6, $7, $3, $8, $9)", + ) + .bind(owner.community.as_uuid()) + .bind(&id) + .bind(author) + .bind(chrono::Utc::now() - chrono::Duration::minutes(minutes)) + .bind(kind as i32) + .bind(sqlx::types::Json(Vec::>::new())) + .bind("") + .bind(owner.channel) + .bind(chrono::Utc::now()) + .execute(&f.db.pool) + .await + .expect("record"); + ids.push(id); + } + + let removed = + f.db.reap_expired_pin_command_records() + .await + .expect("sweep"); + assert!(removed >= 3, "removed {removed}"); + for ((owner, kind, minutes, erased, kept), id) in rows.into_iter().zip(ids) { + let stored: bool = sqlx::query_scalar( + "SELECT EXISTS (SELECT 1 FROM events WHERE community_id = $1 AND id = $2)", + ) + .bind(owner.community.as_uuid()) + .bind(&id) + .fetch_one(&f.db.pool) + .await + .expect("row"); + assert_eq!( + stored, kept, + "kind {kind}, {minutes} minutes old, erased: {erased}" + ); + } + assert!(f.is_stored(&command).await, "a live command stays"); +} + +/// A message delete's pin cleanup reads only the list's own month, and no +/// `events` partition when the channel has no list, as the delete itself +/// locks only its target's month (`production_known_target_deletion_locks_one_partition`). +/// Mutation: read the list in `unpin_deleted_messages` through `lock_pins` +/// → RED (every partition is locked). +#[tokio::test] +#[ignore = "requires Postgres"] +async fn a_message_delete_locks_only_the_months_it_reads() { + // One connection, so every round reuses its statement cache: a cached + // statement can flip to a generic plan, which locks every partition. + let f = fixture_on( + sqlx::postgres::PgPoolOptions::new() + .max_connections(1) + .connect(&crate::test_support::database_url()) + .await + .expect("test database"), + ) + .await; + let unlisted = channel(&f.db.pool, *f.community.as_uuid()).await; + let pinned = f.message().await; + let list = f.pin(&pinned).await.expect("pin").list.expect("a list"); + let list_month: String = sqlx::query_scalar( + "SELECT tableoid::regclass::text FROM events WHERE community_id = $1 AND id = $2", + ) + .bind(f.community.as_uuid()) + .bind(list.event.id.as_bytes().as_slice()) + .fetch_one(&f.db.pool) + .await + .expect("the list's partition"); + assert_ne!(list_month, "events_p2026_01"); + + // A January message, so its month differs from the list's. + let january = |channel: Uuid| { + EventBuilder::new(Kind::Custom(9), "") + .tag(Tag::parse(["h", &channel.to_string()]).expect("h")) + .custom_created_at(nostr::Timestamp::from(1_768_003_200)) // 2026-01-10 UTC + .sign_with_keys(&Keys::generate()) + .expect("signed event") + }; + let cases = [ + ("a channel with no list", unlisted, vec!["events_p2026_01"]), + ( + "a channel whose list holds another message", + f.channel, + vec!["events_p2026_01", list_month.as_str()], + ), + ]; + for (case, channel, months) in cases { + let message = january(channel); + crate::test_support::insert_historical_event(&f.db.pool, f.community, &message, channel) + .await; + let created_at = chrono::DateTime::from_timestamp(message.created_at.as_secs() as i64, 0) + .expect("timestamp"); + for round in 0..10 { + let mut tx = crate::begin_community_event_write_transaction( + &f.db.pool, + f.community, + crate::observability::WriterOperation::EventWrite, + ) + .await + .expect("admit deletion"); + let (deleted, message_channel) = + crate::event::soft_delete_event_and_update_thread_in_tx( + &mut tx, + message.id.as_bytes(), + Some(created_at), + None, + None, + ) + .await + .expect("delete"); + assert!(deleted, "{case}, round {round}"); + assert_eq!(message_channel, Some(channel)); + let lists = + unpin_deleted_messages(&mut tx, &[(channel, message.id.as_bytes())], &f.relay) + .await + .expect("unpin"); + assert!(lists.is_empty(), "{case}: the message was not pinned"); + let locked = crate::test_support::locked_event_partitions(&mut tx).await; + tx.rollback().await.expect("rollback"); + assert!( + locked.iter().all(|name| months.contains(&name.as_str())), + "{case}, round {round}: locked {locked:?}, expected within {months:?}" + ); + } + } +} diff --git a/crates/buzz-db/src/store/relay_admin_actions.rs b/crates/buzz-db/src/store/relay_admin_actions.rs index 5dff624624..49716d526b 100644 --- a/crates/buzz-db/src/store/relay_admin_actions.rs +++ b/crates/buzz-db/src/store/relay_admin_actions.rs @@ -777,6 +777,11 @@ pub async fn execute_kick_with_marker( /// /// The delete is idempotent: if the event is already deleted the marker is still /// committed (soft-delete is already-done = success). +/// +/// A pinned target leaves its channel's NIP-PM pin list in the same +/// transaction; the list is re-signed with `relay_signer`. Returns whether +/// this call committed the marker, and the pin list it rewrote. +#[allow(clippy::too_many_arguments)] pub async fn execute_delete_with_marker( pool: &PgPool, action_id: Uuid, @@ -785,7 +790,8 @@ pub async fn execute_delete_with_marker( target_event_id: &[u8], parent_event_id: Option<&[u8]>, root_event_id: Option<&[u8]>, -) -> Result { + relay_signer: &nostr::Keys, +) -> Result<(bool, Option)> { let mut tx = crate::begin_community_event_write_transaction( pool, community_id, @@ -811,7 +817,7 @@ pub async fn execute_delete_with_marker( if !owned { tx.rollback().await?; - return Ok(false); + return Ok((false, None)); } // Acquire the action-row lock before evaluating the wall-clock expiry check. @@ -839,8 +845,9 @@ pub async fn execute_delete_with_marker( // Canonical delete + thread_metadata counters, fenced by this transaction. // Counters move only when the row transitions to deleted, so a second // action against an already-deleted target leaves them unchanged. + let mut message = None; if let Some((_, created_at)) = target { - crate::event::soft_delete_event_and_update_thread_in_tx( + let (_, channel_id) = crate::event::soft_delete_event_and_update_thread_in_tx( &mut tx, target_event_id, Some(created_at), @@ -848,7 +855,11 @@ pub async fn execute_delete_with_marker( root_event_id, ) .await?; + message = channel_id.map(|channel_id| (channel_id, target_event_id)); } + let pin_list = crate::pins::unpin_deleted_messages(&mut tx, message.as_slice(), relay_signer) + .await? + .pop(); let marker = sqlx::query( r#" @@ -868,11 +879,11 @@ pub async fn execute_delete_with_marker( if marker.rows_affected() == 0 { tx.rollback().await?; - return Ok(false); + return Ok((false, None)); } tx.commit().await?; - Ok(true) + Ok((true, pin_list)) } /// Commit the core mutation step and advance the step_marker to @@ -2211,8 +2222,10 @@ impl crate::Db { } /// Atomically execute a soft-delete mutation and commit the step marker. - /// Returns `true` if this driver committed the marker, `false` if already marked or lease lost. + /// Returns `true` if this driver committed the marker, `false` if already marked or lease lost, + /// and the NIP-PM pin list the delete rewrote. #[datastore_span(name = "execute_delete_with_marker", system = "postgresql")] + #[allow(clippy::too_many_arguments)] pub async fn execute_delete_with_marker( &self, action_id: uuid::Uuid, @@ -2221,7 +2234,8 @@ impl crate::Db { target_event_id: &[u8], parent_event_id: Option<&[u8]>, root_event_id: Option<&[u8]>, - ) -> Result { + relay_signer: &nostr::Keys, + ) -> Result<(bool, Option)> { execute_delete_with_marker( &self.pool, action_id, @@ -2230,6 +2244,7 @@ impl crate::Db { target_event_id, parent_event_id, root_event_id, + relay_signer, ) .await } @@ -3385,9 +3400,11 @@ mod postgres_tests { &nested, Some(&reply), Some(&root), + &nostr::Keys::generate(), ) .await - .expect("delete"); + .expect("delete") + .0; assert!(committed, "each action commits its own marker"); assert_eq!( counts(&pool, cid, &reply).await, @@ -3420,9 +3437,11 @@ mod postgres_tests { &nested, Some(&reply), Some(&root), + &nostr::Keys::generate(), ) .await - .expect("delete"); + .expect("delete") + .0; assert!(!committed, "expired lease must not commit"); let deleted: bool = sqlx::query_scalar( @@ -3487,6 +3506,7 @@ mod postgres_tests { &nr, Some(&pr), Some(&rr), + &nostr::Keys::generate(), ) .await }); @@ -3555,7 +3575,7 @@ mod postgres_tests { // Release the event row without writing a new version. locker.rollback().await.expect("release event-row lock"); - let committed = worker.await.expect("worker join").expect("worker result"); + let committed = worker.await.expect("worker join").expect("worker result").0; let deleted: bool = sqlx::query_scalar( "SELECT deleted_at IS NOT NULL FROM events WHERE community_id = $1 AND id = $2", @@ -3639,6 +3659,7 @@ mod postgres_tests { &nr, Some(&pr), Some(&rr), + &nostr::Keys::generate(), ) .await }); @@ -3706,7 +3727,7 @@ mod postgres_tests { // Release the row lock without writing a new tuple version. locker.rollback().await.expect("release row lock"); - let committed = worker.await.expect("worker join").expect("worker result"); + let committed = worker.await.expect("worker join").expect("worker result").0; let deleted: bool = sqlx::query_scalar( "SELECT deleted_at IS NOT NULL FROM events WHERE community_id = $1 AND id = $2", @@ -3752,17 +3773,21 @@ mod postgres_tests { let lease_until = Utc::now() + chrono::Duration::seconds(60); let (action_id, token) = enforcing_action(&pool, community_id, lease_until).await; - assert!(execute_delete_with_marker( - &pool, - action_id, - token, - cid, - &reply, - Some(&root), - Some(&root) - ) - .await - .expect("first delete")); + assert!( + execute_delete_with_marker( + &pool, + action_id, + token, + cid, + &reply, + Some(&root), + Some(&root), + &nostr::Keys::generate() + ) + .await + .expect("first delete") + .0 + ); let second = execute_delete_with_marker( &pool, action_id, @@ -3771,9 +3796,11 @@ mod postgres_tests { &nested, Some(&reply), Some(&root), + &nostr::Keys::generate(), ) .await - .expect("second delete"); + .expect("second delete") + .0; assert!(!second, "marker already set must roll back"); let deleted: bool = sqlx::query_scalar( @@ -3797,6 +3824,82 @@ mod postgres_tests { ); } + /// A relay admin's delete of a pinned message takes it out of the + /// channel's NIP-PM pin list in the same transaction. The list itself is + /// not an admin's to delete. + /// Mutation: drop the `unpin_deleted_messages` call → RED; drop the pin + /// list check from the shared soft delete → RED. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn admin_delete_unpins_the_message() { + use nostr::{EventBuilder, Keys, Kind}; + + let pool = setup_pool().await; + let community_id = make_community(&pool).await; + let cid = CommunityId::from_uuid(community_id); + let [root, _, _] = make_thread(&pool, cid).await; + let channel: Uuid = + sqlx::query_scalar("SELECT channel_id FROM events WHERE community_id = $1 AND id = $2") + .bind(community_id) + .bind(&root) + .fetch_one(&pool) + .await + .expect("channel"); + let relay = Keys::generate(); + let sign = |kind: u16, keys: &Keys| { + EventBuilder::new(Kind::Custom(kind), "") + .sign_with_keys(keys) + .expect("sign") + }; + let notice = sign(40099, &relay); + let pinned = crate::Db::from_pool(pool.clone()) + .apply_pin_command( + cid, + channel, + &sign(40010, &Keys::generate()), + &root, + crate::pins::PinChange::Pin { notice: ¬ice }, + &relay, + ) + .await + .expect("pin"); + let list = pinned.list.expect("the pin writes the list"); + + let lease_until = Utc::now() + chrono::Duration::seconds(60); + let (action_id, token) = enforcing_action(&pool, community_id, lease_until).await; + let refused = execute_delete_with_marker( + &pool, + action_id, + token, + cid, + list.event.id.as_bytes(), + None, + None, + &relay, + ) + .await + .expect_err("the list is not deleted"); + assert!(refused.to_string().contains("pin list"), "{refused}"); + let (committed, list) = + execute_delete_with_marker(&pool, action_id, token, cid, &root, None, None, &relay) + .await + .expect("delete"); + assert!(committed); + let list = list.expect("the delete rewrites the pin list"); + assert_eq!(list.event.pubkey, relay.public_key()); + assert_eq!( + list.event + .tags + .iter() + .map(|tag| tag.as_slice().to_vec()) + .collect::>(), + [ + vec!["d".to_owned(), channel.to_string()], + vec!["h".to_owned(), channel.to_string()], + ] + ); + } + // ── execute_kick_with_marker: provenance — Removed vs AlreadyGone ───────── #[tokio::test] diff --git a/crates/buzz-db/src/store/replaceable.rs b/crates/buzz-db/src/store/replaceable.rs index fbdf65ed9d..f938a73f30 100644 --- a/crates/buzz-db/src/store/replaceable.rs +++ b/crates/buzz-db/src/store/replaceable.rs @@ -347,8 +347,9 @@ async fn replace_parameterized_event_in_transaction_impl( /// /// These are the lists the relay signs and republishes in full on every /// change: the NIP-43 membership list (13534), the NIP-IA archived list -/// (13535) and NIP-29 group state (39000–39002), written by the addressable -/// path, the kind:39002 member snapshot and the kind:13534 writer, which all +/// (13535), the NIP-PM pin list (30623) and NIP-29 group state +/// (39000–39002), written by the addressable path, the kind:39002 member +/// snapshot and the kind:13534 writer, which all /// build their supersede with [`replacement_sql`] from this predicate. A /// retired head is a full copy that no relay reader returns. /// @@ -357,8 +358,8 @@ async fn replace_parameterized_event_in_transaction_impl( /// deleted channel's soft-deleted state, say), the deleted row no longer /// makes the replay a duplicate, and kinds without a channel have no /// created-at floor. Only the relay can submit these events: ingest requires -/// the signer to be the authenticated pubkey, kinds 13534 and 13535 are -/// relay-only, and the relay's writers sign a new event on every attempt. +/// the signer to be the authenticated pubkey, kinds 13534, 13535 and 30623 +/// are relay-only, and the relay's writers sign a new event on every attempt. /// /// The check is by kind, not signer, and every supersede is scoped to the /// event's own pubkey. A client's kind:39000–39002 goes through the NIP-33 @@ -367,11 +368,12 @@ async fn replace_parameterized_event_in_transaction_impl( /// soft-deletes it. pub(crate) const fn hard_deletes_superseded(kind: i32) -> bool { use buzz_core::kind::{ - KIND_IA_ARCHIVED_LIST, KIND_NIP29_GROUP_ADMINS, KIND_NIP29_GROUP_MEMBERS, - KIND_NIP29_GROUP_METADATA, KIND_NIP43_MEMBERSHIP_LIST, + KIND_CHANNEL_PINS, KIND_IA_ARCHIVED_LIST, KIND_NIP29_GROUP_ADMINS, + KIND_NIP29_GROUP_MEMBERS, KIND_NIP29_GROUP_METADATA, KIND_NIP43_MEMBERSHIP_LIST, }; kind == KIND_NIP43_MEMBERSHIP_LIST as i32 || kind == KIND_IA_ARCHIVED_LIST as i32 + || kind == KIND_CHANNEL_PINS as i32 || kind == KIND_NIP29_GROUP_METADATA as i32 || kind == KIND_NIP29_GROUP_ADMINS as i32 || kind == KIND_NIP29_GROUP_MEMBERS as i32 diff --git a/crates/buzz-db/src/store/user_deletion/content_batches/grouped.rs b/crates/buzz-db/src/store/user_deletion/content_batches/grouped.rs index 0a58c51c7e..ad3123f9e3 100644 --- a/crates/buzz-db/src/store/user_deletion/content_batches/grouped.rs +++ b/crates/buzz-db/src/store/user_deletion/content_batches/grouped.rs @@ -203,13 +203,16 @@ async fn erase_events(tx: &mut AdmittedTx, number: i64) -> Result<()> { sqlx::query("UPDATE events e SET pubkey=''::bytea,content='',sig=''::bytea, tags=COALESCE((SELECT jsonb_agg(jsonb_build_array('e',lower(tag->>1),'',tag->>3)) FROM jsonb_array_elements(e.tags) tag WHERE tag->>0='e' - AND tag->>3 IN ('root','reply') AND tag->>1 ~ '^[0-9a-fA-F]{64}$'),'[]'::jsonb), + AND tag->>3 IN ('root','reply') AND tag->>1 ~ '^[0-9a-fA-F]{64}$' + AND NOT(e.kind=ANY($3))),'[]'::jsonb), d_tag=NULL,not_before=NULL,delivered_at=NULL, deleted_at=COALESCE(deleted_at,clock_timestamp()) FROM content_batch_work w WHERE w.table_name='events' AND w.batch=$2 AND w.action='would_scrub' AND e.community_id=$1 AND e.id=decode(w.row_key->>'id','hex') AND e.created_at=(w.row_key->>'created_at')::timestamptz") - .bind(community).bind(number).execute(tx.conn()).await?; + // A pin command's `e` tag names its target, not an ancestor to keep. + .bind(community).bind(number).bind(crate::pins::COMMAND_KINDS.as_slice()) + .execute(tx.conn()).await?; sqlx::query( "DELETE FROM thread_metadata tm USING content_batch_work w WHERE w.table_name='events' AND w.batch=$2 AND w.action='would_delete' diff --git a/crates/buzz-db/src/store/user_deletion/content_batches/legacy_replies.rs b/crates/buzz-db/src/store/user_deletion/content_batches/legacy_replies.rs index 4f8976322c..ed2900908e 100644 --- a/crates/buzz-db/src/store/user_deletion/content_batches/legacy_replies.rs +++ b/crates/buzz-db/src/store/user_deletion/content_batches/legacy_replies.rs @@ -4,6 +4,7 @@ //! lookup as evidence that an event has no replies. //! Exact probes cover lowercase and uppercase references. Mixed-case references //! without thread metadata are not guaranteed; normal metadata uses binary IDs. +//! A NIP-PM pin or unpin command is never a reply: its `e` tag names its target. use super::*; const MAX_CANDIDATES: i64 = 10_000; @@ -13,6 +14,7 @@ pub(super) const CANDIDATES_SQL: &str = "SELECT e.id,e.created_at,e.tags CROSS JOIN LATERAL ( SELECT e.id,e.created_at,e.tags FROM events e WHERE e.community_id=$1 AND e.tags @> probe.tags + AND NOT(e.kind=ANY($4)) AND NOT EXISTS(SELECT 1 FROM thread_metadata tm WHERE tm.community_id=e.community_id AND tm.event_id=e.id AND tm.event_created_at=e.created_at) @@ -61,6 +63,7 @@ pub(super) async fn needed( .bind(community) .bind(json!(probes)) .bind(MAX_CANDIDATES + 1) + .bind(crate::pins::COMMAND_KINDS.as_slice()) .fetch_all(&mut *conn) .await?; sqlx::query("SELECT set_config('statement_timeout',$1,true)") diff --git a/crates/buzz-db/src/store/user_deletion/content_batches/mod.rs b/crates/buzz-db/src/store/user_deletion/content_batches/mod.rs index 3a1fdf1a85..e251daf999 100644 --- a/crates/buzz-db/src/store/user_deletion/content_batches/mod.rs +++ b/crates/buzz-db/src/store/user_deletion/content_batches/mod.rs @@ -31,6 +31,9 @@ const KINDS: &[i32] = &[ 30175, 30176, 30178, 30030, 30180, 30621, // Private per-viewer state: only the trusted relay's matching d/p snapshot. 30622, 1063, + // NIP-PM pin and unpin commands. A recent one keeps its ID and timestamp + // (`crate::pins::keeps_replay_record`). + 40010, 40011, ]; const PAGE_SIZE: i64 = 100; use super::agent_ownership::MAX_TARGETS; @@ -306,11 +309,15 @@ async fn plan( // whose selected ancestor was already physically removed. let metadata = retention::metadata(conn, options.community, &selected).await?; let selected = retention::children_first(selected, &metadata)?; + let now = Utc::now(); + let mut scrubbed_events = 0; for page in selected.chunks(PAGE_SIZE as usize) { rows::event_rows(conn, page, &mut output).await?; for event in page { let id = hex::encode(&event.id); - let scrub = needed.contains(&id); + let scrub = needed.contains(&id) + || crate::pins::keeps_replay_record(event.kind, event.created_at, now); + scrubbed_events += usize::from(scrub); output .repairs .push(json!({"event_id": id, "channel_id": event.channel_id, @@ -347,7 +354,7 @@ async fn plan( batches: output.batches, items: output.seen.len(), warnings: output.warnings, - scrubbed_events: needed.len(), + scrubbed_events, excluded_event_kinds: excluded, }; Ok(Plan { diff --git a/crates/buzz-db/src/store/user_deletion/content_batches/safety_postgres_tests.rs b/crates/buzz-db/src/store/user_deletion/content_batches/safety_postgres_tests.rs index 655cfa09c0..c850cf76d5 100644 --- a/crates/buzz-db/src/store/user_deletion/content_batches/safety_postgres_tests.rs +++ b/crates/buzz-db/src/store/user_deletion/content_batches/safety_postgres_tests.rs @@ -26,6 +26,7 @@ async fn missing_metadata_lookup_can_use_existing_tags_index() { [["e", root.id.to_hex().to_ascii_uppercase()]] ])) .bind(10001_i64) + .bind(crate::pins::COMMAND_KINDS.as_slice()) .fetch_one(&mut *tx) .await .unwrap(); diff --git a/crates/buzz-db/src/store/user_deletion/content_batches/scrub_postgres_tests.rs b/crates/buzz-db/src/store/user_deletion/content_batches/scrub_postgres_tests.rs index f73066410d..3f65d6b1b8 100644 --- a/crates/buzz-db/src/store/user_deletion/content_batches/scrub_postgres_tests.rs +++ b/crates/buzz-db/src/store/user_deletion/content_batches/scrub_postgres_tests.rs @@ -613,3 +613,130 @@ async fn late_legacy_references_block_deletion_for_lower_and_upper_hex() { assert_eq!(row(&db, c, &survivor).await, before); } } + +/// Erasure removes the pin and unpin commands of an account. One under an +/// hour old keeps its ID and timestamp and nothing else, so sending it again +/// cannot pin a message another member has unpinned since. +/// Another member's command names its target, not a reply parent, so it keeps +/// no tombstone of an erased message. +/// Mutation: drop `keeps_replay_record` from the plan → RED (the resend pins +/// again); drop the command kinds from the scrub tag filter → RED (the record +/// keeps the target); drop them from the legacy reply scan → RED (the erased +/// message stays as a tombstone). +#[tokio::test] +#[ignore = "requires Postgres"] +async fn erased_pin_commands_keep_only_a_replay_record() { + use crate::pins::{PinChange, PinCommandWrite}; + + async fn apply( + db: &Db, + c: CommunityId, + ch: Uuid, + relay: &Keys, + command: &nostr::Event, + target: &nostr::Event, + ) -> PinCommandWrite { + let notice = EventBuilder::new(Kind::Custom(40099), command.id.to_hex()) + .tags([Tag::parse(["h", &ch.to_string()]).unwrap()]) + .sign_with_keys(relay) + .unwrap(); + let change = if command.kind == Kind::Custom(40010) { + PinChange::Pin { notice: ¬ice } + } else { + PinChange::Unpin + }; + db.apply_pin_command(c, ch, command, target.id.as_bytes(), change, relay) + .await + .unwrap() + } + + let (db, c, ch, alice, bob) = setup().await; + let relay = Keys::generate(); + let pinned = message(&db, c, ch, &bob, "pinned", None).await; + let own = message(&db, c, ch, &alice, "own", None).await; + let command_for = |target: &nostr::Event, kind: u16, author: &Keys, age_secs: u64| { + EventBuilder::new(Kind::Custom(kind), "") + .tags([ + Tag::parse(["h", &ch.to_string()]).unwrap(), + // Scrubbing keeps a marked reference like this on a message. + Tag::parse(["e", &target.id.to_hex(), "", "reply"]).unwrap(), + ]) + .custom_created_at(Timestamp::from(Timestamp::now().as_secs() - age_secs)) + .sign_with_keys(author) + .unwrap() + }; + let command = + |kind: u16, author: &Keys, age_secs: u64| command_for(&pinned, kind, author, age_secs); + let exists = |event: &nostr::Event| { + sqlx::query_scalar::<_, bool>( + "SELECT EXISTS(SELECT 1 FROM events WHERE community_id=$1 AND id=$2)", + ) + .bind(c.as_uuid()) + .bind(event.id.as_bytes().to_vec()) + .fetch_one(db.pool()) + }; + assert!( + apply(&db, c, ch, &relay, &command_for(&own, 40010, &bob, 0), &own) + .await + .list + .is_some() + ); + + // The relay stores no command this old, so it was stored back then. + let old = command(40011, &alice, 2 * 60 * 60); + sqlx::query( + "INSERT INTO events (community_id,id,pubkey,created_at,kind,tags,content,sig,channel_id) + VALUES ($1,$2,$3,$4,40011,$5,'',$6,$7)", + ) + .bind(c.as_uuid()) + .bind(old.id.as_bytes().as_slice()) + .bind(old.pubkey.to_bytes().as_slice()) + .bind(timestamp(&old)) + .bind(serde_json::to_value(&old.tags).unwrap()) + .bind(old.sig.serialize().as_slice()) + .bind(ch) + .execute(db.pool()) + .await + .unwrap(); + let pin = command(40010, &alice, 0); + assert!(apply(&db, c, ch, &relay, &pin, &pinned) + .await + .list + .is_some()); + + let erased = db + .user_deletion_store() + .run_message_batches( + &options(c, &alice), + ExecutionMode::Delete, + None, + &mut Vec::new(), + ) + .await + .unwrap(); + assert_eq!(erased.scrubbed_events, 1); + assert!( + !exists(&old).await.unwrap(), + "a command too old to resend is removed" + ); + assert!( + !exists(&own).await.unwrap(), + "a message only a command names is removed" + ); + let record = row(&db, c, &pin).await; + assert_eq!(record["pubkey"], "\\x"); + assert_eq!(record["sig"], "\\x"); + assert_eq!(record["content"], ""); + assert_eq!(record["tags"], json!([])); + + let unpin = command(40011, &bob, 0); + assert!(apply(&db, c, ch, &relay, &unpin, &pinned) + .await + .list + .is_some()); + let resent = apply(&db, c, ch, &relay, &pin, &pinned).await; + assert!( + !resent.inserted && resent.list.is_none(), + "the unpin stands" + ); +} diff --git a/crates/buzz-db/src/test_support.rs b/crates/buzz-db/src/test_support.rs index 7df0e26d5f..ad7cef049a 100644 --- a/crates/buzz-db/src/test_support.rs +++ b/crates/buzz-db/src/test_support.rs @@ -529,6 +529,20 @@ pub(crate) async fn wait_for_lock_wait(pool: &sqlx::PgPool, application_name: &s .expect("session reached a lock wait"); } +/// Monthly `events` partitions (not their indexes) this backend holds a +/// relation lock on right now. +pub(crate) async fn locked_event_partitions(tx: &mut crate::AdmittedTx) -> Vec { + sqlx::query_scalar( + "SELECT DISTINCT c.relname::text FROM pg_locks l \ + JOIN pg_class c ON c.oid = l.relation \ + WHERE l.locktype = 'relation' AND l.pid = pg_backend_pid() \ + AND c.relkind = 'r' AND c.relname LIKE 'events\\_p%' ORDER BY 1", + ) + .fetch_all(tx.conn()) + .await + .expect("observe partition locks") +} + /// Loopback TCP proxy that can pause the upstream database, like /// `docker pause` on a replica. While paused, every session (established or /// new) holds the bytes it receives with both sockets open; on resume the diff --git a/crates/buzz-relay/src/api/admin/mod.rs b/crates/buzz-relay/src/api/admin/mod.rs index c29797185b..b1e2177748 100644 --- a/crates/buzz-relay/src/api/admin/mod.rs +++ b/crates/buzz-relay/src/api/admin/mod.rs @@ -6468,9 +6468,11 @@ mod postgres_tests { target_event_id.as_slice(), None, // no parent None, + &nostr::Keys::generate(), ) .await - .expect("execute_delete_with_marker"); + .expect("execute_delete_with_marker") + .0; assert!(committed, "delete mutation+marker must commit"); // Crash point: step_marker is set but action not yet finalized. diff --git a/crates/buzz-relay/src/handlers/ingest.rs b/crates/buzz-relay/src/handlers/ingest.rs index 58edf331c8..6015e8cd94 100644 --- a/crates/buzz-relay/src/handlers/ingest.rs +++ b/crates/buzz-relay/src/handlers/ingest.rs @@ -28,13 +28,14 @@ use buzz_core::kind::{ KIND_NIP29_DELETE_GROUP, KIND_NIP29_EDIT_METADATA, KIND_NIP29_JOIN_REQUEST, KIND_NIP29_LEAVE_REQUEST, KIND_NIP29_PUT_USER, KIND_NIP29_REMOVE_USER, KIND_NIP43_LEAVE_REQUEST, KIND_NIP65_RELAY_LIST_METADATA, KIND_PERSONA, KIND_PIN_LIST, - KIND_PRESENCE_UPDATE, KIND_PRIVATE_MANAGED_AGENT, KIND_PRODUCT_FEEDBACK, KIND_PROFILE, - KIND_PROJECT, KIND_REACTION, KIND_READ_STATE, KIND_REPORT, KIND_SOLO_MEMBER_ROLE, + KIND_PIN_MESSAGE, KIND_PRESENCE_UPDATE, KIND_PRIVATE_MANAGED_AGENT, KIND_PRODUCT_FEEDBACK, + KIND_PROFILE, KIND_PROJECT, KIND_REACTION, KIND_READ_STATE, KIND_REPORT, KIND_SOLO_MEMBER_ROLE, KIND_STREAM_MESSAGE, KIND_STREAM_MESSAGE_BOOKMARKED, KIND_STREAM_MESSAGE_DIFF, KIND_STREAM_MESSAGE_EDIT, KIND_STREAM_MESSAGE_PINNED, KIND_STREAM_MESSAGE_SCHEDULED, KIND_STREAM_MESSAGE_V2, KIND_STREAM_REMINDER, KIND_TEAM, KIND_TEAM_CATALOG, KIND_TEXT_NOTE, - KIND_USER_STATUS, KIND_WORKFLOW_DEF, KIND_WORKFLOW_TRIGGER, RELAY_ADMIN_ADD_MEMBER, - RELAY_ADMIN_CHANGE_ROLE, RELAY_ADMIN_REMOVE_MEMBER, RELAY_ADMIN_SET_WORKSPACE_PROFILE, + KIND_UNPIN_MESSAGE, KIND_USER_STATUS, KIND_WORKFLOW_DEF, KIND_WORKFLOW_TRIGGER, + RELAY_ADMIN_ADD_MEMBER, RELAY_ADMIN_CHANGE_ROLE, RELAY_ADMIN_REMOVE_MEMBER, + RELAY_ADMIN_SET_WORKSPACE_PROFILE, }; use buzz_core::tenant::TenantContext; use buzz_core::verification::verify_event; @@ -641,6 +642,8 @@ fn required_scope_for_kind(kind: u32, event: &Event) -> Result Ok(Scope::MessagesWrite), @@ -892,6 +895,8 @@ pub(crate) fn requires_h_channel_scope(kind: u32) -> bool { | KIND_STREAM_MESSAGE_SCHEDULED | KIND_STREAM_REMINDER | KIND_STREAM_MESSAGE_DIFF + | KIND_PIN_MESSAGE + | KIND_UNPIN_MESSAGE | KIND_CANVAS | KIND_FORUM_POST | KIND_FORUM_VOTE @@ -1123,12 +1128,19 @@ impl ThreadMetadataOwned { /// Whether `target` is in `channel_id` and readable by `reader`. Write paths /// that reference an event reject a target failing this exactly as a missing /// one, so the rejection never reveals whether, or where, the target exists. +/// +/// A NIP-PM pin or unpin command is never such a target. Account erasure +/// removes a command without keeping it as a thread ancestor. fn target_readable_in_channel( target: &buzz_core::StoredEvent, channel_id: Uuid, reader: &[u8], ) -> bool { target.channel_id == Some(channel_id) + && !matches!( + event_kind_u32(&target.event), + KIND_PIN_MESSAGE | KIND_UNPIN_MESSAGE + ) && super::req::event_visible_to_reader(&target.event, reader) } @@ -2703,6 +2715,7 @@ async fn ingest_event_inner( )); } + let pin_command = matches!(kind_u32, KIND_PIN_MESSAGE | KIND_UNPIN_MESSAGE); let required = match required_scope_for_kind(kind_u32, &event) { Ok(scope) => scope, Err(msg) => return Err(IngestError::Rejected(msg.into())), @@ -3449,7 +3462,11 @@ async fn ingest_event_inner( validate_event_imeta(tenant, state, &event, &tenant_media_base).await?; - let thread_meta = if kind_u32 != KIND_SOLO_MEMBER_ROLE && requires_h_channel_scope(kind_u32) { + // A pin command's `e` tag names its target, not a thread parent. + let thread_meta = if kind_u32 != KIND_SOLO_MEMBER_ROLE + && !pin_command + && requires_h_channel_scope(kind_u32) + { if let Some(ch_id) = channel_id { resolve_nip10_thread_meta(tenant.community(), &event, ch_id, state) .await @@ -3715,6 +3732,8 @@ async fn ingest_event_inner( (stored, inserted) } else if kind_u32 == KIND_SOLO_MEMBER_ROLE { super::solo_member_role::persist(tenant, state, &event).await? + } else if pin_command { + super::pins::persist(tenant, state, &event).await? } else if kind_u32 == KIND_NIP29_REMOVE_USER { let thread_params = thread_meta.as_ref().map(|m| m.as_params()); crate::handlers::side_effects::persist_remove_user(tenant, &event, state, thread_params) diff --git a/crates/buzz-relay/src/handlers/mod.rs b/crates/buzz-relay/src/handlers/mod.rs index ad1284feda..0e10176444 100644 --- a/crates/buzz-relay/src/handlers/mod.rs +++ b/crates/buzz-relay/src/handlers/mod.rs @@ -48,6 +48,9 @@ pub mod moderation_commands; pub mod moderation_notices; /// Multi-node fan-out: Redis events to local subscribers, with lossless lag handling. pub mod multinode_fanout; +mod pins; +#[cfg(test)] +mod pins_postgres_tests; /// Product-feedback validation + deployment sidecar persistence. pub mod product_feedback; #[allow(dead_code, missing_docs)] diff --git a/crates/buzz-relay/src/handlers/pins.rs b/crates/buzz-relay/src/handlers/pins.rs new file mode 100644 index 0000000000..8de4cc063c --- /dev/null +++ b/crates/buzz-relay/src/handlers/pins.rs @@ -0,0 +1,119 @@ +//! Transport-neutral ingest for the NIP-PM pin and unpin commands. + +use std::sync::Arc; + +use buzz_core::{ + kind::{event_kind_u32, KIND_CHANNEL_PINS, KIND_PIN_MESSAGE}, + StoredEvent, TenantContext, +}; +use buzz_db::{pins::PinChange, DbError}; +use nostr::{Event, Tag}; +use uuid::Uuid; + +use crate::state::AppState; + +use super::{ + event::dispatch_persistent_event, + ingest::IngestError, + side_effects::{fan_out_system_message, sign_system_message}, +}; + +fn only_tag<'a>(event: &'a Event, name: &str) -> Result<&'a str, IngestError> { + let mut tags = event + .tags + .iter() + .filter(|tag| tag.as_slice().first().is_some_and(|key| key == name)); + if let (Some([_, value, ..]), None) = (tags.next().map(Tag::as_slice), tags.next()) { + return Ok(value); + } + Err(IngestError::Rejected(format!( + "invalid: pin command requires exactly one {name} tag with a value" + ))) +} + +/// Fan out a channel's rewritten pin list after its transaction committed. +pub(super) async fn dispatch_list( + tenant: &TenantContext, + state: &Arc, + list: &StoredEvent, +) { + let relay_pubkey_hex = state.relay_keypair.public_key().to_hex(); + dispatch_persistent_event( + tenant, + state, + list, + KIND_CHANNEL_PINS, + &relay_pubkey_hex, + None, + ) + .await; +} + +pub(super) async fn persist( + tenant: &TenantContext, + state: &Arc, + event: &Event, +) -> Result<(StoredEvent, bool), IngestError> { + if !event.content.is_empty() { + return Err(IngestError::Rejected( + "invalid: pin command content must be empty".into(), + )); + } + let channel_id = only_tag(event, "h")? + .parse::() + .map_err(|_| IngestError::Rejected("invalid: h tag must be a channel UUID".into()))?; + let target_hex = only_tag(event, "e")?; + let target = Some(target_hex) + .filter(|id| id.len() == 64 && !id.bytes().any(|b| b.is_ascii_uppercase())) + .and_then(|id| hex::decode(id).ok()) + .ok_or_else(|| { + IngestError::Rejected("invalid: e tag must be a lowercase hex event ID".into()) + })?; + + let notice = (event_kind_u32(event) == KIND_PIN_MESSAGE) + .then(|| { + sign_system_message( + state, + channel_id, + serde_json::json!({ + "type": "message_pinned", + "actor": event.pubkey.to_hex(), + "target_event_id": target_hex, + // Two pins of one message by one member are two notices. + "command_event_id": event.id.to_hex(), + }), + chrono::Utc::now(), + ) + }) + .transpose() + .map_err(|error| IngestError::Internal(format!("error: {error}")))?; + let change = match ¬ice { + Some(notice) => PinChange::Pin { notice }, + None => PinChange::Unpin, + }; + let write = state + .db + .apply_pin_command( + tenant.community(), + channel_id, + event, + &target, + change, + &state.relay_keypair, + ) + .await + .map_err(|error| match error { + DbError::AccessDenied(reason) => IngestError::Rejected(format!("invalid: {reason}")), + error => IngestError::Internal(format!("error: pin write failed: {}", error.kind())), + })?; + + // The command is committed. What follows only updates live subscribers, + // so a failure is logged; the next read returns the stored list. + if let Some(list) = &write.list { + dispatch_list(tenant, state, list).await; + if let Some(notice) = ¬ice { + fan_out_system_message(tenant, state, channel_id, notice).await; + } + } + Ok((write.stored, write.inserted)) +} diff --git a/crates/buzz-relay/src/handlers/pins_postgres_tests.rs b/crates/buzz-relay/src/handlers/pins_postgres_tests.rs new file mode 100644 index 0000000000..4e8502149d --- /dev/null +++ b/crates/buzz-relay/src/handlers/pins_postgres_tests.rs @@ -0,0 +1,602 @@ +//! Postgres-backed tests for NIP-PM channel pins through ingest and REQ: who +//! may pin, what the relay answers, who can read the list, and that deleting a +//! pinned message rewrites it. + +use std::sync::Arc; + +use buzz_core::kind::{ + KIND_CHANNEL_PINS, KIND_DM_OPEN, KIND_PIN_MESSAGE, KIND_SYSTEM_MESSAGE, KIND_UNPIN_MESSAGE, +}; +use buzz_core::TenantContext; +use nostr::{Event, EventBuilder, Keys, Kind, Tag}; +use serde_json::{json, Value}; +use uuid::Uuid; + +use super::group_state_postgres_tests::{community, create_channel, http_auth, test_conn}; +use crate::handlers::ingest::{ingest_event, IngestError, IngestResult}; +use crate::state::AppState; + +struct Fixture { + state: Arc, + tenant: TenantContext, +} + +async fn fixture() -> Fixture { + let state = crate::api::bridge::postgres_tests::bridge_handler_test_state() + .await + .expect("local Postgres and Redis"); + let tenant = community(&state, "pins").await; + Fixture { state, tenant } +} + +fn signed(keys: &Keys, kind: u32, content: &str, tags: &[&[&str]]) -> Event { + EventBuilder::new(Kind::Custom(kind as u16), content) + .tags( + tags.iter() + .map(|tag| Tag::parse(tag.iter().copied()).expect("tag")), + ) + .sign_with_keys(keys) + .expect("sign") +} + +/// A pin or unpin of `target` in `channel`. The `client-id` tag makes two +/// commands for one target different events. +fn command(keys: &Keys, kind: u32, channel: Uuid, target: &str) -> Event { + signed( + keys, + kind, + "", + &[ + &["h", &channel.to_string()], + &["e", target], + &["client-id", &Uuid::new_v4().to_string()], + ], + ) +} + +impl Fixture { + async fn send(&self, keys: &Keys, event: Event) -> Result { + ingest_event(&self.state, &self.tenant, event, http_auth(keys)).await + } + + /// Ingest `event` and return its `OK` message. + async fn accept(&self, keys: &Keys, event: Event) -> String { + let kind = event.kind; + let result = self + .send(keys, event) + .await + .unwrap_or_else(|error| panic!("kind:{kind}: {error:?}")); + assert!(result.accepted, "kind:{kind}: {}", result.message); + result.message + } + + async fn message(&self, keys: &Keys, channel: Uuid) -> String { + // Unique content: two messages of one author are different events. + let content = Uuid::new_v4().to_string(); + let message = signed(keys, 9, &content, &[&["h", &channel.to_string()]]); + let id = message.id.to_hex(); + self.accept(keys, message).await; + id + } + + async fn pin(&self, keys: &Keys, channel: Uuid, target: &str) -> String { + self.accept(keys, command(keys, KIND_PIN_MESSAGE, channel, target)) + .await + } + + async fn unpin(&self, keys: &Keys, channel: Uuid, target: &str) -> String { + self.accept(keys, command(keys, KIND_UNPIN_MESSAGE, channel, target)) + .await + } + + /// The events a historical REQ returns to `reader`. + async fn read(&self, reader: &Keys, filter: Value) -> Vec { + read(&self.state, &self.tenant, reader, filter).await + } + + /// The pinned IDs `reader` gets when it reads `channel`'s list by `#h`. + /// `None` when the relay returns no list. + async fn pins(&self, reader: &Keys, channel: Uuid) -> Option> { + let mut lists = self + .read( + reader, + json!({"kinds": [KIND_CHANNEL_PINS], "#h": [channel.to_string()]}), + ) + .await; + assert!(lists.len() <= 1, "a channel has one pin list"); + lists.pop().map(|list| pinned(&list)) + } + + /// The content of each pin notice stored in `channel`, ordered by target. + async fn notices(&self, reader: &Keys, channel: Uuid) -> Vec { + let notices = self + .read( + reader, + json!({"kinds": [KIND_SYSTEM_MESSAGE], "#h": [channel.to_string()]}), + ) + .await; + let mut notices: Vec = notices + .iter() + .map(|notice| serde_json::from_str(¬ice.content).expect("notice content")) + .filter(|content: &Value| content["type"] == "message_pinned") + .collect(); + notices.sort_by_key(|notice| notice["target_event_id"].to_string()); + notices + } +} + +async fn read( + state: &Arc, + tenant: &TenantContext, + reader: &Keys, + filter: Value, +) -> Vec { + let (conn, mut rx) = test_conn(tenant, reader); + let filter: nostr::Filter = serde_json::from_value(filter).expect("filter"); + crate::handlers::req::handle_req("p".into(), vec![filter], vec![None], conn, state.clone()) + .await; + let mut events = Vec::new(); + while let Ok(frame) = rx.try_recv() { + let axum::extract::ws::Message::Text(text) = frame else { + continue; + }; + let message: Value = serde_json::from_str(&text).expect("relay frame"); + match message[0].as_str() { + Some("EVENT") => { + events.push(serde_json::from_value(message[2].clone()).expect("event")) + } + Some("EOSE") | Some("CLOSED") => return events, + other => panic!("unexpected frame {other:?}: {text}"), + } + } + panic!("no EOSE"); +} + +fn pinned(list: &Event) -> Vec { + list.tags + .iter() + .map(|tag| tag.as_slice()) + .filter(|tag| tag[0] == "e") + .map(|tag| tag[1].clone()) + .collect() +} + +/// A live subscription of `reader` to `channel`'s pin lists by `#h`, on a +/// connection fan-out can reach. +struct LiveLists(tokio::sync::mpsc::Receiver); + +impl LiveLists { + async fn open(f: &Fixture, reader: &Keys, channel: Uuid) -> Self { + let (conn, mut rx) = test_conn(&f.tenant, reader); + f.state.conn_manager.register( + conn.conn_id, + conn.send_tx.clone(), + conn.ctrl_tx.clone(), + conn.terminal_ctrl_tx.clone(), + None, + conn.cancel.clone(), + f.tenant.community(), + conn.backpressure_count.clone(), + conn.subscriptions.clone(), + conn.grace_limit, + crate::state::CommunityConnectionControl::new(conn.cancel.clone()), + ); + f.state + .conn_manager + .set_authenticated_pubkey(conn.conn_id, reader.public_key().to_bytes().to_vec()); + let filter = json!({"kinds": [KIND_CHANNEL_PINS], "#h": [channel.to_string()]}); + crate::handlers::req::handle_req( + "live".into(), + vec![serde_json::from_value(filter).expect("filter")], + vec![None], + conn, + f.state.clone(), + ) + .await; + // Drain the stored history; what follows is live. + while rx.try_recv().is_ok() {} + Self(rx) + } + + /// The pinned IDs of the next `count` lists, oldest list first. Fan-out + /// runs in tasks of its own, so this waits for each list and orders them + /// by `created_at`, not by arrival. No further list has arrived. + async fn delivered(&mut self, count: usize) -> Vec> { + let mut lists = Vec::new(); + while lists.len() < count { + let frame = tokio::time::timeout(std::time::Duration::from_secs(5), self.0.recv()) + .await + .expect("a live pin list") + .expect("open connection"); + let axum::extract::ws::Message::Text(text) = frame else { + continue; + }; + let message: Value = serde_json::from_str(&text).expect("relay frame"); + assert_eq!(message[0], "EVENT", "{text}"); + let list: Event = serde_json::from_value(message[2].clone()).expect("event"); + assert_eq!(list.kind.as_u16() as u32, KIND_CHANNEL_PINS); + lists.push(list); + } + assert!(self.0.try_recv().is_err(), "an unexpected live frame"); + lists.sort_by_key(|list| list.created_at); + lists.iter().map(pinned).collect() + } +} + +fn refusal(result: Result) -> String { + match result { + Err(IngestError::Rejected(reason)) => reason, + Err(error) => panic!("unexpected error: {error:?}"), + Ok(result) => panic!("accepted: {:?}", result.message), + } +} + +/// The journey: members pin and unpin, the relay answers each command, keeps +/// one relay-signed list with the newest pin first, announces each pin that +/// changes it, and sends every new list to `#h` subscribers. +/// Mutation: drop `dispatch_list` from `pins::persist` → RED (no live list); +/// answer a stored command like a new one → RED (no `duplicate:`); drop +/// `command_event_id` from the notice → RED (re-pins share one notice); let +/// `target_readable_in_channel` pass a command → RED (the reply is stored). +#[tokio::test] +#[ignore = "requires Postgres and Redis"] +async fn members_pin_and_unpin_through_one_relay_signed_list() { + let f = fixture().await; + let (owner, other) = (Keys::generate(), Keys::generate()); + let channel = create_channel(&f.state, &f.tenant, &owner, &[]).await; + let first = f.message(&owner, channel).await; + let second = f.message(&other, channel).await; + assert_eq!(f.pins(&owner, channel).await, None, "no list before a pin"); + let mut live = LiveLists::open(&f, &other, channel).await; + + // An open channel lets anyone who may post pin, not only its creator. + // Elements after a tag's value, such as a relay hint, carry no meaning. + let hinted = signed( + &other, + KIND_PIN_MESSAGE, + "", + &[ + &["h", &channel.to_string(), "wss://relay.example.org"], + &["e", &first, "wss://relay.example.org"], + ], + ); + assert_eq!(f.accept(&other, hinted.clone()).await, ""); + let again = command(&owner, KIND_PIN_MESSAGE, channel, &second); + assert_eq!(f.accept(&owner, again.clone()).await, ""); + assert_eq!( + f.pins(&owner, channel).await, + Some(vec![second.clone(), first.clone()]) + ); + + let lists = f + .read( + &owner, + json!({"kinds": [KIND_CHANNEL_PINS], "#h": [channel.to_string()]}), + ) + .await; + let [list] = lists.as_slice() else { + panic!("one list by #h, got {}", lists.len()); + }; + assert_eq!(list.pubkey, f.state.relay_keypair.public_key()); + assert_eq!(list.content, ""); + assert_eq!( + list.tags + .iter() + .map(|tag| tag.as_slice().to_vec()) + .collect::>(), + [ + vec!["d".to_owned(), channel.to_string()], + vec!["h".to_owned(), channel.to_string()], + vec!["e".to_owned(), second.clone()], + vec!["e".to_owned(), first.clone()], + ] + ); + assert!(list.verify().is_ok()); + + // A resend is a duplicate; a new pin of a pinned message changes nothing. + assert_eq!(f.accept(&owner, again.clone()).await, "duplicate:"); + assert_eq!(f.pin(&owner, channel, &first).await, ""); + assert_eq!( + f.unpin(&owner, channel, &f.message(&owner, channel).await) + .await, + "" + ); + let mut notices = [ + json!({"type": "message_pinned", "actor": other.public_key().to_hex(), + "target_event_id": first, "command_event_id": hinted.id.to_hex()}), + json!({"type": "message_pinned", "actor": owner.public_key().to_hex(), + "target_event_id": second, "command_event_id": again.id.to_hex()}), + ]; + notices.sort_by_key(|notice| notice["target_event_id"].to_string()); + assert_eq!( + f.notices(&owner, channel).await, + notices, + "one notice for each pin that changed the list" + ); + + assert_eq!(f.unpin(&other, channel, &second).await, ""); + assert_eq!(f.unpin(&owner, channel, &first).await, ""); + assert_eq!(f.pins(&owner, channel).await, Some(Vec::new())); + assert_eq!(f.notices(&owner, channel).await.len(), 2, "no unpin notice"); + + // Each pin has its own notice, however quickly the same member pins the + // same message again. + for _ in 0..3 { + assert_eq!(f.pin(&owner, channel, &first).await, ""); + assert_eq!(f.unpin(&owner, channel, &first).await, ""); + } + assert_eq!(f.notices(&owner, channel).await.len(), 5); + let mut delivered = vec![ + vec![first.clone()], + vec![second.clone(), first.clone()], + vec![first.clone()], + Vec::new(), + ]; + for _ in 0..3 { + delivered.extend([vec![first.clone()], Vec::new()]); + } + assert_eq!(live.delivered(delivered.len()).await, delivered); + + // A command is not a message: nothing replies to it. + let reply = signed( + &owner, + 9, + "reply", + &[ + &["h", &channel.to_string()], + &["e", &hinted.id.to_hex(), "", "reply"], + ], + ); + let reason = refusal(f.send(&owner, reply).await); + assert!(reason.contains("reply parent not found"), "{reason}"); +} + +/// Only those who can read a channel get its pin list: stored by `#h` or by +/// `#d`, live by `#h`. A DM is a channel like any other. `#h` names the +/// channel, so it also reads an unlisted channel the reader has not joined. +/// Mutation: store the list without its channel → RED (an outsider reads a +/// private channel's pins). +#[tokio::test] +#[ignore = "requires Postgres and Redis"] +async fn the_list_is_read_like_the_channel() { + let f = fixture().await; + let (owner, peer, outsider) = (Keys::generate(), Keys::generate(), Keys::generate()); + let private = create_channel(&f.state, &f.tenant, &owner, &[&["visibility", "private"]]).await; + let opened = f + .accept( + &owner, + signed( + &owner, + KIND_DM_OPEN, + "", + &[&["p", &peer.public_key().to_hex()]], + ), + ) + .await; + let opened: Value = + serde_json::from_str(opened.strip_prefix("response:").expect("DM response")).expect("json"); + let dm: Uuid = opened["channel_id"] + .as_str() + .expect("channel_id") + .parse() + .expect("uuid"); + + for (channel, readers) in [(private, vec![&owner]), (dm, vec![&owner, &peer])] { + let mut live = LiveLists::open(&f, &outsider, channel).await; + let mut member = LiveLists::open(&f, &owner, channel).await; + let message = f.message(&owner, channel).await; + assert_eq!(f.pin(&owner, channel, &message).await, ""); + let by_d = json!({"kinds": [KIND_CHANNEL_PINS], "#d": [channel.to_string()]}); + for reader in readers { + assert_eq!(f.pins(reader, channel).await, Some(vec![message.clone()])); + assert_eq!(f.read(reader, by_d.clone()).await.len(), 1); + } + assert_eq!(f.pins(&outsider, channel).await, None); + assert!(f.read(&outsider, by_d).await.is_empty()); + // The member's list has arrived, so the outsider's would have too. + assert_eq!(member.delivered(1).await, [vec![message.clone()]]); + assert!(live.delivered(0).await.is_empty()); + + let refused = command(&outsider, KIND_PIN_MESSAGE, channel, &message); + refusal(f.send(&outsider, refused).await); + } + + let unlisted = create_channel(&f.state, &f.tenant, &owner, &[&["unlisted", "true"]]).await; + let message = f.message(&owner, unlisted).await; + assert_eq!(f.pin(&owner, unlisted, &message).await, ""); + assert_eq!(f.pins(&outsider, unlisted).await, Some(vec![message])); + let by_d = json!({"kinds": [KIND_CHANNEL_PINS], "#d": [unlisted.to_string()]}); + assert!( + f.read(&outsider, by_d).await.is_empty(), + "`#d` does not name a channel for this kind" + ); +} + +/// Each refusal stores nothing and leaves the list alone. +/// Mutation: drop any one check in `pins::persist` → RED for its row. +#[tokio::test] +#[ignore = "requires Postgres and Redis"] +async fn refused_commands_change_nothing() { + let f = fixture().await; + let (owner, guest) = (Keys::generate(), Keys::generate()); + let channel = create_channel(&f.state, &f.tenant, &owner, &[]).await; + let elsewhere = create_channel(&f.state, &f.tenant, &owner, &[]).await; + let message = f.message(&owner, channel).await; + let foreign = f.message(&owner, elsewhere).await; + let h = channel.to_string(); + f.accept( + &owner, + signed( + &owner, + 9000, + "", + &[&["h", &h], &["p", &guest.public_key().to_hex(), "guest"]], + ), + ) + .await; + + let malformed: [(&str, Event, &str); 6] = [ + ( + "two e tags", + signed( + &owner, + KIND_PIN_MESSAGE, + "", + &[&["h", &h], &["e", &message], &["e", &foreign]], + ), + "invalid: pin command requires exactly one e tag with a value", + ), + ( + "no e tag", + signed(&owner, KIND_UNPIN_MESSAGE, "", &[&["h", &h]]), + "invalid: pin command requires exactly one e tag with a value", + ), + ( + "an uppercase ID", + signed( + &owner, + KIND_PIN_MESSAGE, + "", + &[&["h", &h], &["e", &message.to_uppercase()]], + ), + "invalid: e tag must be a lowercase hex event ID", + ), + ( + "a short ID", + signed( + &owner, + KIND_PIN_MESSAGE, + "", + &[&["h", &h], &["e", &message[..62]]], + ), + "invalid: e tag must be a lowercase hex event ID", + ), + ( + "content", + signed( + &owner, + KIND_PIN_MESSAGE, + "why", + &[&["h", &h], &["e", &message]], + ), + "invalid: pin command content must be empty", + ), + ( + "a message of another channel", + command(&owner, KIND_PIN_MESSAGE, channel, &foreign), + "invalid: target is not a message in this channel", + ), + ]; + let mut refused = Vec::new(); + for (case, event, reason) in malformed { + assert_eq!( + refusal(f.send(&owner, event.clone()).await), + reason, + "{case}" + ); + refused.push(event); + } + + let by_guest = command(&guest, KIND_PIN_MESSAGE, channel, &message); + refusal(f.send(&guest, by_guest.clone()).await); + refused.push(by_guest); + + // Clients never write the list. + let forged = signed( + &owner, + KIND_CHANNEL_PINS, + "", + &[&["d", &h], &["e", &message]], + ); + assert_eq!( + refusal(f.send(&owner, forged.clone()).await), + "restricted: relay-only kind" + ); + refused.push(forged); + + assert_eq!(f.pin(&owner, channel, &message).await, ""); + sqlx::query("UPDATE channels SET archived_at = NOW() WHERE id = $1") + .bind(channel) + .execute(f.state.db.pool()) + .await + .expect("archive"); + let archived = command(&owner, KIND_UNPIN_MESSAGE, channel, &message); + assert_eq!( + refusal(f.send(&owner, archived.clone()).await), + "invalid: channel is archived" + ); + refused.push(archived); + + let ids: Vec> = refused + .iter() + .map(|event| event.id.to_bytes().to_vec()) + .collect(); + let stored: i64 = + sqlx::query_scalar("SELECT count(*) FROM events WHERE community_id = $1 AND id = ANY($2)") + .bind(f.tenant.community().as_uuid()) + .bind(&ids) + .fetch_one(f.state.db.pool()) + .await + .expect("count refused events"); + assert_eq!(stored, 0, "a refused command is not stored"); + assert_eq!(f.pins(&owner, channel).await, Some(vec![message])); + assert_eq!(f.notices(&owner, channel).await.len(), 1); +} + +/// A pinned message deleted by its author (kind:5) or by a channel admin +/// (kind:9005) leaves the list with the delete, and subscribers get the new +/// list. +/// Mutation: stop dispatching `pin_lists` in `persist_deletion` → RED (no +/// live list); drop `unpin_deleted_messages` → RED (the list keeps the ID). +#[tokio::test] +#[ignore = "requires Postgres and Redis"] +async fn deleting_a_pinned_message_rewrites_the_list() { + let f = fixture().await; + let (owner, author) = (Keys::generate(), Keys::generate()); + let channel = create_channel(&f.state, &f.tenant, &owner, &[]).await; + let h = channel.to_string(); + let by_author = f.message(&author, channel).await; + let by_admin = f.message(&author, channel).await; + let kept = f.message(&owner, channel).await; + for message in [&by_author, &by_admin, &kept] { + f.pin(&owner, channel, message).await; + } + let mut live = LiveLists::open(&f, &owner, channel).await; + + f.accept(&author, signed(&author, 5, "", &[&["e", &by_author]])) + .await; + assert_eq!( + f.pins(&owner, channel).await, + Some(vec![kept.clone(), by_admin.clone()]) + ); + + f.accept( + &owner, + signed(&owner, 9005, "", &[&["h", &h], &["e", &by_admin]]), + ) + .await; + let by_d = json!({"kinds": [KIND_CHANNEL_PINS], "#d": [h]}); + let lists = f.read(&owner, by_d).await; + assert_eq!( + lists.iter().map(pinned).collect::>(), + [vec![kept.clone()]] + ); + assert_eq!( + live.delivered(2).await, + [vec![kept.clone(), by_admin], vec![kept.clone()]] + ); + + // The list itself is not a channel admin's to delete. + let list = signed( + &owner, + 9005, + "", + &[&["h", &h], &["e", &lists[0].id.to_hex()]], + ); + let reason = refusal(f.send(&owner, list).await); + assert!( + reason.contains("the pin list cannot be deleted"), + "{reason}" + ); + assert_eq!(f.pins(&owner, channel).await, Some(vec![kept])); +} diff --git a/crates/buzz-relay/src/handlers/report_resolution.rs b/crates/buzz-relay/src/handlers/report_resolution.rs index c04ec08c8f..a7e364fba2 100644 --- a/crates/buzz-relay/src/handlers/report_resolution.rs +++ b/crates/buzz-relay/src/handlers/report_resolution.rs @@ -846,7 +846,7 @@ async fn run_atomic_mutation( .map_err(|e| anyhow::anyhow!("thread metadata lookup failed: {e}"))?; let parent_id = meta.as_ref().and_then(|m| m.parent_event_id.clone()); let root_id = meta.as_ref().and_then(|m| m.root_event_id.clone()); - let committed = state + let (committed, pin_list) = state .db .execute_delete_with_marker( action_id, @@ -855,9 +855,13 @@ async fn run_atomic_mutation( target, parent_id.as_deref(), root_id.as_deref(), + &state.relay_keypair, ) .await .map_err(|e| anyhow::anyhow!("delete failed: {e}"))?; + if let Some(list) = &pin_list { + crate::handlers::pins::dispatch_list(tenant, state, list).await; + } // Same post-commit refresh as NIP-29 DELETE_EVENT: push a fresh // 39005 so live badge counts also count down. if let (true, Some(meta), Some(root_id)) = (committed, meta, root_id) { diff --git a/crates/buzz-relay/src/handlers/side_effects.rs b/crates/buzz-relay/src/handlers/side_effects.rs index e6438e3507..f0862327af 100644 --- a/crates/buzz-relay/src/handlers/side_effects.rs +++ b/crates/buzz-relay/src/handlers/side_effects.rs @@ -1015,6 +1015,11 @@ pub async fn validate_admin_event( "artifact removal markers cannot be deleted" )); } + // Deleting the list would clear a channel's pins without a new + // list for subscribers to replace their copy with. + if event_kind_u32(&target_event.event) == buzz_core::kind::KIND_CHANNEL_PINS { + return Err(anyhow::anyhow!("the pin list cannot be deleted")); + } Ok(()) } 9008 => { @@ -1077,7 +1082,7 @@ pub async fn emit_system_message( } /// Sign a kind:40099 system message for `channel_id` with the relay keypair. -fn sign_system_message( +pub(super) fn sign_system_message( state: &Arc, channel_id: Uuid, content: serde_json::Value, @@ -1094,7 +1099,7 @@ fn sign_system_message( /// Fan out a stored system message. Best-effort: clients can retrieve the /// persisted event. -async fn fan_out_system_message( +pub(super) async fn fan_out_system_message( tenant: &TenantContext, state: &Arc, channel_id: Uuid, @@ -3554,10 +3559,20 @@ pub(crate) async fn persist_deletion( }) }) .collect::>()?; - let (stored, inserted, deleted) = state + let (stored, inserted, deleted, pin_lists) = state .db - .insert_deletion_event(tenant.community(), event, channel_id, thread_meta, &targets) + .insert_deletion_event( + tenant.community(), + event, + channel_id, + thread_meta, + &targets, + &state.relay_keypair, + ) .await?; + for list in &pin_lists { + super::pins::dispatch_list(tenant, state, list).await; + } let mut repaired = false; for (planned, deleted) in planned.iter().zip(deleted) { diff --git a/crates/buzz-relay/src/main.rs b/crates/buzz-relay/src/main.rs index b69a4e30d7..d0caf91773 100644 --- a/crates/buzz-relay/src/main.rs +++ b/crates/buzz-relay/src/main.rs @@ -2317,7 +2317,8 @@ fn emit_in_memory_usage_metrics(state: &AppState) { } /// Run one usage-metrics tick. Every pod emits its own in-memory gauges, while -/// one leader reaps expired invites and publishes the stored storage snapshot. +/// one leader reaps expired invites and erased pin command records and +/// publishes the stored storage snapshot. async fn run_usage_metrics_tick( state: &AppState, leader: &mut Option, @@ -2356,6 +2357,15 @@ async fn run_usage_metrics_tick( warn!(error = %error, "failed to reap expired relay invites"); } } + match state.db.reap_expired_pin_command_records().await { + Ok(removed) if removed > 0 => { + info!(removed, "reaped expired pin command records"); + } + Ok(_) => {} + Err(error) => { + warn!(error = %error, "failed to reap expired pin command records"); + } + } run_storage_sweep_tick(state).await; } diff --git a/crates/buzz-test-client/tests/e2e_channel_pins.rs b/crates/buzz-test-client/tests/e2e_channel_pins.rs new file mode 100644 index 0000000000..729b82365e --- /dev/null +++ b/crates/buzz-test-client/tests/e2e_channel_pins.rs @@ -0,0 +1,196 @@ +//! End-to-end test for NIP-PM channel pins against a running relay: the `OK` +//! answer to each command, the relay-signed list over a live subscription and +//! a fresh read, and the list after a delete. +//! +//! # Running +//! +//! Start the relay, then run: +//! +//! ```text +//! RELAY_URL=ws://localhost:3000 cargo test -p buzz-test-client --test e2e_channel_pins -- --ignored +//! ``` + +use std::time::Duration; + +use buzz_test_client::{BuzzTestClient, RelayMessage}; +use nostr::{Event, EventBuilder, Filter, Keys, Kind, Tag}; +use serde_json::{json, Value}; + +const WAIT: Duration = Duration::from_secs(10); + +fn relay_url() -> String { + std::env::var("RELAY_URL").unwrap_or_else(|_| "ws://localhost:3000".to_string()) +} + +fn sign(keys: &Keys, kind: u16, content: &str, tags: &[&[&str]]) -> Event { + EventBuilder::new(Kind::Custom(kind), content) + .tags( + tags.iter() + .map(|tag| Tag::parse(tag.iter().copied()).expect("tag")), + ) + .sign_with_keys(keys) + .expect("sign") +} + +/// Send `event` and return the message of its `OK true`. +async fn accept(client: &mut BuzzTestClient, event: Event) -> String { + let kind = event.kind; + let ok = client.send_event(event).await.expect("OK"); + assert!(ok.accepted, "kind:{kind} refused: {}", ok.message); + ok.message +} + +fn filter(value: Value) -> Filter { + serde_json::from_value(value).expect("filter") +} + +fn pinned(list: &Event) -> Vec { + list.tags + .iter() + .map(|tag| tag.as_slice()) + .filter(|tag| tag[0] == "e") + .map(|tag| tag[1].clone()) + .collect() +} + +/// The next pin list the relay sends on the live subscription. +async fn next_list(reader: &mut BuzzTestClient, relay: &str) -> Vec { + loop { + if let RelayMessage::Event { event, .. } = reader.recv_event(WAIT).await.expect("live list") + { + assert_eq!(event.kind.as_u16(), 30623); + assert_eq!(event.pubkey.to_hex(), relay, "the relay signs the list"); + return pinned(&event); + } + } +} + +#[tokio::test] +#[ignore] +async fn test_channel_pins_wire() { + let url = relay_url(); + let http = url + .replace("wss://", "https://") + .replace("ws://", "http://"); + let info: Value = reqwest::Client::new() + .get(&http) + .header(reqwest::header::ACCEPT, "application/nostr+json") + .send() + .await + .expect("NIP-11") + .json() + .await + .expect("NIP-11 JSON"); + let relay = info["self"].as_str().expect("relay pubkey").to_owned(); + + let (owner, member) = (Keys::generate(), Keys::generate()); + let mut owner_ws = BuzzTestClient::connect(&url, &owner).await.expect("owner"); + let channel = uuid::Uuid::new_v4().to_string(); + let create = sign( + &owner, + 9007, + "", + &[ + &["h", &channel], + &["name", &format!("pins-{channel}")], + &["channel_type", "stream"], + &["visibility", "open"], + ], + ); + accept(&mut owner_ws, create).await; + let mut messages = Vec::new(); + for content in ["first", "second"] { + let message = sign(&owner, 9, content, &[&["h", &channel]]); + messages.push(message.id.to_hex()); + accept(&mut owner_ws, message).await; + } + let (first, second) = (messages[0].clone(), messages[1].clone()); + + let mut reader = BuzzTestClient::connect(&url, &member) + .await + .expect("member"); + reader + .subscribe( + "live", + vec![filter(json!({"kinds": [30623], "#h": [channel]}))], + ) + .await + .expect("subscribe"); + let history = reader.collect_until_eose("live", WAIT).await.expect("EOSE"); + assert!(history.is_empty(), "no list before the first pin"); + + let pin = sign(&owner, 40010, "", &[&["h", &channel], &["e", &first]]); + assert_eq!(accept(&mut owner_ws, pin.clone()).await, ""); + assert_eq!(next_list(&mut reader, &relay).await, vec![first.clone()]); + assert_eq!(accept(&mut owner_ws, pin).await, "duplicate:"); + + // Any member who may post can pin. + let mut member_ws = BuzzTestClient::connect(&url, &member) + .await + .expect("member"); + let pin = sign(&member, 40010, "", &[&["h", &channel], &["e", &second]]); + assert_eq!(accept(&mut member_ws, pin).await, ""); + assert_eq!( + next_list(&mut reader, &relay).await, + [second.clone(), first.clone()] + ); + + let mut fresh = BuzzTestClient::connect(&url, &member) + .await + .expect("member"); + fresh + .subscribe( + "list", + vec![filter(json!({"kinds": [30623], "#h": [channel]}))], + ) + .await + .expect("subscribe"); + let lists = fresh.collect_until_eose("list", WAIT).await.expect("EOSE"); + assert_eq!( + lists.iter().map(pinned).collect::>(), + [vec![second.clone(), first.clone()]] + ); + fresh + .subscribe( + "notices", + vec![filter(json!({"kinds": [40099], "#h": [channel]}))], + ) + .await + .expect("subscribe"); + let notices = fresh + .collect_until_eose("notices", WAIT) + .await + .expect("EOSE"); + let mut announced: Vec<(String, String)> = notices + .iter() + .map(|notice| serde_json::from_str::(¬ice.content).expect("notice")) + .filter(|notice| notice["type"] == "message_pinned") + .map(|notice| { + let field = |name: &str| notice[name].as_str().expect(name).to_owned(); + (field("actor"), field("target_event_id")) + }) + .collect(); + announced.sort(); + let mut expected = vec![ + (owner.public_key().to_hex(), first.clone()), + (member.public_key().to_hex(), second.clone()), + ]; + expected.sort(); + assert_eq!(announced, expected); + + // Deleting a pinned message takes it out of the list. + accept(&mut owner_ws, sign(&owner, 5, "", &[&["e", &second]])).await; + assert_eq!(next_list(&mut reader, &relay).await, vec![first.clone()]); + + let unpin = sign(&member, 40011, "", &[&["h", &channel], &["e", &first]]); + assert_eq!(accept(&mut member_ws, unpin).await, ""); + assert!(next_list(&mut reader, &relay).await.is_empty()); + + let foreign = sign(&owner, 40010, "", &[&["h", &channel], &["e", &second]]); + let refused = owner_ws.send_event(foreign).await.expect("OK"); + assert!(!refused.accepted); + assert_eq!( + refused.message, + "invalid: target is not a message in this channel" + ); +} diff --git a/docs/operator-user-account-retention.md b/docs/operator-user-account-retention.md index 8fb856b316..0363704373 100644 --- a/docs/operator-user-account-retention.md +++ b/docs/operator-user-account-retention.md @@ -15,6 +15,7 @@ Do not infer permission to delete another person's data from a matching key. | Shared device registrations | Keep registrations used by other accounts. Delete only with proven exclusive ownership; preserve and report uncertain ownership. Relay identity keys and client installation strings do not establish gateway ownership. | | Shared signed membership lists | Rebuild current member/admin/metadata lists using the existing relay signer, atomically with each channel membership removal. Preserve superseded historical events and creator attribution. Never edit a signed payload in place. | | Multi-subject commands and membership notices | Preserve; attribution and historical-message removal remain separate. | +| Pin and unpin commands | Content cleanup removes them. A command under an hour old keeps its event ID, timestamp, kind and channel, with no author, tags or signature, so that sending it again cannot repeat a pin. A running relay removes that record on its periodic maintenance tick once the command is an hour old. The relay-signed `message_pinned` notice of a pin stays, and names the member and the command ID. | | Deletion evidence and replay protection | Keep deletion requests, approvals, inventories, stage history, fences and replay watermarks. Watermark removal is not unfinished cleanup. | These are explicit retention exceptions, not assertions of anonymous data.