From 40c1c474e74686cbd3218866ee926211cb3365db Mon Sep 17 00:00:00 2001 From: Will Pfleger Date: Tue, 13 Oct 2026 14:45:59 -0400 Subject: [PATCH] fix(relay): hide deletions of author-only events from other readers (#8197) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 🤖 Opened by an agent (Hayt) for Will Pfleger. The relay keeps `AUTHOR_ONLY_KINDS` (event reminders `30300`, push leases `30350`, private managed agents `30179`) readable only by their author, but a NIP-09 deletion request (`kind:5`) for one of those events was readable by any community reader. The deletion carries no `h` tag, so ingest stores it with its target's channel (none), and every read gate classified it by its own kind, `5`. Another reader could read and count it by author, by id, live, or over HTTP, learning the deleted ids, how many, and when. A deletion is now exactly as private as the event it deletes: - **Classification by the deletion's own `k` tag.** `buzz_core::kind::is_author_only_event_kind` treats a `kind:5` that names an author-only kind in a `k` tag as author-only. Only the canonical decimal spelling counts (`"30300"`, not `"030300"` or `"+30300"`), so Rust classification, ingest and the admin SQL (which matches the tag text) always agree. Because it reads the deletion, not a target lookup, the deletion stays private after its target is soft-deleted or gone. It is generic over `AUTHOR_ONLY_KINDS`, so a kind added to the list later (for example `44300`) is covered automatically. - **Every read surface.** The shared per-event gate (`is_author_only_event`, used by WS REQ historical and lookup by id, COUNT fallbacks, HTTP `/query`, `/count`, search hydration and the thread window), live fan-out in `handlers/event.rs`, the COUNT fast-path guard (`filter_can_match_author_only_kinds` now treats any filter that can match `kind:5`, including unfiltered and id-only filters, as needing per-event filtering), the channel-window aux closure in the bridge, and admin event preview plus report list and detail (SQL suppression of `kind:5` rows with a tag whose first two elements are `k` and an author-only kind, matching the Rust classifier; soft-deleted rows included). - **Enforcement still reaches the author.** The admin report query takes the private-deletion `k` list from its caller next to the hidden kinds. HTTP-facing reads pass both; `admin_get_report_for_enforcement` passes neither, so report-directed bans, timeouts and action recovery still resolve the stored author of a reported private deletion. - **Ingest agreement.** `validate_standard_deletion_event` rejects a deletion of a stored (including soft-deleted) author-only event, by `e` or by `a` coordinate, unless it carries the matching canonical `["k",""]`. It also rejects an author-only `k` on a deletion of any other kind, so a public deletion can't hide itself from the readers who need it. A deletion whose target is itself a private deletion is rejected with `invalid: cannot delete a private deletion request`: it would otherwise be stored as a public event revealing the private deletion's id and timing, and NIP-09 gives a deletion of a deletion no effect. A deletion of a public deletion is unchanged. The `k` tag only narrows who can read the request; it grants no one new deletion authority. - **Unauthorized deletions learn nothing about the target.** On every delete-by-id path, no target-dependent error (its kind, the artifact and `k`-marker errors, the artifact-removal-marker error, or where it lives) is returned until every access check that could block the deletion has passed. A sender who fails any of them gets `invalid: deletion target not found or not deletable by you`, the same text and status as for a missing target. Errors that depend only on the request, never on the target, are unchanged: for example a `kind:9005` whose own `h` channel is archived still gets `channel is archived`, for a missing target and a real one alike. "May not delete" includes an author who has since been removed from the target's private channel, an author whose token is scoped to a different channel, and anyone deleting in an archived channel. The single-target rule (exactly one `e` or `a` tag) now runs before any target lookup, so every target faces the gates. For `kind:5` with an `e` target, ingest decides authority (effective author or the owning human of the authoring agent) first, then takes the channel from that same lookup, soft-deleted targets included, so tombstones face the same gates; an authorized re-deletion of a soft-deleted target now keeps the target's stored channel instead of being treated as global, so historical access checks, `#h` filtering and live routing all use that channel: readers outside a private channel no longer see it, and that channel's members and subscribers do. The token channel scope, scoped-token global-event, membership and archived checks then reject with the shared denial, all before `validate_standard_deletion_event` returns its artifact and `k`-marker errors. Other kinds, and `kind:5` with only `a` coordinates, keep their existing errors. For NIP-29 `kind:9005`, a target outside the `h` channel is denied like a missing one, so the relay no longer returns "different channel" or "no channel"; `may_delete_channel_event` (the author while still a member or the channel is open, a channel owner/admin, or the owning human of the author agent) is then checked in the `h` channel before the artifact-removal-marker error. No access restriction is removed and nothing becomes newly deletable. An authorized sender who names the wrong `h` channel for a `kind:9005` now gets the shared denial. Whether kind:5 content is full-text indexed depends on how the database was built. The desired-state schema (`schema/schema.sql`, which CI applies) and databases created before migration `0008` index it; an empty database initialized through `0008` gets a positive allowlist that doesn't. Where it is indexed, the per-event gate on search hydration is what keeps a private deletion out of other readers' search results. No current client is affected by the new rejection. `buzz-app`'s signer only allows `kind:5` for channel messages (with `h`) and managed-agent `30177` coordinates, and neither `buzz-app` nor this repo's desktop or CLI publishes deletions for `30300`, `30350` or `30179` today. NIP-ER already requires `k=30300` on reminder deletions. Coverage: - `crates/buzz-test-client/tests/e2e_author_only_deletion.rs` (Backend Integration job): a non-author gets nothing from WS REQ, WS COUNT, HTTP `/query` and `/count` (by author, mixed kinds, and id), search, or live delivery, while the author gets the deletion. Search runs WS and HTTP against a private deletion and a public control deletion sharing a reason word; with `BUZZ_TEST_SEARCH_INDEXES_DELETIONS=1` (set by the CI step) the author must get exactly both and another reader exactly the control; ingest rejects a missing, wrong, non-canonical, or public-target marker, and an untagged deletion of an already soft-deleted target. - `e2e_author_only_deletion.rs` also sends one non-owner's deletions over HTTP and WS for a missing, live, soft-deleted, private-channel and global target, plus the `kind:9005` equivalents including a target in another channel and one with no channel, and requires the identical rejection text and HTTP status in every case; another member's deletion of a private event never names its kind. - `e2e_author_only_deletion.rs` `removed_author_deletion_does_not_reveal_target`: an author removed from a private channel gets the missing-target rejection over HTTP and WS for `kind:5` and `kind:9005` (with `h` set to a channel they can write to) against their retained message; the channel owner can still delete the removed author's message, and the author can still delete in a channel they can write to. - `e2e_author_only_deletion.rs` `archived_target_deletion_does_not_reveal_target`: over HTTP and WS, `kind:5` against a message, the same message with a wrong `k`, and an artifact in an archived channel, and `kind:9005` against the archived-channel message with `h` set to an active channel, all match the missing-target rejection; a `kind:9005` for an artifact-removal marker in the archived channel matches a missing target with the same `h`; in an active channel the owner still gets the `k`-mismatch and artifact errors. - `e2e_author_only_deletion.rs` `deletion_of_private_deletion_rejected`: over HTTP and WS, the author's deletion of their private deletion, with no `k` and with `k=5`, gets the rejection and stores nothing; a non-author's gets the missing-target rejection; a `kind:9005` against it gets the missing-target rejection; the private deletion stays hidden from another reader in WS REQ and COUNT, HTTP `/query` and `/count`, and live delivery; a deletion of a public deletion is still accepted. - `e2e_author_only_deletion.rs` `soft_deleted_target_keeps_its_channel`: an author removed from a private channel, and an author in an archived channel, re-deleting their own soft-deleted message get the missing-target rejection; a distinct successful re-deletion is readable by a channel member and not by an outsider, by id and by `#h`, and is delivered live to the member's `#h` subscription but not to the outsider's. - `e2e_author_only_deletion.rs` `multi_target_deletion_error_ignores_targets`: deletions with two `e` tags, or an `e` and an `a` tag, get the identical single-target error whether the first target is missing, live, in another private channel, a private reminder or an artifact. - `handlers::ingest::postgres_tests::scoped_token_deletion_rejection_does_not_reveal_target`: a non-owner and the target's author, each with a token scoped to another channel, get the same rejection for a missing, live, soft-deleted and global target, and the author's `kind:9005` naming the token's channel gets it for a missing target, a live target in another channel and a global target; a token scoped to the target's channel still deletes, and its re-deletion of the soft-deleted target is stored with that target's channel. - `thread_window::postgres_tests`: stored private deletions never reach a non-signer through the thread-window or channel-window aux closures, or by id once their target is gone. - `api::admin::postgres_tests`: ban and stranded-ban recovery on a reported private deletion reach the stored author while report detail hides it; `admin_moderation` tests treat non-canonical markers as public. --------- Signed-off-by: Will Pfleger Co-authored-by: Hayt <211b96e6a2b7f45fd4047988976c7bbbeeda0c15f3ae7b32eec20834b5a55118@buzz.block.builderlab.xyz> --- .github/workflows/_ci-relay.yml | 5 +- Justfile | 2 +- crates/buzz-core/src/kind.rs | 64 + crates/buzz-db/src/store/admin_moderation.rs | 200 ++- crates/buzz-relay/src/api/admin/mod.rs | 61 +- crates/buzz-relay/src/api/bridge.rs | 9 +- .../bridge/thread_window/postgres_tests.rs | 61 + crates/buzz-relay/src/handlers/event.rs | 7 +- crates/buzz-relay/src/handlers/ingest.rs | 297 ++++- crates/buzz-relay/src/handlers/req.rs | 32 +- .../buzz-relay/src/handlers/side_effects.rs | 211 +-- .../tests/e2e_author_only_deletion.rs | 1128 +++++++++++++++++ scripts/run-tests.sh | 3 +- 13 files changed, 1881 insertions(+), 199 deletions(-) create mode 100644 crates/buzz-test-client/tests/e2e_author_only_deletion.rs diff --git a/.github/workflows/_ci-relay.yml b/.github/workflows/_ci-relay.yml index b6cab48aaf..dff24c5f75 100644 --- a/.github/workflows/_ci-relay.yml +++ b/.github/workflows/_ci-relay.yml @@ -110,6 +110,7 @@ jobs: -p buzz-test-client \ --lib \ --test e2e_event_reminder \ + --test e2e_author_only_deletion \ --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' @@ -580,10 +581,12 @@ jobs: run: | cargo nextest run \ --archive-file target/ci/backend-integration-tests.tar.zst \ - -E 'binary(e2e_event_reminder)' \ + -E 'binary(e2e_event_reminder) | binary(e2e_author_only_deletion)' \ --run-ignored ignored-only env: RELAY_URL: ws://localhost:3000 + # schema/schema.sql (applied above) indexes kind:5 content. + BUZZ_TEST_SEARCH_INDEXES_DELETIONS: "1" - name: Upload relay log if: failure() uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 diff --git a/Justfile b/Justfile index 04c6e46e70..3e7ead1528 100644 --- a/Justfile +++ b/Justfile @@ -528,7 +528,7 @@ test-unit: # are infra-free; config parses env into a struct and never connects. # `^config::` is anchored so it does not also select nip_fi_config. cargo nextest run -p buzz-relay --lib --bin buzz-relay \ - -E 'test(/^api::admin::/) + test(/^push_runtime::/) + test(/^handlers::channel_authz::/) + test(/^handlers::moderation_authz::/) + test(/^handlers::side_effects::tests::/) + test(/^storage_sweep::tests::/) + test(/^nip_fi_core::tests::/) + test(/^nip_fi_http::tests::/) + test(/^nip_fi_config::tests::/) + test(/^readiness::tests::/) + test(/^router::tests::/) + test(/^api::parse_query_tests::/) + test(/^api::git::transport::off_mode_precedence_tests::/) + test(/^audio::join::tests::/) + test(/^audio::handler::tests::/) + test(/^nip_fi_gate::tests::/) + test(/^nip_fi_session::tests::/) + test(/^nip_fi_shadow::tests::/) + test(/^nip_fi_shadow_session::tests::/) + test(/^startup_steps::tests::/) + test(/^telemetry::tests::/) + test(/^config::tests::/) + test(=state::tests::neither_a_confirmed_inactive_community_nor_a_failed_lookup_admits_the_socket) + test(=state::tests::periodic_revalidation_disconnects_inside_the_fenced_callback) + test(=state::tests::bare_community_disconnect_fails_closed_when_the_fence_is_unavailable) + test(=connection::tests::send_loop_sends_policy_close_when_community_is_archived) + test(=state::tests::community_disconnect_then_nip_fi_keeps_community_deleted_reason) + test(=state::tests::disconnect_community_wins_reason_losing_nip_fi_does_not_enqueue_frame) + test(=handlers::req::tests::timed_out_historical_read_deregisters_before_closed) + test(=handlers::req::tests::superseded_timeout_leaves_replacement_intact) + test(=handlers::req::tests::search_claim_retires_live_and_yields_to_replacement) + test(=handlers::req::tests::concurrent_claims_and_stale_teardowns_keep_the_last_owner) + test(=handlers::req::tests::timeout_closed_is_emitted_before_a_replacement_can_claim) + test(=handlers::req::tests::revoke_then_replacement_keeps_replacement_whole) + test(=handlers::req::tests::claims_after_connection_cleanup_are_refused) + test(=handlers::req::tests::dropped_terminal_frame_cancels_connection) + test(=handlers::req::tests::revoke_dropped_terminal_frame_cancels_connection) + (kind(bin) & (test(/^tests::/) + test(/^composition_tests::/) + test(/^env_filter_tests::/)) - test(/^tests::postgres_tests::/))' + -E 'test(/^api::admin::/) + test(/^push_runtime::/) + test(/^handlers::channel_authz::/) + test(/^handlers::moderation_authz::/) + test(/^handlers::side_effects::tests::/) + test(/^storage_sweep::tests::/) + test(/^nip_fi_core::tests::/) + test(/^nip_fi_http::tests::/) + test(/^nip_fi_config::tests::/) + test(/^readiness::tests::/) + test(/^router::tests::/) + test(/^api::parse_query_tests::/) + test(/^api::git::transport::off_mode_precedence_tests::/) + test(/^audio::join::tests::/) + test(/^audio::handler::tests::/) + test(/^nip_fi_gate::tests::/) + test(/^nip_fi_session::tests::/) + test(/^nip_fi_shadow::tests::/) + test(/^nip_fi_shadow_session::tests::/) + test(/^startup_steps::tests::/) + test(/^telemetry::tests::/) + test(/^config::tests::/) + test(=state::tests::neither_a_confirmed_inactive_community_nor_a_failed_lookup_admits_the_socket) + test(=state::tests::periodic_revalidation_disconnects_inside_the_fenced_callback) + test(=state::tests::bare_community_disconnect_fails_closed_when_the_fence_is_unavailable) + test(=connection::tests::send_loop_sends_policy_close_when_community_is_archived) + test(=state::tests::community_disconnect_then_nip_fi_keeps_community_deleted_reason) + test(=state::tests::disconnect_community_wins_reason_losing_nip_fi_does_not_enqueue_frame) + test(=handlers::req::tests::timed_out_historical_read_deregisters_before_closed) + test(=handlers::req::tests::superseded_timeout_leaves_replacement_intact) + test(=handlers::req::tests::search_claim_retires_live_and_yields_to_replacement) + test(=handlers::req::tests::concurrent_claims_and_stale_teardowns_keep_the_last_owner) + test(=handlers::req::tests::timeout_closed_is_emitted_before_a_replacement_can_claim) + test(=handlers::req::tests::revoke_then_replacement_keeps_replacement_whole) + test(=handlers::req::tests::claims_after_connection_cleanup_are_refused) + test(=handlers::req::tests::dropped_terminal_frame_cancels_connection) + test(=handlers::req::tests::revoke_dropped_terminal_frame_cancels_connection) + test(=handlers::req::tests::count_fallback_covers_filters_that_can_match_private_deletions) + (kind(bin) & (test(/^tests::/) + test(/^composition_tests::/) + test(/^env_filter_tests::/)) - test(/^tests::postgres_tests::/))' # Note on audio::join::tests scope: the full suite is infra-free (no DB, # no Redis). The infra-free audio/FI regression witnesses — bootstrap # ordering barrier, CommitConfirmed arm, pending-close invisibility, diff --git a/crates/buzz-core/src/kind.rs b/crates/buzz-core/src/kind.rs index 332e97d958..db05ea922f 100644 --- a/crates/buzz-core/src/kind.rs +++ b/crates/buzz-core/src/kind.rs @@ -132,6 +132,35 @@ pub const AUTHOR_ONLY_KINDS: &[u32] = &[ KIND_PRIVATE_MANAGED_AGENT, ]; +/// Returns `true` if the event is readable only by its author: an +/// [`AUTHOR_ONLY_KINDS`] event, or a NIP-09 deletion whose `k` tag names one. +/// +/// A deletion request reveals its targets' ids and deletion timing, so it +/// inherits the target's privacy. It is classified by its own `k` tag, not by +/// a target lookup, so it stays private after the target is gone; ingest +/// rejects a deletion of a stored author-only event without that tag. +pub fn is_author_only_event_kind(event: &nostr::Event) -> bool { + let kind = event_kind_u32(event); + if AUTHOR_ONLY_KINDS.contains(&kind) { + return true; + } + kind == KIND_DELETION && k_tag_kinds(event).any(|k| AUTHOR_ONLY_KINDS.contains(&k)) +} + +/// Kinds named by an event's well-formed `["k", ""]` tags. +/// +/// Only canonical decimal values count (`"30300"`, not `"030300"` or +/// `"+30300"`), so this agrees with SQL that matches the tag value as text. +pub fn k_tag_kinds(event: &nostr::Event) -> impl Iterator + '_ { + event.tags.iter().filter_map(|tag| match tag.as_slice() { + [name, value, ..] if name == "k" => value + .parse::() + .ok() + .filter(|kind| kind.to_string() == *value), + _ => None, + }) +} + /// Kinds that require a result-level read gate beyond the filter-layer /// `#p` check: even a reader who knows an event id MUST match the event's /// `#p` tag to receive the event. This closes the kindless `{ids:[…]}` read @@ -972,6 +1001,41 @@ mod tests { .unwrap() } + #[test] + fn deletion_privacy_follows_its_k_tag() { + for &kind in AUTHOR_ONLY_KINDS { + let k = kind.to_string(); + assert!(is_author_only_event_kind(&make_event_of_kind(kind, &[]))); + assert!(is_author_only_event_kind(&make_event_of_kind( + KIND_DELETION, + &[&["e", &"ab".repeat(32)], &["k", &k]] + ))); + assert!(is_author_only_event_kind(&make_event_of_kind( + KIND_DELETION, + &[&["k", "1"], &["k", &k]] + ))); + } + for tags in [ + &[][..], + &[&["k", "1"][..]][..], + &[&["k", "not-a-kind"][..]][..], + // Non-canonical spellings are not markers; SQL matches text. + &[&["k", "030300"][..]][..], + &[&["k", "+30300"][..]][..], + &[&["k", " 30300"][..]][..], + ] { + assert!(!is_author_only_event_kind(&make_event_of_kind( + KIND_DELETION, + tags + ))); + } + // A `k` tag classifies only deletions. + assert!(!is_author_only_event_kind(&make_event_of_kind( + 1, + &[&["k", &KIND_EVENT_REMINDER.to_string()]] + ))); + } + fn make_persona_event(tags: &[&[&str]]) -> nostr::Event { make_event_of_kind(KIND_PERSONA, tags) } diff --git a/crates/buzz-db/src/store/admin_moderation.rs b/crates/buzz-db/src/store/admin_moderation.rs index 1c7de25cc0..7ff6eabdfd 100644 --- a/crates/buzz-db/src/store/admin_moderation.rs +++ b/crates/buzz-db/src/store/admin_moderation.rs @@ -31,6 +31,13 @@ fn admin_hidden_kinds() -> Vec { .collect() } +/// `k` values that make a NIP-09 deletion as private as the author-only event +/// it deletes (see `buzz_core::kind::is_author_only_event_kind`). Admin reads +/// hide such deletions with `NOT (kind = 5 AND tags name one of these)`. +fn private_deletion_k_values() -> Vec { + AUTHOR_ONLY_KINDS.iter().map(u32::to_string).collect() +} + fn bounded_limit(limit: i64) -> i64 { limit.clamp(1, MAX_PAGE_SIZE) } @@ -225,6 +232,9 @@ pub async fn list_reports( AND e.community_id = r.community_id AND e.id = r.target_event_id AND e.kind <> ALL($10) + AND NOT (e.kind = 5 AND EXISTS ( + SELECT 1 FROM jsonb_array_elements(e.tags) t + WHERE t->>0 = 'k' AND t->>1 = ANY($11::text[]))) ORDER BY e.created_at DESC LIMIT 1 ) target ON TRUE @@ -249,17 +259,20 @@ pub async fn list_reports( .bind(cursor_id) .bind(bounded_limit(limit)) .bind(admin_hidden_kinds()) + .bind(private_deletion_k_values()) .fetch_all(pool) .await?; rows.into_iter().map(row_to_report).collect() } /// Fetch one report globally by its row id, including its event target content. -/// Targets whose kind is in `hidden_kinds` come back as `message: None`. +/// Targets whose kind is in `hidden_kinds`, and deletions whose `k` tag names +/// one of `private_deletion_ks`, come back as `message: None`. async fn get_report( pool: &PgPool, report_id: Uuid, hidden_kinds: &[i32], + private_deletion_ks: &[String], ) -> Result> { let row = sqlx::query( r#" @@ -294,6 +307,9 @@ async fn get_report( AND e.community_id = r.community_id AND e.id = r.target_event_id AND e.kind <> ALL($2) + AND NOT (e.kind = 5 AND EXISTS ( + SELECT 1 FROM jsonb_array_elements(e.tags) t + WHERE t->>0 = 'k' AND t->>1 = ANY($3::text[]))) ORDER BY e.created_at DESC LIMIT 1 ) target ON TRUE @@ -314,6 +330,7 @@ async fn get_report( ) .bind(report_id) .bind(hidden_kinds) + .bind(private_deletion_ks) .fetch_optional(pool) .await?; row.map(|row| { @@ -535,6 +552,9 @@ pub async fn get_event_preview( SELECT id, pubkey, kind, content, created_at, deleted_at, channel_id FROM events WHERE community_id = $1 AND id = $2 AND kind <> ALL($3) + AND NOT (kind = 5 AND EXISTS ( + SELECT 1 FROM jsonb_array_elements(tags) t + WHERE t->>0 = 'k' AND t->>1 = ANY($4::text[]))) ORDER BY created_at DESC LIMIT 1 "#, @@ -542,6 +562,7 @@ pub async fn get_event_preview( .bind(community_id) .bind(id) .bind(admin_hidden_kinds()) + .bind(private_deletion_k_values()) .fetch_optional(pool) .await?; row.map(|row| { @@ -591,7 +612,13 @@ impl Db { /// back as `message: None`, exactly like a missing event. #[datastore_span(name = "admin_get_report", system = "postgresql")] pub async fn admin_get_report(&self, id: Uuid) -> Result> { - get_report(&self.pool, id, &admin_hidden_kinds()).await + get_report( + &self.pool, + id, + &admin_hidden_kinds(), + &private_deletion_k_values(), + ) + .await } /// Fetch one report with its target unfiltered, for report enforcement and @@ -602,7 +629,7 @@ impl Db { &self, id: Uuid, ) -> Result> { - get_report(&self.pool, id, &[]).await + get_report(&self.pool, id, &[], &[]).await } /// List feedback for the deployment-global read-only admin plane. @@ -787,10 +814,15 @@ mod postgres_tests { .await; let report_id = insert_event_report(&pool, report_community, &event_id).await; - let detail = get_report(&pool, report_id, &admin_hidden_kinds()) - .await - .expect("query report") - .expect("report exists"); + let detail = get_report( + &pool, + report_id, + &admin_hidden_kinds(), + &private_deletion_k_values(), + ) + .await + .expect("query report") + .expect("report exists"); let message = detail.message.expect("reported message exists"); assert_eq!(message.content, "reported message"); assert_eq!(message.author_pubkey, hex::encode([5_u8; 32])); @@ -912,6 +944,52 @@ mod postgres_tests { insert_event_report(&pool, community_id, &event_id).await, )); } + // Deletions of author-only events are private by their `k` tag alone, + // live or soft-deleted; a deletion with a public or non-canonical `k` + // stays readable, matching `buzz_core::kind::k_tag_kinds`. + // An unrelated tag that merely contains `"k"` and an author-only kind + // is not a marker: matching is positional, as in Rust. + let mut public_deletions = Vec::new(); + let cases = AUTHOR_ONLY_KINDS + .iter() + .map(|k| (format!(r#"[["k","{k}"]]"#), true)) + .chain( + [ + r#"[["k","1"]]"#, + r#"[["k","030300"]]"#, + r#"[["k","+30300"]]"#, + r#"[["k","1"],["meta","k","30300"]]"#, + ] + .map(|tags| (tags.to_string(), false)), + ); + for (i, (tags, private)) in cases.enumerate() { + let event_id = vec![0x60 + i as u8; 32]; + sqlx::query( + r#" + INSERT INTO events (community_id, id, pubkey, created_at, kind, tags, content, sig, deleted_at) + VALUES ($1, $2, $3, now(), 5, $4::jsonb, '', $5, CASE WHEN $6 THEN now() END) + "#, + ) + .bind(community_id) + .bind(&event_id) + .bind(author) + .bind(&tags) + .bind(vec![3_u8; 64]) + .bind(i % 2 == 1) + .execute(&pool) + .await + .expect("insert deletion event"); + let report = insert_event_report(&pool, community_id, &event_id).await; + let preview = get_event_preview(&pool, community_id, &event_id) + .await + .expect("preview"); + assert_eq!(preview.is_none(), private, "preview, deletion tags {tags}"); + if private { + hidden.push((5, report)); + } else { + public_deletions.push((tags, report)); + } + } let visible_id = vec![0x3f_u8; 32]; insert_event(&pool, community_id, &visible_id, &author, "public", None).await; let visible = insert_event_report(&pool, community_id, &visible_id).await; @@ -939,17 +1017,44 @@ mod postgres_tests { }; for &(kind, report_id) in &hidden { assert_eq!(author_of(report_id), None, "list, kind {kind}"); - let detail = get_report(&pool, report_id, &admin_hidden_kinds()) - .await - .expect("query report") - .expect("report exists"); - assert!(detail.message.is_none(), "detail, kind {kind}"); - } - assert_eq!(author_of(visible), Some(hex::encode(author))); - let detail = get_report(&pool, visible, &admin_hidden_kinds()) + let detail = get_report( + &pool, + report_id, + &admin_hidden_kinds(), + &private_deletion_k_values(), + ) .await .expect("query report") .expect("report exists"); + assert!(detail.message.is_none(), "detail, kind {kind}"); + } + assert_eq!(author_of(visible), Some(hex::encode(author))); + for (tags, report_id) in public_deletions { + assert_eq!( + author_of(report_id), + Some(hex::encode(author)), + "list, deletion tags {tags}" + ); + let detail = get_report( + &pool, + report_id, + &admin_hidden_kinds(), + &private_deletion_k_values(), + ) + .await + .expect("query report") + .expect("report exists"); + assert!(detail.message.is_some(), "detail, deletion tags {tags}"); + } + let detail = get_report( + &pool, + visible, + &admin_hidden_kinds(), + &private_deletion_k_values(), + ) + .await + .expect("query report") + .expect("report exists"); assert_eq!(detail.message.expect("message shown").content, "public"); sqlx::query("DELETE FROM events WHERE community_id = $1") @@ -967,10 +1072,15 @@ mod postgres_tests { let community_id = insert_community(&pool, "pubkey-target").await; let report_id = insert_pubkey_report(&pool, community_id).await; - let detail = get_report(&pool, report_id, &admin_hidden_kinds()) - .await - .expect("query report") - .expect("report exists"); + let detail = get_report( + &pool, + report_id, + &admin_hidden_kinds(), + &private_deletion_k_values(), + ) + .await + .expect("query report") + .expect("report exists"); assert_eq!(detail.report.target_kind, "pubkey"); assert!(detail.message.is_none()); @@ -985,10 +1095,15 @@ mod postgres_tests { let missing_event_id = vec![8_u8; 32]; let report_id = insert_event_report(&pool, community_id, &missing_event_id).await; - let detail = get_report(&pool, report_id, &admin_hidden_kinds()) - .await - .expect("query report") - .expect("report exists"); + let detail = get_report( + &pool, + report_id, + &admin_hidden_kinds(), + &private_deletion_k_values(), + ) + .await + .expect("query report") + .expect("report exists"); assert_eq!(detail.report.target_kind, "event"); assert_eq!(detail.report.target, hex::encode(missing_event_id)); assert!(detail.message.is_none()); @@ -1052,10 +1167,15 @@ mod postgres_tests { .await; set_report_status(&pool, community_id, report_id, "dismissed").await; - let detail = get_report(&pool, report_id, &admin_hidden_kinds()) - .await - .expect("query report") - .expect("report exists"); + let detail = get_report( + &pool, + report_id, + &admin_hidden_kinds(), + &private_deletion_k_values(), + ) + .await + .expect("query report") + .expect("report exists"); assert_eq!(detail.report.status, "dismissed"); let action = detail .active_action @@ -1092,10 +1212,15 @@ mod postgres_tests { .await; set_report_status(&pool, community_id, report_id, "resolved").await; - let detail = get_report(&pool, report_id, &admin_hidden_kinds()) - .await - .expect("query report") - .expect("report exists"); + let detail = get_report( + &pool, + report_id, + &admin_hidden_kinds(), + &private_deletion_k_values(), + ) + .await + .expect("query report") + .expect("report exists"); let action = detail.active_action.expect("an action surfaces"); assert_eq!( action.id, @@ -1126,10 +1251,15 @@ mod postgres_tests { ) .await; - let detail = get_report(&pool, report_id, &admin_hidden_kinds()) - .await - .expect("query report") - .expect("report exists"); + let detail = get_report( + &pool, + report_id, + &admin_hidden_kinds(), + &private_deletion_k_values(), + ) + .await + .expect("query report") + .expect("report exists"); assert!( detail.active_action.is_none(), "reopen audit row must not surface as an enforcement action" diff --git a/crates/buzz-relay/src/api/admin/mod.rs b/crates/buzz-relay/src/api/admin/mod.rs index 20935e9fed..b5cfa1ef49 100644 --- a/crates/buzz-relay/src/api/admin/mod.rs +++ b/crates/buzz-relay/src/api/admin/mod.rs @@ -7308,9 +7308,30 @@ mod postgres_tests { assert!(banned, "the stored author must be banned"); } - /// Seed an event report in the `admin.example` community whose target is a - /// hidden (shared-gated) kind authored by `author`. Returns the report id. - async fn seed_hidden_kind_event_report(pool: &sqlx::PgPool, author: &[u8]) -> Uuid { + /// Targets admin reads must hide but enforcement must still reach: a + /// hidden (shared-gated) kind, and a deletion of an author-only event, + /// which is private by its `k` tag alone. + fn hidden_targets() -> [(i32, serde_json::Value); 2] { + [ + ( + buzz_core::kind::SHARED_GATED_KINDS[0] as i32, + serde_json::json!([["shared", "true"]]), + ), + ( + buzz_core::kind::KIND_DELETION as i32, + serde_json::json!([["k", buzz_core::kind::KIND_EVENT_REMINDER.to_string()]]), + ), + ] + } + + /// Seed an event report in the `admin.example` community whose target is + /// authored by `author` and stored with `kind` and `tags`. Returns the + /// report id. + async fn seed_hidden_kind_event_report( + pool: &sqlx::PgPool, + author: &[u8], + (kind, tags): &(i32, serde_json::Value), + ) -> Uuid { let host_report = seed_admin_host_report(pool, "open").await; let community_id: Uuid = sqlx::query_scalar("SELECT community_id FROM moderation_reports WHERE id = $1") @@ -7321,16 +7342,14 @@ mod postgres_tests { cleanup_admin_host_report(pool, host_report).await; let (report_id, _channel_id, target_event_id) = e2e_event_report_with_author(pool, community_id, author).await; - sqlx::query( - r#"UPDATE events SET kind = $3, tags = '[["shared","true"]]'::jsonb - WHERE community_id = $1 AND id = $2"#, - ) - .bind(community_id) - .bind(target_event_id.as_slice()) - .bind(buzz_core::kind::SHARED_GATED_KINDS[0] as i32) - .execute(pool) - .await - .expect("make target a hidden kind"); + sqlx::query("UPDATE events SET kind = $3, tags = $4 WHERE community_id = $1 AND id = $2") + .bind(community_id) + .bind(target_event_id.as_slice()) + .bind(kind) + .bind(tags) + .execute(pool) + .await + .expect("make target a hidden kind"); report_id } @@ -7339,11 +7358,17 @@ mod postgres_tests { #[tokio::test] #[ignore = "requires Postgres — resolve ban on a hidden-kind target bans the author, detail stays hidden"] async fn resolve_ban_on_hidden_kind_target_bans_author_without_revealing_it() { + for target in hidden_targets() { + resolve_ban_on_hidden_target(&target).await; + } + } + + async fn resolve_ban_on_hidden_target(target: &(i32, serde_json::Value)) { let keys = nostr::Keys::generate(); let state = nip98_state(vec![keys.public_key().to_hex()]).await; let pool = e2e_pool().await; let author = nostr::Keys::generate().public_key().to_bytes().to_vec(); - let report_id = seed_hidden_kind_event_report(&pool, &author).await; + let report_id = seed_hidden_kind_event_report(&pool, &author, target).await; let path = format!("/reports/{report_id}/resolve"); let body = serde_json::json!({ "action": "ban", "requestId": Uuid::new_v4() }).to_string(); @@ -7424,9 +7449,15 @@ mod postgres_tests { #[tokio::test] #[ignore = "requires Postgres — stranded ban on a hidden-kind target recovers"] async fn stranded_ban_on_hidden_kind_target_recovers_via_worker() { + for target in hidden_targets() { + stranded_ban_on_hidden_target_recovers(&target).await; + } + } + + async fn stranded_ban_on_hidden_target_recovers(target: &(i32, serde_json::Value)) { let pool = e2e_pool().await; let author = nostr::Keys::generate().public_key().to_bytes().to_vec(); - let report_id = seed_hidden_kind_event_report(&pool, &author).await; + let report_id = seed_hidden_kind_event_report(&pool, &author, target).await; let (community_id, channel_id): (Uuid, Option) = sqlx::query_as("SELECT community_id, channel_id FROM moderation_reports WHERE id = $1") .bind(report_id) diff --git a/crates/buzz-relay/src/api/bridge.rs b/crates/buzz-relay/src/api/bridge.rs index d631df7500..bd39ada46e 100644 --- a/crates/buzz-relay/src/api/bridge.rs +++ b/crates/buzz-relay/src/api/bridge.rs @@ -686,6 +686,7 @@ async fn handle_channel_window_filter( raw: &Value, filter: &nostr::Filter, accessible_channels: &[uuid::Uuid], + reader_pubkey_bytes: &[u8], events: &mut Vec, ) -> Result<(), (StatusCode, Json)> { use buzz_core::kind::{KIND_THREAD_SUMMARY, KIND_WINDOW_BOUNDS}; @@ -790,7 +791,12 @@ async fn handle_channel_window_filter( } // Deletions can be stored channel-less; access-check instead // of channel-constraining so they aren't silently dropped. - if !event_in_accessible_channel(&se, accessible_channels) { + if !event_in_accessible_channel(&se, accessible_channels) + || !crate::handlers::req::event_visible_to_reader( + &se.event, + reader_pubkey_bytes, + ) + { continue; } hop_ids.push(se.event.id.to_hex()); @@ -1501,6 +1507,7 @@ async fn query_events_authed( raw, filter, &accessible_channels, + &pubkey_bytes, &mut events, ) .await?; diff --git a/crates/buzz-relay/src/api/bridge/thread_window/postgres_tests.rs b/crates/buzz-relay/src/api/bridge/thread_window/postgres_tests.rs index 9cee67ea3b..02ef106cda 100644 --- a/crates/buzz-relay/src/api/bridge/thread_window/postgres_tests.rs +++ b/crates/buzz-relay/src/api/bridge/thread_window/postgres_tests.rs @@ -532,3 +532,64 @@ async fn thread_window_router_aux_row_cap_and_corrupt_page() { mod failure_postgres_tests; mod review_postgres_tests; + +/// A deletion of an author-only event is private by its `k` tag alone. Neither +/// window's aux closure returns one to anyone but its signer, and a read by id +/// stays author-only after its target is physically gone. Ordinary ingest can +/// build neither case, so both use stored fixtures. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn private_deletions_reach_only_their_signer_through_windows_and_id_reads() { + let f = Fixture::new().await; + let reply = f.reply(0).await; + let reply_reaction = f.aux(7, &reply, Some(f.channel)).await; + let root_reaction = f.aux(7, &f.root, Some(f.channel)).await; + let signer = Keys::generate(); + let deletion = |target: &str, k: &str| { + EventBuilder::new(Kind::EventDeletion, "") + .tags([ + Tag::parse(["e", target]).unwrap(), + Tag::parse(["k", k]).unwrap(), + ]) + .custom_created_at(Timestamp::from(f.root.created_at.as_secs() + 120)) + .sign_with_keys(&signer) + .unwrap() + }; + let reminder = buzz_core::kind::KIND_EVENT_REMINDER.to_string(); + let thread_private = deletion(&reply_reaction.id.to_hex(), &reminder); + let thread_public = deletion(&reply_reaction.id.to_hex(), "7"); + let channel_private = deletion(&root_reaction.id.to_hex(), &reminder); + let channel_public = deletion(&root_reaction.id.to_hex(), "7"); + let orphan_private = deletion(&"ab".repeat(32), &reminder); + for event in [ + &thread_private, + &thread_public, + &channel_private, + &channel_public, + &orphan_private, + ] { + f.state + .db + .insert_event(f.community, event, None) + .await + .unwrap(); + } + + let thread = f.query(&f.filter()).await; + let thread = ids(&thread, Some(5)); + assert!(thread.contains(&thread_public.id.to_hex().as_str())); + assert!(!thread.contains(&thread_private.id.to_hex().as_str())); + + let window = json!({"top_level":true,"#h":[f.channel],"kinds":[9],"include_aux":true}); + let window = f.query(&window).await; + let window = ids(&window, Some(5)); + assert!(window.contains(&channel_public.id.to_hex().as_str())); + assert!(!window.contains(&channel_private.id.to_hex().as_str())); + + let by_id = json!([{"ids":[orphan_private.id.to_hex()]}]); + for (reader, visible) in [(&f.keys, false), (&signer, true)] { + let (status, body) = f.post(reader, "/query", by_id.clone()).await; + assert_eq!(status, StatusCode::OK, "{body}"); + assert_eq!(ids(&body, Some(5)).len(), usize::from(visible), "{body}"); + } +} diff --git a/crates/buzz-relay/src/handlers/event.rs b/crates/buzz-relay/src/handlers/event.rs index a937ff0e4f..f57c10b150 100644 --- a/crates/buzz-relay/src/handlers/event.rs +++ b/crates/buzz-relay/src/handlers/event.rs @@ -7,9 +7,8 @@ use tracing::{debug, error, info, warn}; use buzz_core::event::StoredEvent; use buzz_core::kind::{ - event_kind_u32, is_ephemeral, is_unshared_gated_event, AUTHOR_ONLY_KINDS, - KIND_AGENT_OBSERVER_FRAME, KIND_AGENT_PRESENCE, KIND_GIFT_WRAP, KIND_PRESENCE_UPDATE, - KIND_TYPING_INDICATOR, + event_kind_u32, is_ephemeral, is_unshared_gated_event, KIND_AGENT_OBSERVER_FRAME, + KIND_AGENT_PRESENCE, KIND_GIFT_WRAP, KIND_PRESENCE_UPDATE, KIND_TYPING_INDICATOR, }; use buzz_core::observer::{ content_looks_like_nip44, OBSERVER_AGENT_TAG, OBSERVER_FRAME_CONTROL, OBSERVER_FRAME_TAG, @@ -137,7 +136,7 @@ pub async fn filter_fanout_by_access( // only paths that route author-only kinds — so no such delivery can bypass // it. It runs before (and independent of) the channel-membership filter // below because author-only kinds are stored globally (channel_id = None). - let matches = if AUTHOR_ONLY_KINDS.contains(&event_kind_u32(&stored_event.event)) { + let matches = if buzz_core::kind::is_author_only_event_kind(&stored_event.event) { let author = stored_event.event.pubkey.to_bytes(); matches .into_iter() diff --git a/crates/buzz-relay/src/handlers/ingest.rs b/crates/buzz-relay/src/handlers/ingest.rs index 564ad3d00d..5aad9689aa 100644 --- a/crates/buzz-relay/src/handlers/ingest.rs +++ b/crates/buzz-relay/src/handlers/ingest.rs @@ -2597,6 +2597,34 @@ async fn ingest_event_inner( }); } + // NIP-09: kind:5 may reference targets via `e` tag (regular events) OR + // `a` tag (addressable/parameterized-replaceable events like kind:30620). + // Checked before any target lookup so every target faces the gates below. + if kind_u32 == KIND_NIP29_DELETE_EVENT || kind_u32 == KIND_DELETION { + let e_count = count_e_tags(&event); + let a_count = event + .tags + .iter() + .filter(|t| t.kind().to_string() == "a") + .count(); + if (e_count + a_count) != 1 { + return Err(IngestError::Rejected(format!( + "invalid: deletion events must reference exactly one target via e or a tag (got e={e_count}, a={a_count})" + ))); + } + } + + // A kind 5 targeting an event derives its channel from that target, so + // every channel gate below would reveal the target's existence or + // location. Their rejections all collapse to the shared denial. + let deletion_targets_event = kind_u32 == KIND_DELETION + && !crate::handlers::side_effects::extract_target_event_ids(&event).is_empty(); + let deletion_denied = || { + IngestError::Rejected(format!( + "invalid: {}", + crate::handlers::side_effects::DELETION_TARGET_DENIED + )) + }; let mut channel_id = if kind_u32 == KIND_REACTION { match derive_reaction_channel(tenant.community(), &state.db, &event).await { ReactionChannelResult::Channel(ch_id) => Some(ch_id), @@ -2620,43 +2648,25 @@ async fn ingest_event_inner( } else if is_gift_wrap { None } else if kind_u32 == KIND_DELETION { - // Standard deletion (kind:5): derive channel from the target event. - // kind:5 events don't carry an h-tag, so we look up the target event - // and use its channel_id. This ensures token-channel, membership, and - // archived checks run against the correct channel. - let target_hex = event.tags.iter().find_map(|t| { - if t.kind().to_string() == "e" { - t.content().and_then(|v| { - if v.len() == 64 && v.chars().all(|c| c.is_ascii_hexdigit()) { - Some(v.to_string()) - } else { - None - } - }) - } else { - None + // Standard deletion (kind:5): decide authority over the target before + // the channel gates below, whose errors would otherwise reveal whether + // the target exists and where. The target's channel, soft-deleted or + // not (kind:5 carries no h-tag), then faces the token-channel, + // membership, and archived checks. + match crate::handlers::side_effects::extract_target_event_ids(&event).first() { + Some(target_id) => { + let actor = effective_message_author(&event, &state.relay_keypair.public_key()); + crate::handlers::side_effects::authorized_standard_deletion_target( + tenant, state, &actor, target_id, + ) + .await + .map_err(|e| { + IngestError::Internal(format!("error: looking up deletion target: {e}")) + })? + .ok_or_else(deletion_denied)? + .channel_id } - }); - match target_hex { - Some(hex) => { - let target_bytes = hex::decode(&hex).map_err(|_| { - IngestError::Rejected("invalid: malformed deletion target id".into()) - })?; - match state - .db - .get_event_by_id_for_event_write(tenant.community(), &target_bytes) - .await - { - Ok(Some(target)) => target.channel_id, - Ok(None) => None, // target not found — validate_standard_deletion will catch this - Err(e) => { - return Err(IngestError::Internal(format!( - "error: looking up deletion target: {e}" - ))); - } - } - } - None => None, // no e-tag — will be caught by single-target enforcement (step 12) + None => None, } } else { extract_channel_id(&event) @@ -2673,7 +2683,15 @@ async fn ingest_event_inner( } if let Some(ch_id) = channel_id { - check_token_channel_access(&auth, ch_id).map_err(IngestError::AuthFailed)?; + check_token_channel_access(&auth, ch_id).map_err(|e| { + if deletion_targets_event { + deletion_denied() + } else { + IngestError::AuthFailed(e) + } + })?; + } else if deletion_targets_event && auth.channel_ids().is_some() { + return Err(deletion_denied()); } else if auth.channel_ids().is_some() { // Channel-scoped tokens cannot publish global events — that would bypass // the token's channel restriction. This covers kind:1 (global text notes), @@ -2756,7 +2774,13 @@ async fn ingest_event_inner( }, state_for_request(tenant, auth.pubkey()), ); - auth_result.map_err(IngestError::Rejected)?; + auth_result.map_err(|e| { + if deletion_targets_event { + deletion_denied() + } else { + IngestError::Rejected(e) + } + })?; } } @@ -2894,6 +2918,15 @@ async fn ingest_event_inner( } if kind_u32 == KIND_DELETION { + // The target's archived channel blocks the deletion, so it must + // reject before the validator's target-kind diagnostics. + if deletion_targets_event + && channel_row + .as_ref() + .is_some_and(|ch| ch.archived_at.is_some()) + { + return Err(deletion_denied()); + } crate::handlers::side_effects::validate_standard_deletion_event(tenant, &event, state) .await .map_err(|e| IngestError::Rejected(format!("invalid: {e}")))?; @@ -2934,22 +2967,6 @@ async fn ingest_event_inner( return Ok(result); } - // NIP-09: kind:5 may reference targets via `e` tag (regular events) OR - // `a` tag (addressable/parameterized-replaceable events like kind:30620). - if kind_u32 == KIND_NIP29_DELETE_EVENT || kind_u32 == KIND_DELETION { - let e_count = count_e_tags(&event); - let a_count = event - .tags - .iter() - .filter(|t| t.kind().to_string() == "a") - .count(); - if (e_count + a_count) != 1 { - return Err(IngestError::Rejected(format!( - "invalid: deletion events must reference exactly one target via e or a tag (got e={e_count}, a={a_count})" - ))); - } - } - if kind_u32 == KIND_STREAM_MESSAGE_EDIT { validate_edit_ownership(tenant.community(), &event, state) .await @@ -6728,6 +6745,178 @@ mod postgres_tests { .expect("untagged canvas write must append unconditionally"); } + /// A channel-scoped token gets the same kind 5 rejection for a target it + /// has no authority over whether that target is missing, soft-deleted + /// (no live channel), or live in a channel outside the token's scope. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn scoped_token_deletion_rejection_does_not_reveal_target() { + use buzz_db::channel::{ChannelType, ChannelVisibility}; + use nostr::{Keys, Kind, Tag}; + + let db_url = std::env::var("BUZZ_TEST_DATABASE_URL") + .or_else(|_| std::env::var("DATABASE_URL")) + .unwrap_or_else(|_| "postgres://buzz:buzz_dev@localhost:5432/buzz".to_string()); // sadscan:disable np.postgres.1 + let pool = sqlx::PgPool::connect(&db_url) + .await + .expect("connect test Postgres"); + let state = build_canvas_ingest_state(&db_url, &pool).await; + let host = format!("scoped-deletion-{}.test", Uuid::new_v4().simple()); + let community = state + .db + .ensure_configured_community(&host) + .await + .expect("ensure community") + .id; + let tenant = TenantContext::resolved(community, &host); + let tracer: Arc = Arc::new(VecTracer::default()); + + let author = Keys::generate(); + let sender = Keys::generate(); + let mut channels = Vec::new(); + for creator in [&author, &sender] { + let channel_id = Uuid::new_v4(); + state + .db + .create_channel_with_id( + community, + channel_id, + &format!("scoped-deletion-{}", channel_id.simple()), + ChannelType::Stream, + ChannelVisibility::Open, + None, + creator.public_key().to_bytes().as_slice(), + None, + ) + .await + .expect("create test channel"); + channels.push(channel_id); + } + let author_auth = || IngestAuth::Http { + pubkey: author.public_key(), + scopes: vec![Scope::MessagesWrite], + auth_method: HttpAuthMethod::Nip98, + }; + let publish = |kind: u16, tags: Vec, keys: &Keys| { + nostr::EventBuilder::new(Kind::Custom(kind), Uuid::new_v4().to_string()) + .tags(tags) + .sign_with_keys(keys) + .expect("sign") + }; + let h = Tag::parse(["h", &channels[0].to_string()]).unwrap(); + let live = publish(9, vec![h.clone()], &author); + let deleted = publish(9, vec![h.clone()], &author); + let global = publish(1, vec![], &author); + let in_scope = publish(9, vec![h], &author); + for event in [ + live.clone(), + deleted.clone(), + global.clone(), + in_scope.clone(), + ] { + ingest_event_inner(&state, &tracer, &tenant, event, author_auth()) + .await + .expect("store message"); + } + let delete = |target: &str, keys: &Keys| { + publish( + KIND_DELETION as u16, + vec![Tag::parse(["e", target]).unwrap()], + keys, + ) + }; + ingest_event_inner( + &state, + &tracer, + &tenant, + delete(&deleted.id.to_hex(), &author), + author_auth(), + ) + .await + .expect("soft-delete message"); + + let scoped_auth = |keys: &Keys, channel: Uuid| IngestAuth::Nip42 { + pubkey: keys.public_key(), + scopes: vec![Scope::MessagesWrite], + channel_ids: Some(vec![channel]), + conn_id: Uuid::new_v4(), + }; + // Neither a non-owner nor the author holding a token scoped to the + // sender's channel may delete; both get the missing-target rejection. + for keys in [&sender, &author] { + for target in [ + "a".repeat(64), + live.id.to_hex(), + deleted.id.to_hex(), + global.id.to_hex(), + ] { + let auth = scoped_auth(keys, channels[1]); + match ingest_event_inner(&state, &tracer, &tenant, delete(&target, keys), auth) + .await + { + Err(IngestError::Rejected(msg)) => assert_eq!( + msg, "invalid: deletion target not found or not deletable by you", + "target {target}" + ), + Err(other) => panic!("target {target}: {other:?}"), + Ok(_) => panic!("target {target}: deletion accepted"), + } + } + } + // Kind 9005 from the author's out-of-scope token, naming the channel + // the token covers, cannot reveal where the target lives either. + let redact = |target: &str| { + publish( + KIND_NIP29_DELETE_EVENT as u16, + vec![ + Tag::parse(["e", target]).unwrap(), + Tag::parse(["h", &channels[1].to_string()]).unwrap(), + ], + &author, + ) + }; + for target in ["a".repeat(64), live.id.to_hex(), global.id.to_hex()] { + match ingest_event_inner( + &state, + &tracer, + &tenant, + redact(&target), + scoped_auth(&author, channels[1]), + ) + .await + { + Err(IngestError::Rejected(msg)) => assert_eq!( + msg, "invalid: deletion target not found or not deletable by you", + "9005 target {target}" + ), + Err(other) => panic!("9005 target {target}: {other:?}"), + Ok(_) => panic!("9005 target {target}: deletion accepted"), + } + } + // A token scoped to the target's channel still deletes. + ingest_event_inner( + &state, + &tracer, + &tenant, + delete(&in_scope.id.to_hex(), &author), + scoped_auth(&author, channels[0]), + ) + .await + .expect("in-scope token deletes the author's message"); + // Re-deleting a soft-deleted message stores the deletion in its channel. + let redeletion = delete(&deleted.id.to_hex(), &author); + ingest_event_inner(&state, &tracer, &tenant, redeletion.clone(), author_auth()) + .await + .expect("author re-deletes a soft-deleted message"); + let stored = state + .db + .get_event_by_id(community, redeletion.id.as_bytes()) + .await + .expect("read re-deletion") + .expect("re-deletion stored"); + assert_eq!(stored.channel_id, Some(channels[0])); + } + // ── Owner-aware ban/timeout coverage ───────────────────────────────────── /// Fresh community plus an agent owned by `owner` (users.agent_owner_pubkey). diff --git a/crates/buzz-relay/src/handlers/req.rs b/crates/buzz-relay/src/handlers/req.rs index c2296ee717..7572774b3a 100644 --- a/crates/buzz-relay/src/handlers/req.rs +++ b/crates/buzz-relay/src/handlers/req.rs @@ -8,7 +8,7 @@ use tracing::{debug, warn}; use buzz_core::filter::filters_match; use buzz_core::kind::{ is_unshared_gated_event, AUTHOR_ONLY_KINDS, KIND_AGENT_ENGRAM, KIND_AGENT_TURN_METRIC, - KIND_DM_VISIBILITY, KIND_HUDDLE_LIVENESS, P_GATED_KINDS, RESULT_GATED_KINDS, + KIND_DELETION, KIND_DM_VISIBILITY, KIND_HUDDLE_LIVENESS, P_GATED_KINDS, RESULT_GATED_KINDS, SHARED_GATED_KINDS, }; use buzz_core::tenant::TenantContext; @@ -1607,8 +1607,11 @@ pub(crate) fn engram_filters_authorized(filters: &[Filter], authed_pubkey_hex: & /// author-only events from the aggregate count. pub(crate) fn filter_can_match_author_only_kinds(filter: &Filter) -> bool { filter.kinds.as_ref().is_none_or(|ks| { - ks.iter() - .any(|k| AUTHOR_ONLY_KINDS.contains(&(k.as_u16() as u32))) + ks.iter().any(|k| { + let k = k.as_u16() as u32; + // Deletions of author-only events inherit their privacy. + k == KIND_DELETION || AUTHOR_ONLY_KINDS.contains(&k) + }) }) } @@ -1667,12 +1670,13 @@ pub(crate) fn result_gated_count_safe_for_pushdown( .is_some_and(|values| !values.is_empty() && values.iter().all(|v| v == authed_pubkey_hex)) } -/// Returns `true` if the event is an author-only kind and the requester is NOT -/// the author. Used as a per-event filter during historical delivery and fan-out +/// Returns `true` if the event is author-only (see +/// [`buzz_core::kind::is_author_only_event_kind`]) and the requester is NOT the +/// author. Used as a per-event filter during historical delivery and fan-out /// to silently omit unauthorized events from mixed-kind result sets. pub(crate) fn is_author_only_event(event: &nostr::Event, requester_pubkey_bytes: &[u8]) -> bool { - let kind_u32 = event.kind.as_u16() as u32; - AUTHOR_ONLY_KINDS.contains(&kind_u32) && event.pubkey.to_bytes() != requester_pubkey_bytes + buzz_core::kind::is_author_only_event_kind(event) + && event.pubkey.to_bytes() != requester_pubkey_bytes } /// Combined per-event result-visibility check for all gated event classes. @@ -3009,6 +3013,20 @@ mod tests { (agent, owner, attacker) } + #[test] + fn count_fallback_covers_filters_that_can_match_private_deletions() { + assert!(filter_can_match_author_only_kinds(&Filter::new())); + assert!(filter_can_match_author_only_kinds( + &Filter::new().id(nostr::EventId::all_zeros()) + )); + assert!(filter_can_match_author_only_kinds( + &Filter::new().kinds([nostr::Kind::EventDeletion, nostr::Kind::TextNote]) + )); + assert!(!filter_can_match_author_only_kinds( + &Filter::new().kind(nostr::Kind::TextNote) + )); + } + #[test] fn push_lease_requires_self_author_filter_and_count_fallback() { let (owner, other, _) = three_pubkeys(); diff --git a/crates/buzz-relay/src/handlers/side_effects.rs b/crates/buzz-relay/src/handlers/side_effects.rs index 250b289f44..8cc7d3abc6 100644 --- a/crates/buzz-relay/src/handlers/side_effects.rs +++ b/crates/buzz-relay/src/handlers/side_effects.rs @@ -7,11 +7,11 @@ use tracing::{info, warn}; use uuid::Uuid; use buzz_core::kind::{ - event_kind_u32, is_parameterized_replaceable, KIND_AGENT_PROFILE, KIND_DM_VISIBILITY, - KIND_GIT_REPO_ANNOUNCEMENT, KIND_IA_ARCHIVED, KIND_IA_ARCHIVED_LIST, KIND_IA_UNARCHIVED, - KIND_MEMBER_ADDED_NOTIFICATION, KIND_MEMBER_REMOVED_NOTIFICATION, KIND_NIP29_GROUP_ADMINS, - KIND_NIP29_GROUP_MEMBERS, KIND_NIP29_GROUP_METADATA, KIND_NIP43_MEMBERSHIP_LIST, KIND_REACTION, - KIND_THREAD_SUMMARY, + event_kind_u32, is_parameterized_replaceable, AUTHOR_ONLY_KINDS, KIND_AGENT_PROFILE, + KIND_DM_VISIBILITY, KIND_GIT_REPO_ANNOUNCEMENT, KIND_IA_ARCHIVED, KIND_IA_ARCHIVED_LIST, + KIND_IA_UNARCHIVED, KIND_MEMBER_ADDED_NOTIFICATION, KIND_MEMBER_REMOVED_NOTIFICATION, + KIND_NIP29_GROUP_ADMINS, KIND_NIP29_GROUP_MEMBERS, KIND_NIP29_GROUP_METADATA, + KIND_NIP43_MEMBERSHIP_LIST, KIND_REACTION, KIND_THREAD_SUMMARY, }; use buzz_core::StoredEvent; use buzz_db::channel::{MemberRecord, MemberRole}; @@ -358,6 +358,70 @@ pub async fn handle_side_effects( } } +/// Rejection for a deletion whose sender may not delete the target. A missing +/// target gets the same text, so the error never reveals whether, or where, +/// the target exists. +pub(crate) const DELETION_TARGET_DENIED: &str = "deletion target not found or not deletable by you"; + +/// The kind 5 target `target_id`, including a soft-deleted one, when `actor` +/// is its effective author or that author's owning human; `None` when the +/// target is missing or `actor` has no authority over it. +pub(crate) async fn authorized_standard_deletion_target( + tenant: &TenantContext, + state: &Arc, + actor: &[u8], + target_id: &[u8], +) -> anyhow::Result> { + let Some(target) = state + .db + .get_event_by_id_including_deleted_for_event_write(tenant.community(), target_id) + .await? + else { + return Ok(None); + }; + let author = effective_message_author(&target.event, &state.relay_keypair.public_key()); + let authorized = author == actor + || state + .db + .is_agent_owner(tenant.community(), &author, actor) + .await?; + Ok(authorized.then_some(target)) +} + +/// Whether `actor` may delete `author`'s event in `channel_id` with kind 9005: +/// the author while still a member or the channel is open (a removed member +/// of a private channel loses this), a channel owner/admin, or the owning +/// human of the author agent, even when that human is not a channel member. +async fn may_delete_channel_event( + tenant: &TenantContext, + state: &Arc, + event: &Event, + channel_id: Uuid, + author: &[u8], + actor: &[u8], +) -> anyhow::Result { + if author_delete_can_use_self_delete_path(author, actor, event) + && (state + .is_member_cached(tenant.community(), channel_id, actor) + .await? + || state + .db + .get_channel_for_event_write(tenant.community(), channel_id) + .await + .map(|ch| ch.visibility == "open") + .unwrap_or(false)) + { + return Ok(true); + } + Ok(actor_is_channel_owner_or_admin( + &state.db.get_members(tenant.community(), channel_id).await?, + actor, + ) || state + .db + .is_agent_owner(tenant.community(), author, actor) + .await?) +} + /// Validate a standard NIP-09 deletion event before it is stored. /// /// Buzz accepts standard deletions for self-authored events, plus the owning @@ -383,6 +447,9 @@ pub async fn validate_standard_deletion_event( if parts.len() < 2 { return Err(anyhow::anyhow!("invalid a-tag format")); } + if let Ok(target_kind) = parts[0].parse() { + check_deletion_privacy_k_tag(event, target_kind)?; + } let target_pubkey_bytes = hex::decode(parts[1]).map_err(|_| anyhow::anyhow!("invalid pubkey in a-tag"))?; if target_pubkey_bytes != actor_bytes @@ -391,38 +458,57 @@ pub async fn validate_standard_deletion_event( .is_agent_owner(tenant.community(), &target_pubkey_bytes, &actor_bytes) .await? { - return Err(anyhow::anyhow!("must be event author")); + return Err(anyhow::anyhow!(DELETION_TARGET_DENIED)); } return Ok(()); } for target_id in target_ids { - let target_event = state - .db - .get_event_by_id_including_deleted_for_event_write(tenant.community(), &target_id) - .await? - .ok_or_else(|| anyhow::anyhow!("target event not found"))?; - + // Authority first: every later error depends on the target's kind, + // which a sender without authority must not learn. + let target_event = + authorized_standard_deletion_target(tenant, state, &actor_bytes, &target_id) + .await? + .ok_or_else(|| anyhow::anyhow!(DELETION_TARGET_DENIED))?; if matches!(target_event.event.kind.as_u16(), 45010 | 45011) { anyhow::bail!( "artifacts cannot be deleted with kind 5; use op=delete or kind 9005 redaction" ); } - let target_author = - effective_message_author(&target_event.event, &state.relay_keypair.public_key()); - if target_author != actor_bytes - && !state - .db - .is_agent_owner(tenant.community(), &target_author, &actor_bytes) - .await? + // A deletion of a private deletion would be stored publicly and reveal + // the private one's id and timing; NIP-09 gives it no effect anyway. + if target_event.event.kind.as_u16() == 5 + && buzz_core::kind::is_author_only_event_kind(&target_event.event) { - return Err(anyhow::anyhow!("must be event author")); + anyhow::bail!("cannot delete a private deletion request"); } + check_deletion_privacy_k_tag(event, event_kind_u32(&target_event.event))?; } Ok(()) } +/// A deletion's read privacy follows its `k` tag (see +/// `buzz_core::kind::is_author_only_event_kind`), so the tag must agree with +/// the target: required when the target is author-only, so the deletion cannot +/// leak its existence, and otherwise forbidden, so a public deletion cannot be +/// hidden from the readers who need it. +fn check_deletion_privacy_k_tag(event: &Event, target_kind: u32) -> anyhow::Result<()> { + let target_is_author_only = AUTHOR_ONLY_KINDS.contains(&target_kind); + let mut names_target = false; + for k in buzz_core::kind::k_tag_kinds(event) { + if k == target_kind { + names_target = true; + } else if AUTHOR_ONLY_KINDS.contains(&k) { + anyhow::bail!("k tag {k} does not match the deletion target's kind {target_kind}"); + } + } + if target_is_author_only && !names_target { + anyhow::bail!("deletion of an author-only kind {target_kind} event requires [\"k\",\"{target_kind}\"]"); + } + Ok(()) +} + /// Returns `true` if `actor_bytes` is the NIP-OA owner of **any** active owner-role /// member in `members`. Used by kind:9002 and kind:9008 to authorize the owning /// human of a channel's agent-owner(s) even when the human is not a channel member. @@ -724,77 +810,42 @@ pub async fn validate_admin_event( }) .ok_or_else(|| anyhow::anyhow!("missing e tag for target event"))?; - // Verify the target event exists and belongs to the h-tag channel - // BEFORE storage. Fail closed: missing target → reject. + // Decide authority before any error that depends on the target: + // a missing target and one the actor may not delete share one + // rejection. Tombstoned targets read as missing. + let denied = || anyhow::anyhow!(DELETION_TARGET_DENIED); let target_event = state .db .get_event_by_id_for_event_write(tenant.community(), &target_id) .await .map_err(|e| anyhow::anyhow!("db error looking up target: {e}"))? - .ok_or_else(|| anyhow::anyhow!("target event not found"))?; + .ok_or_else(denied)?; + // For relay-signed REST messages, the real author is in the p tag. + let author = + effective_message_author(&target_event.event, &state.relay_keypair.public_key()); - match target_event.channel_id { - Some(target_ch) if target_ch != channel_id => { - return Err(anyhow::anyhow!( - "target event belongs to a different channel" - )); - } - None => { - return Err(anyhow::anyhow!("target event has no channel")); - } - _ => {} // Same channel — OK + // A target outside the `h` channel is denied like a missing one: + // telling where it lives would need every access gate of a second + // channel. The `h` channel's token and archive gates already ran. + if target_event.channel_id != Some(channel_id) + || !may_delete_channel_event( + tenant, + state, + event, + channel_id, + &author, + &actor_bytes, + ) + .await? + { + return Err(denied()); } if target_event.event.kind.as_u16() == 45011 { return Err(anyhow::anyhow!( "artifact removal markers cannot be deleted" )); } - - // Check if actor is the event author. - // For relay-signed REST messages, the real author is in the p tag. - let author = - effective_message_author(&target_event.event, &state.relay_keypair.public_key()); - if author_delete_can_use_self_delete_path(&author, &actor_bytes, event) { - // Author deleting their own message: re-gate on membership/open visibility so that - // a removed private-channel member cannot mutate old messages after access is revoked. - let is_member = state - .is_member_cached(tenant.community(), channel_id, &actor_bytes) - .await?; - if is_member { - return Ok(()); - } - let is_open = state - .db - .get_channel_for_event_write(tenant.community(), channel_id) - .await - .map(|ch| ch.visibility == "open") - .unwrap_or(false); - if is_open { - return Ok(()); - } - // Not a member and channel is private — fall through to owner/admin/owner-of-agent check. - } - - // Not the author, or author who is no longer a member of a private channel — - // must be owner/admin or the owning human of the message's agent-author. - let members = state.db.get_members(tenant.community(), channel_id).await?; - if actor_is_channel_owner_or_admin(&members, &actor_bytes) { - Ok(()) - } else { - // Allow the owning human of the agent that authored the target message, - // even when the human is not a channel member. - if state - .db - .is_agent_owner(tenant.community(), &author, &actor_bytes) - .await? - { - Ok(()) - } else { - Err(anyhow::anyhow!( - "must be event author or channel owner/admin" - )) - } - } + Ok(()) } 9008 => { // DELETE_GROUP: owner only, or the owning human of the channel's agent-owner. @@ -2563,7 +2614,7 @@ fn has_e_tag(event: &Event) -> bool { event.tags.iter().any(|t| t.kind().to_string() == "e") } -fn extract_target_event_ids(event: &Event) -> Vec> { +pub(crate) fn extract_target_event_ids(event: &Event) -> Vec> { event .tags .iter() diff --git a/crates/buzz-test-client/tests/e2e_author_only_deletion.rs b/crates/buzz-test-client/tests/e2e_author_only_deletion.rs new file mode 100644 index 0000000000..e820aabd13 --- /dev/null +++ b/crates/buzz-test-client/tests/e2e_author_only_deletion.rs @@ -0,0 +1,1128 @@ +//! End-to-end tests: NIP-09 deletion requests (kind:5) for author-only kinds +//! are exactly as private as the events they delete. +//! +//! A deletion request names its target ids and reveals when they were +//! deleted. For a kind in `AUTHOR_ONLY_KINDS` (here the NIP-ER reminder, +//! kind:30300) the relay must hide that deletion from everyone but its author +//! on every read surface, and must reject one that omits the matching `k` tag. +//! A deletion from anyone without authority over its target is rejected +//! before any of that, with one message whether the target is missing, live, +//! soft-deleted, or in any channel, so the rejection reveals nothing about it. +//! +//! # Running +//! +//! Start the relay, then run: +//! +//! ```text +//! RELAY_URL=ws://localhost:3001 cargo test -p buzz-test-client --test e2e_author_only_deletion -- --ignored +//! ``` +//! +//! On a database built from the desired-state schema (`schema/schema.sql`), +//! which indexes kind:5 content, also set `BUZZ_TEST_SEARCH_INDEXES_DELETIONS=1`. +//! Without it, the search test only checks that results stay within the +//! permitted sets, not that search actually returns them. + +use std::collections::BTreeSet; +use std::time::Duration; + +use buzz_test_client::{BuzzTestClient, RelayMessage, TestClientError}; +use nostr::{EventBuilder, EventId, Filter, Keys, Kind, Tag}; +use reqwest::Client; +use serde_json::Value; + +const KIND_EVENT_REMINDER: u16 = 30300; + +fn relay_url() -> String { + std::env::var("RELAY_URL").unwrap_or_else(|_| "ws://localhost:3001".to_string()) +} + +fn relay_http_url() -> String { + relay_url() + .replace("wss://", "https://") + .replace("ws://", "http://") + .trim_end_matches('/') + .to_string() +} + +fn sub_id(name: &str) -> String { + format!("e2e-aod-{name}-{}", uuid::Uuid::new_v4()) +} + +fn http_client() -> Client { + Client::builder() + .timeout(Duration::from_secs(10)) + .build() + .expect("failed to build HTTP client") +} + +fn tag(parts: &[&str]) -> Tag { + Tag::parse(parts.to_vec()).expect("valid tag") +} + +fn build_reminder(keys: &Keys) -> nostr::Event { + EventBuilder::new( + Kind::Custom(KIND_EVENT_REMINDER), + "nip44-ciphertext-placeholder", + ) + .tags(vec![ + tag(&["d", &uuid::Uuid::new_v4().to_string()]), + tag(&["alt", "Encrypted reminder"]), + ]) + .sign_with_keys(keys) + .unwrap() +} + +fn build_deletion(keys: &Keys, tags: Vec) -> nostr::Event { + build_deletion_with_reason(keys, tags, "") +} + +fn build_deletion_with_reason(keys: &Keys, tags: Vec, reason: &str) -> nostr::Event { + EventBuilder::new(Kind::EventDeletion, reason) + .tags(tags) + .sign_with_keys(keys) + .unwrap() +} + +async fn submit(client: &Client, keys: &Keys, event: &nostr::Event) -> (bool, String) { + let resp = client + .post(format!("{}/events", relay_http_url())) + .header("X-Pubkey", keys.public_key().to_hex()) + .json(event) + .send() + .await + .expect("submit event"); + let ok = resp.status().is_success(); + let body: Value = resp.json().await.expect("parse response"); + if ok { + ( + body["accepted"].as_bool().unwrap_or(false), + body["message"].as_str().unwrap_or("").to_string(), + ) + } else { + (false, body["error"].as_str().unwrap_or("").to_string()) + } +} + +async fn submit_ok(client: &Client, keys: &Keys, event: &nostr::Event) { + let (accepted, msg) = submit(client, keys, event).await; + assert!(accepted, "setup event rejected: {msg}"); +} + +/// Store a reminder as `author`, then delete it with a `k`-tagged kind:5 +/// whose reason is a unique search term. Returns the reminder and deletion. +async fn store_deleted_reminder(client: &Client, author: &Keys) -> (nostr::Event, nostr::Event) { + let reminder = build_reminder(author); + submit_ok(client, author, &reminder).await; + let deletion = build_deletion_with_reason( + author, + vec![ + tag(&["e", &reminder.id.to_hex()]), + tag(&["k", &KIND_EVENT_REMINDER.to_string()]), + ], + &search_term(author), + ); + submit_ok(client, author, &deletion).await; + let reminder_reads = http_query_ids(client, author, &Filter::new().id(reminder.id)).await; + assert!(reminder_reads.is_empty(), "the reminder must be deleted"); + (reminder, deletion) +} + +/// A search term unique to `author`'s deletion reason. +fn search_term(author: &Keys) -> String { + format!("aodreason{}", &author.public_key().to_hex()[..16]) +} + +/// Filters that each match only the deletion `store_deleted_reminder` left: +/// by kind, mixed kinds, and id. The id filter is the kindless COUNT case; +/// broader kindless filters can match `#p`-gated kinds, so the relay closes +/// them before any read runs. +fn deletion_filters(author: &Keys, deletion: EventId) -> Vec { + vec![ + Filter::new() + .kind(Kind::EventDeletion) + .author(author.public_key()), + Filter::new() + .kinds([Kind::EventDeletion, Kind::TextNote]) + .author(author.public_key()), + Filter::new().id(deletion), + ] +} + +async fn http_query_ids(client: &Client, reader: &Keys, filter: &Filter) -> Vec { + let resp = client + .post(format!("{}/query", relay_http_url())) + .header("X-Pubkey", reader.public_key().to_hex()) + .json(&vec![filter]) + .send() + .await + .expect("query events"); + assert!( + resp.status().is_success(), + "query failed: {}", + resp.status() + ); + resp.json::>() + .await + .expect("parse query response") + .iter() + .filter_map(|e| e["id"].as_str().map(str::to_string)) + .collect() +} + +async fn http_count(client: &Client, reader: &Keys, filter: &Filter) -> u64 { + let resp = client + .post(format!("{}/count", relay_http_url())) + .header("X-Pubkey", reader.public_key().to_hex()) + .json(&vec![filter]) + .send() + .await + .expect("count events"); + assert!( + resp.status().is_success(), + "count failed: {}", + resp.status() + ); + let body: Value = resp.json().await.expect("parse count response"); + body["count"].as_u64().expect("count field") +} + +async fn ws_query_ids(ws: &mut BuzzTestClient, filter: &Filter) -> Vec { + let sid = sub_id("req"); + ws.subscribe(&sid, vec![filter.clone()]).await.expect("REQ"); + let events = ws + .collect_until_eose(&sid, Duration::from_secs(5)) + .await + .expect("EOSE"); + ws.close_subscription(&sid).await.expect("CLOSE"); + events.into_iter().map(|e| e.id).collect() +} + +async fn ws_count(ws: &mut BuzzTestClient, filter: &Filter) -> u64 { + let sid = sub_id("count"); + ws.send_raw(&serde_json::json!(["COUNT", sid, filter])) + .await + .expect("COUNT"); + loop { + match ws + .recv_event(Duration::from_secs(5)) + .await + .expect("COUNT reply") + { + RelayMessage::Count { + subscription_id, + count, + } if subscription_id == sid => return count, + RelayMessage::Closed { + subscription_id, + message, + } if subscription_id == sid => panic!("COUNT closed: {message}"), + _ => {} + } + } +} + +/// Every historical read surface returns the deletion to `reader` iff +/// `visible`: WS REQ, WS COUNT, HTTP `/query` and HTTP `/count`, by author +/// and by id. +async fn assert_deletion_visibility( + reader: &Keys, + author: &Keys, + deletion: EventId, + visible: bool, +) { + let client = http_client(); + let mut ws = BuzzTestClient::connect(&relay_url(), reader) + .await + .expect("connect reader"); + let expected = u64::from(visible); + let mut mismatches = Vec::new(); + for filter in deletion_filters(author, deletion) { + let observed = [ + ("WS REQ", ws_query_ids(&mut ws, &filter).await.len() as u64), + ("WS COUNT", ws_count(&mut ws, &filter).await), + ( + "HTTP /query", + http_query_ids(&client, reader, &filter).await.len() as u64, + ), + ("HTTP /count", http_count(&client, reader, &filter).await), + ]; + for (surface, n) in observed { + if n != expected { + mismatches.push(format!("{surface} {filter:?}: {n}, expected {expected}")); + } + } + } + assert!(mismatches.is_empty(), "{}", mismatches.join("\n")); + ws.disconnect().await.expect("disconnect"); +} + +/// Whether the relay's `search_tsv` indexes kind:5 content. The desired +/// schema (`schema/schema.sql`, which CI applies) does; an empty database +/// initialized through migration 0008 gets a positive allowlist that doesn't. +fn search_indexes_deletions() -> bool { + std::env::var("BUZZ_TEST_SEARCH_INDEXES_DELETIONS").is_ok_and(|v| v == "1") +} + +/// Search results for `filter` over WS REQ and HTTP `/query`, as hex ids. +async fn search_ids(reader: &Keys, filter: &Filter) -> [(&'static str, BTreeSet); 2] { + let mut ws = BuzzTestClient::connect(&relay_url(), reader) + .await + .expect("connect reader"); + let ws_ids = ws_query_ids(&mut ws, filter) + .await + .iter() + .map(EventId::to_hex) + .collect(); + ws.disconnect().await.expect("disconnect"); + let http_ids = http_query_ids(&http_client(), reader, filter) + .await + .into_iter() + .collect(); + [("WS REQ search", ws_ids), ("HTTP /query search", http_ids)] +} + +#[tokio::test] +#[ignore] +async fn author_only_deletion_search_reaches_only_author() { + let client = http_client(); + let author = Keys::generate(); + let (_, private) = store_deleted_reminder(&client, &author).await; + // Public control: an ordinary deletion carrying the same reason word. + let note = EventBuilder::text_note("public note") + .sign_with_keys(&author) + .unwrap(); + submit_ok(&client, &author, ¬e).await; + let public = build_deletion_with_reason( + &author, + vec![tag(&["e", ¬e.id.to_hex()]), tag(&["k", "1"])], + &search_term(&author), + ); + submit_ok(&client, &author, &public).await; + + let search = Filter::new() + .kind(Kind::EventDeletion) + .search(search_term(&author)); + let (private, public) = (private.id.to_hex(), public.id.to_hex()); + let strict = search_indexes_deletions(); + let mut mismatches = Vec::new(); + for (reader, name, allowed) in [ + ( + &author, + "author", + BTreeSet::from([private.clone(), public.clone()]), + ), + (&Keys::generate(), "other", BTreeSet::from([public.clone()])), + ] { + for (surface, ids) in search_ids(reader, &search).await { + let ok = if strict { + ids == allowed + } else { + ids.is_subset(&allowed) + }; + if !ok { + mismatches.push(format!( + "{surface} as {name}: {ids:?}, expected {allowed:?} (strict={strict})" + )); + } + } + } + assert!(mismatches.is_empty(), "{}", mismatches.join("\n")); +} + +#[tokio::test] +#[ignore] +async fn author_only_deletion_hidden_from_other_readers() { + let client = http_client(); + let author = Keys::generate(); + let (_, deletion) = store_deleted_reminder(&client, &author).await; + assert_deletion_visibility(&Keys::generate(), &author, deletion.id, false).await; +} + +#[tokio::test] +#[ignore] +async fn author_only_deletion_visible_to_author() { + let client = http_client(); + let author = Keys::generate(); + let (_, deletion) = store_deleted_reminder(&client, &author).await; + assert_deletion_visibility(&author, &author, deletion.id, true).await; +} + +#[tokio::test] +#[ignore] +async fn author_only_deletion_live_fanout_reaches_only_author() { + let client = http_client(); + let author = Keys::generate(); + let reminder = build_reminder(&author); + submit_ok(&client, &author, &reminder).await; + + let live = Filter::new() + .kind(Kind::EventDeletion) + .author(author.public_key()); + let mut subscribers = Vec::new(); + for keys in [author.clone(), Keys::generate()] { + let mut ws = BuzzTestClient::connect(&relay_url(), &keys) + .await + .expect("connect"); + let sid = sub_id("live"); + ws.subscribe(&sid, vec![live.clone()]).await.expect("REQ"); + assert!(ws + .collect_until_eose(&sid, Duration::from_secs(5)) + .await + .expect("EOSE") + .is_empty()); + subscribers.push((ws, sid)); + } + + let deletion = build_deletion( + &author, + vec![ + tag(&["e", &reminder.id.to_hex()]), + tag(&["k", &KIND_EVENT_REMINDER.to_string()]), + ], + ); + submit_ok(&client, &author, &deletion).await; + + for (i, (mut ws, sid)) in subscribers.into_iter().enumerate() { + let delivered = live_event_ids(&mut ws, &sid).await.contains(&deletion.id); + let is_author = i == 0; + assert_eq!(delivered, is_author, "live delivery to subscriber {i}"); + ws.disconnect().await.expect("disconnect"); + } +} + +#[tokio::test] +#[ignore] +async fn deletion_of_author_only_event_requires_matching_k_tag() { + let client = http_client(); + let author = Keys::generate(); + let reminder = build_reminder(&author); + submit_ok(&client, &author, &reminder).await; + let target = tag(&["e", &reminder.id.to_hex()]); + let coordinate = format!( + "{KIND_EVENT_REMINDER}:{}:{}", + author.public_key().to_hex(), + reminder.tags.identifier().expect("d tag") + ); + let coordinate = tag(&["a", &coordinate]); + + for tags in [ + vec![target.clone()], + vec![target.clone(), tag(&["k", "1"])], + vec![coordinate.clone()], + ] { + let (accepted, msg) = + submit(&client, &author, &build_deletion(&author, tags.clone())).await; + assert!( + !accepted, + "deletion {tags:?} must be rejected without k=30300 (got: {msg})" + ); + } + submit_ok( + &client, + &author, + &build_deletion( + &author, + vec![coordinate, tag(&["k", &KIND_EVENT_REMINDER.to_string()])], + ), + ) + .await; +} + +#[tokio::test] +#[ignore] +async fn untagged_deletion_of_soft_deleted_author_only_event_rejected() { + let client = http_client(); + let author = Keys::generate(); + let (reminder, _) = store_deleted_reminder(&client, &author).await; + let untagged = build_deletion(&author, vec![tag(&["e", &reminder.id.to_hex()])]); + let (accepted, msg) = submit(&client, &author, &untagged).await; + assert!( + !accepted, + "an untagged deletion of a soft-deleted reminder must be rejected (got: {msg})" + ); +} + +#[tokio::test] +#[ignore] +async fn non_canonical_k_tag_is_not_a_private_marker() { + let client = http_client(); + let author = Keys::generate(); + let reminder = build_reminder(&author); + submit_ok(&client, &author, &reminder).await; + for k in ["030300", "+30300"] { + let deletion = build_deletion( + &author, + vec![tag(&["e", &reminder.id.to_hex()]), tag(&["k", k])], + ); + let (accepted, msg) = submit(&client, &author, &deletion).await; + assert!( + !accepted, + "k={k} must not satisfy the k=30300 rule (got: {msg})" + ); + } +} + +#[tokio::test] +#[ignore] +async fn public_deletion_cannot_claim_author_only_kind() { + let client = http_client(); + let author = Keys::generate(); + let note = EventBuilder::text_note("public note") + .sign_with_keys(&author) + .unwrap(); + submit_ok(&client, &author, ¬e).await; + let deletion = build_deletion( + &author, + vec![ + tag(&["e", ¬e.id.to_hex()]), + tag(&["k", &KIND_EVENT_REMINDER.to_string()]), + ], + ); + let (accepted, msg) = submit(&client, &author, &deletion).await; + assert!( + !accepted, + "a public deletion must not hide behind k=30300 (got: {msg})" + ); +} + +/// The one rejection a sender without authority over a deletion target gets, +/// whether the target exists, is soft-deleted, or lives in any channel. +const DENIED: &str = "invalid: deletion target not found or not deletable by you"; + +/// Submit `deletion` as `sender` over HTTP and WS and return how each +/// rejected it: the HTTP status and error, and the WS `OK` message. +async fn rejection( + client: &Client, + sender: &Keys, + deletion: nostr::Event, +) -> (u16, String, String) { + let resp = client + .post(format!("{}/events", relay_http_url())) + .header("X-Pubkey", sender.public_key().to_hex()) + .json(&deletion) + .send() + .await + .expect("submit event"); + let status = resp.status().as_u16(); + let body: Value = resp.json().await.expect("parse response"); + let http_msg = body["error"].as_str().unwrap_or("").to_string(); + let mut ws = BuzzTestClient::connect(&relay_url(), sender) + .await + .expect("connect"); + let ok = ws.send_event(deletion).await.expect("OK"); + ws.disconnect().await.expect("disconnect"); + assert!(!ok.accepted, "WS must reject the deletion"); + (status, http_msg, ok.message) +} + +/// Submit `deletion` as `sender` over HTTP and WS; both must give the +/// generic denial, which cannot reveal the target's kind. +async fn assert_rejected_as_non_author(client: &Client, sender: &Keys, deletion: nostr::Event) { + let (status, http_msg, ws_msg) = rejection(client, sender, deletion).await; + assert!(status >= 400, "HTTP must reject the deletion"); + for msg in [http_msg, ws_msg] { + assert_eq!(msg, DENIED); + } +} + +async fn create_channel(client: &Client, owner: &Keys, visibility: &str) -> String { + let id = uuid::Uuid::new_v4().to_string(); + let event = EventBuilder::new(Kind::Custom(9007), "") + .tags(vec![ + tag(&["h", &id]), + tag(&["name", &format!("aod-{id}")]), + tag(&["channel_type", "stream"]), + tag(&["visibility", visibility]), + ]) + .sign_with_keys(owner) + .unwrap(); + submit_ok(client, owner, &event).await; + id +} + +async fn post_message(client: &Client, author: &Keys, channel: &str) -> nostr::Event { + let message = EventBuilder::new(Kind::Custom(9), uuid::Uuid::new_v4().to_string()) + .tags(vec![tag(&["h", channel])]) + .sign_with_keys(author) + .unwrap(); + submit_ok(client, author, &message).await; + message +} + +/// A sender without authority over a deletion target gets one rejection, +/// identical in HTTP status, HTTP error and WS `OK` message, for kind 5 and +/// kind 9005 alike, whether the target is missing, live, soft-deleted, in a +/// private channel the sender has not joined, or in another channel. +#[tokio::test] +#[ignore] +async fn unauthorized_deletion_does_not_reveal_target_existence() { + let client = http_client(); + let author = Keys::generate(); + let other = Keys::generate(); + let open = create_channel(&client, &author, "open").await; + let private = create_channel(&client, &author, "private").await; + // A channel `other` owns, so 9005 there passes as owner/admin authority. + let others = create_channel(&client, &other, "open").await; + let live = post_message(&client, &author, &open).await; + let deleted = post_message(&client, &author, &open).await; + submit_ok( + &client, + &author, + &build_deletion(&author, vec![tag(&["e", &deleted.id.to_hex()])]), + ) + .await; + let hidden = post_message(&client, &author, &private).await; + let reminder = build_reminder(&author); + submit_ok(&client, &author, &reminder).await; + let missing = "a".repeat(64); + + assert_ne!(live.id, deleted.id); + let delete = |target: &str| build_deletion(&other, vec![tag(&["e", target])]); + let redact = |target: &str, channel: &str| { + EventBuilder::new(Kind::Custom(9005), "") + .tags(vec![tag(&["e", target]), tag(&["h", channel])]) + .sign_with_keys(&other) + .unwrap() + }; + let cases = [ + ("kind 5, missing", delete(&missing)), + ("kind 5, live", delete(&live.id.to_hex())), + ("kind 5, soft-deleted", delete(&deleted.id.to_hex())), + ("kind 5, private channel", delete(&hidden.id.to_hex())), + ("kind 5, global reminder", delete(&reminder.id.to_hex())), + ("9005, missing", redact(&missing, &others)), + ("9005, live", redact(&live.id.to_hex(), &open)), + ("9005, soft-deleted", redact(&deleted.id.to_hex(), &open)), + ( + "9005, private channel", + redact(&hidden.id.to_hex(), &private), + ), + ("9005, other channel", redact(&live.id.to_hex(), &others)), + ("9005, no channel", redact(&reminder.id.to_hex(), &others)), + ]; + let mut expected = None; + for (case, deletion) in cases { + let (status, http_msg, ws_msg) = rejection(&client, &other, deletion).await; + assert_eq!(http_msg, DENIED, "{case}: HTTP"); + assert_eq!(ws_msg, DENIED, "{case}: WS"); + assert_eq!( + *expected.get_or_insert(status), + status, + "{case}: HTTP status" + ); + } +} + +#[tokio::test] +#[ignore] +async fn non_author_deletion_does_not_reveal_target_kind() { + let client = http_client(); + let author = Keys::generate(); + let other = Keys::generate(); + let live = build_reminder(&author); + submit_ok(&client, &author, &live).await; + let (deleted, _) = store_deleted_reminder(&client, &author).await; + + for target in [&live, &deleted] { + for k in [None, Some("30350"), Some("30300")] { + let mut tags = vec![tag(&["e", &target.id.to_hex()])]; + tags.extend(k.map(|k| tag(&["k", k]))); + assert_rejected_as_non_author(&client, &other, build_deletion(&other, tags)).await; + } + } +} + +/// An author removed from a private channel can no longer delete their +/// messages there, so kind 5 and kind 9005 (sent from a channel they still +/// write to) must reject exactly as for a missing target, while the channel +/// owner and the author's own still-writable messages keep working. +#[tokio::test] +#[ignore] +async fn removed_author_deletion_does_not_reveal_target() { + let client = http_client(); + let owner = Keys::generate(); + let author = Keys::generate(); + let private = create_channel(&client, &owner, "private").await; + let own = create_channel(&client, &author, "open").await; + let membership = |kind: u16| { + EventBuilder::new(Kind::Custom(kind), "") + .tags(vec![ + tag(&["h", &private]), + tag(&["p", &author.public_key().to_hex()]), + ]) + .sign_with_keys(&owner) + .unwrap() + }; + submit_ok(&client, &owner, &membership(9000)).await; + let retained = post_message(&client, &author, &private).await; + let moderated = post_message(&client, &author, &private).await; + submit_ok(&client, &owner, &membership(9001)).await; + let missing = "a".repeat(64); + + let delete = |target: &str| build_deletion(&author, vec![tag(&["e", target])]); + let redact = |keys: &Keys, target: &str, channel: &str| { + EventBuilder::new(Kind::Custom(9005), "") + .tags(vec![tag(&["e", target]), tag(&["h", channel])]) + .sign_with_keys(keys) + .unwrap() + }; + let cases = [ + ("kind 5, missing", delete(&missing)), + ("kind 5, retained", delete(&retained.id.to_hex())), + ("9005, missing", redact(&author, &missing, &own)), + ( + "9005, retained", + redact(&author, &retained.id.to_hex(), &own), + ), + ]; + let mut expected = None; + for (case, deletion) in cases { + let (status, http_msg, ws_msg) = rejection(&client, &author, deletion).await; + assert_eq!(http_msg, DENIED, "{case}: HTTP"); + assert_eq!(ws_msg, DENIED, "{case}: WS"); + assert_eq!( + *expected.get_or_insert(status), + status, + "{case}: HTTP status" + ); + } + + submit_ok( + &client, + &owner, + &redact(&owner, &moderated.id.to_hex(), &private), + ) + .await; + let still_writable = post_message(&client, &author, &own).await; + submit_ok(&client, &author, &delete(&still_writable.id.to_hex())).await; +} + +/// An NIP-AR artifact revision by `author` homed in `channel`. +fn artifact_revision( + author: &Keys, + artifact: &str, + channel: &str, + op: &str, + prev: Option<&EventId>, +) -> nostr::Event { + let mut tags = vec![ + tag(&["ar", "1"]), + tag(&["d", artifact]), + tag(&["h", channel]), + tag(&["type", "buzz.task"]), + tag(&["op", op]), + tag(&["title", "Task"]), + ]; + tags.extend(prev.map(|p| tag(&["prev", &p.to_hex()]))); + EventBuilder::new(Kind::Custom(45010), "") + .tags(tags) + .sign_with_keys(author) + .unwrap() +} + +/// A live artifact by `author` homed in `channel`. +async fn post_artifact(client: &Client, author: &Keys, channel: &str) -> nostr::Event { + let create = artifact_revision( + author, + &uuid::Uuid::new_v4().to_string(), + channel, + "create", + None, + ); + submit_ok(client, author, &create).await; + create +} + +/// An archived channel blocks every deletion of its events, so kind 5 and +/// kind 9005 must reject as for a missing target before any error about the +/// target's kind or location, even for the author who owns the channel. +#[tokio::test] +#[ignore] +async fn archived_target_deletion_does_not_reveal_target() { + let client = http_client(); + let owner = Keys::generate(); + let archived = create_channel(&client, &owner, "open").await; + let active = create_channel(&client, &owner, "open").await; + let message = post_message(&client, &owner, &archived).await; + let artifact = post_artifact(&client, &owner, &archived).await; + // Moving an artifact out of a channel leaves a removal marker there. + let moved = post_artifact(&client, &owner, &archived).await; + let d = moved.tags.identifier().unwrap().to_string(); + submit_ok( + &client, + &owner, + &artifact_revision(&owner, &d, &active, "move", Some(&moved.id)), + ) + .await; + let marker = http_query_ids( + &client, + &owner, + &Filter::new().kind(Kind::Custom(45011)).custom_tag( + nostr::SingleLetterTag::lowercase(nostr::Alphabet::H), + archived.clone(), + ), + ) + .await + .pop() + .expect("artifact removal marker"); + let archive = EventBuilder::new(Kind::Custom(9002), "") + .tags(vec![tag(&["h", &archived]), tag(&["archived", "true"])]) + .sign_with_keys(&owner) + .unwrap(); + submit_ok(&client, &owner, &archive).await; + let missing = "a".repeat(64); + + let delete = |target: &str, k: Option<&str>| { + let mut tags = vec![tag(&["e", target])]; + tags.extend(k.map(|k| tag(&["k", k]))); + build_deletion(&owner, tags) + }; + let redact = |target: &str, channel: &str| { + EventBuilder::new(Kind::Custom(9005), "") + .tags(vec![tag(&["e", target]), tag(&["h", channel])]) + .sign_with_keys(&owner) + .unwrap() + }; + let message_id = message.id.to_hex(); + let cases = [ + ("kind 5, missing", delete(&missing, None)), + ("kind 5, message", delete(&message_id, None)), + ("kind 5, wrong k", delete(&message_id, Some("30300"))), + ("kind 5, artifact", delete(&artifact.id.to_hex(), None)), + ("9005, missing", redact(&missing, &active)), + ("9005, archived target", redact(&message_id, &active)), + ]; + let mut expected = None; + for (case, deletion) in cases { + let (status, http_msg, ws_msg) = rejection(&client, &owner, deletion).await; + assert_eq!(http_msg, DENIED, "{case}: HTTP"); + assert_eq!(ws_msg, DENIED, "{case}: WS"); + assert_eq!( + *expected.get_or_insert(status), + status, + "{case}: HTTP status" + ); + } + // A 9005 naming the archived channel is refused for that channel before + // the target is read, so the removal marker matches a missing target. + assert_eq!( + rejection(&client, &owner, redact(&marker, &archived)).await, + rejection(&client, &owner, redact(&missing, &archived)).await, + ); + + // In an active channel the owner still gets the target diagnostics. + let live = post_message(&client, &owner, &active).await; + let (_, http_msg, _) = + rejection(&client, &owner, delete(&live.id.to_hex(), Some("30300"))).await; + assert!( + http_msg.contains("does not match the deletion target's kind"), + "{http_msg}" + ); + let live_artifact = post_artifact(&client, &owner, &active).await; + let (_, http_msg, _) = + rejection(&client, &owner, delete(&live_artifact.id.to_hex(), None)).await; + assert!( + http_msg.contains("artifacts cannot be deleted with kind 5"), + "{http_msg}" + ); +} + +/// Whether `reader`'s open subscription `sid` receives any event within 2s. +async fn receives_any(ws: &mut BuzzTestClient, sid: &str) -> bool { + !live_event_ids(ws, sid).await.is_empty() +} + +/// IDs of the events subscription `sid` receives until 2s pass with no +/// message. A dropped connection or a `CLOSED` for `sid` fails the test, so +/// a dead subscription can never pass for one that saw nothing. +async fn live_event_ids(ws: &mut BuzzTestClient, sid: &str) -> Vec { + let mut ids = Vec::new(); + loop { + match ws.recv_event(Duration::from_secs(2)).await { + Ok(RelayMessage::Event { + subscription_id, + event, + }) if subscription_id == sid => ids.push(event.id), + Ok(RelayMessage::Closed { + subscription_id, + message, + }) if subscription_id == sid => panic!("{sid} closed: {message}"), + Ok(_) => {} + Err(TestClientError::Timeout) => return ids, + Err(e) => panic!("{sid} receive failed: {e}"), + } + } +} + +/// Deleting a private deletion would store a public event naming it, so the +/// author is refused (NIP-09 gives such a deletion no effect), everyone else +/// gets the shared denial, and no reader but the author ever sees either. +#[tokio::test] +#[ignore] +async fn deletion_of_private_deletion_rejected() { + let client = http_client(); + let author = Keys::generate(); + let other = Keys::generate(); + let (_, private) = store_deleted_reminder(&client, &author).await; + let own = create_channel(&client, &author, "open").await; + + let live = Filter::new() + .kind(Kind::EventDeletion) + .author(author.public_key()); + let mut watcher = BuzzTestClient::connect(&relay_url(), &other) + .await + .expect("connect"); + let sid = sub_id("chain"); + watcher.subscribe(&sid, vec![live]).await.expect("REQ"); + assert!(watcher + .collect_until_eose(&sid, Duration::from_secs(5)) + .await + .expect("EOSE") + .is_empty()); + + let target = private.id.to_hex(); + for k in [None, Some("5")] { + let mut tags = vec![tag(&["e", &target])]; + tags.extend(k.map(|k| tag(&["k", k]))); + let (status, http_msg, ws_msg) = + rejection(&client, &author, build_deletion(&author, tags)).await; + assert!(status >= 400, "k={k:?}: HTTP must reject"); + for msg in [http_msg, ws_msg] { + assert_eq!( + msg, "invalid: cannot delete a private deletion request", + "k={k:?}" + ); + } + } + // A 9005 cannot reach the global private deletion from any channel. + let redact = EventBuilder::new(Kind::Custom(9005), "") + .tags(vec![tag(&["e", &target]), tag(&["h", &own])]) + .sign_with_keys(&author) + .unwrap(); + let (_, http_msg, ws_msg) = rejection(&client, &author, redact).await; + assert_eq!((http_msg.as_str(), ws_msg.as_str()), (DENIED, DENIED)); + + let missing = "a".repeat(64); + assert_eq!( + rejection( + &client, + &other, + build_deletion(&other, vec![tag(&["e", &target])]) + ) + .await, + rejection( + &client, + &other, + build_deletion(&other, vec![tag(&["e", &missing])]) + ) + .await, + ); + assert_rejected_as_non_author( + &client, + &other, + build_deletion(&other, vec![tag(&["e", &target])]), + ) + .await; + + // Only the private deletion exists: the author alone reads it. + assert_deletion_visibility(&author, &author, private.id, true).await; + assert_deletion_visibility(&other, &author, private.id, false).await; + assert!( + !receives_any(&mut watcher, &sid).await, + "no deletion may reach another reader live" + ); + watcher.disconnect().await.expect("disconnect"); + + // Deleting a public deletion is unchanged. + let note = EventBuilder::text_note("public note") + .sign_with_keys(&author) + .unwrap(); + submit_ok(&client, &author, ¬e).await; + let public = build_deletion(&author, vec![tag(&["e", ¬e.id.to_hex()])]); + submit_ok(&client, &author, &public).await; + submit_ok( + &client, + &author, + &build_deletion(&author, vec![tag(&["e", &public.id.to_hex()])]), + ) + .await; +} + +/// A soft-deleted target keeps its channel: re-deleting it faces the same +/// membership and archive gates as a live one, and an accepted re-deletion is +/// readable by that channel's members only. Re-deletions now retain the +/// target's stored channel, so historical access, `#h` filtering and live +/// routing use that channel rather than treating a new re-deletion as global. +#[tokio::test] +#[ignore] +async fn soft_deleted_target_keeps_its_channel() { + let client = http_client(); + let owner = Keys::generate(); + let author = Keys::generate(); + let outsider = Keys::generate(); + let private = create_channel(&client, &owner, "private").await; + let archived = create_channel(&client, &author, "open").await; + let membership = |kind: u16| { + EventBuilder::new(Kind::Custom(kind), "") + .tags(vec![ + tag(&["h", &private]), + tag(&["p", &author.public_key().to_hex()]), + ]) + .sign_with_keys(&owner) + .unwrap() + }; + let delete = + |target: &nostr::Event| build_deletion(&author, vec![tag(&["e", &target.id.to_hex()])]); + let soft_deleted = |channel: String| { + let client = client.clone(); + let author = author.clone(); + async move { + let message = post_message(&client, &author, &channel).await; + submit_ok(&client, &author, &delete(&message)).await; + message + } + }; + + submit_ok(&client, &owner, &membership(9000)).await; + let redeletable = soft_deleted(private.clone()).await; + let redeletion = build_deletion_with_reason( + &author, + vec![tag(&["e", &redeletable.id.to_hex()])], + "re-deletion", + ); + assert_ne!(redeletion.id, delete(&redeletable).id); + + // Subscribe before the re-deletion: the member by channel, the outsider + // by author. A global control deletion proves the outsider's is alive. + let h = nostr::SingleLetterTag::lowercase(nostr::Alphabet::H); + let mut watchers = Vec::new(); + for (reader, filter) in [ + ( + &owner, + Filter::new() + .kind(Kind::EventDeletion) + .custom_tag(h, private.clone()), + ), + ( + &outsider, + Filter::new() + .kind(Kind::EventDeletion) + .author(author.public_key()), + ), + ] { + let mut ws = BuzzTestClient::connect(&relay_url(), reader) + .await + .expect("connect"); + let sid = sub_id("redeletion"); + ws.subscribe(&sid, vec![filter]).await.expect("REQ"); + ws.collect_until_eose(&sid, Duration::from_secs(5)) + .await + .expect("EOSE"); + watchers.push((ws, sid)); + } + let (accepted, msg) = submit(&client, &author, &redeletion).await; + assert!( + accepted && !msg.starts_with("duplicate:"), + "re-deletion: {msg}" + ); + let note = EventBuilder::text_note("control") + .sign_with_keys(&author) + .unwrap(); + submit_ok(&client, &author, ¬e).await; + let control = delete(¬e); + submit_ok(&client, &author, &control).await; + let [member_ids, outsider_ids] = { + let mut out = [Vec::new(), Vec::new()]; + for (slot, (mut ws, sid)) in out.iter_mut().zip(watchers) { + *slot = live_event_ids(&mut ws, &sid).await; + ws.disconnect().await.expect("disconnect"); + } + out + }; + assert_eq!(member_ids, vec![redeletion.id], "member live delivery"); + assert_eq!(outsider_ids, vec![control.id], "outsider live delivery"); + + let removed = soft_deleted(private.clone()).await; + submit_ok(&client, &owner, &membership(9001)).await; + let in_archive = soft_deleted(archived.clone()).await; + let archive = EventBuilder::new(Kind::Custom(9002), "") + .tags(vec![tag(&["h", &archived]), tag(&["archived", "true"])]) + .sign_with_keys(&author) + .unwrap(); + submit_ok(&client, &author, &archive).await; + + let missing = build_deletion(&author, vec![tag(&["e", &"a".repeat(64)])]); + let expected = rejection(&client, &author, missing).await; + assert_eq!(expected.1, DENIED); + for (case, target) in [("removed", &removed), ("archived", &in_archive)] { + assert_eq!( + rejection(&client, &author, delete(target)).await, + expected, + "{case}" + ); + } + + for (reader, name, visible) in [(&owner, "member", true), (&outsider, "outsider", false)] { + for filter in [ + Filter::new().id(redeletion.id), + Filter::new() + .kind(Kind::EventDeletion) + .custom_tag(h, private.clone()), + ] { + let ids = http_query_ids(&client, reader, &filter).await; + assert_eq!( + ids.contains(&redeletion.id.to_hex()), + visible, + "{name} {filter:?}: {ids:?}" + ); + } + } +} + +/// The single-target rule depends only on the request, so a deletion naming +/// two targets gets the same error whatever those targets are. +#[tokio::test] +#[ignore] +async fn multi_target_deletion_error_ignores_targets() { + let client = http_client(); + let author = Keys::generate(); + let owner = Keys::generate(); + let open = create_channel(&client, &author, "open").await; + let elsewhere = create_channel(&client, &owner, "private").await; + let foreign = post_message(&client, &owner, &elsewhere).await; + let live = post_message(&client, &author, &open).await; + let reminder = build_reminder(&author); + submit_ok(&client, &author, &reminder).await; + let artifact = post_artifact(&client, &author, &open).await; + let coordinate = format!( + "{KIND_EVENT_REMINDER}:{}:{}", + author.public_key().to_hex(), + reminder.tags.identifier().expect("d tag") + ); + let missing = "a".repeat(64); + let targets = [ + ("missing", missing.clone()), + ("live", live.id.to_hex()), + ("other channel", foreign.id.to_hex()), + ("private kind", reminder.id.to_hex()), + ("artifact", artifact.id.to_hex()), + ]; + let shapes = [ + ("two e", "(got e=2, a=0)", "e", missing.as_str()), + ("e plus a", "(got e=1, a=1)", "a", coordinate.as_str()), + ]; + for (shape, counts, second, value) in shapes { + let expected = format!( + "invalid: deletion events must reference exactly one target via e or a tag {counts}" + ); + let mut status = None; + for (case, target) in &targets { + let deletion = + build_deletion(&author, vec![tag(&["e", target]), tag(&[second, value])]); + let (code, http_msg, ws_msg) = rejection(&client, &author, deletion).await; + assert_eq!(http_msg, expected, "{shape}, {case}: HTTP"); + assert_eq!(ws_msg, expected, "{shape}, {case}: WS"); + assert_eq!(*status.get_or_insert(code), code, "{shape}, {case}: status"); + } + } +} diff --git a/scripts/run-tests.sh b/scripts/run-tests.sh index 4f5ed92ba3..b51e575973 100755 --- a/scripts/run-tests.sh +++ b/scripts/run-tests.sh @@ -239,7 +239,8 @@ run_unit_tests() { handlers::req::tests::revoke_then_replacement_keeps_replacement_whole \ handlers::req::tests::claims_after_connection_cleanup_are_refused \ handlers::req::tests::dropped_terminal_frame_cancels_connection \ - handlers::req::tests::revoke_dropped_terminal_frame_cancels_connection + handlers::req::tests::revoke_dropped_terminal_frame_cancels_connection \ + handlers::req::tests::count_fallback_covers_filters_that_can_match_private_deletions run_test_step "buzz-relay readiness tests" \ cargo test -p buzz-relay --lib readiness::tests:: -- --nocapture