diff --git a/NOSTR.md b/NOSTR.md index c3265bfabb..c0498a3678 100644 --- a/NOSTR.md +++ b/NOSTR.md @@ -315,7 +315,9 @@ out unless they ask for it: channel with this label". Push notifications use the same rule: a lease filter pushes events from a -system channel only when its `#h` names that channel. Every kind:44100/44101 +system channel only when its `#h` names that channel. Push also requires +membership, except that a message in a listed channel wakes a non-member it +`p`-tags (see `docs/buzz-push.md`). Every kind:44100/44101 membership notification carries its channel type as `t`, and a filter without `#t` sees only the legacy types, so system channel notices reach only a filter with `#t:["system"]` (see NIP-CL). diff --git a/crates/buzz-db/src/store/channel_members.rs b/crates/buzz-db/src/store/channel_members.rs index 958751feef..64dfd3bc67 100644 --- a/crates/buzz-db/src/store/channel_members.rs +++ b/crates/buzz-db/src/store/channel_members.rs @@ -1904,6 +1904,33 @@ pub async fn named_only_channels_among( .await?) } +/// The channels in `channel_ids` the channel directory lists +/// ([`crate::store::channel::LISTED_CHANNEL_SQL`]). Push lets a non-member's +/// lease match a mention only in these. +pub async fn listed_channels_among( + pool: &PgPool, + community_id: CommunityId, + channel_ids: &[Uuid], +) -> Result> { + if channel_ids.is_empty() { + return Ok(Vec::new()); + } + let mut connection = crate::observability::acquire_writer( + pool, + crate::observability::WriterOperation::Authorization, + ) + .await?; + let sql = format!( + "SELECT id FROM channels WHERE community_id = $1 AND id = ANY($2) AND {}", + crate::store::channel::LISTED_CHANNEL_SQL + ); + Ok(sqlx::query_scalar(sqlx::AssertSqlSafe(sql)) + .bind(community_id.as_uuid()) + .bind(channel_ids) + .fetch_all(&mut *connection) + .await?) +} + /// A large channel whose canonical active-member count may need its legacy /// discovery snapshot repaired. #[derive(Debug, Clone, PartialEq, Eq)] @@ -2883,6 +2910,16 @@ impl Db { named_only_channels_among(&self.pool, community_id, channel_ids).await } + /// The channels in `channel_ids` the channel directory lists. + #[datastore_span(name = "listed_channels_among", system = "postgresql")] + pub async fn listed_channels_among( + &self, + community_id: CommunityId, + channel_ids: &[Uuid], + ) -> Result> { + listed_channels_among(&self.pool, community_id, channel_ids).await + } + /// Returns large active-channel rosters whose relay-authored snapshots differ. #[datastore_span( name = "list_large_channel_rosters_needing_reconciliation", diff --git a/crates/buzz-db/src/store/push.rs b/crates/buzz-db/src/store/push.rs index 78a1ab3740..713137d313 100644 --- a/crates/buzz-db/src/store/push.rs +++ b/crates/buzz-db/src/store/push.rs @@ -1248,6 +1248,47 @@ pub async fn revalidate_wake_for_send( }) } +/// Whether a lease author still passes the relay's connection gate: no active +/// ban on them or their recorded owner, and `admission`. Mirrors +/// `operator_listener::load_deliverable_event`. +pub async fn author_admitted( + pool: &PgPool, + community: CommunityId, + author: &[u8], + admission: crate::operator_listener::DeliveryAdmission, +) -> Result { + let mut connection = + acquire_operation_connection(pool, crate::observability::WriterOperation::Maintenance) + .await?; + Ok(sqlx::query_scalar( + "WITH principals AS ( \ + SELECT $2::bytea AS pubkey \ + UNION ALL \ + SELECT agent_owner_pubkey FROM users \ + WHERE community_id = $1 AND pubkey = $2 AND agent_owner_pubkey IS NOT NULL \ + ) \ + SELECT (NOT $5 OR EXISTS ( \ + SELECT 1 FROM pubkey_allowlist a \ + WHERE a.community_id = $1 AND a.pubkey = $2)) \ + AND NOT EXISTS ( \ + SELECT 1 FROM community_bans b \ + WHERE b.community_id = $1 AND b.pubkey IN (SELECT pubkey FROM principals) \ + AND b.banned AND (b.ban_expires_at IS NULL OR b.ban_expires_at > now())) \ + AND (NOT $3 OR EXISTS ( \ + SELECT 1 FROM relay_members rm \ + WHERE rm.community_id = $1 AND rm.pubkey IN ( \ + SELECT encode(p.pubkey, 'hex') FROM principals p \ + WHERE $4 OR p.pubkey = $2)))", + ) + .bind(community.as_uuid()) + .bind(author) + .bind(admission.require_membership) + .bind(admission.allow_owner_membership) + .bind(admission.require_allowlist) + .fetch_one(&mut *connection) + .await?) +} + /// Mark a fenced claim delivered. Stale workers cannot complete a newer claim. pub async fn complete_wake( pool: &PgPool, @@ -1520,6 +1561,17 @@ impl Db { crate::push::revalidate_wake_for_send(&self.pool, community, id, claim_id).await } + /// Whether a lease author still passes the relay's connection gate. + #[datastore_span(name = "push_author_admitted", system = "postgresql")] + pub async fn push_author_admitted( + &self, + community: CommunityId, + author: &[u8], + admission: crate::operator_listener::DeliveryAdmission, + ) -> Result { + crate::push::author_admitted(&self.pool, community, author, admission).await + } + /// Mark a fenced wake claim delivered. #[datastore_span(name = "complete_push_wake", system = "postgresql")] pub async fn complete_push_wake( diff --git a/crates/buzz-db/src/store/push/delivery_postgres_tests.rs b/crates/buzz-db/src/store/push/delivery_postgres_tests.rs index eeecb888a9..2c5af7bb9a 100644 --- a/crates/buzz-db/src/store/push/delivery_postgres_tests.rs +++ b/crates/buzz-db/src/store/push/delivery_postgres_tests.rs @@ -295,3 +295,130 @@ async fn concurrent_discovery_preserves_exclusive_claims_and_recovery_fencing() .unwrap() ); } + +/// Mirrors the operator listener's admission tests: a ban on the author or +/// their recorded owner blocks, and membership and the allowlist apply only +/// when configured. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn author_admission_matches_the_connection_gate() { + use crate::operator_listener::DeliveryAdmission; + + let pool = PgPool::connect(&crate::test_support::database_url()) + .await + .expect("isolated database"); + let community = make_community(&pool).await; + let (agent, owner) = ([31u8; 32], [32u8; 32]); + let open = DeliveryAdmission { + require_membership: false, + allow_owner_membership: false, + require_allowlist: false, + }; + let closed = DeliveryAdmission { + require_membership: true, + ..open + }; + let closed_with_owner = DeliveryAdmission { + allow_owner_membership: true, + ..closed + }; + let allowlisted = DeliveryAdmission { + require_allowlist: true, + ..open + }; + let admitted = |author: [u8; 32], admission: DeliveryAdmission| { + let pool = pool.clone(); + async move { + author_admitted(&pool, community, &author, admission) + .await + .expect("check admission") + } + }; + let run = |sql: &'static str, pubkey: [u8; 32]| { + let pool = pool.clone(); + async move { + sqlx::query(sql) + .bind(community.as_uuid()) + .bind(pubkey.as_slice()) + .execute(&pool) + .await + .expect(sql); + } + }; + const BAN: &str = "INSERT INTO community_bans (community_id, pubkey, banned, actor_pubkey) \ + VALUES ($1, $2, true, $2)"; + const UNBAN: &str = "DELETE FROM community_bans WHERE community_id = $1 AND pubkey = $2"; + const JOIN: &str = "INSERT INTO relay_members (community_id, pubkey, role) \ + VALUES ($1, encode($2, 'hex'), 'member')"; + + sqlx::query( + "INSERT INTO users (community_id, pubkey, agent_owner_pubkey) \ + VALUES ($1, $3, NULL), ($1, $2, $3)", + ) + .bind(community.as_uuid()) + .bind(agent.as_slice()) + .bind(owner.as_slice()) + .execute(&pool) + .await + .expect("record agent owner"); + assert!(admitted(agent, open).await); + + // Bans: an expired ban admits, an active one blocks, and a ban on the + // owner cascades to the agent but not the other way round. + run( + "INSERT INTO community_bans (community_id, pubkey, banned, actor_pubkey, ban_expires_at) \ + VALUES ($1, $2, true, $2, now() - interval '1 second')", + agent, + ) + .await; + assert!(admitted(agent, open).await, "an expired ban admits"); + run(UNBAN, agent).await; + run(BAN, agent).await; + assert!(!admitted(agent, open).await, "an active ban blocks"); + assert!( + admitted(owner, open).await, + "an agent's ban leaves its owner" + ); + run(UNBAN, agent).await; + run(BAN, owner).await; + assert!( + !admitted(agent, open).await, + "an owner's ban blocks its agent" + ); + run(UNBAN, owner).await; + + // Closed community: direct membership, or a member owner with NIP-OA. + assert!(!admitted(agent, closed).await, "a non-member is blocked"); + run(JOIN, owner).await; + assert!(!admitted(agent, closed).await); + assert!(admitted(agent, closed_with_owner).await); + run(JOIN, agent).await; + assert!(admitted(agent, closed).await, "a member is admitted"); + run( + "DELETE FROM relay_members WHERE community_id = $1 AND pubkey = encode($2, 'hex')", + agent, + ) + .await; + assert!( + !admitted(agent, closed).await, + "a removed member is blocked" + ); + + // Allowlist: only the author's own entry counts. + assert!(!admitted(agent, allowlisted).await); + run( + "INSERT INTO pubkey_allowlist (community_id, pubkey) VALUES ($1, $2)", + owner, + ) + .await; + assert!( + !admitted(agent, allowlisted).await, + "an owner's entry is not the agent's" + ); + run( + "INSERT INTO pubkey_allowlist (community_id, pubkey) VALUES ($1, $2)", + agent, + ) + .await; + assert!(admitted(agent, allowlisted).await); +} diff --git a/crates/buzz-relay/src/push_runtime.rs b/crates/buzz-relay/src/push_runtime.rs index f4e614f009..dbee317241 100644 --- a/crates/buzz-relay/src/push_runtime.rs +++ b/crates/buzz-relay/src/push_runtime.rs @@ -1,6 +1,7 @@ //! Durable NIP-PL event matcher and gateway delivery worker. use std::{ + collections::HashSet, sync::Arc, time::{Duration, Instant}, }; @@ -126,12 +127,14 @@ async fn matcher_loop(state: &AppState) { } /// Per-batch state shared by every job: the community's active leases, the -/// exact (channel, lease author) membership pairs the jobs can consult, and -/// the batch's named-only channels (system channels and any type added later). +/// exact (channel, lease author) membership pairs the jobs can consult, the +/// batch's named-only channels (system channels and any type added later), and +/// its listed channels, where a mention reaches a non-member. struct MatchContext { leases: Vec, memberships: std::collections::HashSet<(uuid::Uuid, Vec)>, named_only: NamedOnlyChannels, + listed: std::collections::HashSet, } async fn load_match_context( @@ -161,10 +164,17 @@ async fn load_match_context( .named_only_channels_among(batch.community, &channels) .await?, ); + let listed = state + .db + .listed_channels_among(batch.community, &channels) + .await? + .into_iter() + .collect(); Ok(MatchContext { leases, memberships, named_only, + listed, }) } @@ -293,6 +303,12 @@ fn match_job( context: &MatchContext, ) -> anyhow::Result> { let mut wakes = Vec::new(); + // Collected once per event: the per-lease check below runs for every + // non-member lease on every listed-channel message. + let mentioned = match job.event.channel_id { + Some(channel) if context.listed.contains(&channel) => mentioned_readers(&job.event.event), + _ => HashSet::new(), + }; for lease in &context.leases { let author_hex = hex::encode(&lease.author); if !reader_authorized_for_event(&job.event.event, &author_hex) { @@ -302,6 +318,7 @@ fn match_job( if !context .memberships .contains(&(channel, lease.author.clone())) + && !mentioned.contains(author_hex.as_str()) { continue; } @@ -361,6 +378,25 @@ fn match_job( Ok(wakes) } +/// The pubkeys `event` mentions with a `p` tag. Workflow owner attribution +/// is not a mention. +fn mentioned_readers(event: &nostr::Event) -> HashSet<&str> { + event + .tags + .iter() + .filter(|tag| { + tag.as_slice().first().is_some_and(|name| name == "p") + && !is_workflow_owner_attribution(event, tag) + }) + .filter_map(|tag| tag.content()) + .collect() +} + +/// Whether `event` mentions `reader_hex`, by the same rule as matching. +fn mentions_reader(event: &nostr::Event, reader_hex: &str) -> bool { + mentioned_readers(event).contains(reader_hex) +} + /// Whether a lease filter may push an event in `channel`, by the same rule as /// REQ: a legacy-type channel is in every filter's scope (membership is /// checked separately), and a named-only channel is in scope only when the @@ -380,6 +416,50 @@ fn push_filter_reads_channel( filter_channel_scope(filter, &[], named_only).contains(&channel) } +/// Send-time counterpart of the matcher's channel rule: the lease author is a +/// member, or the event mentions them, the channel is still listed and they +/// still pass the connection gate. +async fn channel_authorizes_wake( + state: &AppState, + wake: &buzz_db::push::ClaimedWake, + channel: uuid::Uuid, +) -> buzz_db::Result { + if state + .db + .is_member(wake.community, channel, &wake.author) + .await? + { + return Ok(true); + } + // A non-member reads the channel only through REQ, so apply its gate. + let admission = buzz_db::operator_listener::DeliveryAdmission { + require_membership: state.config.require_relay_membership, + allow_owner_membership: state.config.allow_nip_oa_auth, + require_allowlist: state.config.pubkey_allowlist_enabled, + }; + if !state + .db + .push_author_admitted(wake.community, &wake.author, admission) + .await? + { + return Ok(false); + } + if state + .db + .listed_channels_among(wake.community, &[channel]) + .await? + .is_empty() + { + return Ok(false); + } + let author_hex = hex::encode(&wake.author); + Ok(state + .db + .get_event_by_id(wake.community, &wake.event_id) + .await? + .is_some_and(|stored| mentions_reader(&stored.event, &author_hex))) +} + /// Match-time counterpart of REQ's filter-level `#p` authorization gate. /// Kind 1059 is globally stored and leaks recipient activity through wake /// timing, so a lease may only match gift wraps addressed to its own author. @@ -501,11 +581,7 @@ async fn deliver_one( metrics::histogram!("buzz_push_wake_queue_seconds").record(wake_queue_seconds); } if let Some(channel) = outcome.channel_id { - match state - .db - .is_member(outcome.community, channel, &outcome.author) - .await - { + match channel_authorizes_wake(state, &outcome, channel).await { Ok(true) => {} Ok(false) => { let _ = state @@ -829,6 +905,7 @@ mod tests { (system, "system".to_owned()), (future, "later-type".to_owned()), ]), + listed: Default::default(), }; let job = |channel: Option| { let mut event = EventBuilder::new(Kind::Custom(9), "hi"); @@ -921,6 +998,7 @@ mod tests { .map(|keys| (channel, author(keys))) .collect(), named_only: NamedOnlyChannels::from_typed([]), + listed: Default::default(), }; let relay = nostr::Keys::generate(); let owner_hex = owner.public_key().to_hex(); @@ -969,6 +1047,7 @@ mod tests { }], memberships: [(channel, author(&agent))].into_iter().collect(), named_only: NamedOnlyChannels::from_typed([]), + listed: Default::default(), }; let event = EventBuilder::new(Kind::Custom(9), "workflow output") .tag(Tag::parse(["p", &owner_hex, "", "owner"]).unwrap()) @@ -991,6 +1070,83 @@ mod tests { assert_eq!(gated(&[&agent, &owner]), 0, "two mentions over the gate"); } + /// A non-member's lease wakes only for a message that mentions them in a + /// listed channel. Mutations: drop the mention check → RED + /// (plain and someone-else messages wake); drop the listed check → + /// RED (private, unlisted or system mentions wake); count owner + /// attribution as a mention → RED. + #[test] + fn nonmember_wakes_only_when_mentioned_in_a_listed_channel() { + let outsider = nostr::Keys::generate(); + let other = nostr::Keys::generate(); + let sender = nostr::Keys::generate(); + let open = uuid::Uuid::new_v4(); + // Private and unlisted channels are simply absent from `listed`. + let private = uuid::Uuid::new_v4(); + let system = uuid::Uuid::new_v4(); + let me = outsider.public_key().to_hex(); + let context = |filter: Value| MatchContext { + leases: vec![buzz_db::push::MatchLease { + author: outsider.public_key().to_bytes().to_vec(), + installation_id: "phone".into(), + generation: 1, + subscriptions: serde_json::json!([{"filter": filter, "class": "default"}]), + expires_at: Utc::now().timestamp() + 3600, + }], + memberships: Default::default(), + named_only: NamedOnlyChannels::from_typed([(system, "system".to_owned())]), + listed: [open].into_iter().collect(), + }; + let wakes = |filter: Value, channel: uuid::Uuid, tags: &[&[&str]]| { + let event = EventBuilder::new(Kind::Custom(9), "hi") + .tag(Tag::parse(["h", &channel.to_string()]).unwrap()) + .tags( + tags.iter() + .map(|tag| Tag::parse(tag.iter().copied()).unwrap()), + ) + .sign_with_keys(&sender) + .unwrap(); + let job = buzz_db::push::BatchedMatch { + event: buzz_core::StoredEvent::new(event, Some(channel)), + attempt: 1, + }; + match_job(&job, &context(filter)).unwrap().len() + }; + let mine = serde_json::json!({"kinds": [9], "#p": [me]}); + let broad = serde_json::json!({"kinds": [9]}); + let mention: &[&str] = &["p", &me]; + let other_hex = other.public_key().to_hex(); + + assert_eq!(wakes(mine.clone(), open, &[mention]), 1, "mentioned"); + assert_eq!(wakes(broad.clone(), open, &[mention]), 1, "broad lease"); + assert_eq!(wakes(broad.clone(), open, &[]), 0, "plain message"); + assert_eq!( + wakes(broad.clone(), open, &[&["p", &other_hex]]), + 0, + "someone else mentioned" + ); + assert_eq!( + wakes( + broad.clone(), + open, + &[&["p", &me, "", "owner"], &["buzz:workflow", "true"]] + ), + 0, + "owner attribution" + ); + assert_eq!(wakes(mine.clone(), private, &[mention]), 0, "private"); + assert_eq!(wakes(mine, system, &[mention]), 0, "system"); + assert_eq!( + wakes( + serde_json::json!({"kinds": [9], "#h": [system.to_string()]}), + system, + &[mention] + ), + 0, + "system named by #h" + ); + } + async fn capture( State(seen): State>>>, OriginalUri(uri): OriginalUri, @@ -1123,7 +1279,7 @@ mod shutdown_tests { #[cfg(test)] mod postgres_tests { - use super::{load_match_context, match_job}; + use super::{channel_authorizes_wake, load_match_context, match_job}; use nostr::{EventBuilder, Kind, Tag}; /// Real workflow messages from `RelayActionSink` against mobile-shaped @@ -1408,4 +1564,186 @@ mod postgres_tests { "ordinary channel wakes its member's broad lease; system channel wakes only the lease that names it" ); } + + /// Real channel rows: a message that mentions a non-member wakes their + /// lease only in a listed channel, and does not add them. Send-time + /// revalidation applies the same rule, so a channel that turns private + /// after matching stops the wake. + /// Mutations: drop the listed check at match or delivery → RED (private, + /// unlisted or system mentions wake, or the flip still delivers); drop + /// the mention check at delivery → RED (the plain message delivers). + #[tokio::test] + #[ignore = "requires Postgres and Redis"] + async fn nonmember_mentions_wake_only_in_listed_channels() { + use crate::handlers::group_state_postgres_tests::{create_channel, http_auth}; + use crate::handlers::ingest::ingest_event; + + let state = crate::api::bridge::postgres_tests::bridge_handler_test_state() + .await + .expect("local Postgres and Redis"); + let host = format!("push-nonmember-{}.local", uuid::Uuid::new_v4().simple()); + let community = state + .db + .ensure_configured_community(&host) + .await + .expect("ensure community") + .id; + let tenant = buzz_core::TenantContext::resolved(community, &host); + let owner = nostr::Keys::generate(); + let outsider = nostr::Keys::generate(); + let outsider_bytes = outsider.public_key().to_bytes().to_vec(); + let me = outsider.public_key().to_hex(); + + let open = create_channel(&state, &tenant, &owner, &[]).await; + let private = create_channel(&state, &tenant, &owner, &[&["visibility", "private"]]).await; + let unlisted = create_channel(&state, &tenant, &owner, &[&["unlisted", "true"]]).await; + let system = create_channel( + &state, + &tenant, + &owner, + &[&["channel_type", "system"], &["visibility", "open"]], + ) + .await; + for channel in [open, unlisted, system] { + let record = state + .db + .get_channel(community, channel) + .await + .expect("channel"); + assert_eq!(record.visibility, "open", "{channel}"); + } + + // Mobile's lease: wake on my `p`, ignore what I authored. + let subscriptions = serde_json::json!([{ + "filter": {"kinds": [9], "#p": [me]}, + "class": "default", + "ignore": [{"kinds": [9], "authors": [me]}], + }]); + assert_eq!( + buzz_db::push::replace_active_lease( + state.db.pool(), + community, + &outsider.public_key().to_bytes(), + "phone", + buzz_db::push::LeaseVersion { + source_event_id: &[1; 32], + source_created_at: 10, + generation: 1, + expires_at: i64::MAX / 2, + }, + buzz_db::push::ActiveLease { + endpoint_hash: &[42; 32], + endpoint_grant: "opaque-grant", + max_class: "default", + subscriptions: &subscriptions, + }, + ) + .await + .expect("activate lease"), + buzz_db::push::ReplaceLeaseOutcome::Accepted + ); + + let mut jobs = Vec::new(); + for (channel, mention) in [ + (open, true), + (open, false), + (private, true), + (unlisted, true), + (system, true), + ] { + let mut event = EventBuilder::new(Kind::Custom(9), "hello") + .tag(Tag::parse(["h", &channel.to_string()]).unwrap()); + if mention { + event = event.tag(Tag::public_key(outsider.public_key())); + } + let event = event.sign_with_keys(&owner).unwrap(); + let id = event.id; + ingest_event(&state, &tenant, event, http_auth(&owner)) + .await + .expect("ingest message"); + let stored = state + .db + .get_event_by_id(community, id.as_bytes()) + .await + .expect("load message") + .expect("stored message"); + assert_eq!(stored.channel_id, Some(channel)); + jobs.push(buzz_db::push::BatchedMatch { + event: stored, + attempt: 1, + }); + } + let batch = buzz_db::push::ClaimedMatchBatch { + community, + claim_id: uuid::Uuid::new_v4(), + jobs, + }; + let context = load_match_context(&state, &batch) + .await + .expect("match context"); + let woken: Vec = batch + .jobs + .iter() + .map(|job| match_job(job, &context).expect("match").len()) + .collect(); + assert_eq!( + woken, + vec![1, 0, 0, 0, 0], + "only the mention in the listed channel wakes the non-member" + ); + assert!( + !state + .db + .is_member(community, open, &outsider_bytes) + .await + .expect("membership"), + "a mention does not add the non-member" + ); + + let wake = |job: &buzz_db::push::BatchedMatch| buzz_db::push::ClaimedWake { + community, + id: uuid::Uuid::new_v4(), + claim_id: uuid::Uuid::new_v4(), + event_id: job.event.event.id.as_bytes().to_vec(), + channel_id: job.event.channel_id, + author: outsider_bytes.clone(), + installation_id: "phone".into(), + lease_generation: 1, + endpoint_grant: "opaque-grant".into(), + class: "default".into(), + expires_at: i64::MAX / 2, + queued_at: chrono::Utc::now(), + attempt: 1, + }; + let authorizes = |index: usize, channel: uuid::Uuid| { + let wake = wake(&batch.jobs[index]); + let state = &state; + async move { + channel_authorizes_wake(state, &wake, channel) + .await + .expect("revalidate") + } + }; + assert!(authorizes(0, open).await, "mention in a listed channel"); + assert!(!authorizes(1, open).await, "plain message"); + assert!(!authorizes(2, private).await, "private channel"); + assert!(!authorizes(3, unlisted).await, "unlisted channel"); + assert!(!authorizes(4, system).await, "system channel"); + + let flip = EventBuilder::new(Kind::Custom(9002), "") + .tags([ + Tag::parse(["h", &open.to_string()]).unwrap(), + Tag::parse(["visibility", "private"]).unwrap(), + ]) + .sign_with_keys(&owner) + .unwrap(); + let flipped = ingest_event(&state, &tenant, flip, http_auth(&owner)) + .await + .expect("make private"); + assert!(flipped.accepted, "{}", flipped.message); + assert!( + !authorizes(0, open).await, + "a channel that turned private stops the wake" + ); + } } diff --git a/crates/buzz-relay/src/push_runtime/delivery_postgres_tests.rs b/crates/buzz-relay/src/push_runtime/delivery_postgres_tests.rs index ec40e59241..2ba303657b 100644 --- a/crates/buzz-relay/src/push_runtime/delivery_postgres_tests.rs +++ b/crates/buzz-relay/src/push_runtime/delivery_postgres_tests.rs @@ -176,3 +176,246 @@ async fn delivery_worker_reaches_later_pages_before_revisiting_busy_communities( started.elapsed() ); } + +/// A mention wake for someone outside a listed channel reaches the gateway +/// only while they pass the connection gate and the channel stays listed. +/// Mutations: drop `channel_authorizes_wake` from `deliver_one`, swap it for +/// `is_member`, drop its admission check, or ignore any admission setting → RED. +#[tokio::test] +#[ignore = "requires Postgres and Redis"] +async fn nonmember_mention_wakes_reach_the_gateway_only_for_admitted_readers() { + use crate::handlers::group_state_postgres_tests::{create_channel, http_auth}; + use crate::handlers::ingest::ingest_event; + use axum::{extract::State, routing::post, Json, Router}; + use nostr::{EventBuilder, Kind, Tag}; + use std::{collections::HashMap, future::IntoFuture}; + use tokio::sync::mpsc; + + async fn accept( + State(seen): State>, + Json(body): Json, + ) -> Json { + seen.send(body["request_id"].as_str().unwrap().parse().unwrap()) + .unwrap(); + Json(serde_json::json!({"status": "accepted"})) + } + + let (seen, mut received) = mpsc::unbounded_channel(); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let server = tokio::spawn( + axum::serve( + listener, + Router::new() + .route("/deliver", post(accept)) + .with_state(seen), + ) + .into_future(), + ); + let mut state = crate::api::bridge::postgres_tests::bridge_handler_test_state() + .await + .expect("local Postgres and Redis"); + let config = Arc::make_mut(&mut Arc::get_mut(&mut state).expect("unshared state").config); + config.push_gateway_delivery_url = Some(format!("http://{address}/deliver").parse().unwrap()); + config.require_relay_membership = true; + config.pubkey_allowlist_enabled = true; + config.allow_nip_oa_auth = false; + + let host = format!("push-gate-{}.local", uuid::Uuid::new_v4().simple()); + let community = state + .db + .ensure_configured_community(&host) + .await + .expect("ensure community") + .id; + let tenant = buzz_core::TenantContext::resolved(community, &host); + let owner = nostr::Keys::generate(); + let [admitted, banned, removed, not_allowlisted, agent] = + std::array::from_fn(|_| nostr::Keys::generate()); + for (keys, allowlisted) in [ + (&owner, true), + (&admitted, true), + (&banned, true), + (&removed, true), + (¬_allowlisted, false), + ] { + assert!( + state + .db + .add_relay_member( + community, + &keys.public_key().to_hex(), + "member", + None, + &state.relay_keypair, + ) + .await + .expect("add relay member") + .outcome + ); + if allowlisted { + sqlx::query("INSERT INTO pubkey_allowlist (community_id, pubkey) VALUES ($1, $2)") + .bind(community.as_uuid()) + .bind(keys.public_key().to_bytes().as_slice()) + .execute(state.db.pool()) + .await + .expect("allowlist"); + } + } + // An allowlisted agent whose owner is a member, while owner membership is off. + sqlx::query("INSERT INTO pubkey_allowlist (community_id, pubkey) VALUES ($1, $2)") + .bind(community.as_uuid()) + .bind(agent.public_key().to_bytes().as_slice()) + .execute(state.db.pool()) + .await + .expect("allowlist agent"); + sqlx::query( + "INSERT INTO users (community_id, pubkey, agent_owner_pubkey) \ + VALUES ($1, $3, NULL), ($1, $2, $3) \ + ON CONFLICT (community_id, pubkey) DO UPDATE \ + SET agent_owner_pubkey = EXCLUDED.agent_owner_pubkey", + ) + .bind(community.as_uuid()) + .bind(agent.public_key().to_bytes().as_slice()) + .bind(owner.public_key().to_bytes().as_slice()) + .execute(state.db.pool()) + .await + .expect("record agent owner"); + state + .db + .ban_community_member( + community, + &banned.public_key().to_bytes(), + &owner.public_key().to_bytes(), + None, + None, + ) + .await + .expect("ban"); + assert!(matches!( + state + .db + .remove_relay_member( + community, + &removed.public_key().to_hex(), + &state.relay_keypair, + ) + .await + .expect("remove from community") + .outcome, + buzz_db::relay_members::RemoveResult::Removed + )); + + let channel = create_channel(&state, &tenant, &owner, &[]).await; + let outsiders = [&admitted, &banned, &removed, ¬_allowlisted, &agent]; + for (source, keys) in (1u8..).zip(outsiders) { + assert_eq!( + buzz_db::push::replace_active_lease( + state.db.pool(), + community, + &keys.public_key().to_bytes(), + "phone", + buzz_db::push::LeaseVersion { + source_event_id: &[source; 32], + source_created_at: 10, + generation: 1, + expires_at: i64::MAX / 2, + }, + // The outbox is unique per endpoint and event, so each lease gets its own. + buzz_db::push::ActiveLease { + endpoint_hash: &keys.public_key().to_bytes(), + endpoint_grant: "opaque-grant", + max_class: "default", + subscriptions: &serde_json::json!([]), + }, + ) + .await + .expect("activate lease"), + buzz_db::push::ReplaceLeaseOutcome::Accepted + ); + } + + // One mention of every outsider, queued for each as the matcher would. + let deliver = |content: &'static str, authors: Vec<&nostr::Keys>| { + let state = state.clone(); + let authors: Vec> = authors + .into_iter() + .map(|keys| keys.public_key().to_bytes().to_vec()) + .collect(); + let tenant = tenant.clone(); + let owner = owner.clone(); + let mentioned: Vec = + outsiders.iter().map(|keys| keys.public_key()).collect(); + async move { + let mut event = EventBuilder::new(Kind::Custom(9), content) + .tag(Tag::parse(["h", &channel.to_string()]).unwrap()); + for key in mentioned { + event = event.tag(Tag::public_key(key)); + } + let event = event.sign_with_keys(&owner).unwrap(); + let ingested = ingest_event(&state, &tenant, event.clone(), http_auth(&owner)) + .await + .expect("ingest mention"); + assert!(ingested.accepted, "{}", ingested.message); + let mut queued = HashMap::new(); + for author in authors { + let id: uuid::Uuid = sqlx::query_scalar( + "INSERT INTO push_wake_outbox (community_id, author, installation_id, \ + lease_generation, endpoint_hash, event_id, class, expires_at) \ + VALUES ($1, $2, 'phone', 1, $3, $4, 'default', $5) RETURNING id", + ) + .bind(community.as_uuid()) + .bind(&author) + .bind(&author) + .bind(event.id.as_bytes().as_slice()) + .bind(i64::MAX / 2) + .fetch_one(state.db.pool()) + .await + .expect("queue wake"); + queued.insert(id, author); + } + let claimed = state + .db + .claim_due_push_wakes(community, 10, Utc::now() + TimeDelta::seconds(60)) + .await + .expect("claim wakes"); + assert_eq!(claimed.len(), queued.len(), "every queued wake is claimed"); + let http = reqwest::Client::new(); + for wake in claimed { + deliver_one(&state, &http, wake).await; + } + queued + } + }; + + let queued = deliver("hello", outsiders.to_vec()).await; + let mut sent = Vec::new(); + while let Ok(id) = received.try_recv() { + sent.push(queued[&id].clone()); + } + assert_eq!( + sent, + vec![admitted.public_key().to_bytes().to_vec()], + "only the outsider who still passes the connection gate is woken" + ); + + let flip = EventBuilder::new(Kind::Custom(9002), "") + .tags([ + Tag::parse(["h", &channel.to_string()]).unwrap(), + Tag::parse(["visibility", "private"]).unwrap(), + ]) + .sign_with_keys(&owner) + .unwrap(); + let flipped = ingest_event(&state, &tenant, flip, http_auth(&owner)) + .await + .expect("make private"); + assert!(flipped.accepted, "{}", flipped.message); + deliver("hello again", vec![&admitted]).await; + assert!( + received.try_recv().is_err(), + "a channel that turned private sends nothing" + ); + + state.begin_shutdown(); + server.abort(); +} diff --git a/docs/buzz-push.md b/docs/buzz-push.md index 1b7af8ef47..000e9d96fd 100644 --- a/docs/buzz-push.md +++ b/docs/buzz-push.md @@ -45,3 +45,17 @@ skip it, so the owner is not notified by every run of their workflow. When a workflow mentions its owner, the relay adds a plain `["p", ]`, which notifies them like any mention. Mobile's Activity feed, unread mention priority and in-app notification rule apply the same rule. + +## Channel access + +A lease wakes for a channel's events only when its author is a member, with +one exception: a message that `p`-tags a non-member wakes that non-member when +the channel is listed (open, not unlisted, a stream or forum). Workflow owner +attribution does not count as a mention. The relay checks this when it matches +and again before delivery, so a channel that becomes private or unlisted in +between stops the wake. Delivery also applies the connection gate to the +non-member: a ban on them or their agent's owner stops the wake, and so does +losing community membership or their allowlist entry when the relay requires +one. Private channels, unlisted channels, DMs and system channels still require +membership. Anyone in the community can already read a listed channel with +`REQ`, so the exception wakes no one for content they cannot read.