diff --git a/.github/workflows/_ci-relay.yml b/.github/workflows/_ci-relay.yml index fca045d6c3..f9eb369724 100644 --- a/.github/workflows/_ci-relay.yml +++ b/.github/workflows/_ci-relay.yml @@ -694,6 +694,7 @@ jobs: cargo test -p buzz-test-client --test e2e_persona --test e2e_team_catalog --test e2e_nostr_interop --test e2e_thread_roots --test e2e_project -- --ignored --nocapture cargo test -p buzz-test-client --test e2e_relay invite -- --ignored --nocapture cargo test -p buzz-test-client --test e2e_relay nip43_membership_snapshots_are_rejected -- --ignored --nocapture + cargo test -p buzz-test-client --test e2e_relay nip_ia_archive_snapshots_are_rejected -- --ignored --nocapture cargo test -p buzz-test-client --test e2e_relay nip29_departure_wire -- --ignored --nocapture cargo test -p buzz-test-client --test e2e_relay nip29_batch_put_user_wire -- --ignored --nocapture cargo test -p buzz-test-client --test e2e_relay nip29_announce_channel_wire -- --ignored --nocapture diff --git a/crates/buzz-core/src/kind.rs b/crates/buzz-core/src/kind.rs index 26d85177a0..7428c75cfe 100644 --- a/crates/buzz-core/src/kind.rs +++ b/crates/buzz-core/src/kind.rs @@ -926,6 +926,7 @@ pub const fn is_relay_only_kind(kind: u32) -> bool { KIND_VERIFIED_PROFILE | KIND_ARTIFACT_REMOVAL | KIND_NIP43_MEMBERSHIP_LIST + | KIND_IA_ARCHIVED_LIST | KIND_CHANNEL_SUMMARY | KIND_PRESENCE_SNAPSHOT | KIND_DM_VISIBILITY @@ -1024,6 +1025,13 @@ mod tests { assert!(!is_relay_only_kind(KIND_NIP43_LEAVE_REQUEST)); } + #[test] + fn nip_ia_archived_list_is_relay_only() { + assert!(is_relay_only_kind(KIND_IA_ARCHIVED_LIST)); + assert!(!is_relay_only_kind(KIND_IA_ARCHIVE_REQUEST)); + assert!(!is_relay_only_kind(KIND_IA_UNARCHIVE_REQUEST)); + } + #[test] fn thread_window_bounds_is_relay_only() { assert_eq!(KIND_THREAD_WINDOW_BOUNDS, 39007); diff --git a/crates/buzz-db/src/lib.rs b/crates/buzz-db/src/lib.rs index f52ad2a4a4..106b46eda3 100644 --- a/crates/buzz-db/src/lib.rs +++ b/crates/buzz-db/src/lib.rs @@ -28,9 +28,13 @@ /// discard: one per member for every kind:39002 roster republish. `$1` must /// bind the community. /// -/// The three replacement paths that index mentions (NIP-33 parameterized, -/// addressable, and the relay's member snapshot) go through this, so a head -/// and its mention rows leave together on those paths. +/// The addressable path, the relay's member snapshot, and the kind:13534 +/// list writer (whose `member` tags index no mentions) supersede through +/// this, so a head and its mention rows leave together when a newer head +/// replaces it. NIP-33 parameterized replacement drops its superseded rows' +/// mentions itself (`remove_coordinate_versions_in_tx`). Channel deletion +/// (`soft_delete_discovery_events`) retires live heads without a +/// replacement and does not go through this. macro_rules! superseded_with_mentions_sql { ($retire:expr) => { concat!( diff --git a/crates/buzz-db/src/store/channel_members.rs b/crates/buzz-db/src/store/channel_members.rs index 1ba517c547..a002805bda 100644 --- a/crates/buzz-db/src/store/channel_members.rs +++ b/crates/buzz-db/src/store/channel_members.rs @@ -494,15 +494,17 @@ impl LockedMemberSnapshot { let created_at_secs = event.created_at.as_secs() as i64; let created_at = chrono::DateTime::from_timestamp(created_at_secs, 0) .ok_or(DbError::InvalidTimestamp(created_at_secs))?; - let existing: Option<(chrono::DateTime, Vec)> = sqlx::query_as( - "SELECT created_at, id 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(community_id.as_uuid()) - .bind(kind) - .bind(pubkey.as_slice()) - .bind(channel_id) - .fetch_optional(self.tx.conn()) - .await?; + let (head_sql, supersede_sql) = crate::replaceable::replacement_sql( + true, + crate::replaceable::hard_deletes_superseded(kind), + ); + let existing: Option<(chrono::DateTime, Vec)> = sqlx::query_as(head_sql) + .bind(community_id.as_uuid()) + .bind(kind) + .bind(pubkey.as_slice()) + .bind(channel_id) + .fetch_optional(self.tx.conn()) + .await?; let incoming_id = event.id.as_bytes().as_slice(); if let Some((existing_ts, existing_id)) = existing { if created_at < existing_ts @@ -527,11 +529,14 @@ impl LockedMemberSnapshot { Some(channel_id), ) .await?; - sqlx::query(superseded_with_mentions_sql!( - "UPDATE events SET deleted_at = NOW() WHERE community_id = $1 AND kind = $2 AND pubkey = $3 AND channel_id = $4 AND deleted_at IS NULL" - )) - .bind(community_id.as_uuid()).bind(kind).bind(pubkey.as_slice()).bind(channel_id) - .execute(self.tx.conn()).await?; + // A superseded roster is deleted, not soft-deleted. + sqlx::query(supersede_sql) + .bind(community_id.as_uuid()) + .bind(kind) + .bind(pubkey.as_slice()) + .bind(channel_id) + .execute(self.tx.conn()) + .await?; let received_at = Utc::now(); let sig = event.sig.serialize(); let inserted = sqlx::query("INSERT INTO events (community_id, id, pubkey, created_at, kind, tags, content, sig, received_at, channel_id, d_tag) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11) ON CONFLICT DO NOTHING") diff --git a/crates/buzz-db/src/store/relay_members.rs b/crates/buzz-db/src/store/relay_members.rs index 81b832f587..b8973d2b71 100644 --- a/crates/buzz-db/src/store/relay_members.rs +++ b/crates/buzz-db/src/store/relay_members.rs @@ -1099,8 +1099,9 @@ pub(crate) async fn write_nip43_membership_snapshot( .bind(community_id.as_uuid()) .fetch_all(tx.conn()) .await?; - // Retired lists count too: a list newer than every prior one can't - // repeat an earlier list's id. + // Soft-deleted lists count too: a list newer than every prior one can't + // repeat an earlier list's id. A superseded list is deleted below, but the + // live head it gives way to is always newer. let newest_created_at: Option> = sqlx::query_scalar( "SELECT max(created_at) FROM events \ WHERE community_id = $1 AND kind = $2 AND pubkey = $3 AND channel_id IS NULL", @@ -1140,17 +1141,16 @@ pub(crate) async fn write_nip43_membership_snapshot( let received_at = Utc::now(); let d_tag = crate::event::extract_d_tag(&event); - // The relay is authoritative: retire every prior list unconditionally. - sqlx::query( - "UPDATE events SET deleted_at = NOW() \ - WHERE community_id = $1 AND kind = $2 AND pubkey = $3 \ - AND channel_id IS NULL AND deleted_at IS NULL", - ) - .bind(community_id.as_uuid()) - .bind(kind_i32) - .bind(pubkey_bytes.as_slice()) - .execute(tx.conn()) - .await?; + // The relay is authoritative: retire every prior live list + // unconditionally. A superseded list is deleted, not soft-deleted. + let (_, supersede_sql) = + replaceable::replacement_sql(false, replaceable::hard_deletes_superseded(kind_i32)); + sqlx::query(supersede_sql) + .bind(community_id.as_uuid()) + .bind(kind_i32) + .bind(pubkey_bytes.as_slice()) + .execute(tx.conn()) + .await?; sqlx::query( "INSERT INTO events (community_id, id, pubkey, created_at, kind, tags, content, sig, received_at, channel_id, d_tag) \ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, NULL, $10)", @@ -2588,6 +2588,16 @@ mod postgres_tests { .expect("transfer ownership"); assert!(matches!(write.outcome, TransferResult::Transferred { .. })); assert_membership_list_matches(&pool, community, &keys, write.snapshot.as_ref()).await; + // Each write above deleted the list it superseded, so only the live + // list is stored. + let stored: i64 = + sqlx::query_scalar("SELECT count(*) FROM events WHERE community_id = $1 AND kind = $2") + .bind(community.as_uuid()) + .bind(buzz_core::kind::KIND_NIP43_MEMBERSHIP_LIST as i32) + .fetch_one(&pool) + .await + .expect("count stored lists"); + assert_eq!(stored, 1, "superseded lists are deleted"); let provisioned = make_test_community(&pool).await; let write = db diff --git a/crates/buzz-db/src/store/replaceable.rs b/crates/buzz-db/src/store/replaceable.rs index c7ca35e517..b67cc12dd5 100644 --- a/crates/buzz-db/src/store/replaceable.rs +++ b/crates/buzz-db/src/store/replaceable.rs @@ -342,6 +342,41 @@ async fn replace_parameterized_event_in_transaction_impl( )) } +/// Whether the relay's replacement writers delete a superseded head of +/// `kind` instead of soft-deleting it. +/// +/// 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 +/// build their supersede with [`replacement_sql`] from this predicate. A +/// retired head is a full copy that no relay reader returns. +/// +/// While the coordinate has a live head, a replay of a deleted id is still +/// rejected: its `created_at` does not beat the head's. With no live head (a +/// 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 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 +/// path, which keeps the soft delete. Channel deletion +/// (`soft_delete_discovery_events`) retires the live head and still +/// 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 == KIND_NIP43_MEMBERSHIP_LIST as i32 + || kind == KIND_IA_ARCHIVED_LIST as i32 + || kind == KIND_NIP29_GROUP_METADATA as i32 + || kind == KIND_NIP29_GROUP_ADMINS as i32 + || kind == KIND_NIP29_GROUP_MEMBERS as i32 +} + /// The `WHERE` predicate (after the keyword, which each caller spells so the /// floor policy can see where a `SET` list ends) of one replaceable /// coordinate's head read and supersede. @@ -374,6 +409,48 @@ macro_rules! replacement_head_sql { }; } +/// The statement that retires a coordinate's live head: `soft` sets +/// `deleted_at`, `hard` deletes the row (`hard_deletes_superseded`). Either +/// way the head's mention rows are deleted with it. +macro_rules! replacement_supersede_sql { + (soft, $scope:tt) => { + superseded_with_mentions_sql!(concat!( + "UPDATE events SET deleted_at = NOW() WHERE ", + replacement_scope!($scope) + )) + }; + (hard, $scope:tt) => { + superseded_with_mentions_sql!(concat!( + "DELETE FROM events WHERE ", + replacement_scope!($scope) + )) + }; +} + +/// The head read and the supersede statement of one replaceable coordinate, +/// in a channel (`$4` binds it) or global, retiring the head by delete when +/// `hard_delete` holds and by soft delete otherwise. The addressable path, +/// the kind:39002 member snapshot and the kind:13534 writer build their +/// replacement statements here, so the index-condition test covers each +/// replacement statement they run. The snapshot locks' own head reads +/// (`latest_member_event_timestamp`, `lock_group_state_snapshot`) are +/// separate SQL that the test does not check. The NIP-33 path keys on +/// `d_tag` and builds its own. +pub(crate) fn replacement_sql(in_channel: bool, hard_delete: bool) -> (&'static str, &'static str) { + let head = if in_channel { + replacement_head_sql!(in_channel) + } else { + replacement_head_sql!(global) + }; + let supersede = match (in_channel, hard_delete) { + (true, false) => replacement_supersede_sql!(soft, in_channel), + (true, true) => replacement_supersede_sql!(hard, in_channel), + (false, false) => replacement_supersede_sql!(soft, global), + (false, true) => replacement_supersede_sql!(hard, global), + }; + (head, supersede) +} + /// Take the replacement lock of the `(kind, pubkey, channel_id)` coordinate /// on `tx`, serializing every writer of that coordinate until the transaction /// ends. Key collisions only cause extra serialization; they cannot change @@ -409,7 +486,7 @@ pub(crate) async fn take_replacement_lock( /// /// Returns `(event, false)` for a stale write or a duplicate ID. The caller /// commits only when the event was inserted and rolls back otherwise: a -/// duplicate leaves the previous event soft-deleted on the transaction. +/// duplicate leaves the previous event retired on the transaction. pub(crate) async fn replace_addressable_event_under_lock( tx: &mut AdmittedTx, event: &nostr::Event, @@ -424,23 +501,8 @@ pub(crate) async fn replace_addressable_event_under_lock( // Check for the newest existing event. ORDER BY + LIMIT 1 is defensive against // historical data where prior bugs may have left multiple live rows. - let (head_sql, supersede_sql) = if channel_id.is_some() { - ( - replacement_head_sql!(in_channel), - superseded_with_mentions_sql!(concat!( - "UPDATE events SET deleted_at = NOW() WHERE ", - replacement_scope!(in_channel) - )), - ) - } else { - ( - replacement_head_sql!(global), - superseded_with_mentions_sql!(concat!( - "UPDATE events SET deleted_at = NOW() WHERE ", - replacement_scope!(global) - )), - ) - }; + let (head_sql, supersede_sql) = + replacement_sql(channel_id.is_some(), hard_deletes_superseded(kind_i32)); let mut head = sqlx::query_as(head_sql) .bind(community_id.as_uuid()) .bind(kind_i32) @@ -471,7 +533,8 @@ pub(crate) async fn replace_addressable_event_under_lock( crate::channel_members::guard_channel_roster_event(tx, kind_i32, channel_id, &tags_json) .await?; - // Soft-delete the old event (if any). + // Retire the old event (if any): soft-delete it, or delete a relay-owned + // list's head (`hard_deletes_superseded`). let mut supersede = sqlx::query(supersede_sql) .bind(community_id.as_uuid()) .bind(kind_i32) @@ -713,6 +776,21 @@ impl Db { } } +#[cfg(test)] +mod tests { + use super::hard_deletes_superseded; + + #[test] + fn only_relay_owned_lists_hard_delete_their_superseded_heads() { + for kind in [13534, 13535, 39000, 39001, 39002] { + assert!(hard_deletes_superseded(kind), "kind {kind}"); + } + for kind in [-1, 0, 3, 10002, 13533, 13536, 30078, 38999, 39003] { + assert!(!hard_deletes_superseded(kind), "kind {kind}"); + } + } +} + #[cfg(test)] mod postgres_tests { use super::*; @@ -1017,24 +1095,13 @@ mod postgres_tests { .expect("populated partitions"); populated.sort(); - let statements = [ - ( - true, - replacement_head_sql!(in_channel), - superseded_with_mentions_sql!(concat!( - "UPDATE events SET deleted_at = NOW() WHERE ", - replacement_scope!(in_channel) - )), - ), - ( - false, - replacement_head_sql!(global), - superseded_with_mentions_sql!(concat!( - "UPDATE events SET deleted_at = NOW() WHERE ", - replacement_scope!(global) - )), - ), - ]; + // The statements production runs, for every scope and retire mode. + let statements = [(true, false), (false, false), (true, true), (false, true)].map( + |(in_channel, hard_delete)| { + let (head_sql, supersede_sql) = replacement_sql(in_channel, hard_delete); + (in_channel, head_sql, supersede_sql) + }, + ); for (in_channel, head_sql, supersede_sql) in statements { for sql in [head_sql, supersede_sql] { let explain = format!("EXPLAIN (FORMAT JSON) {sql}"); @@ -1133,13 +1200,16 @@ mod postgres_tests { let base = Timestamp::now().as_secs(); // Every supersede path retires the old head with a soft delete, except - // NIP-RS read state and mesh status, which the NIP-33 path hard-deletes. - // The relay roster writer is the production kind:39002 path; its p tags - // must match the channel's members. The relay-signed kind:13535 list - // goes through the addressable path. + // NIP-RS read state and mesh status, which the NIP-33 path hard-deletes, + // and the relay-signed lists (`hard_deletes_superseded`), which the + // relay's writers hard-delete. The relay roster writer is the + // production kind:39002 path; its p tags must match the channel's + // members. The relay-signed kind:13535 list and the channel's + // kind:39000 metadata go through the addressable path, as does a + // user's kind:3 contact list, which keeps the soft delete. enum Path { MemberSnapshot, - Addressable, + Addressable(Option), Parameterized, } let roster_p = vec![vec![owner.as_str(), "", "owner"]]; @@ -1154,15 +1224,33 @@ mod postgres_tests { Some(channel.to_string()), vec![], roster_p, - false, + true, ), ( - "addressable", - Path::Addressable, + "archived list", + Path::Addressable(None), 13535_u16, None, vec![], people_p(), + true, + ), + ( + "group metadata", + Path::Addressable(Some(channel)), + 39000_u16, + Some(channel.to_string()), + vec![], + people_p(), + true, + ), + ( + "contact list", + Path::Addressable(None), + 3_u16, + None, + vec![], + people_p(), false, ), ( @@ -1234,8 +1322,8 @@ mod postgres_tests { snapshot.release().await.expect("commit roster"); inserted } - Path::Addressable => { - db.replace_addressable_event(community, &event, None) + Path::Addressable(channel_id) => { + db.replace_addressable_event(community, &event, *channel_id) .await .expect("replace addressable") .1 diff --git a/crates/buzz-relay/src/api/bridge.rs b/crates/buzz-relay/src/api/bridge.rs index 7429c411c3..3357dbf32b 100644 --- a/crates/buzz-relay/src/api/bridge.rs +++ b/crates/buzz-relay/src/api/bridge.rs @@ -11170,7 +11170,8 @@ pub(crate) mod postgres_tests { // A schema whose `users` table can be taken away after the link, // so only the owner-to-agent lookup fails at revoke time. It // carries `communities` so writes pass community write admission, - // and `events` for the member list each membership change writes. + // and `events` and `event_mentions` for the member list each + // membership change writes and the superseded list it deletes. let db_url = crate::test_support::database_url(); let schema = format!("late_owner_{}", uuid::Uuid::new_v4().simple()); sqlx::raw_sql(sqlx::AssertSqlSafe(format!( @@ -11182,7 +11183,8 @@ pub(crate) mod postgres_tests { CREATE TABLE {schema}.join_policy_acceptances \ (LIKE public.join_policy_acceptances INCLUDING ALL); \ CREATE TABLE {schema}.communities (LIKE public.communities INCLUDING ALL); \ - CREATE TABLE {schema}.events (LIKE public.events INCLUDING ALL);" + CREATE TABLE {schema}.events (LIKE public.events INCLUDING ALL); \ + CREATE TABLE {schema}.event_mentions (LIKE public.event_mentions INCLUDING ALL);" ))) .execute(state.db.pool()) .await diff --git a/crates/buzz-relay/src/handlers/group_state_postgres_tests.rs b/crates/buzz-relay/src/handlers/group_state_postgres_tests.rs index c6955c3a4d..9134433a4e 100644 --- a/crates/buzz-relay/src/handlers/group_state_postgres_tests.rs +++ b/crates/buzz-relay/src/handlers/group_state_postgres_tests.rs @@ -1072,15 +1072,15 @@ enum HoldPublisher { /// holds the join after its read behind the lock until the edit is waiting /// for that lock, so the edit must still win with its own state. /// -/// Both legs also check the timestamps: every kind:39000 publication for -/// the coordinate, replaced rows included, leaves exactly one row, and -/// their `created_at` strictly increase in storage order. The live event is -/// first pinned an hour ahead, so each publication's timestamp is the live -/// one plus a second and the clock cannot separate the two publishers. -/// Mutation: take the live `created_at` before the lock → RED every time: -/// the publisher that locks second computes the same second as the first, -/// and either loses the id tie and leaves no row, or wins it and repeats -/// the second. +/// Both legs also check the timestamps. A superseded kind:39000 is deleted, +/// so the coordinate stores exactly one row, and it is two seconds past the +/// pinned one: each of the two publications stored the live `created_at` +/// plus a second. The live event is first pinned an hour ahead, so the clock +/// cannot separate the two publishers. Mutation: take the live `created_at` +/// before the lock → RED every time: the publisher that locks second +/// computes the same second as the first, and either loses the id tie and +/// stores nothing, or wins it and repeats the second; either way the live +/// row is one second past the pinned one. #[tokio::test] #[ignore = "requires Postgres"] async fn a_publisher_that_read_before_an_edit_cannot_replace_it() { @@ -1089,8 +1089,10 @@ async fn a_publisher_that_read_before_an_edit_cannot_replace_it() { } } -/// `created_at` of every relay-signed kind:39000 row for `channel_id`, -/// replaced rows included, in storage order. +/// `created_at` of every stored relay-signed kind:39000 row for +/// `channel_id`, in storage order. Superseded rows are deleted, so a +/// soft-deleted row here would come only from channel deletion or an older +/// relay. async fn stored_metadata_created_at( state: &AppState, tenant: &TenantContext, @@ -1155,9 +1157,13 @@ async fn join_publisher_held_against_an_auto_join_edit(hold: HoldPublisher) { .expect("store pinned kind:39000") .1 ); - let rows_before = stored_metadata_created_at(&state, &tenant, channel_id) - .await - .len(); + let pinned_at = chrono::DateTime::from_timestamp(pinned.created_at.as_secs() as i64, 0) + .expect("pinned created_at"); + assert_eq!( + stored_metadata_created_at(&state, &tenant, channel_id).await, + [pinned_at], + "{hold:?}: the pinned kind:39000 deleted the heads it superseded" + ); let (arrived, release) = match hold { HoldPublisher::BeforeLock => { @@ -1233,15 +1239,11 @@ async fn join_publisher_held_against_an_auto_join_edit(hold: HoldPublisher) { !tags.contains(&vec!["auto_join".to_string()]), "{hold:?}: the join's stale kind:39000 replaced the edit's: {tags:?}" ); - let created_at = stored_metadata_created_at(&state, &tenant, channel_id).await; assert_eq!( - created_at.len(), - rows_before + 2, - "{hold:?}: the join and the edit each leave one kind:39000 row: {created_at:?}" - ); - assert!( - created_at.windows(2).all(|pair| pair[0] < pair[1]), - "{hold:?}: kind:39000 timestamps must strictly increase in storage order: {created_at:?}" + stored_metadata_created_at(&state, &tenant, channel_id).await, + [pinned_at + chrono::Duration::seconds(2)], + "{hold:?}: the join and the edit each publish one second past the live kind:39000, \ + and each deletes the head it supersedes" ); } diff --git a/crates/buzz-relay/src/handlers/identity_archive.rs b/crates/buzz-relay/src/handlers/identity_archive.rs index 0daa80b409..58e0dbae12 100644 --- a/crates/buzz-relay/src/handlers/identity_archive.rs +++ b/crates/buzz-relay/src/handlers/identity_archive.rs @@ -705,9 +705,14 @@ mod tests { /// NIP-IA: every snapshot's `created_at` is strictly past the previous /// one's, even when publishers race on one head. Concurrent publishers - /// each read the head behind the replacement lock. RED-on-revert: with the - /// head read before the lock, publishers keep tying on head + 1 and one - /// exhausts its replacement attempts. + /// each read the head behind the replacement lock. The head is first + /// pinned an hour ahead, so each snapshot is stamped exactly one second + /// past the one it replaces. A superseded kind:13535 is deleted, so the + /// coordinate stores one row, 16 seconds past the pinned one only if + /// each of the 16 publishers stored exactly one snapshot one second + /// later. RED-on-revert: with the head read before the lock, publishers + /// keep tying on head + 1, so a same-second replacement leaves the row + /// short of + 16 s, or a publisher exhausts its replacement attempts. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] #[ignore = "requires Postgres and Redis"] async fn concurrent_archival_publishers_stamp_strictly_increasing_snapshots() { @@ -718,6 +723,26 @@ mod tests { .await .expect("Redis for an ignored test"); let tenant = seed_test_community(&pool).await; + let pinned = EventBuilder::new( + Kind::Custom(buzz_core::kind::KIND_IA_ARCHIVED_LIST as u16), + "", + ) + .tags([Tag::parse(["-"]).expect("'-' tag")]) + .custom_created_at(nostr::Timestamp::from( + nostr::Timestamp::now().as_secs() + 3600, + )) + .sign_with_keys(&state.relay_keypair) + .expect("sign pinned kind:13535"); + assert!( + state + .db + .replace_addressable_event(tenant.community(), &pinned, None) + .await + .expect("store pinned kind:13535") + .1 + ); + let pinned_at = chrono::DateTime::from_timestamp(pinned.created_at.as_secs() as i64, 0) + .expect("pinned created_at"); let publishers: Vec<_> = (0..16) .map(|_| { @@ -733,8 +758,7 @@ mod tests { .expect("publisher succeeds"); } - // Superseded snapshots stay as soft-deleted rows, so every snapshot - // ever stored is visible here. + // Every stored row of the coordinate, retired rows included. let stamps: Vec> = sqlx::query_scalar( "SELECT created_at FROM events WHERE community_id = $1 AND kind = $2 \ AND pubkey = $3 ORDER BY created_at", @@ -745,10 +769,11 @@ mod tests { .fetch_all(&pool) .await .expect("read stored snapshots"); - assert_eq!(stamps.len(), 16, "every publisher stores its own snapshot"); - assert!( - stamps.windows(2).all(|pair| pair[0] < pair[1]), - "snapshots must never share a created_at: {stamps:?}" + assert_eq!( + stamps, + [pinned_at + chrono::Duration::seconds(16)], + "each publisher stores one snapshot one second past the head it \ + replaces, and deletes that head" ); } } diff --git a/crates/buzz-test-client/tests/e2e_relay.rs b/crates/buzz-test-client/tests/e2e_relay.rs index 6a214860a7..e854102f06 100644 --- a/crates/buzz-test-client/tests/e2e_relay.rs +++ b/crates/buzz-test-client/tests/e2e_relay.rs @@ -223,22 +223,43 @@ async fn test_connect_and_authenticate() { #[tokio::test] #[ignore] async fn test_client_submitted_nip43_membership_snapshots_are_rejected() { - let url = relay_url(); let keys = Keys::generate(); // Prove this actor can submit a normal event so the rejection below is // specifically the relay-only invariant, not a broader authorization failure. create_test_channel(&keys).await; - let forged = EventBuilder::new(Kind::Custom(13_534), "") - .tags([Tag::parse(["member", &keys.public_key().to_hex(), "owner"]).unwrap()]) - .sign_with_keys(&keys) - .expect("sign forged membership snapshot"); + let member = Tag::parse(["member", &keys.public_key().to_hex(), "owner"]).unwrap(); + assert_relay_only_snapshot_rejected(&keys, 13_534, member).await; +} - let mut ws = BuzzTestClient::connect(&url, &keys).await.expect("connect"); +/// NIP-IA's kind:13535 archived-identities list is relay-signed, like the +/// kind:13534 membership list; a client-signed copy is rejected at ingest. +#[tokio::test] +#[ignore] +async fn test_client_submitted_nip_ia_archive_snapshots_are_rejected() { + let keys = Keys::generate(); + create_test_channel(&keys).await; + let archived = Tag::parse(["p", &Keys::generate().public_key().to_hex()]).unwrap(); + assert_relay_only_snapshot_rejected(&keys, 13_535, archived).await; +} + +/// Submit a `kind` snapshot signed by `keys` over WebSocket and HTTP and +/// assert that both transports reject it as a relay-only kind. +async fn assert_relay_only_snapshot_rejected(keys: &Keys, kind: u16, tag: Tag) { + let url = relay_url(); + let forged = EventBuilder::new(Kind::Custom(kind), "") + .tags([tag]) + .sign_with_keys(keys) + .expect("sign forged snapshot"); + + let mut ws = BuzzTestClient::connect(&url, keys).await.expect("connect"); let ok = ws .send_event(forged.clone()) .await .expect("submit forged snapshot via websocket"); - assert!(!ok.accepted, "forged WebSocket snapshot must be rejected"); + assert!( + !ok.accepted, + "forged WebSocket kind:{kind} snapshot must be rejected" + ); assert_eq!(ok.message, "restricted: relay-only kind"); ws.disconnect().await.expect("disconnect"); @@ -254,7 +275,7 @@ async fn test_client_submitted_nip43_membership_snapshots_are_rejected() { let body = response.text().await.expect("read HTTP rejection"); assert!( body.contains("restricted: relay-only kind"), - "unexpected HTTP rejection: {body}" + "unexpected kind:{kind} HTTP rejection: {body}" ); } diff --git a/docs/admin/README.md b/docs/admin/README.md index 2ffe30f1be..d343e88731 100644 --- a/docs/admin/README.md +++ b/docs/admin/README.md @@ -393,7 +393,11 @@ not the JSON error envelope, before authentication). All four accept a signed owner's. - `GET /api/admin/v1/events/{id}?communityHost=` Reads a single event scoped to that community, including soft-deleted - ones. Response: `{"id", "authorPubkey", "kind", "content", "createdAt", + ones. A relay-signed list (kinds 13534, 13535, and 39000–39002) that a + newer list replaced is deleted, so its ID returns `404 event_not_found`. + A list retired another way (channel deletion, NIP-09, or a replacement + written before this behavior) stays soft-deleted and is returned with + `deletedAt` set. Response: `{"id", "authorPubkey", "kind", "content", "createdAt", "deletedAt"|null, "channelId"|null}`. Never returns author-only kinds (event reminders, push leases, private managed agents) or result-gated kinds (DM visibility, agent turn metrics). Absent, other-community,