From 5634b57964c5367664b36a902f0a353715d2b915 Mon Sep 17 00:00:00 2001 From: morgmart <98432065+morgmart@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:12:46 -0800 Subject: [PATCH 1/3] Answer which named people can read a channel POST /query with {"access":"readers","channel":..,"pubkeys":[...]} says, for up to 100 people, whether each can read the channel, by the check a task's assignees meet: member rows, open channels, and the parents under parent_access. Everyone named gets an entry, so false always means "cannot read". Only a signer who can read the channel may ask. Otherwise, and for a missing or deleted channel alike, the request is refused with 403 "not-allowed", never answered with a list of falses. NOSTR.md states the disclosure this allows: an asker learns that a named person reads the channel through a parent the asker isn't in. NIP-11 advertises buzz-channel-readers. Co-Authored-By: Claude Opus 5.5 Signed-off-by: morgmart <98432065+morgmart@users.noreply.github.com> --- NOSTR.md | 26 +++ .../src/api/bridge/channel_access.rs | 121 ++++++++-- .../buzz-relay/src/handlers/channel_access.rs | 47 ++++ .../handlers/channel_access_postgres_tests.rs | 213 +++++++++++++++++- crates/buzz-relay/src/nip11.rs | 5 + 5 files changed, 398 insertions(+), 14 deletions(-) diff --git a/NOSTR.md b/NOSTR.md index 3a4264d9868..cabf57134b9 100644 --- a/NOSTR.md +++ b/NOSTR.md @@ -353,6 +353,32 @@ channels the signer has not joined all get the same answer. answered, the whole request fails with 503 and is retried; a channel is only ever left out of a complete answer. The answer is a snapshot, and every post is still checked when it arrives. +- **Who else can read.** `POST /query` with exactly + `[{"access":"readers","channel":,"pubkeys":[, ...]}]`: + one lowercase channel ID and 1 to 100 distinct lowercase hex pubkeys, + with no other keys. The NIP-98 proof must carry a `payload` tag. Any + other shape is refused with 400. The answer is a JSON array with one + entry per pubkey, in request order: `{"pubkey":,"read":}`. + Nobody named is left out, so `false` always means "cannot read". + Reading is judged by the check a task's assignees meet + ([NIP-AR](docs/nips/NIP-AR.md)): a member row, an open channel, or what + the parents give under `parent_access`; a conversation follows its home. + - **Who may ask.** Only a signer who can read the channel. Otherwise the + request is refused with 403 and + `{"error":"not-allowed: the signer cannot read this channel"}`. A + missing or deleted channel is refused the same way, so the answer + can't show whether a private channel exists. There are no partial + answers: a refusal is never a list of `false`s. + - **What it discloses, by design.** Someone who can read a channel can + learn that a named person reads it through a parent the asker isn't + in, such as a private project. It answers only for a channel the + asker can already read, and it says only whether the person reads + it, never how. + - If any person cannot be answered, the whole request fails with 503 and + is retried. The answer is a snapshot: after a kind:20004 for the + channel, ask again. + - Relays that support this advertise `buzz-channel-readers` in NIP-11 + `supported_extensions`. - **Ask again.** After a committed change to who may read or post in a channel, the relay sends an ephemeral kind:20004, signed by the relay, with empty content and only `["h", ]`, to that channel and to diff --git a/crates/buzz-relay/src/api/bridge/channel_access.rs b/crates/buzz-relay/src/api/bridge/channel_access.rs index a0cb3317664..0bba47073e5 100644 --- a/crates/buzz-relay/src/api/bridge/channel_access.rs +++ b/crates/buzz-relay/src/api/bridge/channel_access.rs @@ -1,6 +1,8 @@ //! `POST /query` with `[{"access":"channels","ids":[...]}]`: what the signer //! may do in each named channel, or, without `ids`, one page of the channels -//! it can reach (NOSTR.md, Channel access). +//! it can reach; or, with `[{"access":"readers","channel":..,"pubkeys":[...]}]`, +//! which of the named people can read one channel the signer can read +//! (NOSTR.md, Channel access). use axum::{http::StatusCode, Json}; use buzz_core::TenantContext; @@ -8,7 +10,7 @@ use serde_json::Value; use uuid::Uuid; use crate::api::api_error; -use crate::handlers::channel_access::{answer, reachable, MAX_IDS}; +use crate::handlers::channel_access::{answer, reachable, readers, MAX_IDS}; use crate::state::AppState; /// How long one answer may take before the request fails and is retried. @@ -25,14 +27,62 @@ enum Asked { Named(Vec), /// One page of the channels the signer can reach. Reachable { after: Option, limit: usize }, + /// Which of the named people, in request order, can read the channel. + Readers { + channel: Uuid, + pubkeys: Vec<[u8; 32]>, + }, } +/// The refusal when the signer cannot read the channel it asks about. A +/// missing or deleted channel gets the same one, so it can't be told apart +/// from a private one. +const NOT_ALLOWED: &str = "not-allowed: the signer cannot read this channel"; + /// A canonical (lowercase, hyphenated) channel id. fn channel_id(value: &Value) -> Option { let s = value.as_str()?; Uuid::parse_str(s).ok().filter(|id| id.to_string() == s) } +/// A lowercase hex pubkey. +fn pubkey(value: &Value) -> Option<[u8; 32]> { + let s = value.as_str()?; + if s.len() != 64 || s.bytes().any(|b| b.is_ascii_uppercase()) { + return None; + } + let mut key = [0u8; 32]; + hex::decode_to_slice(s, &mut key).ok()?; + Some(key) +} + +/// Exactly `{"access":"readers","channel":,"pubkeys":[...]}` +/// with 1 to [`MAX_IDS`] distinct lowercase hex pubkeys. +fn asked_readers(filter: &serde_json::Map) -> Result { + const SHAPE: &str = "reader access requires one filter with exactly \ + {\"access\":\"readers\"}, \"channel\": \ + and \"pubkeys\":[1 to 100 distinct lowercase hex pubkeys]"; + if filter.len() != 3 { + return Err(SHAPE); + } + let channel = filter.get("channel").and_then(channel_id).ok_or(SHAPE)?; + let Some(Value::Array(raw)) = filter.get("pubkeys") else { + return Err(SHAPE); + }; + if raw.is_empty() || raw.len() > MAX_IDS { + return Err(SHAPE); + } + let mut pubkeys = Vec::with_capacity(raw.len()); + for value in raw { + let key = pubkey(value).ok_or(SHAPE)?; + if pubkeys.contains(&key) { + return Err(SHAPE); + } + pubkeys.push(key); + } + Ok(Asked::Readers { channel, pubkeys }) +} + /// Exactly one filter with `access` set to `channels` and either `ids` /// holding 1 to [`MAX_IDS`] distinct canonical channel ids, or no `ids` and /// optionally `after` (a canonical channel id) and `limit` (1 to @@ -45,8 +95,10 @@ fn asked(filters: &[Value]) -> Result { let [Value::Object(filter)] = filters else { return Err(SHAPE); }; - if filter.get("access").and_then(Value::as_str) != Some("channels") { - return Err(SHAPE); + match filter.get("access").and_then(Value::as_str) { + Some("channels") => {} + Some("readers") => return asked_readers(filter), + _ => return Err(SHAPE), } let Some(raw) = filter.get("ids") else { if filter @@ -93,26 +145,35 @@ pub(super) async fn query( ) -> Result, (StatusCode, Json)> { let asked = asked(filters).map_err(|e| api_error(StatusCode::BAD_REQUEST, e))?; let (community, pubkey) = (tenant.community(), viewer.to_bytes()); + // `None` only when the signer may not ask: reader access to a channel + // they can't read. let answered = tokio::time::timeout(DEADLINE, async { match asked { Asked::Named(ids) => answer(state, community, &pubkey, &ids) .await - .map(serde_json::to_value), + .map(|answer| Some(serde_json::to_value(answer))), Asked::Reachable { after, limit } => reachable(state, community, &pubkey, after, limit) .await - .map(serde_json::to_value), + .map(|page| Some(serde_json::to_value(page))), + Asked::Readers { channel, pubkeys } => { + readers(state, community, &pubkey, channel, &pubkeys) + .await + .map(|readers| readers.map(serde_json::to_value)) + } } }) .await .map_err(|_| "timed out".to_string()) .and_then(|answered| answered.map_err(|e| e.to_string())); - let encoded = answered.map_err(|e| { - tracing::warn!(error = %e, "channel access lookup failed"); - api_error( - StatusCode::SERVICE_UNAVAILABLE, - "error: channel access lookup failed; retry", - ) - })?; + let encoded = answered + .map_err(|e| { + tracing::warn!(error = %e, "channel access lookup failed"); + api_error( + StatusCode::SERVICE_UNAVAILABLE, + "error: channel access lookup failed; retry", + ) + })? + .ok_or_else(|| api_error(StatusCode::FORBIDDEN, NOT_ALLOWED))?; Ok(Json(encoded.map_err(|_| { api_error( StatusCode::INTERNAL_SERVER_ERROR, @@ -183,6 +244,40 @@ mod tests { } } + #[test] + fn accepts_only_the_exact_readers_shape() { + let (p, q) = ( + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + ); + assert_eq!( + asked(&[json!({"access":"readers","channel":A,"pubkeys":[p, q]})]).unwrap(), + Asked::Readers { + channel: Uuid::parse_str(A).unwrap(), + pubkeys: vec![[0xaa; 32], [0xbb; 32]], + } + ); + let too_many: Vec = (0..=MAX_IDS).map(|i| format!("{i:064x}")).collect(); + for refused in [ + json!([{"access":"readers","channel":A}]), + json!([{"access":"readers","pubkeys":[p]}]), + json!([{"access":"readers","channel":A,"pubkeys":[]}]), + json!([{"access":"readers","channel":A,"pubkeys":too_many}]), + json!([{"access":"readers","channel":A,"pubkeys":[p, p]}]), + json!([{"access":"readers","channel":A,"pubkeys":[p.to_uppercase()]}]), + json!([{"access":"readers","channel":A,"pubkeys":[&p[1..]]}]), + json!([{"access":"readers","channel":A,"pubkeys":["z".repeat(64)]}]), + json!([{"access":"readers","channel":A,"pubkeys":p}]), + json!([{"access":"readers","channel":A.to_uppercase(),"pubkeys":[p]}]), + json!([{"access":"readers","channel":[A],"pubkeys":[p]}]), + json!([{"access":"readers","channel":A,"pubkeys":[p],"ids":[A]}]), + json!([{"access":"readers","channel":A,"pubkeys":[p]}, {"access":"readers","channel":B,"pubkeys":[p]}]), + ] { + let filters: Vec = serde_json::from_value(refused.clone()).unwrap(); + assert!(asked(&filters).is_err(), "{refused}"); + } + } + /// A request the relay cannot answer fails whole, so a client never /// takes a left-out channel for "cannot read". /// Mutation: skip a channel whose lookup fails instead of failing → RED. diff --git a/crates/buzz-relay/src/handlers/channel_access.rs b/crates/buzz-relay/src/handlers/channel_access.rs index db9f365f0ba..0db1afb95db 100644 --- a/crates/buzz-relay/src/handlers/channel_access.rs +++ b/crates/buzz-relay/src/handlers/channel_access.rs @@ -135,6 +135,53 @@ pub(crate) async fn reachable( Ok(ReachablePage { channels, next }) } +/// Whether one named person can read the place asked about. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Reader { + /// The person, as lowercase hex. + pub pubkey: String, + /// Whether they can read the place now. + pub read: bool, +} + +/// Which of `pubkeys` can read `channel_id`, in request order, by the check +/// a task's assignees meet ([`can_read`]). `None` when `asker` cannot read +/// it themselves, whether it is private to them, deleted or missing, so the +/// answer never covers a place the asker can't see. Any lookup failure +/// fails the whole batch. +pub(crate) async fn readers( + state: &AppState, + community_id: CommunityId, + asker: &[u8], + channel_id: Uuid, + pubkeys: &[[u8; 32]], +) -> Result>, buzz_db::DbError> { + // Read every row fresh: a push can arrive before another node has + // dropped its cached rows for these people. + state.invalidate_membership_local(community_id, Uuid::nil(), asker); + if !can_read(state, community_id, asker, channel_id).await? { + return Ok(None); + } + for pubkey in pubkeys { + state.invalidate_membership_local(community_id, Uuid::nil(), pubkey); + } + let read: Vec = stream::iter(pubkeys.iter().copied()) + .map(|pubkey| async move { can_read(state, community_id, &pubkey, channel_id).await }) + .buffered(super::req::FILTER_QUERY_CONCURRENCY) + .try_collect() + .await?; + Ok(Some( + pubkeys + .iter() + .zip(read) + .map(|(pubkey, read)| Reader { + pubkey: hex::encode(pubkey), + read, + }) + .collect(), + )) +} + fn role_name(role: MemberRole) -> &'static str { match role { MemberRole::Owner => "owner", diff --git a/crates/buzz-relay/src/handlers/channel_access_postgres_tests.rs b/crates/buzz-relay/src/handlers/channel_access_postgres_tests.rs index 71d29830737..946d9cfcc62 100644 --- a/crates/buzz-relay/src/handlers/channel_access_postgres_tests.rs +++ b/crates/buzz-relay/src/handlers/channel_access_postgres_tests.rs @@ -19,7 +19,7 @@ use uuid::Uuid; use crate::handlers::artifact_conversation_postgres_tests::{create_task, open, send, task}; use crate::handlers::group_state_postgres_tests::{community, create_channel, edit_channel}; -use crate::handlers::parent_access_postgres_tests::{add, post, set_parent}; +use crate::handlers::parent_access_postgres_tests::{add, post, set_parent, set_parent_access}; use crate::state::AppState; use buzz_core::kind::{KIND_CHANNEL_ACCESS_CHANGED, KIND_VIEWER_ACCESS_CHANGED}; @@ -1014,3 +1014,214 @@ async fn a_timeout_closes_posting_and_is_pushed_to_that_person_only() { assert!(post(state, tenant, keys, f.child).await.is_err()); } } + +/// `POST /query` asking which of `people` can read `channel`, signed by +/// `asker`. +async fn ask_readers( + state: &Arc, + tenant: &TenantContext, + asker: &Keys, + channel: Uuid, + people: &[&Keys], +) -> (StatusCode, Value) { + let pubkeys: Vec = people.iter().map(|p| p.public_key().to_hex()).collect(); + let body = json!([{"access": "readers", "channel": channel, "pubkeys": pubkeys}]); + query(state, tenant, asker, &body, true).await +} + +/// The answer for `people`, asserting the request succeeded. +async fn readers( + state: &Arc, + tenant: &TenantContext, + asker: &Keys, + channel: Uuid, + people: &[&Keys], +) -> Vec<(String, bool)> { + let (status, body) = ask_readers(state, tenant, asker, channel, people).await; + assert_eq!(status, StatusCode::OK, "{body}"); + body.as_array() + .expect("answer array") + .iter() + .map(|entry| { + ( + entry["pubkey"].as_str().expect("pubkey").to_string(), + entry["read"].as_bool().expect("read"), + ) + }) + .collect() +} + +fn expect(people: &[(&Keys, bool)]) -> Vec<(String, bool)> { + people + .iter() + .map(|(person, read)| (person.public_key().to_hex(), *read)) + .collect() +} + +/// Removes `person` from `channel`, signed by `actor`. +async fn remove( + state: &Arc, + tenant: &TenantContext, + actor: &Keys, + channel: Uuid, + person: &Keys, +) { + let removal = EventBuilder::new(Kind::Custom(9001), "") + .tags([ + Tag::parse(["h", &channel.to_string()]).unwrap(), + Tag::parse(["p", &person.public_key().to_hex()]).unwrap(), + ]) + .sign_with_keys(actor) + .unwrap(); + send(state, tenant, removal).await.expect("remove"); +} + +/// Someone who can read a place learns which of the named people can read +/// it, by the check a task's assignees meet: through the project and +/// `parent_access` too, even when the asker isn't in the project. Everyone +/// named gets an entry, in request order. Asking about a place the asker +/// can't read is refused the same way whether it is private or missing, and +/// an asker who loses access between two asks is refused, not told that +/// nobody reads it. +/// Mutation: skip the asker check, leave out people who can't read, ignore +/// the parents, or answer an unreadable place with an empty list → RED. +#[tokio::test] +#[ignore = "requires Postgres and Redis"] +async fn a_reader_learns_who_else_can_read_a_place() { + let f = Fixture::new(live_state().await, "readers").await; + let (state, tenant) = (&f.state, &f.tenant); + let project_member = Keys::generate(); + let project_guest = Keys::generate(); + let child_member = Keys::generate(); + let outsider = Keys::generate(); + add( + state, + tenant, + &f.owner, + f.project, + &project_member, + "member", + ) + .await; + add(state, tenant, &f.owner, f.project, &project_guest, "guest").await; + add(state, tenant, &f.owner, f.child, &child_member, "member").await; + + let everyone = [ + &outsider, + &project_member, + &f.owner, + &project_guest, + &child_member, + ]; + let answer = expect(&[ + (&outsider, false), + (&project_member, true), + (&f.owner, true), + (&project_guest, true), + (&child_member, true), + ]); + assert_eq!( + readers(state, tenant, &f.owner, f.child, &everyone).await, + answer, + "everyone named, in request order" + ); + // The disclosure NOSTR.md states: an asker outside the project learns + // that a project member reads the child through it. + assert_eq!( + readers(state, tenant, &child_member, f.child, &everyone).await, + answer, + "a child member outside the project gets the same answer" + ); + assert_eq!( + readers( + state, + tenant, + &project_member, + f.conversation, + &[&child_member, &outsider] + ) + .await, + expect(&[(&child_member, true), (&outsider, false)]), + "a task conversation follows its home" + ); + + set_parent_access(state, tenant, &f.owner, f.child, "none") + .await + .expect("close the parents' grant"); + assert_eq!( + readers( + state, + tenant, + &child_member, + f.child, + &[&project_member, &child_member] + ) + .await, + expect(&[(&project_member, false), (&child_member, true)]), + "parent_access none takes the project's readers away" + ); + set_parent_access(state, tenant, &f.owner, f.child, "member") + .await + .expect("reopen the parents' grant"); + remove(state, tenant, &f.owner, f.project, &project_member).await; + assert_eq!( + readers(state, tenant, &f.owner, f.child, &[&project_member]).await, + expect(&[(&project_member, false)]), + "a removal is seen at once" + ); + + // Not allowed to ask: one refusal, the same for private and missing. + let (status, private) = ask_readers(state, tenant, &outsider, f.child, &[&f.owner]).await; + assert_eq!(status, StatusCode::FORBIDDEN, "{private}"); + assert!( + private["error"] + .as_str() + .unwrap() + .starts_with("not-allowed:"), + "{private}" + ); + let (status, missing) = ask_readers(state, tenant, &f.owner, Uuid::new_v4(), &[&f.owner]).await; + assert_eq!(status, StatusCode::FORBIDDEN); + assert_eq!(missing, private, "a missing place looks like a private one"); + + // Losing access between two asks gets the refusal, not a list of falses. + assert_eq!( + readers(state, tenant, &child_member, f.child, &[&f.owner]).await, + expect(&[(&f.owner, true)]) + ); + // Removed by a write that skips this node's own removal path. + let community = tenant.community(); + let owner = f.owner.public_key().to_bytes(); + assert_eq!( + readers(state, tenant, &f.owner, f.child, &[&project_guest]).await, + expect(&[(&project_guest, true)]) + ); + state + .db + .remove_member( + community, + f.project, + &project_guest.public_key().to_bytes(), + &owner, + ) + .await + .expect("remove elsewhere"); + assert_eq!( + readers(state, tenant, &f.owner, f.child, &[&project_guest]).await, + expect(&[(&project_guest, false)]), + "a named person's rows are read fresh" + ); + state + .db + .remove_member( + community, + f.child, + &child_member.public_key().to_bytes(), + &owner, + ) + .await + .expect("remove elsewhere"); + let (status, body) = ask_readers(state, tenant, &child_member, f.child, &[&f.owner]).await; + assert_eq!(status, StatusCode::FORBIDDEN, "{body}"); + assert_eq!(body, private); +} diff --git a/crates/buzz-relay/src/nip11.rs b/crates/buzz-relay/src/nip11.rs index 997453fe842..f5cb45477bf 100644 --- a/crates/buzz-relay/src/nip11.rs +++ b/crates/buzz-relay/src/nip11.rs @@ -284,6 +284,10 @@ impl RelayInfo { // Channel access). "buzz-channel-access".to_string(), "buzz-artifact-assignees".to_string(), + // `POST /query` answers `{"access":"readers"}` with which named + // people can read a channel the signer can read (NOSTR.md, + // Channel access). + "buzz-channel-readers".to_string(), ]; let gif = gif_provider.map(|provider| { supported_extensions.push("buzz-gif".to_string()); @@ -857,6 +861,7 @@ mod tests { assert!(extensions.contains(&"buzz-channel-parent-access".to_string())); assert!(extensions.contains(&"buzz-artifact-conversations".to_string())); assert!(extensions.contains(&"buzz-channel-access".to_string())); + assert!(extensions.contains(&"buzz-channel-readers".to_string())); assert!(extensions.contains(&"buzz-artifact-assignees".to_string())); } From 9c6db3016c61fcb9fb208b2103341baf4dcef8ef Mon Sep 17 00:00:00 2001 From: morgmart <98432065+morgmart@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:29:36 -0800 Subject: [PATCH 2/3] Count a banned person as reading nothing The shared read check, which both the assignee rule and the readers answer use, now says false for someone banned from the community, or an agent whose owner is, open channels included. A banned person can no longer be assigned to a task they can't open, and the readers answer agrees with the ban refusal they get when they ask for themselves. A timeout leaves reading alone. NIP-AR and NOSTR.md state the rule. Co-Authored-By: Claude Opus 5.5 Signed-off-by: morgmart <98432065+morgmart@users.noreply.github.com> --- NOSTR.md | 6 + .../artifact_assignee_postgres_tests.rs | 60 ++++++++- .../buzz-relay/src/handlers/channel_access.rs | 12 +- .../handlers/channel_access_postgres_tests.rs | 117 +++++++++++++++++- docs/nips/NIP-AR.md | 1 + 5 files changed, 193 insertions(+), 3 deletions(-) diff --git a/NOSTR.md b/NOSTR.md index cabf57134b9..52af6391149 100644 --- a/NOSTR.md +++ b/NOSTR.md @@ -363,9 +363,15 @@ channels the signer has not joined all get the same answer. Reading is judged by the check a task's assignees meet ([NIP-AR](docs/nips/NIP-AR.md)): a member row, an open channel, or what the parents give under `parent_access`; a conversation follows its home. + Someone banned from the community, or an agent whose owner is, reads + nothing and is answered `false`, as every request from them is refused. + A timeout doesn't change reading: a timed-out person is answered `true` + where they read, and may ask. - **Who may ask.** Only a signer who can read the channel. Otherwise the request is refused with 403 and `{"error":"not-allowed: the signer cannot read this channel"}`. A + banned signer is refused earlier, with the ban's own `blocked:` reason, + like every request from them. A missing or deleted channel is refused the same way, so the answer can't show whether a private channel exists. There are no partial answers: a refusal is never a list of `false`s. diff --git a/crates/buzz-relay/src/handlers/artifact_assignee_postgres_tests.rs b/crates/buzz-relay/src/handlers/artifact_assignee_postgres_tests.rs index cb275cc7bca..85d749a07ce 100644 --- a/crates/buzz-relay/src/handlers/artifact_assignee_postgres_tests.rs +++ b/crates/buzz-relay/src/handlers/artifact_assignee_postgres_tests.rs @@ -10,7 +10,7 @@ use serde_json::{json, Value}; use uuid::Uuid; use crate::handlers::artifact_conversation_postgres_tests::send; -use crate::handlers::channel_access_postgres_tests::{live_state, query}; +use crate::handlers::channel_access_postgres_tests::{live_state, moderate, query, relay_member}; use crate::handlers::group_state_postgres_tests::{community, create_channel}; use crate::handlers::parent_access_postgres_tests::{add, set_parent}; use crate::state::AppState; @@ -838,3 +838,61 @@ async fn find_reads_unassigned_tasks_within_a_project_page_by_page() { ); } } + +/// Someone banned from the community can't be assigned, because they read +/// nothing. A timed-out person still reads, so they can. +/// Mutation: drop the ban from the shared check → RED. +#[tokio::test] +#[ignore = "requires Postgres and Redis"] +async fn a_banned_person_cannot_be_assigned() { + let f = Fixture::new("assign-ban").await; + let (state, tenant) = (&f.state, &f.tenant); + let banned = Keys::generate(); + relay_member(state, tenant, &f.owner, "owner").await; + add(state, tenant, &f.owner, f.project, &banned, "member").await; + moderate( + state, + tenant, + &f.owner, + buzz_core::kind::KIND_MODERATION_BAN, + &banned, + None, + ) + .await; + moderate( + state, + tenant, + &f.owner, + buzz_core::kind::KIND_MODERATION_TIMEOUT, + &f.member, + Some(chrono::Utc::now().timestamp() + 3600), + ) + .await; + let banned_hex = banned.public_key().to_hex(); + let member_hex = f.member.public_key().to_hex(); + refused( + f.save(&revision( + &f.owner, + f.child, + Uuid::new_v4(), + "create", + None, + &[["assignee", &banned_hex]], + now(), + )) + .await, + "assignee-unreadable", + &[&banned_hex], + ); + f.save(&revision( + &f.owner, + f.child, + Uuid::new_v4(), + "create", + None, + &[["assignee", &member_hex]], + now(), + )) + .await + .expect("a timed-out person can be assigned"); +} diff --git a/crates/buzz-relay/src/handlers/channel_access.rs b/crates/buzz-relay/src/handlers/channel_access.rs index 0db1afb95db..e886a24d5e8 100644 --- a/crates/buzz-relay/src/handlers/channel_access.rs +++ b/crates/buzz-relay/src/handlers/channel_access.rs @@ -194,13 +194,23 @@ fn role_name(role: MemberRole) -> &'static str { } /// Whether `pubkey` can read `channel_id`, by the rule the answer leaves -/// unreadable channels out with. +/// unreadable channels out with. Someone banned from the community, or an +/// agent whose owner is, reads nothing, as every request from them is +/// refused. A timeout leaves reading alone. pub(crate) async fn can_read( state: &AppState, community_id: CommunityId, pubkey: &[u8], channel_id: Uuid, ) -> Result { + if state + .db + .moderation_restriction_state(community_id, pubkey) + .await? + .banned + { + return Ok(false); + } Ok(readable(state, community_id, pubkey, channel_id) .await? .is_some()) diff --git a/crates/buzz-relay/src/handlers/channel_access_postgres_tests.rs b/crates/buzz-relay/src/handlers/channel_access_postgres_tests.rs index 946d9cfcc62..d6ab16637ca 100644 --- a/crates/buzz-relay/src/handlers/channel_access_postgres_tests.rs +++ b/crates/buzz-relay/src/handlers/channel_access_postgres_tests.rs @@ -788,7 +788,7 @@ pub(crate) async fn viewer_pushes( } /// Apply a moderation command signed by `actor` against `target`. -async fn moderate( +pub(crate) async fn moderate( state: &Arc, tenant: &TenantContext, actor: &Keys, @@ -1225,3 +1225,118 @@ async fn a_reader_learns_who_else_can_read_a_place() { assert_eq!(status, StatusCode::FORBIDDEN, "{body}"); assert_eq!(body, private); } + +/// Makes `keys` a relay member with `role`, so they may moderate. +pub(crate) async fn relay_member( + state: &AppState, + tenant: &TenantContext, + keys: &Keys, + role: &str, +) { + state + .db + .add_relay_member( + tenant.community(), + &keys.public_key().to_hex(), + role, + None, + &Keys::generate(), + ) + .await + .map(|write| write.outcome) + .expect("relay member"); +} + +/// Someone banned from the community, and an agent whose owner is, read +/// nothing, so the answer says false for them, and a banned asker is +/// refused with the ban's reason, as every request from them is. A timed-out +/// person still reads. Lifting the ban restores them. +/// Mutation: drop the ban from the shared check → RED. +#[tokio::test] +#[ignore = "requires Postgres and Redis"] +async fn a_banned_person_reads_nothing() { + let f = Fixture::new(live_state().await, "readers-ban").await; + let (state, tenant) = (&f.state, &f.tenant); + let (banned, agent, timed_out) = (Keys::generate(), Keys::generate(), Keys::generate()); + relay_member(state, tenant, &f.owner, "owner").await; + for keys in [&banned, &agent] { + state + .db + .ensure_user(tenant.community(), keys.public_key().as_bytes()) + .await + .expect("user row"); + } + assert!(state + .db + .set_agent_owner( + tenant.community(), + agent.public_key().as_bytes(), + banned.public_key().as_bytes(), + ) + .await + .expect("own the agent")); + for keys in [&banned, &agent, &timed_out] { + add(state, tenant, &f.owner, f.project, keys, "member").await; + } + let open_channel = create_channel(state, tenant, &f.owner, &[]).await; + let people = [&banned, &agent, &timed_out]; + for place in [f.child, open_channel] { + assert_eq!( + readers(state, tenant, &f.owner, place, &people).await, + expect(&[(&banned, true), (&agent, true), (&timed_out, true)]) + ); + } + + let until = chrono::Utc::now().timestamp() + 3600; + moderate( + state, + tenant, + &f.owner, + buzz_core::kind::KIND_MODERATION_TIMEOUT, + &timed_out, + Some(until), + ) + .await; + moderate( + state, + tenant, + &f.owner, + buzz_core::kind::KIND_MODERATION_BAN, + &banned, + None, + ) + .await; + for place in [f.child, open_channel] { + assert_eq!( + readers(state, tenant, &f.owner, place, &people).await, + expect(&[(&banned, false), (&agent, false), (&timed_out, true)]), + "banned and their agent read nothing, an open channel included; a timeout reads" + ); + } + let (status, refused) = ask_readers(state, tenant, &banned, open_channel, &[&f.owner]).await; + assert_eq!(status, StatusCode::FORBIDDEN, "{refused}"); + assert!( + refused["error"].as_str().unwrap().starts_with("blocked:"), + "a banned asker gets the ban's reason: {refused}" + ); + assert_eq!( + readers(state, tenant, &timed_out, f.child, &[&f.owner]).await, + expect(&[(&f.owner, true)]), + "a timed-out person may still ask" + ); + + moderate( + state, + tenant, + &f.owner, + buzz_core::kind::KIND_MODERATION_UNBAN, + &banned, + None, + ) + .await; + assert_eq!( + readers(state, tenant, &f.owner, f.child, &people).await, + expect(&[(&banned, true), (&agent, true), (&timed_out, true)]), + "lifting the ban restores them" + ); +} diff --git a/docs/nips/NIP-AR.md b/docs/nips/NIP-AR.md index c6596a4e86f..8013b254b22 100644 --- a/docs/nips/NIP-AR.md +++ b/docs/nips/NIP-AR.md @@ -70,6 +70,7 @@ Two optional tags name people, and the relay holds them to rules so a reader can - On a `create`, `move` or `restore`, every assignee MUST be able to read the home that revision puts the artifact in, judged when the revision is accepted. - On an `update`, only the assignees it adds, compared with the artifact's current state, are checked. Someone who lost access since being assigned doesn't block an unrelated edit, and can't read the artifact anyway. - A move that would leave an assignee unable to read the destination is rejected, so the client saves it without them. + - Someone banned from the community, or an agent whose owner is, reads nothing, so they can't be assigned. A timeout doesn't change reading, so a timed-out person can still be assigned. - A `delete` carries no assignees. - **Creator.** `["creator", ]`, at most once. On `create` it MUST equal the revision's signer. Every later `update`, `move` and `restore` MUST carry the creator named on `create`: present and equal, or absent when the artifact was created without one. A `delete` carries none. - **Signer.** An artifact revision is signed by a person. An agent acts through its owner's key and names itself in client-defined tags. Comments in the artifact's conversation are ordinary messages and may be signed by agents. From ac63e76f5ed59f43ac60f6e9f7154b46ad6ebe5d Mon Sep 17 00:00:00 2001 From: morgmart <98432065+morgmart@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:42:16 -0800 Subject: [PATCH 3/3] State the ban disclosure and fix the banned-asker sentence The readers answer now documents, as intended, that a ban can be inferred by comparing a "can't read" with the channel's member list, and that the relay never states the reason for someone else. The sentence on banned askers moves after the missing-channel refusal it was splitting. Co-Authored-By: Claude Opus 5.5 Signed-off-by: morgmart <98432065+morgmart@users.noreply.github.com> --- NOSTR.md | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/NOSTR.md b/NOSTR.md index 52af6391149..7e0de68273f 100644 --- a/NOSTR.md +++ b/NOSTR.md @@ -370,16 +370,19 @@ channels the signer has not joined all get the same answer. - **Who may ask.** Only a signer who can read the channel. Otherwise the request is refused with 403 and `{"error":"not-allowed: the signer cannot read this channel"}`. A - banned signer is refused earlier, with the ban's own `blocked:` reason, - like every request from them. A missing or deleted channel is refused the same way, so the answer - can't show whether a private channel exists. There are no partial + can't show whether a private channel exists. A banned signer is + refused before the question is answered, with the ban's own + `blocked:` reason, like every request from them. There are no partial answers: a refusal is never a list of `false`s. - - **What it discloses, by design.** Someone who can read a channel can - learn that a named person reads it through a parent the asker isn't - in, such as a private project. It answers only for a channel the - asker can already read, and it says only whether the person reads - it, never how. + - **What it discloses, by design.** It answers only for a channel the + asker can already read, and it says only whether each person reads + it, never how or why not. The relay never states the reason for + someone else. Two things can still be inferred: + - Someone who can read a channel can learn that a named person reads + it through a parent the asker isn't in, such as a private project. + - An asker who also sees a person in the channel's member list, but + is told they can't read it, can infer that the person is banned. - If any person cannot be answered, the whole request fails with 503 and is retried. The answer is a snapshot: after a kind:20004 for the channel, ask again.