Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions NOSTR.md
Original file line number Diff line number Diff line change
Expand Up @@ -353,6 +353,41 @@ 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":<channel id>,"pubkeys":[<hex pubkey>, ...]}]`:
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":<hex pubkey>,"read":<bool>}`.
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.
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
missing or deleted channel is refused the same way, so the answer
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.** 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.
- 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", <channel id>]`, to that channel and to
Expand Down
121 changes: 108 additions & 13 deletions crates/buzz-relay/src/api/bridge/channel_access.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
//! `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;
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.
Expand All @@ -25,14 +27,62 @@ enum Asked {
Named(Vec<Uuid>),
/// One page of the channels the signer can reach.
Reachable { after: Option<Uuid>, 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<Uuid> {
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":<channel id>,"pubkeys":[...]}`
/// with 1 to [`MAX_IDS`] distinct lowercase hex pubkeys.
fn asked_readers(filter: &serde_json::Map<String, Value>) -> Result<Asked, &'static str> {
const SHAPE: &str = "reader access requires one filter with exactly \
{\"access\":\"readers\"}, \"channel\":<lowercase channel id> \
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
Expand All @@ -45,8 +95,10 @@ fn asked(filters: &[Value]) -> Result<Asked, &'static str> {
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
Expand Down Expand Up @@ -93,26 +145,35 @@ pub(super) async fn query(
) -> Result<Json<Value>, (StatusCode, Json<Value>)> {
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,
Expand Down Expand Up @@ -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<String> = (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<Value> = 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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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");
}
59 changes: 58 additions & 1 deletion crates/buzz-relay/src/handlers/channel_access.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Option<Vec<Reader>>, 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<bool> = 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",
Expand All @@ -147,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<bool, buzz_db::DbError> {
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())
Expand Down
Loading
Loading